A Project for Chronicle 4 based on L2JServer.


    Java Code in DataPack Folder :D

    Share

    micr0

    Posts : 72
    Join date : 2013-01-23
    Age : 23
    Location : Bulgaria

    Java Code in DataPack Folder :D

    Post  micr0 on 16th February 2013, 23:02

    hi all i give my patch for l2jlisvus for java Scritps in DataPack

    Code:
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/GameServer.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/GameServer.java   (revision 35)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/GameServer.java   (revision 36)
    @@ -21,4 +21,5 @@
     import java.io.File;
     import java.io.FileInputStream;
    +import java.io.IOException;
     import java.io.InputStream;
     import java.util.Calendar;
    @@ -190,4 +191,5 @@
     import net.sf.l2j.gameserver.pathfinding.geonodes.GeoPathFinding;
     import net.sf.l2j.gameserver.script.faenor.FaenorScriptEngine;
    +import net.sf.l2j.gameserver.scripting.L2ScriptEngineManager;
     import net.sf.l2j.gameserver.taskmanager.KnownListUpdateTaskManager;
     import net.sf.l2j.gameserver.taskmanager.TaskManager;
    @@ -368,4 +370,15 @@
           QuestManager.getInstance();
           
    +      try
    +      {
    +         _log.info("Loading Server Scripts");
    +         File scripts = new File("data/scripts.cfg");
    +         L2ScriptEngineManager.getInstance().executeScriptList(scripts);
    +      }
    +      catch (IOException ioe)
    +      {
    +         _log.severe("Failed loading scripts.cfg, no script going to be loaded");
    +      }
    +      
           if (Config.SAVE_DROPPED_ITEM)
           {
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/instancemanager/QuestManager.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/instancemanager/QuestManager.java   (revision 35)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/instancemanager/QuestManager.java   (revision 36)
    @@ -1,49 +1,40 @@
     /*
    - * This program is free software; you can redistribute it and/or modify
    - * it under the terms of the GNU General Public License as published by
    - * the Free Software Foundation; either version 2, 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 General Public License for more details.
    - *
    - * You should have received a copy of the GNU General Public License
    - * along with this program; if not, write to the Free Software
    - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
    - * 02111-1307, USA.
    - *
    - * http://www.gnu.org/copyleft/gpl.html
    + * This program is free software: you can redistribute it and/or modify it under
    + * the terms of the GNU 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 General Public License for more
    + * details.
    + *
    + * You should have received a copy of the GNU General Public License along with
    + * this program. If not, see <http://www.gnu.org/licenses/>.
      */
     package net.sf.l2j.gameserver.instancemanager;
     
    -import java.util.List;
    +import java.util.Map;
     import java.util.logging.Logger;
     
    -import javolution.util.FastList;
    -import net.sf.l2j.Config;
    +import javolution.util.FastMap;
     import net.sf.l2j.gameserver.model.quest.Quest;
    -import net.sf.l2j.gameserver.model.quest.jython.QuestJython;
    +import net.sf.l2j.gameserver.scripting.ScriptManager;
     
    -public class QuestManager
    +public class QuestManager extends ScriptManager<Quest>
     {
    -   protected static Logger _log = Logger.getLogger(QuestManager.class.getName());
    +   protected static final Logger _log = Logger.getLogger(QuestManager.class.getName());
        
        // =========================================================
    -   private static QuestManager _Instance;
    +   private static QuestManager _instance;
        
        public static final QuestManager getInstance()
        {
    -      if (_Instance == null)
    +      if (_instance == null)
           {
    -         System.out.println("Initializing QuestManager");
    -         _Instance = new QuestManager();
    -         if (!Config.ALT_DEV_NO_QUESTS)
    -         {
    -            _Instance.load();
    -         }
    +         _log.info("Initializing QuestManager");
    +         _instance = new QuestManager();
           }
    -      return _Instance;
    +      return _instance;
        }
        
    @@ -52,5 +43,5 @@
        // =========================================================
        // Data Field
    -   private List<Quest> _Quests;
    +   private Map<String, Quest> _quests = new FastMap<>();
        
        // =========================================================
    @@ -62,19 +53,41 @@
        // =========================================================
        // Method - Public
    -   // NOT WORKING CORRECTLY BECAUSE BSFMANAGER DOEN'T UNLOAD JYTHON SCRIPT
    -   // NEED TO FIND THE SOLUTION BEFORE THIS WILL WORK CORRECLY
    -   public final void reload()
    +   public final boolean reload(String questFolder)
        {
    -      /*
    -       * Re-add later just incase problem exist now this.getQuests().clear(); this.load();
    -       */
    +      Quest q = getQuest(questFolder);
    +      if (q == null)
    +      {
    +         return false;
    +      }
    +      return q.reload();
        }
        
    -   // =========================================================
    -   // Method - Private
    -   private final void load()
    +   /**
    +    * Reloads a the quest given by questId.<BR>
    +    * <B>NOTICE: Will only work if the quest name is equal the quest folder name</B>
    +    * @param questId The id of the quest to be reloaded
    +    * @return true if reload was succesful, false otherwise
    +    */
    +   public final boolean reload(int questId)
        {
    -      QuestJython.init();
    -      System.out.println("Loaded: " + getQuests().size() + " quests");
    +      Quest q = this.getQuest(questId);
    +      if (q == null)
    +      {
    +         return false;
    +      }
    +      return q.reload();
    +   }
    +   
    +   public final void report()
    +   {
    +      _log.info("Loaded: " + getQuests().size() + " quests");
    +   }
    +   
    +   public final void save()
    +   {
    +      for (Quest q : getQuests().values())
    +      {
    +         q.saveGlobalData();
    +      }
        }
        
    @@ -83,57 +96,85 @@
        public final Quest getQuest(String name)
        {
    -      int index = getQuestIndex(name);
    -      if (index >= 0)
    +      return getQuests().get(name);
    +   }
    +   
    +   public final Quest getQuest(int questId)
    +   {
    +      for (Quest q : getQuests().values())
           {
    -         return getQuests().get(index);
    +         if (q.getQuestIntId() == questId)
    +         {
    +            return q;
    +         }
           }
           return null;
        }
        
    -   public final Quest getQuest(int questId)
    +   public final void addQuest(Quest newQuest)
        {
    -      int index = getQuestIndex(questId);
    -      if (index >= 0)
    +      if (newQuest == null)
           {
    -         return getQuests().get(index);
    +         throw new IllegalArgumentException("Quest argument cannot be null");
           }
    -      return null;
    +      Quest old = this.getQuests().get(newQuest.getName());
    +      
    +      // FIXME: unloading the old quest at this point is a tad too late.
    +      // the new quest has already initialized itself and read the data, starting
    +      // an unpredictable number of tasks with that data. The old quest will now
    +      // save data which will never be read.
    +      // However, requesting the newQuest to re-read the data is not necessarily a
    +      // good option, since the newQuest may have already started timers, spawned NPCs
    +      // or taken any other action which it might re-take by re-reading the data.
    +      // the current solution properly closes the running tasks of the old quest but
    +      // ignores the data; perhaps the least of all evils...
    +      if (old != null)
    +      {
    +         old.unload();
    +         _log.info("Replaced: (" + old.getName() + ") with a new version (" + newQuest.getName() + ")");
    +         
    +      }
    +      this.getQuests().put(newQuest.getName(), newQuest);
        }
        
    -   public final int getQuestIndex(String name)
    +   public final boolean removeQuest(Quest q)
        {
    -      Quest quest;
    -      for (int i = 0; i < getQuests().size(); i++)
    -      {
    -         quest = getQuests().get(i);
    -         if ((quest != null) && quest.getName().equalsIgnoreCase(name))
    -         {
    -            return i;
    -         }
    -      }
    -      return -1;
    +      return this.getQuests().remove(q.getName()) != null;
        }
        
    -   public final int getQuestIndex(int questId)
    +   public final FastMap<String, Quest> getQuests()
        {
    -      Quest quest;
    -      for (int i = 0; i < getQuests().size(); i++)
    +      if (_quests == null)
           {
    -         quest = getQuests().get(i);
    -         if ((quest != null) && (quest.getQuestIntId() == questId))
    -         {
    -            return i;
    -         }
    +         _quests = new FastMap<>();
           }
    -      return -1;
    +      return (FastMap<String, Quest>) _quests;
        }
        
    -   public final List<Quest> getQuests()
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ScriptManager#getAllManagedScripts()
    +    */
    +   @Override
    +   public Iterable<Quest> getAllManagedScripts()
        {
    -      if (_Quests == null)
    -      {
    -         _Quests = new FastList<Quest>();
    -      }
    -      return _Quests;
    +      return _quests.values();
    +   }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ScriptManager#unload(net.sf.l2j.gameserver.scripting.ManagedScript)
    +    */
    +   @Override
    +   public boolean unload(Quest ms)
    +   {
    +      ms.saveGlobalData();
    +      return this.removeQuest(ms);
    +   }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ScriptManager#getScriptManagerName()
    +    */
    +   @Override
    +   public String getScriptManagerName()
    +   {
    +      return "QuestManager";
        }
     }
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/model/quest/Quest.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/model/quest/Quest.java   (revision 35)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/model/quest/Quest.java   (revision 36)
    @@ -28,4 +28,5 @@
     import java.util.logging.Logger;
     
    +import javolution.util.FastList;
     import javolution.util.FastMap;
     import net.sf.l2j.Config;
    @@ -36,4 +37,6 @@
     import net.sf.l2j.gameserver.model.actor.instance.L2NpcInstance;
     import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
    +import net.sf.l2j.gameserver.scripting.ManagedScript;
    +import net.sf.l2j.gameserver.scripting.ScriptManager;
     import net.sf.l2j.gameserver.serverpackets.NpcHtmlMessage;
     import net.sf.l2j.gameserver.serverpackets.SystemMessage;
    @@ -42,11 +45,13 @@
     /**
      * @author Luis Arias
    + * @modify Micr0
      */
    -public abstract class Quest
    +public class Quest extends ManagedScript
     {
        protected static Logger _log = Logger.getLogger(Quest.class.getName());
        
        /** HashMap containing events from String value of the event */
    -   private static Map<String, Quest> allEventsS = new FastMap<String, Quest>();
    +   private static Map<String, Quest> allEventsS = new FastMap<>();
    +   private static Map<String, FastList<QuestTimer>> _allEventTimers = new FastMap<>();
        
        private final int _questId;
    @@ -78,8 +83,8 @@
           _descr = descr;
           
    -      states = new FastMap<String, State>();
    +      states = new FastMap<>();
           if (questId != 0)
           {
    -         QuestManager.getInstance().getQuests().add(Quest.this);
    +         QuestManager.getInstance().addQuest(Quest.this);
           }
           else
    @@ -87,4 +92,22 @@
              allEventsS.put(name, this);
           }
    +      init_LoadGlobalData();
    +   }
    +   
    +   /**
    +    * The function init_LoadGlobalData is, by default, called by the constructor of all quests. Children of this class can implement this function in order to define what variables to load and what structures to save them in. By default, nothing is loaded.
    +    */
    +   protected void init_LoadGlobalData()
    +   {
    +      
    +   }
    +   
    +   /**
    +    * The function saveGlobalData is, by default, called at shutdown, for all quests, by the QuestManager. Children of this class can implement this function in order to convert their structures into <var, value> tuples and make calls to save them to the database, if needed. By default, nothing is
    +    * saved.
    +    */
    +   public void saveGlobalData()
    +   {
    +      
        }
        
    @@ -245,5 +268,4 @@
        
        // these are methods that java calls to invoke scripts
    -   @SuppressWarnings("unused")
        public String onAttack(L2NpcInstance npc, QuestState qs)
        {
    @@ -251,5 +273,4 @@
        }
        
    -   @SuppressWarnings("unused")
        public String onDeath(L2NpcInstance npc, L2Character character, QuestState qs)
        {
    @@ -257,5 +278,4 @@
        }
        
    -   @SuppressWarnings("unused")
        public String onEvent(String event, QuestState qs)
        {
    @@ -263,5 +283,4 @@
        }
        
    -   @SuppressWarnings("unused")
        public String onKill(L2NpcInstance npc, QuestState qs)
        {
    @@ -269,5 +288,4 @@
        }
        
    -   @SuppressWarnings("unused")
        public String onTalk(L2NpcInstance npc, QuestState qs)
        {
    @@ -639,3 +657,62 @@
           updateQuestVarInDb(qs, "<state>", val);
        }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ManagedScript#getScriptName()
    +    */
    +   @Override
    +   public String getScriptName()
    +   {
    +      return this.getName();
    +   }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ManagedScript#setActive(boolean)
    +    */
    +   @Override
    +   public void setActive(boolean status)
    +   {
    +      // TODO implement me
    +   }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ManagedScript#reload()
    +    */
    +   @Override
    +   public boolean reload()
    +   {
    +      unload();
    +      return super.reload();
    +   }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ManagedScript#unload()
    +    */
    +   @Override
    +   public boolean unload()
    +   {
    +      this.saveGlobalData();
    +      // cancel all pending timers before reloading.
    +      // if timers ought to be restarted, the quest can take care of it
    +      // with its code (example: save global data indicating what timer must
    +      // be restarted).
    +      for (FastList<QuestTimer> timers : _allEventTimers.values())
    +      {
    +         for (QuestTimer timer : timers)
    +         {
    +            timer.cancel();
    +         }
    +      }
    +      _allEventTimers.clear();
    +      return QuestManager.getInstance().removeQuest(this);
    +   }
    +   
    +   /**
    +    * @see net.sf.l2j.gameserver.scripting.ManagedScript#getScriptManager()
    +    */
    +   @Override
    +   public ScriptManager<?> getScriptManager()
    +   {
    +      return QuestManager.getInstance();
    +   }
     }
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/ScriptManager.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/ScriptManager.java   (revision 36)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/ScriptManager.java   (revision 36)
    @@ -0,0 +1,40 @@
    +/*
    + * This program is free software: you can redistribute it and/or modify it under
    + * the terms of the GNU 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 General Public License for more
    + * details.
    + *
    + * You should have received a copy of the GNU General Public License along with
    + * this program. If not, see <http://www.gnu.org/licenses/>.
    + */
    +package net.sf.l2j.gameserver.scripting;
    +
    +/**
    + * @author KenM
    + */
    +public abstract class ScriptManager<S extends ManagedScript>
    +{
    +   public abstract Iterable<S> getAllManagedScripts();
    +   
    +   public boolean reload(S ms)
    +   {
    +      return ms.reload();
    +   }
    +   
    +   public boolean unload(S ms)
    +   {
    +      return ms.unload();
    +   }
    +   
    +   public void setActive(S ms, boolean status)
    +   {
    +      ms.setActive(status);
    +   }
    +   
    +   public abstract String getScriptManagerName();
    +}
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/ManagedScript.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/ManagedScript.java   (revision 36)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/ManagedScript.java   (revision 36)
    @@ -0,0 +1,99 @@
    +/*
    + * This program is free software: you can redistribute it and/or modify it under
    + * the terms of the GNU 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 General Public License for more
    + * details.
    + *
    + * You should have received a copy of the GNU General Public License along with
    + * this program. If not, see <http://www.gnu.org/licenses/>.
    + */
    +package net.sf.l2j.gameserver.scripting;
    +
    +import java.io.File;
    +import java.io.FileNotFoundException;
    +
    +import javax.script.ScriptException;
    +
    +/**
    + * Abstract class for classes that are meant to be implemented by scripts.<BR>
    + * @author KenM
    + */
    +public abstract class ManagedScript
    +{
    +   private final File _scriptFile;
    +   private long _lastLoadTime;
    +   private boolean _isActive;
    +   
    +   public ManagedScript()
    +   {
    +      _scriptFile = L2ScriptEngineManager.getInstance().getCurrentLoadingScript();
    +      this.setLastLoadTime(System.currentTimeMillis());
    +   }
    +   
    +   /**
    +    * Attempts to reload this script and to refresh the necessary bindings with it ScriptControler.<BR>
    +    * Subclasses of this class should override this method to properly refresh their bindings when necessary.
    +    * @return true if and only if the scrip was reloaded, false otherwise.
    +    */
    +   public boolean reload()
    +   {
    +      try
    +      {
    +         L2ScriptEngineManager.getInstance().executeScript(getScriptFile());
    +         return true;
    +      }
    +      catch (FileNotFoundException e)
    +      {
    +         return false;
    +      }
    +      catch (ScriptException e)
    +      {
    +         return false;
    +      }
    +   }
    +   
    +   public abstract boolean unload();
    +   
    +   public void setActive(boolean status)
    +   {
    +      _isActive = status;
    +   }
    +   
    +   public boolean isActive()
    +   {
    +      return _isActive;
    +   }
    +   
    +   /**
    +    * @return Returns the scriptFile.
    +    */
    +   public File getScriptFile()
    +   {
    +      return _scriptFile;
    +   }
    +   
    +   /**
    +    * @param lastLoadTime The lastLoadTime to set.
    +    */
    +   protected void setLastLoadTime(long lastLoadTime)
    +   {
    +      _lastLoadTime = lastLoadTime;
    +   }
    +   
    +   /**
    +    * @return Returns the lastLoadTime.
    +    */
    +   protected long getLastLoadTime()
    +   {
    +      return _lastLoadTime;
    +   }
    +   
    +   public abstract String getScriptName();
    +   
    +   public abstract ScriptManager<?> getScriptManager();
    +}
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/L2ScriptEngineManager.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/L2ScriptEngineManager.java   (revision 36)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/scripting/L2ScriptEngineManager.java   (revision 36)
    @@ -0,0 +1,506 @@
    +/*
    + * This program is free software: you can redistribute it and/or modify it under
    + * the terms of the GNU 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 General Public License for more
    + * details.
    + *
    + * You should have received a copy of the GNU General Public License along with
    + * this program. If not, see <http://www.gnu.org/licenses/>.
    + */
    +package net.sf.l2j.gameserver.scripting;
    +
    +import java.io.BufferedReader;
    +import java.io.File;
    +import java.io.FileInputStream;
    +import java.io.FileNotFoundException;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.io.InputStreamReader;
    +import java.io.LineNumberReader;
    +import java.util.LinkedList;
    +import java.util.List;
    +import java.util.Map;
    +import java.util.logging.Logger;
    +
    +import javax.script.Compilable;
    +import javax.script.CompiledScript;
    +import javax.script.ScriptContext;
    +import javax.script.ScriptEngine;
    +import javax.script.ScriptEngineFactory;
    +import javax.script.ScriptEngineManager;
    +import javax.script.ScriptException;
    +import javax.script.SimpleScriptContext;
    +
    +import javolution.util.FastMap;
    +import net.sf.l2j.Config;
    +
    +/**
    + * Caches script engines and provides funcionality for executing and managing scripts.<BR>
    + * @author KenM
    + */
    +public final class L2ScriptEngineManager
    +{
    +   private static final Logger _log;
    +   
    +   private static final L2ScriptEngineManager INSTANCE;
    +   
    +   public final static File SCRIPT_FOLDER;
    +   
    +   static
    +   {
    +      _log = Logger.getLogger(L2ScriptEngineManager.class.getName());
    +      SCRIPT_FOLDER = new File(Config.DATAPACK_ROOT.getAbsolutePath(), "data/scripts");
    +      INSTANCE = new L2ScriptEngineManager();
    +   }
    +   
    +   public static L2ScriptEngineManager getInstance()
    +   {
    +      return INSTANCE;
    +   }
    +   
    +   private final Map<String, ScriptEngine> _nameEngines = new FastMap<String, ScriptEngine>();
    +   private final Map<String, ScriptEngine> _extEngines = new FastMap<String, ScriptEngine>();
    +   private final List<ScriptManager<?>> _scriptManagers = new LinkedList<ScriptManager<?>>();
    +   private File _currentLoadingScript;
    +   
    +   // Configs
    +   // TODO move to config file
    +   /**
    +    * Informs(logs) the scripts being loaded.<BR>
    +    * Apply only when executing script from files.<BR>
    +    */
    +   private final boolean VERBOSE_LOADING = false;
    +   
    +   /**
    +    * If the script engine supports compilation the script is compiled before execution.<BR>
    +    */
    +   private final boolean ATTEMPT_COMPILATION = false;
    +   
    +   /**
    +    * Clean an previous error log(if such exists) for the script being loaded before trying to load.<BR>
    +    * Apply only when executing script from files.<BR>
    +    */
    +   private final boolean PURGE_ERROR_LOG = true;
    +   
    +   private L2ScriptEngineManager()
    +   {
    +      ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    +      List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
    +      _log.severe("Initializing Script Engine Manager");
    +      
    +      for (ScriptEngineFactory factory : factories)
    +      {
    +         try
    +         {
    +            _log.info("Script Engine: " + factory.getEngineName() + " " + factory.getEngineVersion() + " - Language: " + factory.getLanguageName() + " - Language Version: " + factory.getLanguageVersion());
    +            ScriptEngine engine = factory.getScriptEngine();
    +            
    +            for (String name : factory.getNames())
    +            {
    +               _nameEngines.put(name, engine);
    +            }
    +            for (String ext : factory.getExtensions())
    +            {
    +               if (!ext.equals("java") || factory.getLanguageName().equals("java"))
    +               {
    +                  _extEngines.put(ext, engine);
    +               }
    +            }
    +         }
    +         catch (Exception e)
    +         {
    +            _log.warning("Failed initializing factory. ");
    +            e.printStackTrace();
    +         }
    +      }
    +      
    +      this.preConfigure();
    +   }
    +   
    +   private void preConfigure()
    +   {
    +      // java class path
    +      
    +      // Jython sys.path
    +      String dataPackDirForwardSlashes = SCRIPT_FOLDER.getPath().replaceAll("\\\\", "/");
    +      String configScript = "import sys;sys.path.insert(0,'" + dataPackDirForwardSlashes + "');";
    +      try
    +      {
    +         this.eval("jython", configScript);
    +      }
    +      catch (ScriptException e)
    +      {
    +         _log.severe("Failed preconfiguring jython: " + e.getMessage());
    +      }
    +   }
    +   
    +   private ScriptEngine getEngineByName(String name)
    +   {
    +      return _nameEngines.get(name);
    +   }
    +   
    +   private ScriptEngine getEngineByExtension(String ext)
    +   {
    +      return _extEngines.get(ext);
    +   }
    +   
    +   public void executeScriptList(File list) throws IOException
    +   {
    +      if (list.isFile())
    +      {
    +         LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(list)));
    +         String line;
    +         File file;
    +         
    +         while ((line = lnr.readLine()) != null)
    +         {
    +            String[] parts = line.trim().split("#");
    +            
    +            if ((parts.length > 0) && !parts[0].startsWith("#") && (parts[0].length() > 0))
    +            {
    +               line = parts[0];
    +               
    +               if (line.endsWith("/**"))
    +               {
    +                  line = line.substring(0, line.length() - 3);
    +               }
    +               else if (line.endsWith("/*"))
    +               {
    +                  line = line.substring(0, line.length() - 2);
    +               }
    +               
    +               file = new File(SCRIPT_FOLDER, line);
    +               
    +               if (file.isDirectory() && parts[0].endsWith("/**"))
    +               {
    +                  this.executeAllScriptsInDirectory(file, true, 32);
    +               }
    +               else if (file.isDirectory() && parts[0].endsWith("/*"))
    +               {
    +                  this.executeAllScriptsInDirectory(file);
    +               }
    +               else if (file.isFile())
    +               {
    +                  try
    +                  {
    +                     this.executeScript(file);
    +                  }
    +                  catch (ScriptException e)
    +                  {
    +                     this.reportScriptFileError(file, e);
    +                  }
    +               }
    +               else
    +               {
    +                  _log.warning("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":" + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
    +               }
    +            }
    +         }
    +      }
    +      else
    +      {
    +         throw new IllegalArgumentException("Argument must be an file containing a list of scripts to be loaded");
    +      }
    +   }
    +   
    +   public void executeAllScriptsInDirectory(File dir)
    +   {
    +      this.executeAllScriptsInDirectory(dir, false, 0);
    +   }
    +   
    +   public void executeAllScriptsInDirectory(File dir, boolean recurseDown, int maxDepth)
    +   {
    +      this.executeAllScriptsInDirectory(dir, recurseDown, maxDepth, 0);
    +   }
    +   
    +   private void executeAllScriptsInDirectory(File dir, boolean recurseDown, int maxDepth, int currentDepth)
    +   {
    +      if (dir.isDirectory())
    +      {
    +         for (File file : dir.listFiles())
    +         {
    +            if (file.isDirectory() && recurseDown && (maxDepth > currentDepth))
    +            {
    +               if (VERBOSE_LOADING)
    +               {
    +                  _log.info("Entering folder: " + file.getName());
    +               }
    +               this.executeAllScriptsInDirectory(file, recurseDown, maxDepth, currentDepth + 1);
    +            }
    +            else if (file.isFile())
    +            {
    +               try
    +               {
    +                  String name = file.getName();
    +                  int lastIndex = name.lastIndexOf('.');
    +                  String extension;
    +                  if (lastIndex != -1)
    +                  {
    +                     extension = name.substring(lastIndex + 1);
    +                     ScriptEngine engine = this.getEngineByExtension(extension);
    +                     if (engine != null)
    +                     {
    +                        this.executeScript(engine, file);
    +                     }
    +                  }
    +               }
    +               catch (FileNotFoundException e)
    +               {
    +                  // should never happen
    +                  e.printStackTrace();
    +               }
    +               catch (ScriptException e)
    +               {
    +                  this.reportScriptFileError(file, e);
    +                  // e.printStackTrace();
    +               }
    +            }
    +         }
    +      }
    +      else
    +      {
    +         throw new IllegalArgumentException("The argument directory either doesnt exists or is not an directory.");
    +      }
    +   }
    +   
    +   public void executeScript(File file) throws ScriptException, FileNotFoundException
    +   {
    +      String name = file.getName();
    +      int lastIndex = name.lastIndexOf('.');
    +      String extension;
    +      if (lastIndex != -1)
    +      {
    +         extension = name.substring(lastIndex + 1);
    +      }
    +      else
    +      {
    +         throw new ScriptException("Script file (" + name + ") doesnt has an extension that identifies the ScriptEngine to be used.");
    +      }
    +      
    +      ScriptEngine engine = this.getEngineByExtension(extension);
    +      if (engine == null)
    +      {
    +         throw new ScriptException("No engine registered for extension (" + extension + ")");
    +      }
    +      else
    +      {
    +         this.executeScript(engine, file);
    +      }
    +   }
    +   
    +   public void executeScript(String engineName, File file) throws FileNotFoundException, ScriptException
    +   {
    +      ScriptEngine engine = this.getEngineByName(engineName);
    +      if (engine == null)
    +      {
    +         throw new ScriptException("No engine registered with name (" + engineName + ")");
    +      }
    +      else
    +      {
    +         this.executeScript(engine, file);
    +      }
    +   }
    +   
    +   public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException
    +   {
    +      BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    +      
    +      if (VERBOSE_LOADING)
    +      {
    +         _log.info("Loading Script: " + file.getAbsolutePath());
    +      }
    +      
    +      if (PURGE_ERROR_LOG)
    +      {
    +         String name = file.getAbsolutePath() + ".error.log";
    +         File errorLog = new File(name);
    +         if (errorLog.isFile())
    +         {
    +            errorLog.delete();
    +         }
    +      }
    +      
    +      if ((engine instanceof Compilable) && ATTEMPT_COMPILATION)
    +      {
    +         ScriptContext context = new SimpleScriptContext();
    +         context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE);
    +         context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
    +         context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
    +         context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
    +         
    +         this.setCurrentLoadingScript(file);
    +         try
    +         {
    +            Compilable eng = (Compilable) engine;
    +            CompiledScript cs = eng.compile(reader);
    +            cs.eval(context);
    +         }
    +         finally
    +         {
    +            this.setCurrentLoadingScript(null);
    +            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
    +            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
    +         }
    +      }
    +      else
    +      {
    +         ScriptContext context = new SimpleScriptContext();
    +         context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE);
    +         context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
    +         context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
    +         context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
    +         this.setCurrentLoadingScript(file);
    +         try
    +         {
    +            engine.eval(reader, context);
    +         }
    +         finally
    +         {
    +            this.setCurrentLoadingScript(null);
    +            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
    +            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
    +         }
    +         
    +      }
    +   }
    +   
    +   public static String getClassForFile(File script)
    +   {
    +      String path = script.getAbsolutePath();
    +      String scpPath = SCRIPT_FOLDER.getAbsolutePath();
    +      if (path.startsWith(scpPath))
    +      {
    +         int idx = path.lastIndexOf('.');
    +         return path.substring(scpPath.length() + 1, idx);
    +      }
    +      return null;
    +   }
    +   
    +   public ScriptContext getScriptContext(ScriptEngine engine)
    +   {
    +      return engine.getContext();
    +   }
    +   
    +   public ScriptContext getScriptContext(String engineName)
    +   {
    +      ScriptEngine engine = this.getEngineByName(engineName);
    +      if (engine == null)
    +      {
    +         throw new IllegalStateException("No engine registered with name (" + engineName + ")");
    +      }
    +      else
    +      {
    +         return this.getScriptContext(engine);
    +      }
    +   }
    +   
    +   public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
    +   {
    +      if ((engine instanceof Compilable) && ATTEMPT_COMPILATION)
    +      {
    +         Compilable eng = (Compilable) engine;
    +         CompiledScript cs = eng.compile(script);
    +         return context != null ? cs.eval(context) : cs.eval();
    +      }
    +      else
    +      {
    +         return context != null ? engine.eval(script, context) : engine.eval(script);
    +      }
    +   }
    +   
    +   public Object eval(String engineName, String script) throws ScriptException
    +   {
    +      return this.eval(engineName, script, null);
    +   }
    +   
    +   public Object eval(String engineName, String script, ScriptContext context) throws ScriptException
    +   {
    +      ScriptEngine engine = this.getEngineByName(engineName);
    +      if (engine == null)
    +      {
    +         throw new ScriptException("No engine registered with name (" + engineName + ")");
    +      }
    +      else
    +      {
    +         return this.eval(engine, script, context);
    +      }
    +   }
    +   
    +   public Object eval(ScriptEngine engine, String script) throws ScriptException
    +   {
    +      return this.eval(engine, script, null);
    +   }
    +   
    +   public void reportScriptFileError(File script, ScriptException e)
    +   {
    +      String dir = script.getParent();
    +      String name = script.getName() + ".error.log";
    +      if (dir != null)
    +      {
    +         File file = new File(dir + "/" + name);
    +         
    +         try
    +         {
    +            if (!file.exists())
    +            {
    +               file.createNewFile();
    +            }
    +            
    +            FileOutputStream fos = new FileOutputStream(file);
    +            String errorHeader = "Error on: " + file.getCanonicalPath() + "\r\nLine: " + e.getLineNumber() + " - Column: " + e.getColumnNumber() + "\r\n\r\n";
    +            fos.write(errorHeader.getBytes());
    +            fos.write(e.getMessage().getBytes());
    +            fos.flush();
    +            fos.close();
    +            _log.warning("Failed executing script: " + script.getAbsolutePath() + ". See " + file.getName() + " for details.");
    +         }
    +         catch (IOException ioe)
    +         {
    +            _log.warning("Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage() + "Additionally failed when trying to write an error report on script directory. Reason: " + ioe.getMessage());
    +            ioe.printStackTrace();
    +         }
    +      }
    +      else
    +      {
    +         _log.warning("Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage() + "Additionally failed when trying to write an error report on script directory.");
    +      }
    +   }
    +   
    +   public void registerScriptManager(ScriptManager<?> manager)
    +   {
    +      _scriptManagers.add(manager);
    +   }
    +   
    +   public void removeScriptManager(ScriptManager<?> manager)
    +   {
    +      _scriptManagers.remove(manager);
    +   }
    +   
    +   public List<ScriptManager<?>> getScriptManagers()
    +   {
    +      return _scriptManagers;
    +      
    +   }
    +   
    +   /**
    +    * @param currentLoadingScript The currentLoadingScript to set.
    +    */
    +   protected void setCurrentLoadingScript(File currentLoadingScript)
    +   {
    +      _currentLoadingScript = currentLoadingScript;
    +   }
    +   
    +   /**
    +    * @return Returns the currentLoadingScript.
    +    */
    +   protected File getCurrentLoadingScript()
    +   {
    +      return _currentLoadingScript;
    +   }
    +   
    +}
    Index: /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/handler/admincommandhandlers/AdminQuest.java
    ===================================================================
    --- /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/handler/admincommandhandlers/AdminQuest.java   (revision 35)
    +++ /trunk/Micro_GameServer/java/net/sf/l2j/gameserver/handler/admincommandhandlers/AdminQuest.java   (revision 36)
    @@ -29,10 +29,13 @@
     package net.sf.l2j.gameserver.handler.admincommandhandlers;
     
    +import java.io.File;
     import java.util.StringTokenizer;
    +
    +import javax.script.ScriptException;
     
     import net.sf.l2j.Config;
     import net.sf.l2j.gameserver.handler.IAdminCommandHandler;
    -import net.sf.l2j.gameserver.instancemanager.QuestManager;
     import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
    +import net.sf.l2j.gameserver.scripting.L2ScriptEngineManager;
     
     public class AdminQuest implements IAdminCommandHandler
    @@ -72,5 +75,35 @@
           if (actualCommand.equalsIgnoreCase("admin_quest_reload"))
           {
    -         QuestManager.getInstance().reload();
    +         String[] parts = command.split(" ");
    +         if (parts.length < 2)
    +         {
    +            // activeChar.sendMessage("Example: //script_load <questFolder>/<questSubFolders...>/<filename>.<ext> ");
    +            activeChar.sendMessage("Example: //script_load quests/SagasSuperclass/__init__.py");
    +         }
    +         else
    +         {
    +            File file = new File(L2ScriptEngineManager.SCRIPT_FOLDER, parts[1]);
    +            if (file.isFile())
    +            {
    +               try
    +               {
    +                  L2ScriptEngineManager.getInstance().executeScript(file);
    +               }
    +               catch (ScriptException e)
    +               {
    +                  activeChar.sendMessage("Failed loading: " + parts[1]);
    +                  L2ScriptEngineManager.getInstance().reportScriptFileError(file, e);
    +               }
    +               catch (Exception e)
    +               {
    +                  activeChar.sendMessage("Failed loading: " + parts[1]);
    +               }
    +            }
    +            else
    +            {
    +               activeChar.sendMessage("File Not Found: " + parts[1]);
    +            }
    +         }
    +         
           }
           return true;

    micr0

    Posts : 72
    Join date : 2013-01-23
    Age : 23
    Location : Bulgaria

    Re: Java Code in DataPack Folder :D

    Post  micr0 on 17th February 2013, 03:14

    Full Version

    http://pastebin.com/zLEm82E8

    jar
    Java engine
    Jython Engine

    StartGameServer.bat
    java -Xmx1024m -cp bsf.jar;bsh-2.0.jar;javolution.jar;c3p0-0.9.0.jar;mysql-connector-java-3.1.10-bin.jar;sqljdbc.jar;L2JLisvus.jar;jython.jar;jython-engine-2.2.1.jar net.sf.l2j.gameserver.GameServer
    avatar
    DnR
    Admin
    Admin

    Posts : 1023
    Join date : 2012-12-03

    Re: Java Code in DataPack Folder :D

    Post  DnR on 17th February 2013, 20:32

    Thanks a lot for your share. ^_^
    Let me tell you that i' m going to test it in order to adapt it.
    You can keep using it, so as to provide us with feedback.
    Thanks again.

    Myazz

    Posts : 2
    Join date : 2013-02-23

    Re: Java Code in DataPack Folder :D

    Post  Myazz on 12th April 2013, 20:06

    Bump.

    Added java code in dp folder Razz
    avatar
    Pandragon

    Posts : 19
    Join date : 2013-04-26

    Re: Java Code in DataPack Folder :D

    Post  Pandragon on 26th April 2013, 21:19

    Anyone tried to import quests/boss AIs from acis?
    ^^

    micr0

    Posts : 72
    Join date : 2013-01-23
    Age : 23
    Location : Bulgaria

    Re: Java Code in DataPack Folder :D

    Post  micr0 on 27th April 2013, 22:01

    yes will be nice

    Setekh

    Posts : 1
    Join date : 2013-05-25

    Re: Java Code in DataPack Folder :D

    Post  Setekh on 25th May 2013, 12:04

    I strongly suggest using groovy, then that naive implementation.
    avatar
    DnR
    Admin
    Admin

    Posts : 1023
    Join date : 2012-12-03

    Re: Java Code in DataPack Folder :D

    Post  DnR on 13th May 2014, 20:11

    Script Engine updated, even though it took quite long.
    Thanks for suggesting. Case closed.
    avatar
    Pandragon

    Posts : 19
    Join date : 2013-04-26

    Re: Java Code in DataPack Folder :D

    Post  Pandragon on 16th May 2014, 12:30

    Need to make datapack a Java Project, add src path data\scripts and link it with server.

    These are the settings I use, adapted from latest L2J Beta.

    http://www20.zippyshare.com/v/2696794/file.html
    avatar
    DnR
    Admin
    Admin

    Posts : 1023
    Join date : 2012-12-03

    Re: Java Code in DataPack Folder :D

    Post  DnR on 17th May 2014, 12:25

    Ah i see.
    Thanks a lot. Smile

    Sponsored content

    Re: Java Code in DataPack Folder :D

    Post  Sponsored content


      Current date/time is 25th September 2017, 21:54