FileChecker.java

/*
** Module   : FileChecker.java
** Abstract : Java implementation of for detecting the file type attribute 
*             list of OS-DIR
**
** Copyright (c) 2013-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- ----------------Description-----------------
** 001 CS  20130103 Created initial version for Implement OS-DIR support as
**                  an INPUT stream task.
** 002 CS  20130325 Added getFileCreationTime native function for task 1613
**                  finish FILE-INFO system handle support
**                  Changed logic of getFileType to handle logic for UNIX and 
**                  windows.
** 003 EVL 20140117 The native library call is performing now in dedicated place and only once.
**                  See the ClientCore class.
** 004 EVL 20140221 Add native call to check if the standard console output is redirected to the
**                  file by command line option.
** 005 EVL 20160224 Javadoc fixes to make compatible with Oracle Java 8 for Solaris 10.
** 006 TJD 20220504 Java 11 compatibility minor changes
** 007 GBB 20230328 Moving flag IS_OUTPUT_REDIRECTED from BatchedHelper to use it in
**                  isConsoleRedirected().
** 008 SP  20250522 Added fallback in GetFileType() in case the native checkFileType() returns -1.
*/

/*
** 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 java.io.*;
import java.util.concurrent.atomic.*;

/**
 * Utility class that uses JNI call to get the bitfield representing the 
 * status type of the given file path parameter and return the equivalent
 * Progress OS-DIR status.
 * <p>
 * The following codes are implemented:
 * <p>
 * <b>PRIMARY TYPES</b>
 * <ul>
 *    <li><b>F</b> - Regular file.
 *    <li><b>D</b> - Directory.
 *    <li><b>S</b> - Special Device
 *    <li><b>X</b> - Unknown type
 * </ul>
 * <p>
 * <b>SECONDARY (ADDITIVE) TYPES</b>
 * <ul>
 *    <li><b>H</b> - Hidden file.
 *    <li><b>L</b> - Symbolic link.
 *    <li><b>P</b> - Pipe File.
 * </ul>
 * <p>
 * One of the main types will always appear, and can also be accompanied by 
 * one or more of the secondary types.
 * <p>
 * In some cases the additive status can only be added to a specific main type
 * Ex: the Progress behavior for hidden attribute -&gt; only hidden file are 
 * marked as hidden, hidden directories are only marked as directory.
 * <p>
 * Because the file system may be different from an OS to another (some
 * filetypes are Unix specific) results may be yielded differently, 
 * however this is handled by the native code
 *
 */
public class FileChecker
{
   /**
    * A flag used to show if System.out has been redirected programmatically.
    */
   public static final AtomicBoolean IS_OUTPUT_REDIRECTED = new AtomicBoolean(false);
   
   /** Status code for error */
   private static final int ERROR_TYPE =-1;

   /** Status bitfield code for unknown */
   private static final int UNKNOWN_TYPE = 0;

   /** Status bitfield code for directory */
   private static final int DIRECTORY_TYPE = 1<<0;    // 000001

   /** Status bitfield code for file */
   private static final int FILE_TYPE = 1<<1;         // 000010

   /** Status bitfield code for symbolic link */
   private static final int SYMBOLIC_LINK_TYPE = 1<<2; //000100

   /** Status bitfield code for devices */
   private static final int DEVICE_TYPE = 1<<3;       // 001000

   /** Status bitfield code for pipes */
   private static final int PIPE_TYPE = 1<<4;         // 010000

   /** Status bitfield code for hidden */
   private static final int HIDDEN_TYPE = 1<<5;       // 100000
   
   /** Status code for UNIX */
   private static final int IS_UNIX = 1<<6;
   
   /** Status code for WINDOWS */
   private static final int IS_WINDOWS = 1<<7;

   /** Cache of console redirection flag for current session. */
   private static Boolean consoleRedirected = null;
   
   /**
    * Native utility method that will return a bitfield code representing the
    * status of the file.
    * 
    * @param   filePath
    *          The String representing the path of the file for
    *          which we want to calculate the status code.
    * 
    * @return  The status bitfield code of the file.
    */
   public native static int checkFileType(String filePath);
   
   /**
    * Native utility method that will return the creation date of a file 
    * represented as milliseconds from year 1970.  .
    * 
    * @param   filePath
    *          The String representing the path of the file for
    *          which we want to calculate the creation time.
    * 
    * @return  The file creation time in milliseconds from 1970 or -1 if 
    *          operation has failed , (real data cannot be -1 since precision
    *          for returned date is at the level of seconds).
    */
   public native static long getFileCreationTime(String filePath);

