com.helger.commons.io.file.FileHelper Java Examples

The following examples show how to use com.helger.commons.io.file.FileHelper. 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: JAXBBuilderFuncTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testStreamWriter () throws XMLStreamException
{
  final XMLOutputFactory aOF = XMLOutputFactory.newInstance ();
  final XMLStreamWriter aSW = aOF.createXMLStreamWriter (FileHelper.getBufferedWriter (new File ("target/stream-writer-test.xml"),
                                                                                       StandardCharsets.UTF_8));

  final com.helger.jaxb.mock.external.MockJAXBArchive aArc = new com.helger.jaxb.mock.external.MockJAXBArchive ();
  aArc.setVersion ("1.23");
  for (int i = 0; i < 5; ++i)
  {
    final com.helger.jaxb.mock.external.MockJAXBCollection aCollection = new com.helger.jaxb.mock.external.MockJAXBCollection ();
    aCollection.setDescription ("Internal bla foo");
    aCollection.setID (i);
    aArc.getCollection ().add (aCollection);
  }

  final MockExternalArchiveWriterBuilder aWriter = new MockExternalArchiveWriterBuilder ();
  aWriter.write (aArc, aSW);
}
 
Example #2
Source File: CSSCompressMojo.java    From ph-css with Apache License 2.0 6 votes vote down vote up
private void _scanDirectory (@Nonnull final File aDir)
{
  for (final File aChild : FileHelper.getDirectoryContent (aDir))
  {
    if (aChild.isDirectory ())
    {
      // Shall we recurse into sub-directories?
      if (recursive)
        _scanDirectory (aChild);
    }
    else
      if (aChild.isFile () &&
          CSSFilenameHelper.isCSSFilename (aChild.getName ()) &&
          !_isAlreadyCompressed (aChild.getName ()))
      {
        // We're ready to rumble!
        _compressCSSFile (aChild);
      }
  }
}
 
Example #3
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write a Micro Node to a file.
 *
 * @param aNode
 *        The node to be serialized. May be any kind of node (incl.
 *        documents). May not be <code>null</code>.
 * @param aFile
 *        The file to write to. May not be <code>null</code>.
 * @param aSettings
 *        The settings to be used for the creation. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess writeToFile (@Nonnull final IMicroNode aNode,
                                    @Nonnull final File aFile,
                                    @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aFile, "File");

  final OutputStream aOS = FileHelper.getOutputStream (aFile);
  if (aOS == null)
    return ESuccess.FAILURE;

  // No need to wrap the OS in a BufferedOutputStream as inside, it is later
  // on wrapped in a BufferedWriter
  return writeToStream (aNode, aOS, aSettings);
}
 
Example #4
Source File: InputSourceFactory.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nullable
public static InputSource create (@Nonnull final IReadableResource aResource)
{
  if (aResource instanceof FileSystemResource)
  {
    final File aFile = aResource.getAsFile ();
    if (aFile != null)
    {
      // Potentially use memory mapped files
      final InputSource ret = create (FileHelper.getInputStream (aFile));
      if (ret != null)
      {
        // Ensure system ID is present - may be helpful for resource
        // resolution
        final URL aURL = aResource.getAsURL ();
        if (aURL != null)
          ret.setSystemId (aURL.toExternalForm ());
      }
      return ret;
    }
  }
  return new ReadableResourceSAXInputSource (aResource);
}
 
Example #5
Source File: Issue16Test.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public static boolean validateXMLViaPureSchematron2 (@Nonnull final File aSchematronFile,
                                                     @Nonnull final File aXMLFile) throws Exception
{
  // Read the schematron from file
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  if (!aSchema.isValid (new DoNothingPSErrorHandler ()))
    throw new IllegalArgumentException ("Invalid Schematron!");
  // Resolve the query binding to use
  final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());
  // Pre-process schema
  final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
  aPreprocessor.setKeepTitles (true);
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  // Bind the pre-processed schema
  final IPSBoundSchema aBoundSchema = aQueryBinding.bind (aPreprocessedSchema);
  // Read the XML file
  final Document aXMLNode = DOMReader.readXMLDOM (aXMLFile);
  if (aXMLNode == null)
    return false;
  // Perform the validation
  return aBoundSchema.validatePartially (aXMLNode, FileHelper.getAsURLString (aXMLFile)).isValid ();
}
 
