Package org.geoforge.mgrplg

Source Code of org.geoforge.mgrplg.GfrPluginManagerUtilAbs

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.geoforge.mgrplg;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.xeoh.plugins.base.Plugin;
import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.options.getplugin.PluginSelector;
import net.xeoh.plugins.base.util.PluginManagerUtil;
import org.geoforge.java.io.file.GfrUtilFile;
import org.geoforge.java.io.file.GfrJavIoFileExtension;
import org.geoforge.java.enumeration.GfrEnuSystemPropertiesKeys;
import org.geoforge.java.util.logging.filehandler.FileHandlerLogger;
import org.geoforge.mgrplg.handler.IGfrHandlerPlugin;

/**
*
* @author robert
*
*/
abstract public class GfrPluginManagerUtilAbs extends PluginManagerUtil
{
    final static protected String _STR_SUFFIX_FOLDER_BLACK_BOX_Plugin = "_blackbox";
   
    // required, should be in manifest
   /*
    * memo: value should be 3-letters lowerCase, ie.
    * gfr, gsi, shg, gtc, ogx
    */
   final static private String _STR_KEY_NAME_3LETTERS_DISTRO_ = "PluginGeoforge-Name3lettersDistro";
   final static protected String _STR_KEY_VERSION_DISTRO = "PluginGeoforge-VersionDistro";
  
   
  
   // ---
  
   final private static Logger _LOGGER_ = Logger.getLogger(GfrPluginManagerUtilAbs.class.getName());

   static
   {
      GfrPluginManagerUtilAbs._LOGGER_.addHandler(FileHandlerLogger.s_getInstance());
   }
   
   
   
   
   
    // !!! duplicated code from GfrUtilFile
    static protected void _s_deleteFolder(File fleFolder)
   {
      File[] fles = fleFolder.listFiles();

      if (fles != null)
      { //some JVMs return null for empty dirs
         for (File fleCur : fles)
         {
            if (fleCur.isDirectory())
            {
               _s_deleteFolder(fleCur);
            }
            else
            {
               fleCur.delete();
            }
         }
      }
      fleFolder.delete();
   }
   
   
    // done in a hurry !!!!!!!!
    static protected String s_getNameBlackBox(String strNameFullFilePlugin)
    {
     
       
        if (strNameFullFilePlugin==null || strNameFullFilePlugin.length()<GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[0].length() +1)
            return null;
       
      
       
        int intCut = strNameFullFilePlugin.toLowerCase().lastIndexOf(".jar");
       
        if (intCut == -1)
            return null;
       
        String strRes = strNameFullFilePlugin.substring(0, intCut);
        strRes += _STR_SUFFIX_FOLDER_BLACK_BOX_Plugin;
       
       
        return strRes;
    }
   
   
   
  
  
  
   static protected Attributes _s_getAttributesFromManifest(File fleJar) throws Exception
   {
      JarFile jfe = new JarFile(fleJar);
      Manifest mnf = jfe.getManifest();
     
      if (mnf == null)
      {
         String strLogger = "mnf == null";
         GfrPluginManagerUtilAbs._LOGGER_.warning(strLogger);
         String strError = "Either wrong or corrupted file, no manifest found in JAR";
         throw new Exception(strError);
      }
     
      Attributes att = mnf.getMainAttributes();
     
      if (att == null)
      {
         String strLogger = "att == null";
         GfrPluginManagerUtilAbs._LOGGER_.warning(strLogger);
         String strError = "Either wrong or corrupted file, no attributes found in manifest";
         throw new Exception(strError);
      }
     
      return att;
   }
  
  
   static protected String _s_getKindDistro(Attributes att) throws Exception
   {
      String strResult = att.getValue(GfrPluginManagerUtilAbs._STR_KEY_NAME_3LETTERS_DISTRO_);
     
      if (strResult == null)
      {
         String strLogger = "strResult == null";
         GfrPluginManagerUtilAbs._LOGGER_.warning(strLogger);
         String strError = "Either wrong or corrupted file, no " + GfrPluginManagerUtilAbs._STR_KEY_NAME_3LETTERS_DISTRO_ + " attribute found in manifest";
         throw new Exception(strError);
      }
     
      strResult = strResult.trim();
     
      if (strResult.length() != 3)
      {
         String strLogger = "strResult.length() != 3, strResult.length()=" + strResult.length();
         GfrPluginManagerUtilAbs._LOGGER_.warning(strLogger);
         String strError = "Either wrong or corrupted file, not a valid " + GfrPluginManagerUtilAbs._STR_KEY_NAME_3LETTERS_DISTRO_ + " attribute found in manifest";
         throw new Exception(strError);
      }
     
      return strResult;
   }
  
