Search in sources :

Example 6 with FileIOError

use of com.helger.commons.io.file.FileIOError in project ph-commons by phax.

the class AbstractDAO method checkFileAccess.

/**
 * Check the access to the passed file using the specified mode. If the access
 * is not provided, a {@link DAOException} is thrown. If everything is good,
 * this method returns without a comment.
 *
 * @param aFile
 *        The file to check. May not be <code>null</code>.
 * @param eMode
 *        The access mode. May not be <code>null</code>.
 * @throws DAOException
 *         If the requested access mode cannot be provided.
 */
protected static void checkFileAccess(@Nonnull final File aFile, @Nonnull final EMode eMode) throws DAOException {
    ValueEnforcer.notNull(aFile, "File");
    ValueEnforcer.notNull(eMode, "Mode");
    final String sFilename = aFile.toString();
    if (aFile.exists()) {
        // file exist -> must be a file!
        if (!aFile.isFile())
            throw new DAOException("The passed filename '" + sFilename + "' is not a file - maybe a directory or a symlink? Path is '" + aFile.getAbsolutePath() + "'");
        switch(eMode) {
            case READ:
                // Check for read-rights
                if (!aFile.canRead())
                    throw new DAOException("Read access rights from '" + aFile.getAbsolutePath() + "' are missing.");
                break;
            case WRITE:
                // Check for write-rights
                if (!aFile.canWrite())
                    throw new DAOException("Write access rights to '" + aFile.getAbsolutePath() + "' are missing");
                break;
        }
    } else {
        // Ensure the parent directory is present
        final File aParentDir = aFile.getParentFile();
        if (aParentDir != null) {
            final FileIOError aError = FileOperationManager.INSTANCE.createDirRecursiveIfNotExisting(aParentDir);
            if (aError.isFailure())
                throw new DAOException("Failed to create parent directory '" + aParentDir + "' of '" + aFile.getAbsolutePath() + "': " + aError);
        }
    }
}
Also used : FileIOError(com.helger.commons.io.file.FileIOError) File(java.io.File)

Example 7 with FileIOError

use of com.helger.commons.io.file.FileIOError in project ph-schematron by phax.

the class SchematronValidationMojo method _performValidation.

/**
 * @param aSch
 *        Schematron resource to apply on validation artefacts
 * @param aXMLDirectory
 *        XML directory to be scanned
 * @param aXMLIncludes
 *        XML include mask - may be <code>null</code> or empty
 * @param aXMLExcludes
 *        XML exclude mask - may be <code>null</code> or empty
 * @param aSVRLDirectory
 *        SVRL directory to write to (maybe <code>null</code> in which case
 *        the SVRL is not written)
 * @param bExpectSuccess
 *        <code>true</code> if this is a positive validation,
 *        <code>false</code> if error is expected
 * @param aErrorMessages
 *        The list of collected error messages (only used if fail-fast is
 *        disabled)
 * @throws MojoExecutionException
 *         Internal error
 * @throws MojoFailureException
 *         Validation error
 */
