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

The following examples show how to use com.helger.commons.io.file.FilenameHelper. 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: FileSystemResourceTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testUNC ()
{
  if (EOperatingSystem.getCurrentOS ().isWindowsBased ())
  {
    // Use local UNC prefix for testing
    FileSystemResource aRes = new FileSystemResource (new File (FilenameHelper.WINDOWS_UNC_PREFIX_LOCAL1 +
                                                                new File ("pom.xml").getAbsolutePath ()));
    assertTrue (aRes.exists ());
    assertTrue (aRes.getResourceID ().endsWith ("pom.xml"));
    assertTrue (aRes.getPath ().endsWith ("pom.xml"));

    aRes = new FileSystemResource (new File (FilenameHelper.WINDOWS_UNC_PREFIX_LOCAL2 +
                                             new File ("pom.xml").getAbsolutePath ()));
    assertTrue (aRes.exists ());
    assertTrue (aRes.getResourceID ().endsWith ("pom.xml"));
    assertTrue (aRes.getPath ().endsWith ("pom.xml"));
  }
}
 
Example #2
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 #3
Source File: DefaultResourceResolver.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static ClassPathResource _resolveClassPathResource (final String sSystemId,
                                                            final String sBaseURI,
                                                            final ClassLoader aClassLoader)
{
  // Skip leading "cp:" or "classpath:"
  final String sBaseURIWithoutPrefix = ClassPathResource.getWithoutClassPathPrefix (sBaseURI);

  // Get the parent path of the base path
  final File aBaseFile = new File (sBaseURIWithoutPrefix).getParentFile ();

  // Concatenate the path with the URI to search
  final String sNewPath = FilenameHelper.getCleanPath (aBaseFile == null ? sSystemId
                                                                         : aBaseFile.getPath () + '/' + sSystemId);

  final ClassPathResource ret = new ClassPathResource (sNewPath, aClassLoader);
  if (isDebugResolve ())
    if (LOGGER.isInfoEnabled ())
      LOGGER.info ("  [ClassPath] resolved base + system to " + ret);
  return ret;
}
 
Example #4
Source File: FileSystemResource.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public FileSystemResource (@Nonnull final File aFile)
{
  ValueEnforcer.notNull (aFile, "File");

  // Make absolute and try to remove all ".." etc paths
  // Note: using getCleanPath with String is much faster compared to
  // getCleanPath with a File parameter, as on Unix the
  // UnixFileSystem.getCanonicalPath method is a bottleneck
  final String sPath = FilenameHelper.getCleanPath (aFile.getAbsolutePath ());
  m_aFile = new File (sPath);

  // Note: cache absolute path for performance reasons
  // Note: this path always uses the platform dependent path separator
  m_sPath = m_aFile.getAbsolutePath ();
}
 
Example #5
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 #6
Source File: DefaultResourceResolver.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static URLResource _resolveURLResource (final String sSystemId,
                                                final URL aBaseURL) throws MalformedURLException
{
  // Take only the path
  String sBasePath = aBaseURL.getPath ();

  /*
   * Heuristics to check if the base URI is a file is to check for the
   * existence of a dot ('.') in the last part of the filename. This is not
   * ideal but should do the trick In case you have a filename that has no
   * extension (e.g. 'test') simply append a dot (e.g. 'test.') to have the
   * same effect.
   */
  final String sBaseFilename = FilenameHelper.getWithoutPath (sBasePath);
  if (sBaseFilename != null && sBaseFilename.indexOf ('.') >= 0)
  {
    // Take only the path
    sBasePath = FilenameHelper.getPath (sBasePath);
  }

  // Concatenate the path with the URI to search
  final String sNewPath = FilenameHelper.getCleanConcatenatedUrlPath (sBasePath, sSystemId);

  // Rebuild the URL with the new path
  final URL aNewURL = new URL (aBaseURL.getProtocol (),
                               aBaseURL.getHost (),
                               aBaseURL.getPort (),
                               URLHelper.getURLString (sNewPath, aBaseURL.getQuery (), aBaseURL.getRef ()));
  final URLResource ret = new URLResource (aNewURL);
  if (isDebugResolve ())
    if (LOGGER.isInfoEnabled ())
      LOGGER.info ("  [URL] resolved base + system to " + ret);
  return ret;
}
 
Example #7
Source File: PathRelativeIO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public IReadableResource getResource (@Nonnull @Nonempty final String sRelativePath)
{
  ValueEnforcer.notEmpty (sRelativePath, "RelativePath");

  // Remove any leading slash to avoid that the resource resolver considers
  // this an absolute URL on Linux!
  final String sEffectiveRelativePath = FilenameHelper.startsWithPathSeparatorChar (sRelativePath) ? sRelativePath.substring (1)
                                                                                                   : sRelativePath;

  return DefaultResourceResolver.getResolvedResource (sEffectiveRelativePath, m_sBaseURL);
}
 
Example #8
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
@ReturnsMutableCopy
public ICommonsList <MimeTypeInfo> getAllInfosOfFilename (@Nullable final File aFile)
{
  if (aFile == null)
    return null;

  final String sExtension = FilenameHelper.getExtension (aFile);
  return getAllInfosOfExtension (sExtension);
}
 
Example #9
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 #10
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Get all mime types that are associated to the extension of the specified
 * filename.
 *
 * @param sFilename
 *        The filename to search. May neither be <code>null</code> nor empty.
 * @return Never <code>null</code> but maybe empty set if no mime type is
 *         associated with the extension of the passed filename.
 */