   static private File _s_getFileFolderPluginsApplication_() throws Exception
   {
      String strPathParentJarredPlugins = System.getProperty(
         GfrEnuSystemPropertiesKeys.PATH_ABSOLUTE_FOLDER_PLUGINS_APPLI.getLabel());

      if (strPathParentJarredPlugins==null || strPathParentJarredPlugins.length()<1)
      {
         String strSevere = "strPathParentJarredPlugins==null || strPathParentJarredPlugins.length()<1";
         GfrPluginManagerUtilAbs._LOGGER_.severe(strSevere);
         throw new Exception(strSevere);
      }

      File fleFolderPlugins = new File(strPathParentJarredPlugins);

      if (fleFolderPlugins==null || !fleFolderPlugins.exists() || !fleFolderPlugins.isDirectory())
      {
         String strSevere = "fleFolderPlugins==null || !fleFolderPlugins.exists() || !fleFolderPlugins.isDirectory()";
         strSevere += "\nfleFolderPlugins.getAbsolutePath()=" + fleFolderPlugins.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.severe(strSevere);
         throw new Exception(strSevere);
      }
     
      return fleFolderPlugins;
   }
  
   static protected void _s_addPluginsApplication(PluginManager pmr) throws Exception
   {
      File fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsApplication_();
      String[] strsNameFile = fleFolderPlugins.list();
              
      if (strsNameFile==null || strsNameFile.length<1)
          return;
         
      
        for (int i=0; i<strsNameFile.length; i++)
        {
           
            File fleCur = new File(fleFolderPlugins, strsNameFile[i]);
        
           if (fleCur.isDirectory())
           {
               if (! strsNameFile[i].endsWith(_STR_SUFFIX_FOLDER_BLACK_BOX_Plugin))
               {
                   // WRONG
                   String strWarning = "! strsNameFile[i].endsWith(_STR_SUFFIX_FOLDER_BLACK_BOX_Plugin_)";
                   strWarning += "\nfleCur.getAbsolutePath()="  + fleCur.getAbsolutePath();
                   GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
               }
              
               continue;
           }
           
            boolean blnOkExtension = false;
            // check for valid extension
            for (int j=0; j<GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN.length; j++)
            {
                String strExtensionCur = GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[j];
                strExtensionCur = strExtensionCur.toLowerCase();

                if (strsNameFile[i].toLowerCase().endsWith(strExtensionCur))
                {
                    blnOkExtension = true;
                    break;
                }
            }

        if (! blnOkExtension)
        {
            String strWarning = "Uncaught file extension";
            strWarning += "\nfleCur.getAbsolutePath()="  + fleCur.getAbsolutePath();
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            continue;
        }


        // beg trick: tbrls with File.[delete|deleteOnExit}
        String strExtensionSuffix = null;

        for (int j=0; j<GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN.length; j++)
        {
            if (! strsNameFile[i].toLowerCase().endsWith(GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[j].toLowerCase()))
                continue;

            strExtensionSuffix = GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[j].toLowerCase();
            break;
        }

        if (strExtensionSuffix == null)
        {
            String strWarning = "Uncaught plugin's file extension: " + strsNameFile[i];
            strWarning += "\nfleCur.getAbsolutePath()="  + fleCur.getAbsolutePath();
            strWarning += ", ignoring ...";
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            continue;
        }

        int intIndexEnd = strsNameFile[i].length();
        intIndexEnd -= strExtensionSuffix.length();
        intIndexEnd --; // "."
        String strNameTarget = strsNameFile[i].substring(0, intIndexEnd);
        File fleTmp = GfrUtilFile.s_createTempFile(strNameTarget, "." + strExtensionSuffix);
        GfrUtilFile.s_copy(fleCur, fleTmp);
        pmr.addPluginsFrom(fleTmp.toURI());
        // end trick

        // beg trick: get plugin's ???assigned??? file
        GfrPluginManagerUtilAbs._s_assignNameFileToPlugin(pmr, fleCur);
        // end trick

        }
     
   }
  