private void _performValidation(@Nonnull final ISchematronResource aSch, @Nonnull final File aXMLDirectory, @Nullable final String[] aXMLIncludes, @Nullable final String[] aXMLExcludes, @Nullable final File aSVRLDirectory, final boolean bExpectSuccess, @Nonnull final ICommonsList<String> aErrorMessages) throws MojoExecutionException, MojoFailureException {
    final DirectoryScanner aScanner = new DirectoryScanner();
    aScanner.setBasedir(aXMLDirectory);
    if (ArrayHelper.isNotEmpty(aXMLIncludes))
        aScanner.setIncludes(aXMLIncludes);
    if (ArrayHelper.isNotEmpty(aXMLExcludes))
        aScanner.setExcludes(aXMLExcludes);
    aScanner.setCaseSensitive(true);
    aScanner.scan();
    final String[] aXMLFilenames = aScanner.getIncludedFiles();
    if (aXMLFilenames != null) {
        for (final String sXMLFilename : aXMLFilenames) {
            final File aXMLFile = new File(aXMLDirectory, sXMLFilename);
            // Validate XML file
            getLog().info("Validating XML file '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile + "' expecting " + (bExpectSuccess ? "success" : "failure"));
            try {
                final SchematronOutputType aSOT = aSch.applySchematronValidationToSVRL(TransformSourceFactory.create(aXMLFile));
                if (aSVRLDirectory != null) {
                    // Save SVRL
                    final File aSVRLFile = new File(aSVRLDirectory, sXMLFilename + ".svrl");
                    final FileIOError aIOErr = FileOperationManager.INSTANCE.createDirRecursiveIfNotExisting(aSVRLFile.getParentFile());
                    if (aIOErr.isFailure())
                        getLog().error("Failed to create parent directory of '" + aSVRLFile.getAbsolutePath() + "': " + aIOErr.toString());
                    if (new SVRLMarshaller().write(aSOT, aSVRLFile).isSuccess())
                        getLog().info("Successfully saved SVRL file '" + aSVRLFile.getPath() + "'");
                    else
                        getLog().error("Error saving SVRL file '" + aSVRLFile.getPath() + "'");
                }
                // Failed asserts and Successful reports
                final ICommonsList<AbstractSVRLMessage> aSVRLErrors = SVRLHelper.getAllFailedAssertionsAndSuccessfulReports(aSOT);
                if (bExpectSuccess) {
                    // No failed assertions expected
                    if (aSVRLErrors.isNotEmpty()) {
                        final String sMessage = aSVRLErrors.size() + " failed Schematron assertions for XML file '" + aXMLFile.getPath() + "'";
                        getLog().error(sMessage);
                        aSVRLErrors.forEach(x -> getLog().error(x.getAsResourceError(aXMLFile.getPath()).getAsString(Locale.US)));
                        if (m_bFailFast)
                            throw new MojoFailureException(sMessage);
                        aErrorMessages.add(sMessage);
                    }
                } else {
                    // At least one failed assertions expected
                    if (aSVRLErrors.isEmpty()) {
                        final String sMessage = "No failed Schematron assertions for erroneous XML file '" + aXMLFile.getPath() + "'";
                        getLog().error(sMessage);
                        if (m_bFailFast)
                            throw new MojoFailureException(sMessage);
                        aErrorMessages.add(sMessage);
                    }
                }
            } catch (final MojoExecutionException | MojoFailureException up) {
                throw up;
            } catch (final Exception ex) {
                final String sMessage = "Exception validating XML '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile + "'";
                getLog().error(sMessage, ex);
                throw new MojoExecutionException(sMessage, ex);
            }
        }
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) FileIOError(com.helger.commons.io.file.FileIOError) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) File(java.io.File)

Example 8 with FileIOError

use of com.helger.commons.io.file.FileIOError in project phase4 by phax.

the class AS4ResourceHelper method close.

public void close() {
    // close only once
    if (!m_aInClose.getAndSet(true)) {
        // Close all closeables before deleting files, because the closables might
        // be the files to be deleted :)
        final ICommonsList<Closeable> aCloseables = m_aRWLock.writeLockedGet(() -> {
            final ICommonsList<Closeable> ret = m_aCloseables.getClone();
            m_aCloseables.clear();
            return ret;
        });
        if (aCloseables.isNotEmpty()) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Closing " + aCloseables.size() + " " + CAS4.LIB_NAME + " stream handles");
            for (final Closeable aCloseable : aCloseables) StreamHelper.close(aCloseable);
        }
        // Get and delete all temp files
        final ICommonsList<File> aFiles = m_aRWLock.writeLockedGet(() -> {
            final ICommonsList<File> ret = m_aTempFiles.getClone();
            m_aTempFiles.clear();
            return ret;
        });
        if (aFiles.isNotEmpty()) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Deleting " + aFiles.size() + " temporary " + CAS4.LIB_NAME + " files");
            for (final File aFile : aFiles) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Deleting temporary file '" + aFile.getAbsolutePath() + "'");
                final FileIOError aError = AS4IOHelper.getFileOperationManager().deleteFileIfExisting(aFile);
                if (aError.isFailure())
                    LOGGER.warn("  Failed to delete temporary " + CAS4.LIB_NAME + " file " + aFile.getAbsolutePath() + ": " + aError.toString());
            }
        }
    }
}
Also used : FileIOError(com.helger.commons.io.file.FileIOError) Closeable(java.io.Closeable) File(java.io.File)

Example 9 with FileIOError

use of com.helger.commons.io.file.FileIOError in project ph-commons by phax.

the class AbstractSimpleDAO method getSafeFile.

@Nonnull
protected final File getSafeFile(@Nonnull final String sFilename, @Nonnull final EMode eMode) throws DAOException {
    ValueEnforcer.notNull(sFilename, "Filename");
    ValueEnforcer.notNull(eMode, "Mode");
    final File aFile = m_aIO.getFile(sFilename);
    if (aFile.exists()) {
        // file exist -> must be a file!
        if (!aFile.isFile())
            throw new DAOException("The passed filename '" + sFilename + "' is not a file - maybe a directory? Path is '" + aFile.getAbsolutePath() + "'");
        switch(eMode) {
            case READ:
                // Check for read-rights
                if (!aFile.canRead())
                    throw new DAOException("The DAO of class " + getClass().getName() + " has no access rights to read from '" + aFile.getAbsolutePath() + "'");
                break;
            case WRITE:
                // Check for write-rights
                if (!aFile.canWrite())
                    throw new DAOException("The DAO of class " + getClass().getName() + " has no access rights to write to '" + aFile.getAbsolutePath() + "'");
                break;
        }
    } else {
        // Ensure the parent directory is present
        final File aParentDir = aFile.getParentFile();
        if (aParentDir != null) {
            final FileIOError aError = FileOperationManager.INSTANCE.createDirRecursiveIfNotExisting(aParentDir);
            if (aError.isFailure())
                throw new DAOException("The DAO of class " + getClass().getName() + " failed to create parent directory '" + aParentDir + "': " + aError);
        }
    }
    return aFile;
}
Also used : DAOException(com.helger.dao.DAOException) FileIOError(com.helger.commons.io.file.FileIOError) File(java.io.File) Nonnull(javax.annotation.Nonnull)