Example #6
Source File: DocumentationExamples.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public static boolean validateXMLViaPureSchematron2 (@Nonnull final File aSchematronFile,
                                                     @Nonnull final File aXMLFile) throws Exception
{
  // Read the schematron from file
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  if (!aSchema.isValid (new DoNothingPSErrorHandler ()))
    throw new IllegalArgumentException ("Invalid Schematron!");
  // Resolve the query binding to use
  final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());
  // Pre-process schema
  final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
  aPreprocessor.setKeepTitles (true);
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  // Bind the pre-processed schema
  final IPSBoundSchema aBoundSchema = aQueryBinding.bind (aPreprocessedSchema);
  // Read the XML file
  final Document aXMLNode = DOMReader.readXMLDOM (aXMLFile);
  if (aXMLNode == null)
    return false;
  // Perform the validation
  return aBoundSchema.validatePartially (aXMLNode, FileHelper.getAsURLString (aXMLFile)).isValid ();
}
 
Example #7
Source File: PathRelativeIOTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testURLBased ()
{
  final String sBase = FileHelper.getAsURLString (new File (""));
  final IPathRelativeIO aIO = new PathRelativeIO (sBase);

  assertEquals (sBase, aIO.getBasePath ());
  assertFalse (aIO.getResource ("non-existing").exists ());
  assertTrue (aIO.getResource ("pom.xml").exists ());
  // fails on Linux
  if (EOperatingSystem.WINDOWS.isCurrentOS ())
    assertTrue (aIO.getResource ("/pom.xml").exists ());
  assertTrue (aIO.getResource ("src/etc/javadoc.css").exists ());
  // Passing an absolute path does no longer work on Linux
  if (false)
    assertTrue (aIO.getResource (new File ("pom.xml").getAbsolutePath ()).exists ());
}
 
Example #8
Source File: JavaFileFuncTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressFBWarnings (value = "DMI_HARDCODED_ABSOLUTE_FILENAME")
public void testGetPath ()
{
  _log (new File ("pom.xml"));
  if (EOperatingSystem.getCurrentOS ().isWindowsBased ())
    _log (new File (FilenameHelper.WINDOWS_UNC_PREFIX_LOCAL1 + new File ("pom.xml").getAbsolutePath ()));
  _log (new File ("pom.xml."));
  _log (new File ("c:\\pom.xml"));
  _log (new File ("c:\\", "pom.xml"));
  _log (new File ("c:\\", "pom"));
  _log (new File ("c:\\"));
  File f = new File ("pom.xml\u0000.txt");
  _log (f);

  f = FileHelper.getSecureFile (f);
  _log (f);
}
 
Example #9
Source File: Base64Test.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeToFile () throws IOException
{
  final File f2 = new File ("base64.decoded");
  try
  {
    assertFalse (FileHelper.existsFile (f2));
    final String sEncoded = Base64.safeEncode ("Hallo Wält", StandardCharsets.UTF_8);
    Base64.decodeToFile (sEncoded, f2.getAbsoluteFile ());
    assertTrue (FileHelper.existsFile (f2));
    final String sDecoded = SimpleFileIO.getFileAsString (f2, StandardCharsets.UTF_8);
    assertEquals ("Hallo Wält", sDecoded);
  }
  finally
  {
    FileOperations.deleteFile (f2);
  }
}
 
Example #10
Source File: Base64Test.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeFileToFile () throws IOException
{
  final File f1 = new File ("base64.encoded");
  final File f2 = new File ("base64.decoded");
  try
  {
    assertFalse (FileHelper.existsFile (f2));
    SimpleFileIO.writeFile (f1,
                            Base64.safeEncode ("Hallo Wält", StandardCharsets.UTF_8)
                                  .getBytes (StandardCharsets.ISO_8859_1));
    Base64.decodeFileToFile (f1.getAbsolutePath (), f2.getAbsoluteFile ());
    assertTrue (FileHelper.existsFile (f2));
    final String sDecoded = SimpleFileIO.getFileAsString (f2, StandardCharsets.UTF_8);
    assertEquals ("Hallo Wält", sDecoded);
  }
  finally
  {
    FileOperations.deleteFile (f1);
    FileOperations.deleteFile (f2);
  }
}
 