   static protected void _s_addPluginsGeoforge(PluginManager pmr) throws Exception
   {
      File fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsGeoforge();
      String[] strsNameFile = fleFolderPlugins.list();
              
      if (strsNameFile==null || strsNameFile.length<1)
          return;
         
         
    
      for (int i=0; i<strsNameFile.length; i++)
      {
         File fleCur = new File(fleFolderPlugins, strsNameFile[i]);
        
         if (fleCur.isDirectory())
           {
               if (! strsNameFile[i].endsWith(_STR_SUFFIX_FOLDER_BLACK_BOX_Plugin))
               {
                   // WRONG
                   String strWarning = "! strsNameFile[i].endsWith(_STR_SUFFIX_FOLDER_BLACK_BOX_Plugin_)";
                   strWarning += "\nfleCur.getAbsolutePath()="  + fleCur.getAbsolutePath();
                   GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
               }
              
               continue;
           }
         
         
        boolean blnOkExtension = false;
        // check for valid extension
        for (int j=0; j<GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN.length; j++)
        {
            String strExtensionCur = GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[j];
            strExtensionCur = strExtensionCur.toLowerCase();

            if (strsNameFile[i].toLowerCase().endsWith(strExtensionCur))
            {
                blnOkExtension = true;
                break;
            }
        }

        if (! blnOkExtension)
        {
            String strWarning = "Uncaught file extension";
            strWarning += "\nstrsNameFile[i]=" + strsNameFile[i];
            strWarning += "\nfleCur.getAbsolutePath()="  + fleCur.getAbsolutePath();
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            continue;
        }

        File flePluginCur = new File(fleFolderPlugins, strsNameFile[i]);

        // beg trick: tbrls with File.[delete|deleteOnExit}
        String strExtensionSuffix = null;

        for (int j=0; j<GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN.length; j++)
        {
            if (! strsNameFile[i].toLowerCase().endsWith(GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[j].toLowerCase()))
                continue;

            strExtensionSuffix = GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[j].toLowerCase();
            break;
        }

        if (strExtensionSuffix == null)
        {
            String strWarning = "Uncaught plugin's file extension: " + strsNameFile[i];
            strWarning += "\nfleCur.getAbsolutePath()="  + fleCur.getAbsolutePath();
            strWarning += ", ignoring ...";
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            continue;
        }

        int intIndexEnd = strsNameFile[i].length();
        intIndexEnd -= strExtensionSuffix.length();
        intIndexEnd --; // "."
        String strNameTarget = strsNameFile[i].substring(0, intIndexEnd);
        File fleTmp = GfrUtilFile.s_createTempFile(strNameTarget, "." + strExtensionSuffix);
        GfrUtilFile.s_copy(flePluginCur, fleTmp);
        pmr.addPluginsFrom(fleTmp.toURI());
        // end trick

        // beg trick: get plugin's ???assicated??? file
        GfrPluginManagerUtilAbs._s_assignNameFileToPlugin(pmr, flePluginCur);
        // end trick

        }
     
   }
          
   /*
    * trick, there should be at least one plugin, there should be one unique plugin with "nameFile" equals to nil
    */
   static protected void _s_assignNameFileToPlugin(
           PluginManager pm,
           File fleSource) throws Exception
   {
      PluginManagerUtil pmu = new PluginManagerUtil(pm);
     
      Collection<IGfrHandlerPlugin> col = pmu.getPlugins(IGfrHandlerPlugin.class);
     
      if (col==null || col.isEmpty())
      {
         //pmu.shutdown();
         String strException = "col==null || col.isEmpty(), fleSource=" + fleSource.getAbsolutePath();
         throw new Exception(strException);
      }
     
      for (IGfrHandlerPlugin plgCur: col)
      {
         String strNameFileCur = plgCur.getNameFilePlugin();
        
         if (strNameFileCur!=null && strNameFileCur.length()>0)
            continue;
        
         plgCur.setNameFilePlugin(fleSource.getName());
        
         //pmu.shutdown();
         return;
      }
     
      //pmu.shutdown();
      String strException = "No noNameFile plugin found, fleSource=" + fleSource.getAbsolutePath();
      throw new Exception(strException);
   }
  
