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

The following examples show how to use com.helger.commons.io.file.SimpleFileIO. 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: 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 #2
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 #3
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 #4
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 #5
Source File: WikiWriteCSS.java    From ph-css with Apache License 2.0 6 votes vote down vote up
/**
 * Write a CSS 3.0 declaration to a file using UTF-8 encoding.
 *
 * @param aCSS
 *        The CSS to be written to a file. May not be <code>null</code>.
 * @param aFile
 *        The file to be written. May not be <code>null</code>.
 * @return {@link ESuccess#SUCCESS} if everything went okay, and
 *         {@link ESuccess#FAILURE} if an error occurred
 */
public ESuccess writeCSS30 (final CascadingStyleSheet aCSS, final File aFile)
{
  // 1.param: version to write
  // 2.param: false== non-optimized output
  final CSSWriterSettings aSettings = new CSSWriterSettings (ECSSVersion.CSS30, false);
  try
  {
    final CSSWriter aWriter = new CSSWriter (aSettings);
    // Write the @charset rule: (optional)
    aWriter.setContentCharset (StandardCharsets.UTF_8.name ());
    // Write a nice file header
    aWriter.setHeaderText ("This file was generated by ph-css\nGrab a copy at https://github.com/phax/ph-css");
    // Convert the CSS to a String
    final String sCSSCode = aWriter.getCSSAsString (aCSS);
    // Finally write the String to a file
    return SimpleFileIO.writeFile (aFile, sCSSCode, StandardCharsets.UTF_8);
  }
  catch (final Exception ex)
  {
    LOGGER.error ("Failed to write the CSS to a file", ex);
    return ESuccess.FAILURE;
  }
}
 
Example #6
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 #7
Source File: FileIntIDFactory.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Override
@MustBeLocked (ELockType.WRITE)
protected final int readAndUpdateIDCounter (@Nonnegative final int nReserveCount)
{
  // Read the old content
  final String sContent = SimpleFileIO.getFileAsString (m_aFile, CHARSET_TO_USE);
  final int nRead = sContent != null ? StringParser.parseInt (sContent.trim (), 0) : 0;

  // Write the new content to the new file
  // This will fail, if the disk is full
  SimpleFileIO.writeFile (m_aNewFile, Integer.toString (nRead + nReserveCount), CHARSET_TO_USE);

  FileIOError aIOError;
  boolean bRenamedToPrev = false;
  if (m_aFile.exists ())
  {
    // Rename the existing file to the prev file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aFile, m_aPrevFile);
    bRenamedToPrev = true;
  }
  else
    aIOError = new FileIOError (EFileIOOperation.RENAME_FILE, EFileIOErrorCode.NO_ERROR);
  if (aIOError.isSuccess ())
  {
    // Rename the new file to the destination file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aNewFile, m_aFile);
    if (aIOError.isSuccess ())
    {
      // Finally delete the prev file (may not be existing for fresh
      // instances)
      aIOError = FileOperationManager.INSTANCE.deleteFileIfExisting (m_aPrevFile);
    }
    else
    {
      // 2nd rename failed
      // -> Revert original rename to stay as consistent as possible
      if (bRenamedToPrev)
        FileOperationManager.INSTANCE.renameFile (m_aPrevFile, m_aFile);
    }
  }
  if (aIOError.isFailure ())
    throw new IllegalStateException ("Error on rename(existing-old)/rename(new-existing)/delete(old): " + aIOError);

  return nRead;
}
 
Example #8
Source File: FileLongIDFactory.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Override
protected final long readAndUpdateIDCounter (@Nonnegative final int nReserveCount)
{
  final String sContent = SimpleFileIO.getFileAsString (m_aFile, CHARSET_TO_USE);
  final long nRead = sContent != null ? StringParser.parseLong (sContent.trim (), 0) : 0;

  // Write the new content to the new file
  // This will fail, if the disk is full
  SimpleFileIO.writeFile (m_aNewFile, Long.toString (nRead + nReserveCount), CHARSET_TO_USE);

  FileIOError aIOError;
  boolean bRenamedToPrev = false;
  if (m_aFile.exists ())
  {
    // Rename the existing file to the prev file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aFile, m_aPrevFile);
    bRenamedToPrev = true;
  }
  else
    aIOError = new FileIOError (EFileIOOperation.RENAME_FILE, EFileIOErrorCode.NO_ERROR);
  if (aIOError.isSuccess ())
  {
    // Rename the new file to the destination file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aNewFile, m_aFile);
    if (aIOError.isSuccess ())
    {
      // Finally delete the prev file (may not be existing for fresh
      // instances)
      aIOError = FileOperationManager.INSTANCE.deleteFileIfExisting (m_aPrevFile);
    }
    else
    {
      // 2nd rename failed
      // -> Revert original rename to stay as consistent as possible
      if (bRenamedToPrev)
        FileOperationManager.INSTANCE.renameFile (m_aPrevFile, m_aFile);
    }
  }
  if (aIOError.isFailure ())
    throw new IllegalStateException ("Error on rename(existing-old)/rename(new-existing)/delete(old): " + aIOError);

  return nRead;
}
 
Example #9
Source File: HashCodeGeneratorTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Test
@Ignore ("runs endlessly")
public void testFindIllegalValue () throws InterruptedException
{
  final AtomicBoolean b = new AtomicBoolean (false);
  final Runnable r = () -> {
    final byte [] aBytes = new byte [10000];
    ThreadLocalRandom.current ().nextBytes (aBytes);
    int i = 0;
    try
    {
      final HashCodeGenerator hc = new HashCodeGenerator (byte.class);
      for (; i < aBytes.length; ++i)
        hc.append (i);
    }
    catch (final RuntimeException ex)
    {
      final StringBuilder aSB = new StringBuilder ("new byte[]{");
      for (int j = 0; j < i; ++j)
        aSB.append ("(byte)").append (aBytes[i]).append (',');
      aSB.append ("};");
      SimpleFileIO.writeFile (new File ("HashCode0" + Instant.now ().toEpochMilli () + ".txt"),
                              aSB.toString (),
                              StandardCharsets.ISO_8859_1);
      b.set (true);
      LOGGER.error ("Found match!");
    }
  };

  final int nThreads = SystemHelper.getNumberOfProcessors () * 4;
  final Thread [] aThreads = new Thread [nThreads];

  int nTries = 0;
  while (!b.get ())
  {
    for (int i = 0; i < nThreads; ++i)
    {
      aThreads[i] = new Thread (r, "ph-Thread" + i);
      aThreads[i].start ();
    }
    for (int i = 0; i < nThreads; ++i)
      aThreads[i].join ();

    nTries += nThreads;
    if ((nTries % 1000) == 0)
      LOGGER.info (nTries + " tries");
  }
}
 
Example #10
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");
    }
}