   /**
    * This method will call the native code handling the file type detection,
    * interpret the bitfield result and return the status in Progress format.
    * 
    * @param  filePath
    *         The String representing the path of the file for
    *         which we want to calculate the status code.
    *         
    * @return The composed status of the file.
    */
   public static String getFileType(String filePath)
   {
      StringBuilder sb = new StringBuilder();
      
      int val = checkFileType(filePath);
      if (val == -1)
      {
         getFileTypeFallback(sb, filePath);
         if (sb.length() == 0)
         {
            // TODO This error condition could not be duplicated in Progress
            String errmsg = "Error encountered while getting file status of: " + filePath;
            ErrorManager.recordOrShowError(-1, errmsg, true);
         }
         return sb.toString();
      }
      // cover windows behavior
      if ((val & IS_WINDOWS) != 0)
      {
         // primary type checking
         if ((val & FILE_TYPE) != 0)
         {
            sb.append('F');
            // hidden attribute is only applied to files on windows
            if ((val & HIDDEN_TYPE) != 0)
            {
               sb.append('H');
            }
         }
         else if ((val & DIRECTORY_TYPE) != 0)
         {
            sb.append('D');
         }
         else if ((val & DEVICE_TYPE) != 0)
         {
            sb.append('S');
         }
         else
         {
            // the special case of UNKNOWN_TYPE
            return "X";
         }
         // secondary
         if ((val & SYMBOLIC_LINK_TYPE) != 0)
         {
            // do nothing (windows behavior)
         }
         if ((val & PIPE_TYPE) != 0)
         {
            // do nothing (windows behavior)
         }
      }
      // cover unix behavior
      if ((val & IS_UNIX) != 0)
      {
         if ((val & HIDDEN_TYPE) != 0)
         {
            sb.append('H');
         }
         if ((val & SYMBOLIC_LINK_TYPE) != 0)
         {
            sb.append('L');
         }
         if ((val & FILE_TYPE) != 0)
         {
            sb.append('F');
         }
         else if ((val & DIRECTORY_TYPE) != 0)
         {
            sb.append('D');
         }
         else if ((val & DEVICE_TYPE) != 0)
         {
            sb.append('S');
         }
         else
         {
            // the special case of UNKNOWN_TYPE
            sb.append("X");
         }
         if ((val & PIPE_TYPE) != 0)
         {
            sb.append('P');
         }
      }
      return sb.toString();
   }
   
   /**
    * This method provides a fallback mechanism to determine the type and visibility
    * of a file in cases where native file type detection fails. It uses standard Java
    * file inspection APIs to approximate the file status.
    *
    * @param  sb
    *         The {@code StringBuilder} to which the detected file status characters are appended.
    * @param  filePath
    *         The {@code String} representing the path of the file to evaluate.
    */
   private static void getFileTypeFallback(StringBuilder sb, String filePath)
   {
      File file = new File(filePath);
      String os = EnvironmentOps.getRuntimeOperatingSystem().toJavaType();
      if (os.equalsIgnoreCase("win32"))
      {
         if (file.isFile())
         {
            sb.append('F');
            if (file.isHidden())
            {
               sb.append('H');
            }
         }
         else if (file.isDirectory())
         {
            sb.append('D');
         }
      }
      else if (os.equalsIgnoreCase("unix"))
      {
         if (file.isHidden())
         {
            sb.append('H');
         }
         if (file.isFile())
         {
            sb.append('F');
         }
         else if (file.isDirectory())
         {
            sb.append('D');
         }
      }
   }

   /**
    * Checks if the current STDOUT handle is redirected to the file by OS output redirection
    * command line option("&gt;").
    *
    * @return   <code>true</code> if the current console output is redirected 
    *           <code>false</code> otherwise.
    */
   public static native boolean isStdoutRedirected();

   /**
    * Checks if the current console session is redirected to the file by OS output redirection
    * command line option("&gt;").
    *
    * @return   <code>true</code> if the current console output is redirected 
    *           <code>false</code> otherwise.
    */
   public static synchronized boolean isConsoleRedirected()
   {
      if (consoleRedirected == null)
      {
         consoleRedirected = Boolean.valueOf(isStdoutRedirected());
      }
      
      return consoleRedirected.booleanValue() || IS_OUTPUT_REDIRECTED.get();
   }
}