   // should be private
   static protected File _s_getFileFolderPluginsGeoforge() throws Exception
   {
      String strPathParentJarredPlugins = System.getProperty(
         GfrEnuSystemPropertiesKeys.PATH_ABSOLUTE_FOLDER_PLUGINS_ORG.getLabel());

      if (strPathParentJarredPlugins==null || strPathParentJarredPlugins.length()<1)
      {
         String strSevere = "strPathParentJarredPlugins==null || strPathParentJarredPlugins.length()<1";
         GfrPluginManagerUtilAbs._LOGGER_.severe(strSevere);
         throw new Exception(strSevere);
      }

      File fleFolderPlugins = new File(strPathParentJarredPlugins);

      if (fleFolderPlugins==null || !fleFolderPlugins.exists() || !fleFolderPlugins.isDirectory())
      {
         String strSevere = "fleFolderPlugins==null || !fleFolderPlugins.exists() || !fleFolderPlugins.isDirectory()";
         strSevere += "\nfleFolderPlugins.getAbsolutePath()=" + fleFolderPlugins.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.severe(strSevere);
         throw new Exception(strSevere);
      }
     
      return fleFolderPlugins;
   }
  
   // ---
  
   abstract public IGfrHandlerPlugin addPlugin(File fleJarSource) throws Exception; 

   /*
    * only returns valid plugins, as list sorted by name
    */
   public ArrayList<IGfrHandlerPlugin> getPluginsAsListSortedByName()
    {
        ArrayList<IGfrHandlerPlugin> altResult = new ArrayList<IGfrHandlerPlugin>();
       
        Collection<IGfrHandlerPlugin> colPlg = super.getPlugins(IGfrHandlerPlugin.class);
       
        if (colPlg.isEmpty())
            return altResult;
       
        for (IGfrHandlerPlugin hndCur: colPlg)
            altResult.add(hndCur);
       
        if (altResult.size() < 2)
            return altResult;
       
        // sorting
       
        Collections.sort(altResult , new Comparator<IGfrHandlerPlugin>()
        {
           @Override
           public int compare(IGfrHandlerPlugin hnd1, IGfrHandlerPlugin hnd2)
           {
              return hnd1.getNamePlugin().compareTo(hnd1.getNamePlugin());
           }
         });
       
        // --- ending
        return altResult;
    }
  
   /*
    * only returns valid plugins
    */
   @Override
    public <P extends Plugin> Collection<P> getPlugins(final Class<P> clsPlugin)
   {
      return getPlugins(clsPlugin, new PluginSelector<P>()
      {
         @Override
         public boolean selectPlugin(final P p)
         {
            if (! (p instanceof IGfrHandlerPlugin))
               //return true; // !!!!!!!!!!!!!!!!!!!!!!!!! august ~19, 2014
                return false; // TO BE CHECKED !!!!!!!!!!!!!!!!!!!!!!!!!!!
           
            return ((IGfrHandlerPlugin) p).isValidPlugin();
         }
      });
    }
  
   /*
    * only returns valid plugins that require a license, with valid license
    * for exemple to be activated
    */
    
   public boolean removeAllPlugins() throws Exception
   {
      _deleteOnDiskAll();
      Collection<IGfrHandlerPlugin> col = super.getPlugins(IGfrHandlerPlugin.class);
       
      if (col==null || col.isEmpty()) // should never happen
         return false;

      boolean blnGotIt = false;
     
      for (IGfrHandlerPlugin plgCur: col)
      {
          if (plgCur.isValidPlugin())
          {
              plgCur.setValidPlugin(false);
              blnGotIt |= true;
          }
         
          plgCur.releasePlugin();
      }
     
      return blnGotIt;
   }
  