@Nonnull
@ReturnsMutableCopy
public ICommonsSet <String> getAllMimeTypeStringsForFilename (@Nonnull @Nonempty final String sFilename)
{
  ValueEnforcer.notEmpty (sFilename, "Filename");

  final String sExtension = FilenameHelper.getExtension (sFilename);
  return getAllMimeTypeStringsForExtension (sExtension);
}
 
Example #11
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Get all mime types that are associated to the extension of the specified
 * filename.
 *
 * @param sFilename
 *        The filename to search. May neither be <code>null</code> nor empty.
 * @return Never <code>null</code> but maybe empty set if no mime type is
 *         associated with the extension of the passed filename.
 */
@Nonnull
@ReturnsMutableCopy
public ICommonsSet <IMimeType> getAllMimeTypesForFilename (@Nonnull @Nonempty final String sFilename)
{
  ValueEnforcer.notEmpty (sFilename, "Filename");

  final String sExtension = FilenameHelper.getExtension (sFilename);
  return getAllMimeTypesForExtension (sExtension);
}
 
Example #12
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
@ReturnsMutableCopy
public ICommonsList <MimeTypeInfo> getAllInfosOfFilename (@Nullable final String sFilename)
{
  if (StringHelper.hasNoText (sFilename))
    return null;

  final String sExtension = FilenameHelper.getExtension (sFilename);
  return getAllInfosOfExtension (sExtension);
}
 
Example #13
Source File: DefaultResourceResolver.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static URLResource _resolveJarFileResource (@Nonnull final String sSystemId,
                                                    @Nonnull final String sBaseURI) throws MalformedURLException
{
  // Base URI is inside a jar file? Skip the JAR file
  // See issue #8 - use lastIndexOf here
  final int i = sBaseURI.lastIndexOf ("!/");
  String sPrefix;
  String sBasePath;
  if (i < 0)
  {
    sPrefix = "";
    sBasePath = sBaseURI;
  }
  else
  {
    sPrefix = sBaseURI.substring (0, i + 2);
    sBasePath = sBaseURI.substring (i + 2);
  }

  // Skip any potentially leading path separator
  if (FilenameHelper.startsWithPathSeparatorChar (sBasePath))
    sBasePath = sBasePath.substring (1);

  // Get the parent path of the base path
  final File aBaseFile = new File (sBasePath).getParentFile ();

  // Concatenate the path with the URI to search
  final String sNewPath = FilenameHelper.getCleanPath (aBaseFile == null ? sSystemId
                                                                         : aBaseFile.getPath () + '/' + sSystemId);

  String sAggregatedPath;
  if (sPrefix.endsWith ("/") && sNewPath.startsWith ("/"))
  {
    // Avoid "//"
    sAggregatedPath = sPrefix + sNewPath.substring (1);
  }
  else
    sAggregatedPath = sPrefix + sNewPath;

  final URLResource ret = new URLResource (sAggregatedPath);
  if (isDebugResolve ())
    if (LOGGER.isInfoEnabled ())
      LOGGER.info ("  [JarFile] resolved base + system to " + ret);
  return ret;
}
 
Example #14
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Get the primary (=first) mime type associated with the specified filename.
 *
 * @param sFilename
 *        The filename to retrieve the primary mime type from. May neither be
 *        <code>null</code> nor empty.
 * @return <code>null</code> if no mime type is associated with the extension
 *         of the passed filename
 */
@Nullable
public String getPrimaryMimeTypeStringForFilename (@Nonnull @Nonempty final String sFilename)
{
  ValueEnforcer.notEmpty (sFilename, "Filename");

  final String sExtension = FilenameHelper.getExtension (sFilename);
  return getPrimaryMimeTypeStringForExtension (sExtension);
}
 
Example #15
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Get the primary (=first) mime type associated with the specified filename.
 *
 * @param sFilename
 *        The filename to retrieve the primary mime type from. May neither be
 *        <code>null</code> nor empty.
 * @return <code>null</code> if no mime type is associated with the extension
 *         of the passed filename
 */
@Nullable
public IMimeType getPrimaryMimeTypeForFilename (@Nonnull @Nonempty final String sFilename)
{
  ValueEnforcer.notEmpty (sFilename, "Filename");

  final String sExtension = FilenameHelper.getExtension (sFilename);
  return getPrimaryMimeTypeForExtension (sExtension);
}
 
Example #16
Source File: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 3 votes vote down vote up
/**
 * Check if any mime type is registered for the extension of the specified
 * filename.
 *
 * @param sFilename
 *        The filename to search. May neither be <code>null</code> nor empty.
 * @return <code>true</code> if at least one mime type is associated with the
 *         extension of the passed filename, <code>false</code> otherwise.
 */
public boolean containsMimeTypeForFilename (@Nonnull @Nonempty final String sFilename)
{
  ValueEnforcer.notEmpty (sFilename, "Filename");

  final String sExtension = FilenameHelper.getExtension (sFilename);
  return containsMimeTypeForExtension (sExtension);
}
 
Example #17
Source File: IFileRelativeIO.java    From ph-commons with Apache License 2.0 2 votes vote down vote up
/**
 * Get the relative file name for the passed absolute file.
 *
 * @param aAbsoluteFile
 *        The non-<code>null</code> absolute file to make relative.
 * @return <code>null</code> if the passed file is not a child of this base
 *         directory.
 */
@Nullable
default String getRelativeFilename (@Nonnull final File aAbsoluteFile)
{
  return FilenameHelper.getRelativeToParentDirectory (aAbsoluteFile, getBasePathFile ());
}