Example #11
Source File: Base64Test.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeToFile () throws IOException
{
  final File f2 = new File ("base64.encoded");
  try
  {
    assertFalse (FileHelper.existsFile (f2));
    final String sDecoded = "Hallo Wält";
    Base64.encodeToFile (sDecoded.getBytes (StandardCharsets.UTF_8), f2.getAbsoluteFile ());
    assertTrue (FileHelper.existsFile (f2));
    final String sEncoded = SimpleFileIO.getFileAsString (f2, StandardCharsets.UTF_8);
    assertEquals ("Hallo Wält", Base64.safeDecodeAsString (sEncoded, StandardCharsets.UTF_8));
  }
  finally
  {
    FileOperations.deleteFile (f2);
  }
}
 
Example #12
Source File: Base64Test.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeFileToFile () throws IOException
{
  final File f1 = new File ("base64.decoded");
  final File f2 = new File ("base64.encoded");
  try
  {
    assertFalse (FileHelper.existsFile (f2));
    SimpleFileIO.writeFile (f1, "Hallo Wält", StandardCharsets.UTF_8);
    Base64.encodeFileToFile (f1.getAbsolutePath (), f2.getAbsoluteFile ());
    assertTrue (FileHelper.existsFile (f2));
    final String sEncoded = SimpleFileIO.getFileAsString (f2, StandardCharsets.UTF_8);
    assertEquals ("Hallo Wält", Base64.safeDecodeAsString (sEncoded, StandardCharsets.UTF_8));
  }
  finally
  {
    FileOperations.deleteFile (f1);
    FileOperations.deleteFile (f2);
  }
}
 
Example #13
Source File: CSSTokenizer.java    From ph-css with Apache License 2.0 5 votes vote down vote up
public static void main (final String [] args) throws IOException, CSSTokenizeException
{
  final File f = new File ("src/test/resources/testfiles/css30/good/pure-min.css");
  try (InputStream aIS = StreamHelper.getBuffered (FileHelper.getInputStream (f)))
  {
    new CSSTokenizer ().setDebugMode (false).tokenize (aIS, t -> {
      System.out.println (t);
    });
  }
}
 
Example #14
Source File: IJAXBWriter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Write the passed object to a {@link File}.
 *
 * @param aObject
 *        The object to be written. May not be <code>null</code>.
 * @param aResultFile
 *        The result file to be written to. May not be <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
default ESuccess write (@Nonnull final JAXBTYPE aObject, @Nonnull final File aResultFile)
{
  if (USE_JAXB_CHARSET_FIX)
  {
    final OutputStream aOS = FileHelper.getBufferedOutputStream (aResultFile);
    if (aOS == null)
      return ESuccess.FAILURE;
    return write (aObject, aOS);
  }
  return write (aObject, TransformResultFactory.create (aResultFile));
}
 
Example #15
Source File: AbstractSchematronXSLTBasedResource.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String _findBaseURL (@Nonnull final IReadableResource aRes)
{
  if (aRes instanceof FileSystemResource)
  {
    // Use parent file as resolution base
    return FileHelper.getAsURLString (((FileSystemResource) aRes).getAsFile ().getParentFile ());
  }

  // Generic URL
  final URL aBaseURL = aRes.getAsURL ();
  return aBaseURL != null ? aBaseURL.toExternalForm () : null;
}
 
Example #16
Source File: PathRelativeIO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public PathRelativeIO (@Nonnull @Nonempty final String sBasePath)
{
  ValueEnforcer.notEmpty (sBasePath, "BasePath");
  m_sBasePath = sBasePath;

  // Use special base URL if base path is an existing file!
  String sBaseURL = null;
  final File aFile = new File (sBasePath);
  if (aFile.exists ())
    sBaseURL = FileHelper.getAsURLString (aFile);
  m_sBaseURL = sBaseURL != null ? sBaseURL : sBasePath;
}
 
Example #17
Source File: FileLongIDFactory.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public FileLongIDFactory (@Nonnull final File aFile, @Nonnegative final int nReserveCount)
{
  super (nReserveCount);
  ValueEnforcer.notNull (aFile, "File");

  m_aFile = aFile;
  m_aPrevFile = new File (aFile.getParentFile (), aFile.getName () + ".prev");
  m_aNewFile = new File (aFile.getParentFile (), aFile.getName () + ".new");

  if (!FileHelper.canReadAndWriteFile (m_aFile))
    throw new IllegalArgumentException ("Cannot read and/or write the file " + m_aFile + "!");
  if (!FileHelper.canReadAndWriteFile (m_aPrevFile))
    throw new IllegalArgumentException ("Cannot read and/or write the file " + m_aPrevFile + "!");
  if (!FileHelper.canReadAndWriteFile (m_aNewFile))
    throw new IllegalArgumentException ("Cannot read and/or write the file " + m_aNewFile + "!");

  if (m_aNewFile.exists ())
    throw new IllegalStateException ("The temporary ID file '" +
                                     m_aNewFile.getAbsolutePath () +
                                     "' already exists! Please use the file with the highest number. Please resolve this conflict manually.");
  if (m_aPrevFile.exists ())
    throw new IllegalStateException ("The temporary ID file '" +
                                     m_aPrevFile.getAbsolutePath () +
                                     "' already exists! If the ID file '" +
                                     m_aFile.getAbsolutePath () +
                                     "' exists and contains a higher number, you may consider deleting this file. Please resolve this conflict manually.");
}
 