   private void _checkValidVersionManagerPluginsGeoforge_(Attributes attManifestJarSource) throws Exception
   {
      String strResult = attManifestJarSource.getValue(GfrPluginManagerUtilAbs._STR_KEY_VERSION_DISTRO);
     
      if (strResult == null)
      {
         String strLogger = "strResult == null";
         GfrPluginManagerUtilAbs._LOGGER_.warning(strLogger);
         String strError = "Either wrong or corrupted file, no " + GfrPluginManagerUtilAbs._STR_KEY_VERSION_DISTRO + " attribute found in manifest";
         throw new Exception(strError);
      }
     
      String strVersionSupported = System.getProperty(GfrEnuSystemPropertiesKeys.VERSION_MANAGER_PLUGINS_ORG.getLabel());
     
      if (strResult.compareTo(strVersionSupported) == 0)
         return;
     
      String strError = "Wrong Geoforge plugins manager version in manifest: ";
      strError += "\nExpected: " + strVersionSupported;
      strError += "\nFound: " + strResult;
      GfrPluginManagerUtilAbs._LOGGER_.warning(strError);
      throw new Exception(strError);
   }
  
 
   private void _checkValidVersionManagerPluginsApplication_(Attributes attManifestJarSource) throws Exception
   {
      String strResult = attManifestJarSource.getValue(GfrPluginManagerUtilAbs._STR_KEY_VERSION_DISTRO);
     
      if (strResult == null)
      {
         String strLogger = "strResult == null";
         GfrPluginManagerUtilAbs._LOGGER_.warning(strLogger);
         String strError = "Either wrong or corrupted file, no " + GfrPluginManagerUtilAbs._STR_KEY_VERSION_DISTRO + " attribute found in manifest";
         throw new Exception(strError);
      }
     
      String strVersionSupported = System.getProperty(GfrEnuSystemPropertiesKeys.VERSION_MANAGER_PLUGINS_APPLI.getLabel());
     
      if (strResult.compareTo(strVersionSupported) == 0)
         return;
     
      String strError = "Wrong application plugins manager version in manifest: ";
      strError += "\nExpected: " + strVersionSupported;
      strError += "\nFound: " + strResult;
      GfrPluginManagerUtilAbs._LOGGER_.warning(strError);
      throw new Exception(strError);
   }
   
   protected IGfrHandlerPlugin _addPluginGeoforge(
           File fleJarSource, Attributes attManifest) throws Exception
   {  
      _checkValidVersionManagerPluginsGeoforge_(attManifest);
     
     
      File fleFolderTarget = GfrPluginManagerUtilAbs._s_getFileFolderPluginsGeoforge();
      String strNameSource = fleJarSource.getName();

      File fleTarget = new File(fleFolderTarget, strNameSource);

      if (fleTarget.exists())
      {
         Object objBodyMessage = "Sorry, plugin with same file name already exists in cache:" +
               "\n   " + strNameSource +
                 "\n\n aborting ...";
         String strTitleMessage = "File already exists";

         JOptionPane.showMessageDialog(
               null,
               objBodyMessage,
               strTitleMessage,
               JOptionPane.WARNING_MESSAGE);

         return null;
      }
     
      // beg blackbox
      String strNameFoldeBlackBox = s_getNameBlackBox(strNameSource);
     
      File fleFoldeBlackBox = new File(fleFolderTarget, strNameFoldeBlackBox);
     
      if (fleFoldeBlackBox.exists()) // TODO: clean-up ?? or choice to ...
      {
         Object objBodyMessage = "Plugin's blackbox folder with same file name already exists in cache:" +
               "\n   " + fleFoldeBlackBox +
                 "\n\n ignoring ...";
         //String strTitleMessage = "Folder already exists";
        
         GfrPluginManagerUtilAbs._LOGGER_.warning((String) objBodyMessage);

         /*JOptionPane.showMessageDialog(
               null,
               objBodyMessage,
               strTitleMessage,
               JOptionPane.WARNING_MESSAGE);

         return null;*/
      }
     
      else
         fleFoldeBlackBox.mkdir();
      // end blackbox
     

      // beg trick
      IGfrHandlerPlugin plgNew = _addPluginToRearrange(fleJarSource);
      // end trick

      GfrUtilFile.s_copy(fleJarSource, fleTarget);
      return plgNew;
   }
   
   
    public boolean removePlugin(IGfrHandlerPlugin plg) throws Exception
    {
       Collection<IGfrHandlerPlugin> col = super.getPlugins(IGfrHandlerPlugin.class);
       
        if (col==null || col.isEmpty())
        {
            return false;
        }
       
        for (IGfrHandlerPlugin plgCur: col)
        {
           if (plgCur != plg)
              continue;
          
          
          
           if (plgCur.isValidPlugin())
            {
                plgCur.setValidPlugin(false);
                //blnGotIt |= true;
            }

            plgCur.releasePlugin();

          
           /*
           if (! plgCur.isValidPlugin()) // !!!
              return false;
          
           plgCur.setValidPlugin(false);*/
          
           // destroy respective file
           _deleteOnDisk(plgCur);
           return true;
        }
       
       
        return false;
    }
   
