SearchTrees.java

/*
** Module   : SearchTrees.java
** Abstract : drives the pattern engine service to search for matches to
**            a given expression
**
** Copyright (c) 2007-2023, Golden Code Development Corporation.
**
** -#- -I- --Date-- -T- --JPRM-- ----------------Description-----------------
** 001 GES 20070511 NEW   @33479 Created initial version that provides
**                               support for command line processing based
**                               on given expression. This is an alternate,
**                               special-purpose driver for the pattern
**                               engine.
** 002 GES 20070514 CHG   @33496 Moved debug levels into an interface.
** 003 TJD 20220504              Upgrade do Java 11 minor changes
** 004 GBB 20230512              Logging methods replaced by CentralLogger/ConversionStatus.
*/
/*
** 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.pattern;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import com.goldencode.p2j.convert.*;
import com.goldencode.p2j.util.*;
import com.goldencode.util.*;

/**
 * Special-purpose driver for the pattern engine to search a list of ASTs
 * for matches to a given expression.  This provides a command line
 * interface, please see {@link #main} for the syntax.
 *
 * @author    GES
 */
public class SearchTrees
implements DebugLevels
{
   /** Logger */
   private static final ConversionStatus LOG = ConversionStatus.get(SearchTrees.class);
   
   /**
    * Emit a syntax statement and optional error message to
    * <code>stderr</code>, then exit the process with the specified return
    * code. This method is called from {@link #main} when the user passes
    * command line parameters which are not viable.
    *
    * @param    msg
    *           Optional error message; may be <code>null</code>.
    * @param    rc
    *           Process return code used with <code>System.exit()</code>.
    */
   private static void syntax(String msg, int rc)
   {
      if (msg != null)
      {
         LOG.log(Level.SEVERE, msg);
      }
      
      String[] staticText =
      {
         "",
         "Syntax:",
         "",
         "   java -DP2J_HOME=<home> SearchTrees [options] <expr> <filelist>",
         "   java -DP2J_HOME=<home> SearchTrees -S[options] <expr> " +
         "<directory> \"<filespec>\"",
         "",
         "Where",
         "",
         "   Options",
         "",
         "      Dn = set debug level 'n' (must be a numeric digit between",
         "           " + MSG_NONE + " and " + MSG_TRACE + " inclusive)",
         "      S  = use filespecs instead of an explicit file list",
         "      N  = no recursion in filespec mode",
         "",
         "   expr       = a double quoted string containing a valid TRPL",
         "                expression to evaluate", 
         "   filelist   = arbitrary list of absolute and/or relative file", 
         "                names to scan (default approach)",
         "   directory  = a relative or absolute path (only used when using",
         "                filespecs)",
         "   filespec   = file filter specification of the filenames in the",      
         "                given directory to scan, should be enclosed in",
         "                double quotes if any of the wildcard characters '*'",
         "                or '?' are used (only used when using filespecs)",
         ""
      };

      LOG.log(Level.INFO, StringHelper.arrayToString(staticText));
      
      System.exit(rc);
   }
   
   /**
    * Provides a command line interface for searching a list of ASTs for
    * matches to a given expression. Matches are dumped to 
    * <code>STDOUT</code>.  
    * <p>
    * Syntax:
    * <pre>
    *   java -DP2J_HOME=&lt;home&gt; SearchTrees [options] &lt;expr&gt; &lt;filelist&gt;
    *   java -DP2J_HOME=&lt;home&gt; SearchTrees -S[options] &lt;expr&gt; &lt;directory&gt; &lt;filespec&gt;
    * </pre>
    * Where:
    * <ul>
    *   <li> Options
    *   <ul>
    *      <li> Dn = set debug level 'n' (must be a numeric digit between
    *           MSG_NONE (0) and MSG_TRACE (3) inclusive
    *      <li> S  = use filespecs instead of an explicit file list
    *      <li> N  = no recursion in filespec mode
    *   </ul>
    *   <li> <code>expr</code> is a double quoted string containing a valid 
    *        expression to evaluate
    *   <li> explicit file list mode (default approach)
    *   <ul>
    *      <li> &lt;filelist&gt; is arbitrary list of absolute and/or
    *           relative file names to scan
    *   </ul> 
    *   <li> filespec mode
    *   <ul>
    *      <li> &lt;directory&gt; is the directory to search for files
    *      <li> &quot;filespec&quot; is the file specification that will be
    *           used to create a list of files to process, should be enclosed
    *           in double quotes if any of the wildcard characters '*' or '?'
    *           are used
    *   </ul>
    * </ul>
    *
    * @param   args 
    *          List of command line arguments.
    */
   public static void main(String[] args) 
   {
      // option defaults
      boolean explicit  = true;
      boolean recursion = true;
      int     debug     = MSG_STATUS;
      int     idx       = 0;
      
      // requires (mode + directory + filespec) OR (mode and a filelist)
      if (args.length < 2)
      {
         syntax(null, -1);
      }
      
      // process options
      if (args[0].startsWith("-"))
      {
         idx++;
         String opts = args[0].toLowerCase();
         
         if (opts.indexOf('s') != -1) explicit = false;
         else explicit = true;
         
         if (opts.indexOf('n') != -1) recursion = false;
         else recursion = true;
         
         int dbg = opts.indexOf('d');
         
         if (dbg != -1)
         {
            char level = opts.charAt(dbg + 1);
            
            if (!Character.isDigit(level))
            {
               syntax("Missing numeric debug level character following D" + 
                      " option.",
                      -2);
            }
            else
            {
               debug = Character.digit(level, 10);
               
               if (debug < MSG_NONE || debug > MSG_TRACE)
               {
                  syntax("Debug level must be between " + MSG_NONE +
                         " and " + MSG_TRACE + ".",
                         -3);
               }
            }
         }
      }
      
      // process the expression argument
      HashMap initializers = new HashMap();
      initializers.put("criteria", "'" + args[idx] + "'");
      
      idx++;
      
      FileList files = null;
      
      // at this point idx points to the next arg after the options, this
      // must be one of our various forms of filename input
      if (explicit)
      {
         // there must be at least 1 arg left
         if (args.length <= idx)
         {
            syntax("Missing file list parameter.", -6);
         }
         
         int      len      = args.length;
         String[] filelist = new String[len - idx];
         
         for (int j = idx; j < len; j++)
         {
            filelist[j - idx] = args[j];
         }
         
         files = new ExplicitFileList(filelist);
      }
      else
      {
         // there must be exactly 2 args left
         if ((args.length - idx) != 2)
         {
            syntax("Missing/incomplete filespec parameter.", -7);
         }
         
         files = new FileSpecList(new File(args[idx]),
                                  args[idx+1],
                                  recursion);
      }
      
      try
      {
         // create a new pattern engine, configure it and run
         PatternEngine engine = new PatternEngine();
         engine.addAstSpec(files);
         PatternEngine.setDebugLevel(debug);
         engine.setReadOnly(true);
         engine.setVariableInitializers(initializers);
         engine.run("reports/simple_search");
      }
       
      catch(Exception excpt)
      {
         LOG.log(Level.SEVERE, "", excpt);
      }
   }
}