Example #18
Source File: DOMReaderTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testExternalEntityExpansion ()
{
  // Include a dummy file
  final File aFile = new File ("src/test/resources/test1.txt");
  assertTrue (aFile.exists ());
  final String sFileContent = StreamHelper.getAllBytesAsString (new FileSystemResource (aFile),
                                                                StandardCharsets.ISO_8859_1);

  // The XML with XXE problem
  final String sXML = "<?xml version='1.0' encoding='utf-8'?>" +
                      "<!DOCTYPE root [" +
                      " <!ELEMENT root ANY >" +
                      " <!ENTITY xxe SYSTEM \"" +
                      FileHelper.getAsURLString (aFile) +
                      "\" >]>" +
                      "<root>&xxe;</root>";
  final DOMReaderSettings aDRS = new DOMReaderSettings ().setEntityResolver ( (publicId,
                                                                               systemId) -> InputSourceFactory.create (new URLResource (systemId)));

  // Read successful - entity expansion!
  final Document aDoc = DOMReader.readXMLDOM (sXML, aDRS);
  assertNotNull (aDoc);
  assertEquals (sFileContent, aDoc.getDocumentElement ().getTextContent ());

  // Should fail because inline DTD is present
  final CollectingSAXErrorHandler aCEH = new CollectingSAXErrorHandler ();
  assertNull (DOMReader.readXMLDOM (sXML,
                                    aDRS.getClone ()
                                        .setFeatureValues (EXMLParserFeature.AVOID_XXE_SETTINGS)
                                        .setErrorHandler (aCEH)));
  // Expected
  assertEquals (1, aCEH.getErrorList ().size ());
  assertTrue (aCEH.getErrorList ()
                  .getFirst ()
                  .getErrorText (Locale.ROOT)
                  .contains ("http://apache.org/xml/features/disallow-doctype-decl"));
}
 
Example #19
Source File: FileSystemFolderTree.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
private static void _iterate (@Nonnull final DefaultFolderTreeItem <String, File, ICommonsList <File>> aTreeItem,
                              @Nonnull final File aDir,
                              @Nullable final Predicate <? super File> aDirFilter,
                              @Nullable final Predicate <? super File> aFileFilter)
{
  if (aDir != null)
    for (final File aChild : FileHelper.getDirectoryContent (aDir))
    {
      if (aChild.isFile ())
      {
        // file
        // Check against the optional filter
        if (aFileFilter == null || aFileFilter.test (aChild))
          aTreeItem.getData ().add (aChild);
      }
      else
        if (aChild.isDirectory () && !FilenameHelper.isSystemInternalDirectory (aChild))
        {
          // directory
          // Check against the optional filter
          if (aDirFilter == null || aDirFilter.test (aChild))
          {
            // create item and recursively descend
            final DefaultFolderTreeItem <String, File, ICommonsList <File>> aChildItem = aTreeItem.createChildItem (aChild.getName (),
                                                                                                                    new CommonsArrayList <> ());
            _iterate (aChildItem, aChild, aDirFilter, aFileFilter);
          }
        }
    }
}
 