    public int getCountPluginsValid()
    {
       Collection<IGfrHandlerPlugin> colAll = super.getPlugins(IGfrHandlerPlugin.class);
      
       if (colAll==null || colAll.isEmpty())
        {
            return 0;
        }
      
       int intResult = 0;
      
       for (IGfrHandlerPlugin plgCur: colAll)
        {
           if (plgCur.isValidPlugin())
              intResult ++;
        }
      
       return intResult;
    }
   
  
   // ---
   protected GfrPluginManagerUtilAbs(PluginManager pmr)
   {
      super(pmr);
   }
  
   protected void _deleteOnDiskApplication(IGfrHandlerPlugin plg) throws Exception
   {
      File fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsApplication_();
     
      String strNameFile = plg.getNameFilePlugin();
     
      String strNameFolderBlackBox = GfrPluginManagerUtilAbs.s_getNameBlackBox(strNameFile);
      File fleFolderBlackBox = new File(fleFolderPlugins, strNameFolderBlackBox);
     
      if (fleFolderBlackBox.exists())
      {
          GfrPluginManagerUtilAbs._s_deleteFolder(fleFolderBlackBox);
      }
     
     
     
      File flePluginToDelete = new File(fleFolderPlugins, strNameFile);

      if (! flePluginToDelete.exists())
      {
         String strMessage = "! flePluginToDelete.exists(), flePluginToDelete=" + flePluginToDelete.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.info(strMessage);
         return;
      }


      boolean blnOk = flePluginToDelete.delete();

      if (! blnOk)
      {
         String strWarning = "! blnOk, flePluginToDelete=" + flePluginToDelete.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);

         // ---
         flePluginToDelete.deleteOnExit();
      }