Example 10 with FileIOError

use of com.helger.commons.io.file.FileIOError in project ph-commons by phax.

the class AbstractWALDAO method _writeToFile.

/**
 * 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 WAL DAO file '" + sFilename + "'");
    File aFileNew = null;
    IMicroDocument aDoc = null;
    final String sFilenameNew = _getFilenameNew(sFilename);
    final String sFilenamePrev = _getFilenamePrev(sFilename);
    try {
        // Get the file handle
        aFileNew = getSafeFile(sFilenameNew, 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);
        // Get the output stream
        final OutputStream aOS = FileHelper.getOutputStream(aFileNew);
        if (aOS == null) {
            // Logger warning already emitted
            throw new DAOException("Failed to open output stream for '" + aFileNew.getAbsolutePath() + "'");
        }
        // 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");
        // Rename existing file to old
        FileIOError aIOError;
        boolean bRenamedToPrev = false;
        if (m_aIO.existsFile(sFilename)) {
            aIOError = m_aIO.renameFile(sFilename, sFilenamePrev);
            bRenamedToPrev = true;
        } else
            aIOError = new FileIOError(EFileIOOperation.RENAME_FILE, EFileIOErrorCode.NO_ERROR);
        if (aIOError.isSuccess()) {
            // Rename new file to final
            aIOError = m_aIO.renameFile(sFilenameNew, sFilename);
            if (aIOError.isSuccess()) {
                // Finally delete old file
                aIOError = m_aIO.deleteFileIfExisting(sFilenamePrev);
            } else {
                // -> Revert original rename to stay as consistent as possible
                if (bRenamedToPrev)
                    m_aIO.renameFile(sFilenamePrev, sFilename);
            }
        }
        if (aIOError.isFailure())
            throw new IllegalStateException("Error on rename(existing-old)/rename(new-existing)/delete(old): " + aIOError);
        // Update stats etc.
        m_aStatsCounterWriteTimer.addTime(aSW.stopAndGetMillis());
        m_aStatsCounterWriteSuccess.increment();
        m_nWriteCount++;
        m_aLastWriteDT = PDTFactory.getCurrentLocalDateTime();
        return ESuccess.SUCCESS;
    } catch (final DAOException | RuntimeException ex) {
        final String sErrorFilename = aFileNew != null ? aFileNew.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;
    }
}
Also used : DAOException(com.helger.dao.DAOException) IXMLWriterSettings(com.helger.xml.serialize.write.IXMLWriterSettings) FileIOError(com.helger.commons.io.file.FileIOError) DataOutputStream(java.io.DataOutputStream) OutputStream(java.io.OutputStream) PDTToString(com.helger.commons.datetime.PDTToString) IMicroDocument(com.helger.xml.microdom.IMicroDocument) File(java.io.File) StopWatch(com.helger.commons.timing.StopWatch) MustBeLocked(com.helger.commons.annotation.MustBeLocked) Nonnull(javax.annotation.Nonnull) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

FileIOError (com.helger.commons.io.file.FileIOError)12 File (java.io.File)10 Nonnull (javax.annotation.Nonnull)3 MustBeLocked (com.helger.commons.annotation.MustBeLocked)2 DAOException (com.helger.dao.DAOException)2 Closeable (java.io.Closeable)2 IOException (java.io.IOException)2 AS2Exception (com.helger.as2lib.exception.AS2Exception)1 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)1 IMessage (com.helger.as2lib.message.IMessage)1 CompositeParameters (com.helger.as2lib.params.CompositeParameters)1 DateParameters (com.helger.as2lib.params.DateParameters)1 MessageParameters (com.helger.as2lib.params.MessageParameters)1 PDTToString (com.helger.commons.datetime.PDTToString)1 StopWatch (com.helger.commons.timing.StopWatch)1 AbstractSVRLMessage (com.helger.schematron.svrl.AbstractSVRLMessage)1 SVRLMarshaller (com.helger.schematron.svrl.SVRLMarshaller)1 SchematronOutputType (com.helger.schematron.svrl.jaxb.SchematronOutputType)1 IMicroDocument (com.helger.xml.microdom.IMicroDocument)1 IXMLWriterSettings (com.helger.xml.serialize.write.IXMLWriterSettings)1