Example #20
Source File: FileIntIDFactory.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public FileIntIDFactory (@Nonnull final File aFile, @Nonnegative final int nReserveCount)
{
  super (nReserveCount);
  ValueEnforcer.notNull (aFile, "File");

  m_aFile = aFile;
  m_aPrevFile = new File (aFile.getParentFile (), aFile.getName () + ".prev");
  m_aNewFile = new File (aFile.getParentFile (), aFile.getName () + ".new");

  if (!FileHelper.canReadAndWriteFile (m_aFile))
    throw new IllegalArgumentException ("Cannot read and/or write the file " + m_aFile + "!");
  if (!FileHelper.canReadAndWriteFile (m_aPrevFile))
    throw new IllegalArgumentException ("Cannot read and/or write the file " + m_aPrevFile + "!");
  if (!FileHelper.canReadAndWriteFile (m_aNewFile))
    throw new IllegalArgumentException ("Cannot read and/or write the file " + m_aNewFile + "!");

  if (m_aNewFile.exists ())
    throw new IllegalStateException ("The temporary ID file '" +
                                     m_aNewFile.getAbsolutePath () +
                                     "' already exists! Please use the file with the highest number. Please resolve this conflict manually.");
  if (m_aPrevFile.exists ())
    throw new IllegalStateException ("The temporary ID file '" +
                                     m_aPrevFile.getAbsolutePath () +
                                     "' already exists! If the ID file '" +
                                     m_aFile.getAbsolutePath () +
                                     "' exists and contains a higher number, you may consider deleting this file. Please resolve this conflict manually.");
}
 
Example #21
Source File: Base64.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method for reading a base64-encoded file and decoding it.
 * <p>
 * As of v 2.3, if there is a error, the method will throw an IOException.
 * <b>This is new to v2.3!</b> In earlier versions, it just returned false,
 * but in retrospect that's a pretty poor way to handle it.
 * </p>
 *
 * @param filename
 *        Filename for reading encoded data
 * @return decoded byte array
 * @throws IOException
 *         if there is an error
 * @since 2.1
 */
@Nonnull
@ReturnsMutableCopy
public static byte [] decodeFromFile (@Nonnull final String filename) throws IOException
{
  // Setup some useful variables
  final File file = new File (filename);

  // Check for size of file
  if (file.length () > Integer.MAX_VALUE)
    throw new IOException ("File is too big for this convenience method (" + file.length () + " bytes).");

  final byte [] buffer = new byte [(int) file.length ()];

  // Open a stream
  try (final Base64InputStream bis = new Base64InputStream (FileHelper.getBufferedInputStream (file), DECODE))
  {
    int nOfs = 0;
    int numBytes;

    // Read until done
    while ((numBytes = bis.read (buffer, nOfs, 4096)) >= 0)
    {
      nOfs += numBytes;
    }

    // Save in a variable to return
    final byte [] decodedData = new byte [nOfs];
    System.arraycopy (buffer, 0, decodedData, 0, nOfs);
    return decodedData;
  }
}
 
Example #22
Source File: Base64.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method for reading a binary file and base64-encoding it.
 * <p>
 * As of v 2.3, if there is a error, the method will throw an IOException.
 * <b>This is new to v2.3!</b> In earlier versions, it just returned false,
 * but in retrospect that's a pretty poor way to handle it.
 * </p>
 *
 * @param filename
 *        Filename for reading binary data
 * @return base64-encoded string
 * @throws IOException
 *         if there is an error
 * @since 2.1
 */
@Nonnull
public static String encodeFromFile (@Nonnull final String filename) throws IOException
{
  // Setup some useful variables
  final File file = new File (filename);

  // Open a stream
  try (final Base64InputStream bis = new Base64InputStream (FileHelper.getBufferedInputStream (file), ENCODE))
  {
    // Need max() for math on small files (v2.2.1);
    // Need +1 for a few corner cases (v2.3.5)
    final byte [] aBuffer = new byte [Math.max ((int) (file.length () * 1.4 + 1), 40)];

    int nLength = 0;
    int nBytes;

    // Read until done
    while ((nBytes = bis.read (aBuffer, nLength, 4096)) >= 0)
    {
      nLength += nBytes;
    }

    // Save in a variable to return
    return new String (aBuffer, 0, nLength, PREFERRED_ENCODING);
  }
}
 
Example #23
Source File: FileSystemResource.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nullable
public FileInputStream getInputStream ()
{
  return FileHelper.getInputStream (m_aFile);
}
 