      else
      {
         String strInfo = "blnOk, flePluginCur=" + flePluginToDelete.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.info(strInfo);
      }
   }
  
  
   /*
    * also, if same name, author, version, description
    * then reject attempting to load same plugin with different file name
    *
    * taking care of mandatory fields
    */
   // trick !!!
   protected IGfrHandlerPlugin _addPluginToRearrange(
           File fleSource
           ) throws Exception
   {
      Collection<IGfrHandlerPlugin> colPrev = super.getPlugins(IGfrHandlerPlugin.class);
      // beg trick: tbrls with File.[delete|deleteOnExit}
      String strExtensionSuffix = null;
      String strNameSource = fleSource.getName();
     
      for (int i=0; i<GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN.length; i++)
      {
         if (! strNameSource.toLowerCase().endsWith(GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[i].toLowerCase()))
            continue;
        
         strExtensionSuffix = GfrJavIoFileExtension.STRS_EXTENSION_PLUGIN[i].toLowerCase();
         break;
      }
     
      if (strExtensionSuffix == null)
      {
         String strException = "Uncaught plugin's file extension: " + strNameSource;
         strException += "\nfleSource=" + fleSource;
         GfrPluginManagerUtilAbs._LOGGER_.warning(strException);
         throw new Exception(strException);
      }
     
      int intIndexEnd = strNameSource.length();
      intIndexEnd -= strExtensionSuffix.length();
      intIndexEnd --; // "."
      String strNameTarget = strNameSource.substring(0, intIndexEnd);
      File fleTmp = GfrUtilFile.s_createTempFile(strNameTarget, "." + strExtensionSuffix);
      GfrUtilFile.s_copy(fleSource, fleTmp);
     
      PluginManagerUtil pul = super.addPluginsFrom(fleTmp.toURI());
      // end trick
      Collection<IGfrHandlerPlugin> colNext = super.getPlugins(IGfrHandlerPlugin.class);
     
      if (colNext.size() != colPrev.size()+1)
      {
          String strError = "colNext.size() != colPrev.size()+1";
          strError += "\ncolNext.size()=" + colNext.size();
          strError += "\ncolPrev.size()=" + colPrev.size();
          strError += "\nfleTmp.getAbsolutePath()=" + fleTmp.getAbsolutePath();
          strError += "\nfleSource.getAbsolutePath()=" + fleSource.getAbsolutePath();
         
         
          if (colNext.size() > colPrev.size()+1)
          {
              strError += "\ncolNext.size() > colPrev.size()+1";
              strError += "\n==> More than 1 plugin in this jar!, not allowed";
          }
         
         
         GfrPluginManagerUtilAbs._LOGGER_.warning(strError);
        
         String strDialog = "Failed to load plugin\n\n" + strError;
         throw new Exception(strDialog);
      }
     
      for (IGfrHandlerPlugin plgCurNext: colNext)
      {
         if (colPrev.contains(plgCurNext))
            continue;
        
        
         // ---
         String strNameFileWithSameSignature = _sameSignature(colPrev, plgCurNext);
        
         if (strNameFileWithSameSignature != null)
         {
            plgCurNext.setValidPlugin(false);
            String strWarning = "Plugin already exists with a different name";
            strWarning += "\n file name: " + strNameFileWithSameSignature;
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            throw new Exception(strWarning);
         }

         // ---
         String strName = plgCurNext.getNamePlugin();
        
         if (strName==null || strName.length()<1)
         {
            plgCurNext.setValidPlugin(false);
            String strWarning = "Missing plugin's name";
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            throw new Exception(strWarning);
         }
        
         // ---
         String strVersion = plgCurNext.getVersionThisPlugin();
        
         if (strVersion==null || strVersion.length()<1)
         {
            plgCurNext.setValidPlugin(false);
            String strWarning = "Missing plugin's version";
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            throw new Exception(strWarning);
         }
        
         // ---
         String strAuthor = plgCurNext.getAuthorPlugin();
        
         if (strAuthor==null || strAuthor.length()<1)
         {
            plgCurNext.setValidPlugin(false);
            String strWarning = "Missing plugin's author";
            GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);
            throw new Exception(strWarning);
         }
        
         // ---
         plgCurNext.setNameFilePlugin(fleSource.getName());
         return plgCurNext;
      }
     
     
      GfrPluginManagerUtilAbs._LOGGER_.warning("No new plugin found");
      throw new Exception("Failed to load plugin");
   }
  
   protected void _deleteOnDiskAll() throws Exception
   {
      File fleFolderPlugins = null;
     
      // ---
      fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsGeoforge();
      _deleteOnDiskAll(fleFolderPlugins);
     
      // ---
      fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsApplication_();
      _deleteOnDiskAll(fleFolderPlugins);
   }
  
   protected void _deleteOnDiskAll(File fleFolderPlugins) throws Exception
   {
      String[] strs = fleFolderPlugins.list();
     
      if (strs==null || strs.length<1)
      {
         //String strMessage = "strs==null || strs.length<1";
         //GfrPluginManagerUtilAbs._LOGGER_.info(strMessage);
         return;
      }
     
      for (int i=0; i<strs.length; i++)
      {
          // !!! should be rewritten !!!!!!!!!
          if (! strs[i].toLowerCase().endsWith(".jar"))
              continue;
         
          String strFolderBlackBoxCur = s_getNameBlackBox(strs[i]);
         
          File fleFolderBlackBoxCur = new File(fleFolderPlugins, strFolderBlackBoxCur);
         
          if (fleFolderBlackBoxCur.exists())
              _s_deleteFolder(fleFolderBlackBoxCur);

         
         File fleCurJar = new File(fleFolderPlugins, strs[i]);
        
         boolean blnOk = fleCurJar.delete();
        
         if (blnOk)
         {
            String strMessage = "blnOk: " + fleCurJar.getAbsolutePath();
            GfrPluginManagerUtilAbs._LOGGER_.info(strMessage);
         }
        
         else
         {
            String strMessage = "!blnOk: " + fleCurJar.getAbsolutePath();
            GfrPluginManagerUtilAbs._LOGGER_.warning(strMessage);
         }
      }
   }
  
   protected String _getPathAbsoluteCacheApplication(IGfrHandlerPlugin plg) throws Exception
    {
        File fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsApplication_();
       
        String strNameFolderBlackBox = GfrPluginManagerUtilAbs.s_getNameBlackBox(plg.getNameFilePlugin());
        File fleFolderBlackBox = new File(fleFolderPlugins, strNameFolderBlackBox);
       
        return fleFolderBlackBox.getAbsolutePath();
    }
  
  
   public String getPathAbsoluteCache(IGfrHandlerPlugin plg) throws Exception
    {
        File fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsGeoforge();
       
        String strNameFolderBlackBox = GfrPluginManagerUtilAbs.s_getNameBlackBox(plg.getNameFilePlugin());
        File fleFolderBlackBox = new File(fleFolderPlugins, strNameFolderBlackBox);
       
        return fleFolderBlackBox.getAbsolutePath();
    }

  
   protected void _deleteOnDisk(IGfrHandlerPlugin plg) throws Exception
   {
      File fleFolderPlugins = GfrPluginManagerUtilAbs._s_getFileFolderPluginsGeoforge();
     
      String strNameFile = plg.getNameFilePlugin();
     
      String strNameFolderBlackBox = s_getNameBlackBox(strNameFile);
      File fleFolderBlackBox = new File(fleFolderPlugins, strNameFolderBlackBox);
     
      if (fleFolderBlackBox.exists())
      {
          _s_deleteFolder(fleFolderBlackBox);
      }
     
     
      File flePluginToDelete = new File(fleFolderPlugins, strNameFile);

      if (! flePluginToDelete.exists())
      {
         String strMessage = "! flePluginToDelete.exists(), flePluginToDelete=" + flePluginToDelete.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.info(strMessage);
         return;
      }


      boolean blnOk = flePluginToDelete.delete();

      if (! blnOk)
      {
         String strWarning = "! blnOk, flePluginToDelete=" + flePluginToDelete.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.warning(strWarning);

         // ---
         flePluginToDelete.deleteOnExit();
      }

      else
      {
         String strInfo = "blnOk, flePluginCur=" + flePluginToDelete.getAbsolutePath();
         GfrPluginManagerUtilAbs._LOGGER_.info(strInfo);
      }
   }
  
  
  
   /*
    * rather check for class
    */
   protected String _sameSignature(
           Collection<IGfrHandlerPlugin> col,
           IGfrHandlerPlugin plgToCompare)
   {
      if (col==null || col.isEmpty())
         return null;
     
      String strNameToCompare = plgToCompare.getNamePlugin();
      String strVersionToCompare = plgToCompare.getVersionThisPlugin();
      String strAuthorToCompare = plgToCompare.getAuthorPlugin();
     
      for (IGfrHandlerPlugin plgCur: col)
      {
          if (! plgCur.isValidPlugin()) // by-passing physically removed BUT still in superClass (!isValidPlugin())
              continue;
         
         if (plgCur.getNamePlugin().compareTo(strNameToCompare) != 0)
            continue;
        
         if (plgCur.getVersionThisPlugin().compareTo(strVersionToCompare) != 0)
            continue;
        
         if (plgCur.getAuthorPlugin().compareTo(strAuthorToCompare) != 0)
            continue;
        
         return plgCur.getNameFilePlugin();
      }
     
      return null;
   }
  
   protected IGfrHandlerPlugin _addPluginApplication(File fleSource, Attributes attManifest) throws Exception
   {
      _checkValidVersionManagerPluginsApplication_(attManifest);
     
      File fleFolderTarget = GfrPluginManagerUtilAbs._s_getFileFolderPluginsApplication_();
      String strNameSource = fleSource.getName();
      File fleTarget = new File(fleFolderTarget, strNameSource);

      if (fleTarget.exists())
      {
         Object objBodyMessage = "Sorry, plugin with same file name already exists in cache:" +
               "\n   " + strNameSource +
                 "\n\n aborting ...";
         String strTitleMessage = "File already exists";

         JOptionPane.showMessageDialog(
               null,
               objBodyMessage,
               strTitleMessage,
               JOptionPane.WARNING_MESSAGE);

         return null;
      }
     
      // beg blackbox
     
      String strNameFoldeBlackBox = s_getNameBlackBox(strNameSource);
     
      File fleFoldeBlackBox = new File(fleFolderTarget, strNameFoldeBlackBox);
     
      if (fleFoldeBlackBox.exists()) // TODO: clean-up ?? or choice to ...
      {
         Object objBodyMessage = "Plugin's blackbox folder with same file name already exists in cache:" +
               "\n   " + fleFoldeBlackBox +
                 "\n\n ignoring ...";
        
         //String strTitleMessage = "Folder already exists";
        
         GfrPluginManagerUtilAbs._LOGGER_.warning((String) objBodyMessage);

         /*JOptionPane.showMessageDialog(
               null,
               objBodyMessage,
               strTitleMessage,
               JOptionPane.WARNING_MESSAGE);

         return null;*/
      }
     
      else
        fleFoldeBlackBox.mkdir();
      // end blackbox

      // beg trick
      IGfrHandlerPlugin plgNew = _addPluginToRearrange(fleSource);
      // end trick

      GfrUtilFile.s_copy(fleSource, fleTarget);
      return plgNew;
   }
}
TOP

Related Classes of org.geoforge.mgrplg.GfrPluginManagerUtilAbs

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.