# PathResolverImpl.java

    /*
    ** Module   : PathResolverImpl.java
    ** Abstract : Implements PathResolver to resolve a legacy system absolute file path into its host
    **            system file path.
    **
    ** Copyright (c) 2018-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description----------------------------------
    ** 001 SBI 20180521 Initial version.
    ** 002 ECF 20180613 Performance fix: use compiled regex pattern for path splitting. Removed
    **                  unused instance variable.
    ** 003 SBI 20180724 Changed to resolve legacy path names given by not canonical forms.
    ** 004 GBB 20240826 Moving FileSystem to osresource package.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */
    package com.goldencode.p2j.util;

    import com.goldencode.p2j.util.osresource.FileSystem;

    import java.io.*;
    import java.util.*;
    import java.util.regex.*;

    /**
     * Resolves the legacy file system path to the path on the host system.
     */
    public class PathResolverImpl
    implements PathResolver
    {
       /** Regexp pattern for matching any path separators */
       private static final Pattern ANY_PATH_SEPARATOR = Pattern.compile(FileSystem.ANY_PATH_SEPARATOR);

       /** Defines a parent reference in the path name */
       private static final String PARENT_REFERENCE = "..";

       /** Defines a current directory reference in the path name */
       private static final String CURRENT_DIR_REFERENCE = ".";

       /** The artificial root for the legacy file system */
       private PathTree root;

       /** A map from the given directory subset on the legacy system to the host system */
       private Map<PathTree, String> mountedPaths;

       /** The case insensitive mode on the legacy system */
       private boolean caseInsensitive;

       /**
        * Builds this path resolver for the given legacy file separator for the given
        * case insensitive mode.
        *
        * @param    fileSeparator
        *           The given legacy file separator
        * @param    caseInsensitive
        *           The given case insensitive mode
        */
       public PathResolverImpl(String fileSeparator, boolean caseInsensitive)
       {
          this.caseInsensitive = caseInsensitive;
          this.root = new PathTree();
          this.mountedPaths = new LinkedHashMap<>();
       }

       /**
        * Resolve the given legacy path to the path on the host system.
        *
        * @param    path
        *           The given legacy path to be resolved on the host system
        *
        * @return   The resolved path on the host system
        *
        * @throws   UnresolvedPathException
        *           If the given path can't be resolved
        */
       @Override
       public String resolvePath(String path)
       throws PathResolver.UnresolvedPathException
       {
          // permit paths with mixed '/' and '\\' separators
          String[] pathComponents = ANY_PATH_SEPARATOR.split(path);
          int size = pathComponents.length;
          PathTree parent = this.root;
          int resolvedIndex = -1;
          for(int i = 0; i < size; i++)
          {
             if (pathComponents[i].isEmpty() || CURRENT_DIR_REFERENCE.equals(pathComponents[i]))
             {
                // skip empty path components
                continue;
             }
             else if (PARENT_REFERENCE.equals(pathComponents[i]))
             {
                if (parent.parent != null)
                {
                   parent = parent.parent;
                }
                continue;
             }
             PathTree child = parent.findChild(pathComponents[i]);

             if (child != null)
             {
                parent = child;
                resolvedIndex = i;
             }
             else
             {
                break;
             }
          }

          if (resolvedIndex == -1)
          {
             throw UNRESOLVED_ERROR;
          }

          String commonResolvedPath;

          while ((commonResolvedPath = this.mountedPaths.get(parent)) == null &&
                 resolvedIndex >= 0                                           &&
                 parent.parent != null                                        &&
                 parent.parent != this.root
                )
          {
             parent = parent.parent;
             resolvedIndex--;
          }

          if (commonResolvedPath == null)
          {
             throw UNRESOLVED_ERROR;
          }

          StringBuilder resolvedPath = new StringBuilder(commonResolvedPath);

          for (int i = resolvedIndex + 1; i < size; i++)
          {
             if (pathComponents[i].isEmpty())
             {
                // skip empty path components
                continue;
             }
             resolvedPath.append(File.separatorChar).append(pathComponents[i]);
          }

          return resolvedPath.toString();
       }

       /**
        * Mounts the legacy system paths in the given map to their host system paths.
        *
        * @param    pathMap
        *           Map of legacy system paths to host system paths.
        */
       public void setPathMap(Map<String, String> pathMap)
       {
          for(Map.Entry<String, String> entry : pathMap.entrySet())
          {
             mount(entry.getKey(), entry.getValue());
          }
       }

       /**
        * Mounts the given legacy system path to its host system path.
        *
        * @param    path
        *           The given legacy system path
        * @param    mappedPath
        *           The host system path
        */
       public void mount(String path, String mappedPath)
       {
          mountedPaths.put(addPathTree(path), mappedPath);
       }

       /**
        * Builds a case insensitive key if the current legacy system mode is insensitive.
        *
        * @param    path
        *           The given legacy system path or path component
        *
        * @return   The low case for the given input if the current legacy system mode is
        *           insensitive.
        */
       private String doCaseInsensitive(String path)
       {
          if (this.caseInsensitive && path != null)
          {
             return path.toLowerCase(Locale.ROOT);
          }

          return path;
       }

       /**
        * Builds the tree node for the given legacy system path.
        *
        * @param    path
        *           The given legacy system path
        *
        * @return   The corresponding tree node for the given legacy system path
        */
       private PathTree addPathTree(String path)
       {
          // consider paths to be case insensitive
          // permit paths with mixed '/' and '\\' separators
          String[] pathComponents = ANY_PATH_SEPARATOR.split(doCaseInsensitive(path));
          int size = pathComponents.length;
          PathTree parent = this.root;
          PathTree leaf = null;
          for(int i = 0; i < size; i++)
          {
             if (pathComponents[i].isEmpty())
             {
                // skip empty path components
                continue;
             }
             PathTree child = parent.findChild(pathComponents[i]);

             if (child != null)
             {
                parent = child;
             }
             else
             {
                for(int j = size - 1; j >= i; j--)
                {
                   if (pathComponents[j].isEmpty())
                   {
                      // skip empty path components
                      continue;
                   }
                   PathTree node = new PathTree(pathComponents[j]);
                   if (child == null)
                   {
                      child = node;
                      leaf = child;
                   }
                   else
                   {
                      node.addChild(child);
                      child = node;
                   }
                }
                parent.addChild(child);
                break;
             }
          }

          if (leaf == null)
          {
             leaf = parent;
          }

          return leaf;
       }

       /**
        * Defines a tree node container.
        */
       class PathTree
       {
          /** The node id */
          private String id;

          /** The children nodes */
          private Map<String, PathTree> children;

          /** The parent node */
          private PathTree parent;

          /**
           * Defines the root node constructor.
           */
          public PathTree()
          {
             this(null);
          }

          /**
           * The directory node constructor
           *
           * @param    component
           *           The path component (folder name)
           */
          public PathTree(String component)
          {
             this.id = doCaseInsensitive(component);

             children = new LinkedHashMap<>();
          }

          /**
           * Find the child node by its path component.
           *
           * @param    component
           *           The target component
           *
           * @return   The child node
           */
          public PathTree findChild(String component)
          {
             return children.get(doCaseInsensitive(component));
          }

          /**
           * Add a path node.
           *
           * @param    pathTree
           *           The target node to add.
           */
          public void addChild(PathTree pathTree)
          {
             children.put(pathTree.id, pathTree);
             pathTree.parent = this;
          }
       }
    }