Example #24
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 #25
Source File: JavaFileAccessFuncTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Test
public void testAccessRights () throws IOException, InterruptedException
{
  if (EOperatingSystem.getCurrentOS ().isUnixBased ())
  {
    final FileOperationManager aFOM = new FileOperationManager ();
    aFOM.callbacks ().add (new LoggingFileOperationCallback ());
    final File fTempDir = new File (SystemProperties.getTmpDir (), "helger");
    FileOperations.createDirIfNotExisting (fTempDir);
    assertTrue (fTempDir.getAbsolutePath (), fTempDir.exists ());

    // Create the files for testing
    {
      final boolean [] aTrueFalse = new boolean [] { true, false };
      for (final boolean bReadOwner : aTrueFalse)
        for (final boolean bWriteOwner : aTrueFalse)
          for (final boolean bReadGroup : aTrueFalse)
            for (final boolean bWriteGroup : aTrueFalse)
              for (final boolean bReadOther : aTrueFalse)
                for (final boolean bWriteOther : aTrueFalse)
                  for (final boolean bExec : aTrueFalse)
                  {
                    final int nModeOwn = (bReadOwner ? 4 : 0) | (bWriteOwner ? 2 : 0) | (bExec ? 1 : 0);
                    final int nModeGroup = (bReadGroup ? 4 : 0) | (bWriteGroup ? 2 : 0) | (bExec ? 1 : 0);
                    final int nModeOther = (bReadOther ? 4 : 0) | (bWriteOther ? 2 : 0) | (bExec ? 1 : 0);
                    final String sMod = Integer.toString (nModeOwn) +
                                        Integer.toString (nModeGroup) +
                                        Integer.toString (nModeOther);
                    final String sPrefix = "ph-commons-";

                    final File fFile = new File (fTempDir, sPrefix + sMod + ".dat");
                    if (SimpleFileIO.writeFile (fFile, "content".getBytes (StandardCharsets.ISO_8859_1)).isSuccess ())
                      _exec ("chmod", sMod, fFile.getAbsolutePath ());

                    final File fDir = new File (fTempDir, sPrefix + sMod + ".dir");
                    if (aFOM.createDir (fDir).isSuccess ())
                      _exec ("chmod", sMod, fDir.getAbsolutePath ());
                  }
    }

    _exec ("chmod", "-v", "711", fTempDir.getAbsolutePath ());

    // Test there readability
    final ICommonsList <File> aFiles = FileHelper.getDirectoryContent (fTempDir);
    for (final File f : aFiles.getSorted (Comparator.naturalOrder ()))
    {
      final boolean bCanRead = f.canRead ();
      final boolean bCanWrite = f.canWrite ();
      final boolean bCanExec = f.canRead ();
      final String sRights = bCanRead + "/" + bCanWrite + "/" + bCanExec;
      final File f2 = new File (f.getParentFile (), f.getName () + "2");

      if (f.isFile ())
      {
        _println ("file:" + f.getName () + "    " + sRights);
        if (aFOM.renameFile (f, f2).isSuccess ())
          aFOM.deleteFile (f2);
        else
          aFOM.deleteFile (f);
      }
      else
        if (f.isDirectory ())
        {
          _println ("dir: " + f.getName () + "    " + sRights);
          if (aFOM.renameDir (f, f2).isSuccess ())
            aFOM.deleteDir (f2);
          else
            aFOM.deleteDir (f);
        }
        else
        {
          _println ("Neither file not directory: " + f.getName () + "    " + sRights);
        }
    }

    if (false)
      _exec ("chmod", "--preserve-root", "-v", "-R", "777", fTempDir.getAbsolutePath ());

    aFOM.deleteDirRecursive (fTempDir);
    if (fTempDir.exists ())
      _exec ("rm", "-rf", fTempDir.getAbsolutePath ());

    _println ("done");
  }
  else
    if (EOperatingSystem.getCurrentOS ().isWindowsBased ())
    {
      _exec ("cmd", "/c", "dir");
    }
}
 
Example #26
Source File: FileSystemByteStreamProvider.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nullable
public OutputStream getOutputStream (@Nonnull final String sName, @Nonnull final EAppend eAppend)
{
  return FileHelper.getOutputStream (new File (m_aBasePath, sName), eAppend);
}
 
Example #27
Source File: FileSystemByteStreamProvider.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nullable
public InputStream getInputStream (@Nonnull final String sName)
{
  return FileHelper.getInputStream (new File (m_aBasePath, sName));
}
 
Example #28
Source File: FileSystemResource.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nullable
public URL getAsURL ()
{
  return FileHelper.getAsURL (m_aFile);
}
 
Example #29
Source File: FileSystemResource.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public Writer getWriter (@Nonnull final Charset aCharset, @Nonnull final EAppend eAppend)
{
  return FileHelper.getWriter (m_aFile, eAppend, aCharset);
}
 
Example #30
Source File: FileSystemResource.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nullable
public FileOutputStream getOutputStream (@Nonnull final EAppend eAppend)
{
  return FileHelper.getOutputStream (m_aFile, eAppend);
}