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);
}
}
}
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);
}
}
}
}
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());
}
}
}
}
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;
}
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;
}
}
Aggregations