Updated scripting engine to match newer branches.

This commit is contained in:
MobiusDev 2018-04-03 19:14:20 +00:00
parent 81d82a90ac
commit 52dc86e25d
24 changed files with 1359 additions and 1625 deletions

View File

@ -1,247 +0,0 @@
# This file contains a list of scripts that should be loaded by the GameServer
# The path is relative to the scripts folder, for example scripts/event.java would
# require the following entry:
# event.java
#
# Note: You can also load an script during server runtime using the Admin Panel
# Load Handlers
handlers/MasterHandler.java
# AI Section
# Npc
ai/npc/Abercrombie/Abercrombie.java
ai/npc/Alarm/Alarm.java
ai/npc/Alexandria/Alexandria.java
ai/npc/ArenaManager/ArenaManager.java
ai/npc/Asamah/Asamah.java
ai/npc/AvantGarde/AvantGarde.java
ai/npc/BlackJudge/BlackJudge.java
ai/npc/BlackMarketeerOfMammon/BlackMarketeerOfMammon.java
ai/npc/CastleAmbassador/CastleAmbassador.java
ai/npc/CastleBlacksmith/CastleBlacksmith.java
ai/npc/CastleCourtMagician/CastleCourtMagician.java
ai/npc/CastleChamberlain/CastleChamberlain.java
ai/npc/CastleMercenaryManager/CastleMercenaryManager.java
ai/npc/CastleSiegeManager/CastleSiegeManager.java
ai/npc/CastleTeleporter/CastleTeleporter.java
ai/npc/CastleWarehouse/CastleWarehouse.java
ai/npc/ClanTrader/ClanTrader.java
ai/npc/Dorian/Dorian.java
ai/npc/DragonVortex/DragonVortex.java
ai/npc/FameManager/FameManager.java
ai/npc/ForgeOfTheGods/ForgeOfTheGods.java
ai/npc/ForgeOfTheGods/Rooney.java
ai/npc/ForgeOfTheGods/TarBeetle.java
ai/npc/FortressArcherCaptain/FortressArcherCaptain.java
ai/npc/FortressSiegeManager/FortressSiegeManager.java
ai/npc/FreyasSteward/FreyasSteward.java
ai/npc/Jinia/Jinia.java
ai/npc/Katenar/Katenar.java
ai/npc/KetraOrcSupport/KetraOrcSupport.java
ai/npc/Kier/Kier.java
ai/npc/ManorManager/ManorManager.java
ai/npc/MercenaryCaptain/MercenaryCaptain.java
ai/npc/Minigame/Minigame.java
ai/npc/MonumentOfHeroes/MonumentOfHeroes.java
ai/npc/NevitsHerald/NevitsHerald.java
ai/npc/NpcBuffers/NpcBuffers.java
ai/npc/NpcBuffers/impl/CabaleBuffer.java
ai/npc/PriestOfBlessing/PriestOfBlessing.java
ai/npc/Rignos/Rignos.java
ai/npc/Rafforty/Rafforty.java
ai/npc/Selina/Selina.java
ai/npc/Sirra/Sirra.java
ai/npc/SubclassCertification/SubclassCertification.java
ai/npc/Summons/MerchantGolem/GolemTrader.java
ai/npc/Summons/Servitors/Servitors.java
ai/npc/SupportUnitCaptain/SupportUnitCaptain.java
ai/npc/SymbolMaker/SymbolMaker.java
ai/npc/Teleports/Asher/Asher.java
ai/npc/Teleports/CrumaTower/CrumaTower.java
ai/npc/Teleports/DelusionTeleport/DelusionTeleport.java
ai/npc/Teleports/ElrokiTeleporters/ElrokiTeleporters.java
ai/npc/Teleports/GatekeeperSpirit/GatekeeperSpirit.java
ai/npc/Teleports/GrandBossTeleporters/GrandBossTeleporters.java
ai/npc/Teleports/HuntingGroundsTeleport/HuntingGroundsTeleport.java
ai/npc/Teleports/Klemis/Klemis.java
ai/npc/Teleports/MithrilMinesTeleporter/MithrilMinesTeleporter.java
ai/npc/Teleports/NewbieTravelToken/NewbieTravelToken.java
ai/npc/Teleports/NoblesseTeleport/NoblesseTeleport.java
ai/npc/Teleports/OracleTeleport/OracleTeleport.java
ai/npc/Teleports/PaganTeleporters/PaganTeleporters.java
ai/npc/Teleports/SeparatedSoul/SeparatedSoul.java
ai/npc/Teleports/StakatoNestTeleporter/StakatoNestTeleporter.java
ai/npc/Teleports/SteelCitadelTeleport/SteelCitadelTeleport.java
ai/npc/Teleports/StrongholdsTeleports/StrongholdsTeleports.java
ai/npc/Teleports/Survivor/Survivor.java
ai/npc/Teleports/TeleportToFantasy/TeleportToFantasy.java
ai/npc/Teleports/TeleportToRaceTrack/TeleportToRaceTrack.java
ai/npc/Teleports/TeleportToUndergroundColiseum/TeleportToUndergroundColiseum.java
ai/npc/Teleports/TeleportWithCharm/TeleportWithCharm.java
ai/npc/Teleports/ToIVortex/ToIVortex.java
ai/npc/TerritoryManagers/TerritoryManagers.java
ai/npc/TownPets/TownPets.java
ai/npc/Trainers/HealerTrainer/HealerTrainer.java
ai/npc/Tunatun/Tunatun.java
ai/npc/VarkaSilenosSupport/VarkaSilenosSupport.java
ai/npc/VillageMasters/FirstClassTransferTalk/FirstClassTransferTalk.java
ai/npc/WeaverOlf/WeaverOlf.java
ai/npc/WyvernManager/WyvernManager.java
# Fantasy Isle
ai/fantasy_isle/HandysBlockCheckerEvent.java
ai/fantasy_isle/Parade.java
ai/fantasy_isle/TalentShow.java
# Group Template
ai/group_template/AltarsOfSacrifice.java
ai/group_template/BeastFarm.java
ai/group_template/DenOfEvil.java
ai/group_template/DragonValley.java
ai/group_template/FairyTrees.java
ai/group_template/FeedableBeasts.java
ai/group_template/FleeMonsters.java
ai/group_template/FrozenLabyrinth.java
ai/group_template/GiantsCave.java
ai/group_template/HotSprings.java
ai/group_template/IsleOfPrayer.java
ai/group_template/LairOfAntharas.java
ai/group_template/MinionSpawnManager.java
ai/group_template/MonasteryOfSilence.java
ai/group_template/NonLethalableNpcs.java
ai/group_template/NonTalkingNpcs.java
ai/group_template/PavelArchaic.java
ai/group_template/PlainsOfDion.java
ai/group_template/PlainsOfLizardman.java
ai/group_template/PolymorphingAngel.java
ai/group_template/PolymorphingOnAttack.java
ai/group_template/PrimevalIsle.java
ai/group_template/PrisonGuards.java
ai/group_template/RandomSpawn.java
# ai/group_template/RangeGuard.java
ai/group_template/Remnants.java
ai/group_template/Sandstorms.java
ai/group_template/SeeThroughSilentMove.java
ai/group_template/SelMahumDrill.java
ai/group_template/SelMahumSquad.java
ai/group_template/SilentValley.java
ai/group_template/StakatoNest.java
ai/group_template/SummonPc.java
ai/group_template/TurekOrcs.java
ai/group_template/VarkaKetra.java
ai/group_template/WarriorFishingBlock.java
# Individual
ai/individual/Antharas/Antharas.java
ai/individual/Baium/Baium.java
ai/individual/Sailren/Sailren.java
ai/individual/Venom/Venom.java
ai/individual/Anais.java
ai/individual/Ballista.java
ai/individual/Beleth.java
ai/individual/BlackdaggerWing.java
ai/individual/BleedingFly.java
ai/individual/CrimsonHatuOtis.java
ai/individual/Core.java
ai/individual/DarkWaterDragon.java
ai/individual/DivineBeast.java
ai/individual/DrChaos.java
ai/individual/DustRider.java
ai/individual/EmeraldHorn.java
ai/individual/Epidos.java
ai/individual/EvasGiftBox.java
ai/individual/FrightenedRagnaOrc.java
ai/individual/Gordon.java
ai/individual/GraveRobbers.java
ai/individual/MuscleBomber.java
ai/individual/Orfen.java
ai/individual/QueenAnt.java
ai/individual/QueenShyeed.java
ai/individual/RagnaOrcCommander.java
ai/individual/RagnaOrcHero.java
ai/individual/RagnaOrcSeer.java
ai/individual/ScarletVanHalisha.java
ai/individual/ShadowSummoner.java
ai/individual/SinEater.java
ai/individual/SinWardens.java
ai/individual/Valakas.java
# Village Master
village_master/Clan/Clan.java
village_master/Alliance/Alliance.java
village_master/DarkElfChange1/DarkElfChange1.java
village_master/DarkElfChange2/DarkElfChange2.java
village_master/DwarfBlacksmithChange1/DwarfBlacksmithChange1.java
village_master/DwarfBlacksmithChange2/DwarfBlacksmithChange2.java
village_master/DwarfWarehouseChange1/DwarfWarehouseChange1.java
village_master/DwarfWarehouseChange2/DwarfWarehouseChange2.java
village_master/ElfHumanClericChange2/ElfHumanClericChange2.java
village_master/ElfHumanFighterChange1/ElfHumanFighterChange1.java
village_master/ElfHumanFighterChange2/ElfHumanFighterChange2.java
village_master/ElfHumanWizardChange1/ElfHumanWizardChange1.java
village_master/ElfHumanWizardChange2/ElfHumanWizardChange2.java
village_master/KamaelChange1/KamaelChange1.java
village_master/KamaelChange2/KamaelChange2.java
village_master/OrcChange1/OrcChange1.java
village_master/OrcChange2/OrcChange2.java
# Instance Section
instances/InstanceLoader.java
# Gracia Section
gracia/GraciaLoader.java
# Hellbound Section
hellbound/HellboundLoader.java
# Quests Section
quests/QuestMasterHandler.java
quests/TerritoryWarScripts/TerritoryWarSuperClass.java
# Features
features/SkillTransfer/SkillTransfer.java
# Custom
custom/EchoCrystals/EchoCrystals.java
custom/ShadowWeapons/ShadowWeapons.java
custom/NewbieCoupons/NewbieCoupons.java
custom/RaidbossInfo/RaidbossInfo.java
custom/NpcLocationInfo/NpcLocationInfo.java
custom/Validators/SubClassSkills.java
custom/NpcBuffer/NpcBuffer.java
# Custom Events
custom/events/Elpies/Elpies.java
custom/events/Rabbits/Rabbits.java
custom/events/Race/Race.java
custom/events/TvT/TvTManager/TvTManager.java
custom/events/Wedding/Wedding.java
# Vehicles
vehicles/BoatTalkingGludin.java
vehicles/BoatGiranTalking.java
vehicles/BoatInnadrilTour.java
vehicles/BoatGludinRune.java
vehicles/BoatRunePrimeval.java
# Conquerable Clan Halls
conquerablehalls/flagwar/BanditStronghold/BanditStronghold.java
conquerablehalls/flagwar/WildBeastReserve/WildBeastReserve.java
conquerablehalls/DevastatedCastle/DevastatedCastle.java
conquerablehalls/FortressOfResistance/FortressOfResistance.java
conquerablehalls/FortressOfTheDead/FortressOfTheDead.java
conquerablehalls/RainbowSpringsChateau/RainbowSpringsChateau.java
# Events
events/CharacterBirthday/CharacterBirthday.java
# Disabled by default events
#events/L2Day/L2Day.java
#events/GiftOfVitality/GiftOfVitality.java
#events/HeavyMedal/HeavyMedal.java
#events/TheValentineEvent/TheValentineEvent.java
#events/FreyaCelebration/FreyaCelebration.java
#events/MasterOfEnchanting/MasterOfEnchanting.java
#events/LoveYourGatekeeper/LoveYourGatekeeper.java

View File

@ -1,8 +0,0 @@
Most of the scripts found within the "scripts" folder are initialized on server start, but
do not run anything except when triggered by a player. For scripts that need to be ran
automatically, without any player interaction, cron can be used.
Using the format demonstrated in the example.py script, one can setup tasks that run
automatically at server boot. In addition, advanced users can include other classes from java
and setup timed tasks, such as special events that have universal drops for a certain period of time.
The server admins can feel free to add more folders like cron and include them in their servers.

View File

@ -1,5 +0,0 @@
##############################################
### Author: Layane (andrashe@gmail.com)
##############################################
print "Hi world!"

View File

@ -340,9 +340,4 @@ public final class PailakaDevilsLegacy extends AbstractInstance
}
teleportPlayer(player, TELEPORT, world.getInstanceId());
}
public static void main(String[] args)
{
new PailakaDevilsLegacy();
}
}

View File

@ -17,8 +17,6 @@
package quests.TerritoryWarScripts;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import com.l2jmobius.gameserver.instancemanager.CastleManager;
import com.l2jmobius.gameserver.instancemanager.GlobalVariablesManager;
@ -48,10 +46,6 @@ import quests.Q00176_StepsForHonor.Q00176_StepsForHonor;
*/
public class TerritoryWarSuperClass extends Quest
{
private static Map<Integer, TerritoryWarSuperClass> _forTheSakeScripts = new HashMap<>();
private static Map<Integer, TerritoryWarSuperClass> _protectTheScripts = new HashMap<>();
private static Map<Integer, TerritoryWarSuperClass> _killTheScripts = new HashMap<>();
// "For the Sake of the Territory ..." quests variables
public int CATAPULT_ID;
public int TERRITORY_ID;
@ -253,7 +247,7 @@ public class TerritoryWarSuperClass extends Quest
if (territoryId > 0)
{
// register Territory Quest
final TerritoryWarSuperClass territoryQuest = _forTheSakeScripts.get(territoryId);
final TerritoryWarSuperClass territoryQuest = TerritoryWarSuperClassLoader.getForTheSakeScripts().get(territoryId);
QuestState st = player.getQuestState(territoryQuest.getName());
if (st == null)
{
@ -265,7 +259,7 @@ public class TerritoryWarSuperClass extends Quest
// register player on Death
if (player.getLevel() >= 61)
{
final TerritoryWarSuperClass killthe = _killTheScripts.get(player.getClassId().getId());
final TerritoryWarSuperClass killthe = TerritoryWarSuperClassLoader.getKillTheScripts().get(player.getClassId().getId());
if (killthe != null)
{
st = player.getQuestState(killthe.getName());
@ -379,7 +373,7 @@ public class TerritoryWarSuperClass extends Quest
{
if (player.getSiegeSide() > 0)
{
final TerritoryWarSuperClass territoryQuest = _forTheSakeScripts.get(player.getSiegeSide());
final TerritoryWarSuperClass territoryQuest = TerritoryWarSuperClassLoader.getForTheSakeScripts().get(player.getSiegeSide());
if (territoryQuest == null)
{
continue;
@ -393,7 +387,7 @@ public class TerritoryWarSuperClass extends Quest
// register player on Death
if (player.getLevel() >= 61)
{
final TerritoryWarSuperClass killthe = _killTheScripts.get(player.getClassId().getId());
final TerritoryWarSuperClass killthe = TerritoryWarSuperClassLoader.getKillTheScripts().get(player.getClassId().getId());
if (killthe != null)
{
st = player.getQuestState(killthe.getName());
@ -412,7 +406,7 @@ public class TerritoryWarSuperClass extends Quest
else
{
st.exitQuest(false);
for (Quest q : _protectTheScripts.values())
for (Quest q : TerritoryWarSuperClassLoader.getProtectTheScripts().values())
{
st = player.getQuestState(q.getName());
if (st != null)
@ -421,7 +415,7 @@ public class TerritoryWarSuperClass extends Quest
}
}
// unregister player on Death
final TerritoryWarSuperClass killthe = _killTheScripts.get(player.getClassIndex());
final TerritoryWarSuperClass killthe = TerritoryWarSuperClassLoader.getKillTheScripts().get(player.getClassIndex());
if (killthe != null)
{
st = player.getQuestState(killthe.getName());
@ -506,68 +500,4 @@ public class TerritoryWarSuperClass extends Quest
}
}
}
public static void main(String[] args)
{
// initialize superclass
new TerritoryWarSuperClass(-1, TerritoryWarSuperClass.class.getSimpleName(), "Territory War Superclass");
// initialize subclasses
// "For The Sake" quests
final TerritoryWarSuperClass gludio = new Q00717_ForTheSakeOfTheTerritoryGludio();
_forTheSakeScripts.put(gludio.TERRITORY_ID, gludio);
final TerritoryWarSuperClass dion = new Q00718_ForTheSakeOfTheTerritoryDion();
_forTheSakeScripts.put(dion.TERRITORY_ID, dion);
final TerritoryWarSuperClass giran = new Q00719_ForTheSakeOfTheTerritoryGiran();
_forTheSakeScripts.put(giran.TERRITORY_ID, giran);
final TerritoryWarSuperClass oren = new Q00720_ForTheSakeOfTheTerritoryOren();
_forTheSakeScripts.put(oren.TERRITORY_ID, oren);
final TerritoryWarSuperClass aden = new Q00721_ForTheSakeOfTheTerritoryAden();
_forTheSakeScripts.put(aden.TERRITORY_ID, aden);
final TerritoryWarSuperClass innadril = new Q00722_ForTheSakeOfTheTerritoryInnadril();
_forTheSakeScripts.put(innadril.TERRITORY_ID, innadril);
final TerritoryWarSuperClass goddard = new Q00723_ForTheSakeOfTheTerritoryGoddard();
_forTheSakeScripts.put(goddard.TERRITORY_ID, goddard);
final TerritoryWarSuperClass rune = new Q00724_ForTheSakeOfTheTerritoryRune();
_forTheSakeScripts.put(rune.TERRITORY_ID, rune);
final TerritoryWarSuperClass schuttgart = new Q00725_ForTheSakeOfTheTerritorySchuttgart();
_forTheSakeScripts.put(schuttgart.TERRITORY_ID, schuttgart);
// "Protect the" quests
final TerritoryWarSuperClass catapult = new Q00729_ProtectTheTerritoryCatapult();
_protectTheScripts.put(catapult.getId(), catapult);
final TerritoryWarSuperClass supplies = new Q00730_ProtectTheSuppliesSafe();
_protectTheScripts.put(supplies.getId(), supplies);
final TerritoryWarSuperClass military = new Q00731_ProtectTheMilitaryAssociationLeader();
_protectTheScripts.put(military.getId(), military);
final TerritoryWarSuperClass religious = new Q00732_ProtectTheReligiousAssociationLeader();
_protectTheScripts.put(religious.getId(), religious);
final TerritoryWarSuperClass economic = new Q00733_ProtectTheEconomicAssociationLeader();
_protectTheScripts.put(economic.getId(), economic);
// "Kill" quests
final TerritoryWarSuperClass knights = new Q00734_PierceThroughAShield();
for (int i : knights.CLASS_IDS)
{
_killTheScripts.put(i, knights);
}
final TerritoryWarSuperClass warriors = new Q00735_MakeSpearsDull();
for (int i : warriors.CLASS_IDS)
{
_killTheScripts.put(i, warriors);
}
final TerritoryWarSuperClass wizards = new Q00736_WeakenTheMagic();
for (int i : wizards.CLASS_IDS)
{
_killTheScripts.put(i, wizards);
}
final TerritoryWarSuperClass priests = new Q00737_DenyBlessings();
for (int i : priests.CLASS_IDS)
{
_killTheScripts.put(i, priests);
}
final TerritoryWarSuperClass keys = new Q00738_DestroyKeyTargets();
for (int i : keys.CLASS_IDS)
{
_killTheScripts.put(i, keys);
}
}
}

View File

@ -0,0 +1,109 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 quests.TerritoryWarScripts;
import java.util.HashMap;
import java.util.Map;
/**
* @author Mobius
*/
public class TerritoryWarSuperClassLoader
{
private static Map<Integer, TerritoryWarSuperClass> _forTheSakeScripts = new HashMap<>();
private static Map<Integer, TerritoryWarSuperClass> _protectTheScripts = new HashMap<>();
private static Map<Integer, TerritoryWarSuperClass> _killTheScripts = new HashMap<>();
public static Map<Integer, TerritoryWarSuperClass> getForTheSakeScripts()
{
return _forTheSakeScripts;
}
public static Map<Integer, TerritoryWarSuperClass> getProtectTheScripts()
{
return _protectTheScripts;
}
public static Map<Integer, TerritoryWarSuperClass> getKillTheScripts()
{
return _killTheScripts;
}
public static void main(String[] args)
{
// initialize superclass
new TerritoryWarSuperClass(-1, TerritoryWarSuperClass.class.getSimpleName(), "Territory War Superclass");
// initialize subclasses
// "For The Sake" quests
final TerritoryWarSuperClass gludio = new Q00717_ForTheSakeOfTheTerritoryGludio();
_forTheSakeScripts.put(gludio.TERRITORY_ID, gludio);
final TerritoryWarSuperClass dion = new Q00718_ForTheSakeOfTheTerritoryDion();
_forTheSakeScripts.put(dion.TERRITORY_ID, dion);
final TerritoryWarSuperClass giran = new Q00719_ForTheSakeOfTheTerritoryGiran();
_forTheSakeScripts.put(giran.TERRITORY_ID, giran);
final TerritoryWarSuperClass oren = new Q00720_ForTheSakeOfTheTerritoryOren();
_forTheSakeScripts.put(oren.TERRITORY_ID, oren);
final TerritoryWarSuperClass aden = new Q00721_ForTheSakeOfTheTerritoryAden();
_forTheSakeScripts.put(aden.TERRITORY_ID, aden);
final TerritoryWarSuperClass innadril = new Q00722_ForTheSakeOfTheTerritoryInnadril();
_forTheSakeScripts.put(innadril.TERRITORY_ID, innadril);
final TerritoryWarSuperClass goddard = new Q00723_ForTheSakeOfTheTerritoryGoddard();
_forTheSakeScripts.put(goddard.TERRITORY_ID, goddard);
final TerritoryWarSuperClass rune = new Q00724_ForTheSakeOfTheTerritoryRune();
_forTheSakeScripts.put(rune.TERRITORY_ID, rune);
final TerritoryWarSuperClass schuttgart = new Q00725_ForTheSakeOfTheTerritorySchuttgart();
_forTheSakeScripts.put(schuttgart.TERRITORY_ID, schuttgart);
// "Protect the" quests
final TerritoryWarSuperClass catapult = new Q00729_ProtectTheTerritoryCatapult();
_protectTheScripts.put(catapult.getId(), catapult);
final TerritoryWarSuperClass supplies = new Q00730_ProtectTheSuppliesSafe();
_protectTheScripts.put(supplies.getId(), supplies);
final TerritoryWarSuperClass military = new Q00731_ProtectTheMilitaryAssociationLeader();
_protectTheScripts.put(military.getId(), military);
final TerritoryWarSuperClass religious = new Q00732_ProtectTheReligiousAssociationLeader();
_protectTheScripts.put(religious.getId(), religious);
final TerritoryWarSuperClass economic = new Q00733_ProtectTheEconomicAssociationLeader();
_protectTheScripts.put(economic.getId(), economic);
// "Kill" quests
final TerritoryWarSuperClass knights = new Q00734_PierceThroughAShield();
for (int i : knights.CLASS_IDS)
{
_killTheScripts.put(i, knights);
}
final TerritoryWarSuperClass warriors = new Q00735_MakeSpearsDull();
for (int i : warriors.CLASS_IDS)
{
_killTheScripts.put(i, warriors);
}
final TerritoryWarSuperClass wizards = new Q00736_WeakenTheMagic();
for (int i : wizards.CLASS_IDS)
{
_killTheScripts.put(i, wizards);
}
final TerritoryWarSuperClass priests = new Q00737_DenyBlessings();
for (int i : priests.CLASS_IDS)
{
_killTheScripts.put(i, priests);
}
final TerritoryWarSuperClass keys = new Q00738_DestroyKeyTargets();
for (int i : keys.CLASS_IDS)
{
_killTheScripts.put(i, keys);
}
}
}

View File

@ -32,7 +32,7 @@ import com.l2jmobius.gameserver.scripting.ScriptEngineManager;
*/
public final class QuestManager
{
protected static final Logger _log = Logger.getLogger(QuestManager.class.getName());
protected static final Logger LOGGER = Logger.getLogger(QuestManager.class.getName());
/** Map containing all the quests. */
private final Map<String, Quest> _quests = new ConcurrentHashMap<>();
@ -41,7 +41,6 @@ public final class QuestManager
protected QuestManager()
{
// Prevent initialization.
}
public boolean reload(String questFolder)
@ -75,7 +74,7 @@ public final class QuestManager
*/
public void reloadAllScripts()
{
_log.info(getClass().getSimpleName() + ": Reloading all server scripts.");
LOGGER.info("Reloading all server scripts.");
// Unload quests.
for (Quest quest : _quests.values())
@ -102,7 +101,7 @@ public final class QuestManager
}
catch (Exception e)
{
_log.log(Level.SEVERE, getClass().getSimpleName() + ": Failed loading scripts.cfg, no script going to be loaded!", e);
LOGGER.log(Level.SEVERE, "Failed loading scripts.cfg, no script going to be loaded!", e);
}
QuestManager.getInstance().report();
@ -113,8 +112,8 @@ public final class QuestManager
*/
public void report()
{
_log.info(getClass().getSimpleName() + ": Loaded: " + _quests.size() + " quests.");
_log.info(getClass().getSimpleName() + ": Loaded: " + _scripts.size() + " scripts.");
LOGGER.info(getClass().getSimpleName() + ": Loaded: " + _quests.size() + " quests.");
LOGGER.info(getClass().getSimpleName() + ": Loaded: " + _scripts.size() + " scripts.");
}
/**
@ -191,13 +190,13 @@ public final class QuestManager
if (old != null)
{
old.unload();
_log.info(getClass().getSimpleName() + ": Replaced quest " + old.getName() + " (" + old.getId() + ") with a new version!");
LOGGER.info("Replaced quest " + old.getName() + " (" + old.getId() + ") with a new version!");
}
if (Config.ALT_DEV_SHOW_QUESTS_LOAD_IN_LOGS)
{
final String questName = quest.getName().contains("_") ? quest.getName().substring(quest.getName().indexOf('_') + 1) : quest.getName();
_log.info("Loaded quest " + CommonUtil.splitWords(questName) + ".");
LOGGER.info("Loaded quest " + CommonUtil.splitWords(questName) + ".");
}
}
@ -213,7 +212,7 @@ public final class QuestManager
_quests.remove(script.getName());
return true;
}
if (_scripts.containsKey(script.getName()))
else if (_scripts.containsKey(script.getName()))
{
_scripts.remove(script.getName());
return true;
@ -251,12 +250,12 @@ public final class QuestManager
if (old != null)
{
old.unload();
_log.info(getClass().getSimpleName() + ": Replaced script " + old.getName() + " with a new version!");
LOGGER.info("Replaced script " + old.getName() + " with a new version!");
}
if (Config.ALT_DEV_SHOW_SCRIPTS_LOAD_IN_LOGS)
{
_log.info("Loaded script " + CommonUtil.splitWords(script.getClass().getSimpleName()) + ".");
LOGGER.info("Loaded script " + CommonUtil.splitWords(script.getClass().getSimpleName()) + ".");
}
}

View File

@ -16,6 +16,7 @@
*/
package com.l2jmobius.gameserver.model.quest;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -66,6 +67,7 @@ import com.l2jmobius.gameserver.model.zone.L2ZoneType;
import com.l2jmobius.gameserver.network.serverpackets.ActionFailed;
import com.l2jmobius.gameserver.network.serverpackets.NpcHtmlMessage;
import com.l2jmobius.gameserver.network.serverpackets.NpcQuestHtmlMessage;
import com.l2jmobius.gameserver.scripting.ScriptEngineManager;
/**
* Quest main class.
@ -2524,6 +2526,12 @@ public class Quest extends AbstractScript implements IIdentifiable
return getName();
}
@Override
public Path getScriptPath()
{
return ScriptEngineManager.getInstance().getCurrentLoadingScript();
}
@Override
public void setActive(boolean status)
{

View File

@ -1,75 +1,75 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(final T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(final Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(final String key, final String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(final String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
* @param <T>
*/
public abstract class AbstractExecutionContext<T extends IScriptingEngine> implements IExecutionContext
{
private final T _engine;
private final Map<String, String> _properties;
private volatile Path _currentExecutingScipt;
protected AbstractExecutionContext(T engine)
{
if (engine == null)
{
throw new IllegalArgumentException();
}
_engine = engine;
_properties = new HashMap<>();
}
protected final void setCurrentExecutingScript(Path currentExecutingScript)
{
_currentExecutingScipt = currentExecutingScript;
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
if (!_properties.containsKey(key))
{
return _engine.getProperty(key);
}
return _properties.get(key);
}
@Override
public final Path getCurrentExecutingScript()
{
return _currentExecutingScipt;
}
@Override
public final T getScriptingEngine()
{
return _engine;
}
}

View File

@ -1,74 +1,74 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(final String engineName, final String engineVersion, final String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(final String key, final String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(final String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author HorridoJoho
*/
public abstract class AbstractScriptingEngine implements IScriptingEngine
{
private final String _engineName;
private final String _engineVersion;
private final String[] _commonFileExtensions;
private final Map<String, String> _properties;
protected AbstractScriptingEngine(String engineName, String engineVersion, String... commonFileExtensions)
{
if ((engineName == null) || engineName.isEmpty() || (engineVersion == null) || engineVersion.isEmpty() || (commonFileExtensions == null) || (commonFileExtensions.length == 0))
{
throw new IllegalArgumentException();
}
_engineName = engineName;
_engineVersion = engineVersion;
_commonFileExtensions = commonFileExtensions;
_properties = new HashMap<>();
}
@Override
public final String setProperty(String key, String value)
{
return _properties.put(key, value);
}
@Override
public final String getProperty(String key)
{
return _properties.get(key);
}
@Override
public final String getEngineName()
{
return _engineName;
}
@Override
public final String getEngineVersion()
{
return _engineVersion;
}
@Override
public final String[] getCommonFileExtensions()
{
return Arrays.copyOf(_commonFileExtensions, _commonFileExtensions.length);
}
}

View File

@ -1,71 +1,71 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.nio.file.Path;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author HorridoJoho
*/
public interface IExecutionContext
{
/**
* Properties set here override the settings from the IScriptEngine<br>
* this class was created from.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Executes all script in the iterable.
* @param sourcePaths the scripts to execute
* @return map of failed executions, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception;
/**
* Executes a single file.
* @param sourcePath the script to execute
* @return entry of failed execution, Path=source file Throwable=thrown exception
* @throws Exception preparation for script execution failed
*/
Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception;
/**
* Method to get the specified property value.
* @param key the key
* @return the value, or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the current executing script file.
* @return the currently executing script file, null if non
*/
Path getCurrentExecutingScript();
/**
* Method to get the script engine this execution context belongs to.
* @return the script engine this execution context belongs to
*/
IScriptingEngine getScriptingEngine();
}

View File

@ -1,75 +1,75 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
/**
* @author HorridoJoho
*/
public interface IScriptingEngine
{
/**
* Sets script engine properties. The script values will be available<br>
* to the the insatnces created {@link IExecutionContext} implementation.
* @param key the key
* @param value the value
* @return the previous value, or null when this key was not present before
*/
String setProperty(String key, String value);
/**
* Creates an execution context.
* @return the created execution context.
*/
IExecutionContext createExecutionContext();
/**
* Method to get the specified property value.
* @param key the key
* @return the value,or null if the key is not present
*/
String getProperty(String key);
/**
* Method to get the engine name.
* @return the engine name
*/
String getEngineName();
/**
* Method to get the engine version.
* @return the engine version
*/
String getEngineVersion();
/**
* Method to get the scripting language name.
* @return the scripting engine name
*/
String getLanguageName();
/**
* Method to get the the language version.
* @return the language version
*/
String getLanguageVersion();
/**
* Method to retrive the commonly used file extensions for the language.
* @return the commonly used file extensions for the language
*/
String[] getCommonFileExtensions();
}

View File

@ -34,10 +34,12 @@ public abstract class ManagedScript
public ManagedScript()
{
_scriptFile = ScriptEngineManager.getInstance().getCurrentLoadingScript();
_scriptFile = getScriptPath();
setLastLoadTime(System.currentTimeMillis());
}
public abstract Path getScriptPath();
/**
* 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.

View File

@ -16,12 +16,12 @@
*/
package com.l2jmobius.gameserver.scripting;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
@ -30,7 +30,6 @@ import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -43,11 +42,13 @@ import com.l2jmobius.gameserver.scripting.java.JavaScriptingEngine;
*/
public final class ScriptEngineManager
{
private static final Logger _log = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_LIST_FILE = Paths.get(Config.DATAPACK_ROOT.getAbsolutePath(), "data", "scripts.cfg");
private static final Logger LOGGER = Logger.getLogger(ScriptEngineManager.class.getName());
public static final Path SCRIPT_FOLDER = Paths.get(Config.DATAPACK_ROOT.getAbsolutePath(), "data", "scripts");
public static final Path MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "MasterHandler.java");
public static final Path EFFECT_MASTER_HANDLER_FILE = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "EffectMasterHandler.java");
public static final Path SKILL_CONDITION_HANDLER_FILE = Paths.get(ScriptEngineManager.SCRIPT_FOLDER.toString(), "handlers", "SkillConditionMasterHandler.java");
public static final Path CONDITION_HANDLER_FILE = Paths.get(ScriptEngineManager.SCRIPT_FOLDER.toString(), "handlers", "ConditionMasterHandler.java");
public static final Path ONE_DAY_REWARD_MASTER_HANDLER = Paths.get(SCRIPT_FOLDER.toString(), "handlers", "DailyMissionMasterHandler.java");
private final Map<String, IExecutionContext> _extEngines = new HashMap<>();
private IExecutionContext _currentExecutionContext = null;
@ -74,7 +75,7 @@ public final class ScriptEngineManager
catch (Exception e)
{
props = null;
_log.warning("Couldn't load ScriptEngines.ini: " + e.getMessage());
LOGGER.warning("Couldn't load ScriptEngines.properties: " + e.getMessage());
}
return props;
}
@ -88,7 +89,7 @@ public final class ScriptEngineManager
_extEngines.put(commonExtension, context);
}
_log.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
LOGGER.info("ScriptEngine: " + engine.getEngineName() + " " + engine.getEngineVersion() + " (" + engine.getLanguageName() + " " + engine.getLanguageVersion() + ")");
}
private void maybeSetProperties(String propPrefix, Properties props, IScriptingEngine engine)
@ -98,7 +99,7 @@ public final class ScriptEngineManager
return;
}
for (final Entry<Object, Object> prop : props.entrySet())
for (Entry<Object, Object> prop : props.entrySet())
{
String key = (String) prop.getKey();
String value = (String) prop.getValue();
@ -161,6 +162,21 @@ public final class ScriptEngineManager
executeScript(EFFECT_MASTER_HANDLER_FILE);
}
public void executeSkillConditionMasterHandler() throws Exception
{
executeScript(SKILL_CONDITION_HANDLER_FILE);
}
public void executeConditionMasterHandler() throws Exception
{
executeScript(CONDITION_HANDLER_FILE);
}
public void executeDailyMissionMasterHandler() throws Exception
{
executeScript(ONE_DAY_REWARD_MASTER_HANDLER);
}
public void executeScriptList() throws Exception
{
if (Config.ALT_DEV_NO_QUESTS)
@ -168,61 +184,18 @@ public final class ScriptEngineManager
return;
}
// throws exception if not exists or not file
checkExistingFile("ScriptList", SCRIPT_LIST_FILE);
final Map<IExecutionContext, List<Path>> files = new LinkedHashMap<>();
final Set<String> extWithoutEngine = new HashSet<>();
Files.lines(SCRIPT_LIST_FILE).forEach(line ->
{
line = line.trim();
if (line.isEmpty() || (line.charAt(0) == '#'))
{
return;
}
Path sourceFile = SCRIPT_FOLDER.resolve(line);
try
{
checkExistingFile("ScriptFile", sourceFile);
}
catch (Exception e)
{
_log.warning(e.getMessage());
return;
}
sourceFile = sourceFile.toAbsolutePath();
final String ext = getFileExtension(sourceFile);
if (ext == null)
{
_log.warning("ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
return;
}
final IExecutionContext engine = getEngineByExtension(ext);
if (engine == null)
{
if (extWithoutEngine.add(ext))
{
_log.warning("ScriptEngine: No engine registered for extension " + ext + "!");
}
return;
}
files.computeIfAbsent(engine, k -> new LinkedList<>()).add(sourceFile);
});
processDirectory(SCRIPT_FOLDER.toFile(), files);
for (Entry<IExecutionContext, List<Path>> entry : files.entrySet())
{
_currentExecutionContext = entry.getKey();
try
{
Map<Path, Throwable> invokationErrors = entry.getKey().executeScripts(entry.getValue());
final Map<Path, Throwable> invokationErrors = entry.getKey().executeScripts(entry.getValue());
for (Entry<Path, Throwable> entry2 : invokationErrors.entrySet())
{
_log.log(Level.WARNING, "ScriptEngine: " + entry2.getKey() + " failed execution!", entry2.getValue());
LOGGER.log(Level.WARNING, "ScriptEngine: " + entry2.getKey() + " failed execution!", entry2.getValue());
}
}
finally
@ -232,6 +205,64 @@ public final class ScriptEngineManager
}
}
private void processDirectory(File dir, Map<IExecutionContext, List<Path>> files)
{
for (File file : dir.listFiles())
{
if (file.isDirectory())
{
processDirectory(file, files);
}
else
{
processFile(file, files);
}
}
}
private void processFile(File file, Map<IExecutionContext, List<Path>> files)
{
switch (file.getName())
{
case "package-info.java":
case "MasterHandler.java":
case "EffectMasterHandler.java":
case "SkillConditionMasterHandler.java":
case "ConditionMasterHandler.java":
case "DailyMissionMasterHandler.java":
{
return;
}
}
Path sourceFile = file.toPath();
try
{
checkExistingFile("ScriptFile", sourceFile);
}
catch (Exception e)
{
LOGGER.warning(e.getMessage());
return;
}
sourceFile = sourceFile.toAbsolutePath();
final String ext = getFileExtension(sourceFile);
if (ext == null)
{
LOGGER.warning("ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
return;
}
final IExecutionContext engine = getEngineByExtension(ext);
if (engine == null)
{
return;
}
files.computeIfAbsent(engine, k -> new LinkedList<>()).add(sourceFile);
}
public void executeScript(Path sourceFile) throws Exception
{
Objects.requireNonNull(sourceFile);
@ -245,16 +276,16 @@ public final class ScriptEngineManager
checkExistingFile("ScriptFile", sourceFile);
sourceFile = sourceFile.toAbsolutePath();
String ext = getFileExtension(sourceFile);
final String ext = getFileExtension(sourceFile);
Objects.requireNonNull(sourceFile, "ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
IExecutionContext engine = getEngineByExtension(ext);
final IExecutionContext engine = getEngineByExtension(ext);
Objects.requireNonNull(engine, "ScriptEngine: No engine registered for extension " + ext + "!");
_currentExecutionContext = engine;
try
{
Entry<Path, Throwable> error = engine.executeScript(sourceFile);
final Entry<Path, Throwable> error = engine.executeScript(sourceFile);
if (error != null)
{
throw new Exception("ScriptEngine: " + error.getKey() + " failed execution!", error.getValue());
@ -266,9 +297,9 @@ public final class ScriptEngineManager
}
}
protected Path getCurrentLoadingScript()
public Path getCurrentLoadingScript()
{
return _currentExecutionContext.getCurrentExecutingScript();
return _currentExecutionContext != null ? _currentExecutionContext.getCurrentExecutingScript() : null;
}
public static ScriptEngineManager getInstance()

View File

@ -1,47 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting;
import java.util.Map;
import com.l2jmobius.gameserver.model.events.AbstractScript;
/**
* @author KenM
* @param <S>
*/
public abstract class ScriptManager<S extends AbstractScript>
{
public abstract Map<String, S> getScripts();
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();
}

View File

@ -1,25 +1,32 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 cron;
public class example
{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author UnAfraid
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Disabled
{
}

View File

@ -1,30 +1,28 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
private static final long serialVersionUID = -8330513514176036095L;
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
/**
* @author HorridoJoho
*/
public final class JavaCompilerException extends RuntimeException
{
public JavaCompilerException(String diagnostics)
{
super(diagnostics);
}
}

View File

@ -1,240 +1,255 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
/**
* @author HorridoJoho
*/
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine>
{
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
JavaExecutionContext(final JavaScriptingEngine engine)
{
super(engine);
}
private boolean addOptionIfNotNull(List<String> list, String nullChecked, String before)
{
if (nullChecked == null)
{
return false;
}
if (before.endsWith(":"))
{
list.add(before + nullChecked);
}
else
{
list.add(before);
list.add(nullChecked);
}
return true;
}
private ClassLoader determineScriptParentClassloader()
{
String classloader = getProperty("classloader");
if (classloader == null)
{
return ClassLoader.getSystemClassLoader();
}
switch (classloader)
{
case "ThreadContext":
{
return Thread.currentThread().getContextClassLoader();
}
case "System":
{
return ClassLoader.getSystemClassLoader();
}
default:
{
try
{
return Class.forName(classloader).getClassLoader();
}
catch (ClassNotFoundException e)
{
return ClassLoader.getSystemClassLoader();
}
}
}
}
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (final ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{
final List<String> options = new LinkedList<>();
addOptionIfNotNull(options, getProperty("source"), "-source");
addOptionIfNotNull(options, getProperty("sourcepath"), "-sourcepath");
if (!addOptionIfNotNull(options, getProperty("cp"), "-cp") && !addOptionIfNotNull(options, getProperty("classpath"), "-classpath"))
{
addOptionIfNotNull(options, System.getProperty("java.class.path"), "-cp");
}
addOptionIfNotNull(options, getProperty("g"), "-g:");
// we always add the target JVM to the current running version
final String targetVersion = System.getProperty("java.specification.version");
if (!targetVersion.contains("."))
{
options.add("-target");
options.add(targetVersion);
}
else
{
String[] versionSplit = targetVersion.split("\\.");
if (versionSplit.length > 1)
{
options.add("-target");
options.add(versionSplit[0] + '.' + versionSplit[1]);
}
else
{
throw new JavaCompilerException("Could not determine target version!");
}
}
// we really need an iterable of files or strings
final List<String> sourcePathStrings = new LinkedList<>();
for (Path sourcePath : sourcePaths)
{
sourcePathStrings.add(sourcePath.toString());
}
final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess)
{
out.println();
out.println("----------------");
out.println("File diagnostics");
out.println("----------------");
for (Diagnostic<? extends JavaFileObject> diagnostic : fileManagerDiagnostics.getDiagnostics())
{
out.println("\t" + diagnostic.getKind() + ": " + diagnostic.getSource().getName() + ", Line " + diagnostic.getLineNumber() + ", Column " + diagnostic.getColumnNumber());
out.println("\t\tcode: " + diagnostic.getCode());
out.println("\t\tmessage: " + diagnostic.getMessage(null));
}
out.println();
out.println("-----------------------");
out.println("Compilation diagnostics");
out.println("-----------------------");
for (Diagnostic<? extends JavaFileObject> diagnostic : compilationDiagnostics.getDiagnostics())
{
out.println("\t" + diagnostic.getKind() + ": " + diagnostic.getSource().getName() + ", Line " + diagnostic.getLineNumber() + ", Column " + diagnostic.getColumnNumber());
out.println("\t\tcode: " + diagnostic.getCode());
out.println("\t\tmessage: " + diagnostic.getMessage(null));
}
throw new JavaCompilerException(strOut.toString());
}
final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths)
{
boolean found = false;
for (ScriptingOutputFileObject compiledClass : compiledClasses)
{
Path compiledSourcePath = compiledClass.getSourcePath();
// sourePath can be relative, so we have to use endsWith
if ((compiledSourcePath != null) && (compiledSourcePath.equals(sourcePath) || compiledSourcePath.endsWith(sourcePath)))
{
String javaName = compiledClass.getJavaName();
if (javaName.indexOf('$') != -1)
{
continue;
}
found = true;
setCurrentExecutingScript(compiledSourcePath);
try
{
ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
Class<?> javaCls = loader.loadClass(javaName);
javaCls.getMethod("main", String[].class).invoke(null, (Object) new String[]
{
compiledSourcePath.toString()
});
}
catch (Exception e)
{
executionFailures.put(compiledSourcePath, e);
}
finally
{
setCurrentExecutingScript(null);
}
break;
}
}
if (!found)
{
LOGGER.severe("Compilation successfull, but class coresponding to " + sourcePath.toString() + " not found!");
}
}
return executionFailures;
}
}
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
if (!executionFailures.isEmpty())
{
return executionFailures.entrySet().iterator().next();
}
return null;
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import com.l2jmobius.gameserver.scripting.AbstractExecutionContext;
import com.l2jmobius.gameserver.scripting.annotations.Disabled;
/**
* @author HorridoJoho
*/
public final class JavaExecutionContext extends AbstractExecutionContext<JavaScriptingEngine>
{
private static final Logger LOGGER = Logger.getLogger(JavaExecutionContext.class.getName());
JavaExecutionContext(JavaScriptingEngine engine)
{
super(engine);
}
private boolean addOptionIfNotNull(List<String> list, String nullChecked, String before)
{
if (nullChecked == null)
{
return false;
}
if (before.endsWith(":"))
{
list.add(before + nullChecked);
}
else
{
list.add(before);
list.add(nullChecked);
}
return true;
}
private ClassLoader determineScriptParentClassloader()
{
final String classloader = getProperty("classloader");
if (classloader == null)
{
return ClassLoader.getSystemClassLoader();
}
switch (classloader)
{
case "ThreadContext":
{
return Thread.currentThread().getContextClassLoader();
}
case "System":
{
return ClassLoader.getSystemClassLoader();
}
default:
{
try
{
return Class.forName(classloader).getClassLoader();
}
catch (ClassNotFoundException e)
{
return ClassLoader.getSystemClassLoader();
}
}
}
}
@Override
public Map<Path, Throwable> executeScripts(Iterable<Path> sourcePaths) throws Exception
{
final DiagnosticCollector<JavaFileObject> fileManagerDiagnostics = new DiagnosticCollector<>();
final DiagnosticCollector<JavaFileObject> compilationDiagnostics = new DiagnosticCollector<>();
try (ScriptingFileManager fileManager = new ScriptingFileManager(getScriptingEngine().getCompiler().getStandardFileManager(fileManagerDiagnostics, null, StandardCharsets.UTF_8)))
{
final List<String> options = new LinkedList<>();
addOptionIfNotNull(options, getProperty("source"), "-source");
addOptionIfNotNull(options, getProperty("sourcepath"), "-sourcepath");
if (!addOptionIfNotNull(options, getProperty("cp"), "-cp") && !addOptionIfNotNull(options, getProperty("classpath"), "-classpath"))
{
addOptionIfNotNull(options, System.getProperty("java.class.path"), "-cp");
}
addOptionIfNotNull(options, getProperty("g"), "-g:");
// we always add the target JVM to the current running version
final String targetVersion = System.getProperty("java.specification.version");
if (!targetVersion.contains("."))
{
options.add("-target");
options.add(targetVersion);
}
else
{
final String[] versionSplit = targetVersion.split("\\.");
if (versionSplit.length > 1)
{
options.add("-target");
options.add(versionSplit[0] + '.' + versionSplit[1]);
}
else
{
throw new JavaCompilerException("Could not determine target version!");
}
}
// we really need an iterable of files or strings
final List<String> sourcePathStrings = new LinkedList<>();
for (Path sourcePath : sourcePaths)
{
sourcePathStrings.add(sourcePath.toString());
}
final StringWriter strOut = new StringWriter();
final PrintWriter out = new PrintWriter(strOut);
final boolean compilationSuccess = getScriptingEngine().getCompiler().getTask(out, fileManager, compilationDiagnostics, options, null, fileManager.getJavaFileObjectsFromStrings(sourcePathStrings)).call();
if (!compilationSuccess)
{
out.println();
out.println("----------------");
out.println("File diagnostics");
out.println("----------------");
for (Diagnostic<? extends JavaFileObject> diagnostic : fileManagerDiagnostics.getDiagnostics())
{
out.println("\t" + diagnostic.getKind() + ": " + diagnostic.getSource().getName() + ", Line " + diagnostic.getLineNumber() + ", Column " + diagnostic.getColumnNumber());
out.println("\t\tcode: " + diagnostic.getCode());
out.println("\t\tmessage: " + diagnostic.getMessage(null));
}
out.println();
out.println("-----------------------");
out.println("Compilation diagnostics");
out.println("-----------------------");
for (Diagnostic<? extends JavaFileObject> diagnostic : compilationDiagnostics.getDiagnostics())
{
out.println("\t" + diagnostic.getKind() + ": " + diagnostic.getSource().getName() + ", Line " + diagnostic.getLineNumber() + ", Column " + diagnostic.getColumnNumber());
out.println("\t\tcode: " + diagnostic.getCode());
out.println("\t\tmessage: " + diagnostic.getMessage(null));
}
throw new JavaCompilerException(strOut.toString());
}
final ClassLoader parentClassLoader = determineScriptParentClassloader();
final Map<Path, Throwable> executionFailures = new LinkedHashMap<>();
final Iterable<ScriptingOutputFileObject> compiledClasses = fileManager.getCompiledClasses();
for (Path sourcePath : sourcePaths)
{
boolean found = false;
for (ScriptingOutputFileObject compiledClass : compiledClasses)
{
final Path compiledSourcePath = compiledClass.getSourcePath();
// sourePath can be relative, so we have to use endsWith
if ((compiledSourcePath != null) && (compiledSourcePath.equals(sourcePath) || compiledSourcePath.endsWith(sourcePath)))
{
final String javaName = compiledClass.getJavaName();
if (javaName.indexOf('$') != -1)
{
continue;
}
found = true;
setCurrentExecutingScript(compiledSourcePath);
try
{
final ScriptingClassLoader loader = new ScriptingClassLoader(parentClassLoader, compiledClasses);
final Class<?> javaClass = loader.loadClass(javaName);
Method mainMethod = null;
for (Method m : javaClass.getMethods())
{
if (m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && (m.getParameterCount() == 1) && (m.getParameterTypes()[0] == String[].class))
{
mainMethod = m;
break;
}
}
if ((mainMethod != null) && !javaClass.isAnnotationPresent(Disabled.class))
{
mainMethod.invoke(null, (Object) new String[]
{
compiledSourcePath.toString()
});
}
}
catch (Exception e)
{
executionFailures.put(compiledSourcePath, e);
}
finally
{
setCurrentExecutingScript(null);
}
break;
}
}
if (!found)
{
LOGGER.severe("Compilation successfull, but class coresponding to " + sourcePath.toString() + " not found!");
}
}
return executionFailures;
}
}
@Override
public Entry<Path, Throwable> executeScript(Path sourcePath) throws Exception
{
final Map<Path, Throwable> executionFailures = executeScripts(Arrays.asList(sourcePath));
if (!executionFailures.isEmpty())
{
return executionFailures.entrySet().iterator().next();
}
return null;
}
}

View File

@ -1,138 +1,138 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ServiceLoader;
import javax.lang.model.SourceVersion;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/**
* @author HorridoJoho
*/
public final class JavaScriptingEngine extends AbstractScriptingEngine
{
private volatile JavaCompiler _compiler;
public JavaScriptingEngine()
{
super("L2J Java Engine", "1.0", "java");
}
private void determineCompilerOrThrow()
{
final String preferedCompiler = getProperty("preferedCompiler");
LinkedList<JavaCompiler> allCompilers = null;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler != null)
{
if ((preferedCompiler == null) || compiler.getClass().getName().equals(preferedCompiler))
{
_compiler = compiler;
return;
}
allCompilers = new LinkedList<>();
allCompilers.add(compiler);
}
final ServiceLoader<JavaCompiler> thirdPartyCompilers = ServiceLoader.load(JavaCompiler.class);
Iterator<JavaCompiler> compilersIterator = thirdPartyCompilers.iterator();
while (compilersIterator.hasNext())
{
compiler = compilersIterator.next();
if ((preferedCompiler == null) || compiler.getClass().getName().equals(preferedCompiler))
{
_compiler = compiler;
return;
}
if (allCompilers == null)
{
allCompilers = new LinkedList<>();
}
allCompilers.add(compilersIterator.next());
}
if (allCompilers != null)
{
compilersIterator = allCompilers.iterator();
while (compilersIterator.hasNext())
{
compiler = compilersIterator.next();
if ((preferedCompiler == null) || compiler.getClass().getName().equals(preferedCompiler))
{
break;
}
}
}
if (compiler == null)
{
throw new IllegalStateException("No javax.tools.JavaCompiler service installed!");
}
_compiler = compiler;
}
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{
if (_compiler == null)
{
determineCompilerOrThrow();
}
}
}
}
JavaCompiler getCompiler()
{
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this);
}
@Override
public String getLanguageName()
{
return "Java";
}
@Override
public String getLanguageVersion()
{
ensureCompilerOrThrow();
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ServiceLoader;
import javax.lang.model.SourceVersion;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import com.l2jmobius.gameserver.scripting.AbstractScriptingEngine;
import com.l2jmobius.gameserver.scripting.IExecutionContext;
/**
* @author HorridoJoho
*/
public final class JavaScriptingEngine extends AbstractScriptingEngine
{
private volatile JavaCompiler _compiler;
public JavaScriptingEngine()
{
super("L2J Java Engine", "1.0", "java");
}
private void determineCompilerOrThrow()
{
final String preferedCompiler = getProperty("preferedCompiler");
LinkedList<JavaCompiler> allCompilers = null;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler != null)
{
if ((preferedCompiler == null) || compiler.getClass().getName().equals(preferedCompiler))
{
_compiler = compiler;
return;
}
allCompilers = new LinkedList<>();
allCompilers.add(compiler);
}
final ServiceLoader<JavaCompiler> thirdPartyCompilers = ServiceLoader.load(JavaCompiler.class);
Iterator<JavaCompiler> compilersIterator = thirdPartyCompilers.iterator();
while (compilersIterator.hasNext())
{
compiler = compilersIterator.next();
if ((preferedCompiler == null) || compiler.getClass().getName().equals(preferedCompiler))
{
_compiler = compiler;
return;
}
if (allCompilers == null)
{
allCompilers = new LinkedList<>();
}
allCompilers.add(compilersIterator.next());
}
if (allCompilers != null)
{
compilersIterator = allCompilers.iterator();
while (compilersIterator.hasNext())
{
compiler = compilersIterator.next();
if ((preferedCompiler == null) || compiler.getClass().getName().equals(preferedCompiler))
{
break;
}
}
}
if (compiler == null)
{
throw new IllegalStateException("No javax.tools.JavaCompiler service installed!");
}
_compiler = compiler;
}
private void ensureCompilerOrThrow()
{
if (_compiler == null)
{
synchronized (this)
{
if (_compiler == null)
{
determineCompilerOrThrow();
}
}
}
}
JavaCompiler getCompiler()
{
return _compiler;
}
@Override
public IExecutionContext createExecutionContext()
{
ensureCompilerOrThrow();
return new JavaExecutionContext(this);
}
@Override
public String getLanguageName()
{
return "Java";
}
@Override
public String getLanguageVersion()
{
ensureCompilerOrThrow();
return Arrays.deepToString(_compiler.getSourceVersions().toArray(new SourceVersion[0])).replace("RELEASE_", "");
}
}

View File

@ -1,55 +1,55 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.util.logging.Logger;
/**
* @author HorridoJoho
*/
public final class ScriptingClassLoader extends ClassLoader
{
public static final Logger LOGGER = Logger.getLogger(ScriptingClassLoader.class.getName());
private Iterable<ScriptingOutputFileObject> _compiledClasses;
ScriptingClassLoader(final ClassLoader parent, final Iterable<ScriptingOutputFileObject> compiledClasses)
{
super(parent);
_compiledClasses = compiledClasses;
}
void removeCompiledClasses()
{
_compiledClasses = null;
}
@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException
{
for (final ScriptingOutputFileObject compiledClass : _compiledClasses)
{
if (compiledClass.getJavaName().equals(name))
{
final byte[] classBytes = compiledClass.getJavaData();
return defineClass(name, classBytes, 0, classBytes.length);
}
}
return super.findClass(name);
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.util.logging.Logger;
/**
* @author HorridoJoho
*/
public final class ScriptingClassLoader extends ClassLoader
{
public static final Logger LOGGER = Logger.getLogger(ScriptingClassLoader.class.getName());
private Iterable<ScriptingOutputFileObject> _compiledClasses;
ScriptingClassLoader(ClassLoader parent, Iterable<ScriptingOutputFileObject> compiledClasses)
{
super(parent);
_compiledClasses = compiledClasses;
}
void removeCompiledClasses()
{
_compiledClasses = null;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
for (ScriptingOutputFileObject compiledClass : _compiledClasses)
{
if (compiledClass.getJavaName().equals(name))
{
final byte[] classBytes = compiledClass.getJavaData();
return defineClass(name, classBytes, 0, classBytes.length);
}
}
return super.findClass(name);
}
}

View File

@ -1,185 +1,185 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardJavaFileManager;
/**
* @author HorridoJoho
*/
final class ScriptingFileManager implements StandardJavaFileManager
{
private final StandardJavaFileManager _wrapped;
private final LinkedList<ScriptingOutputFileObject> _classOutputs = new LinkedList<>();
public ScriptingFileManager(StandardJavaFileManager wrapped)
{
_wrapped = wrapped;
}
Iterable<ScriptingOutputFileObject> getCompiledClasses()
{
return Collections.unmodifiableCollection(_classOutputs);
}
@Override
public int isSupportedOption(String option)
{
return _wrapped.isSupportedOption(option);
}
@Override
public ClassLoader getClassLoader(Location location)
{
return _wrapped.getClassLoader(location);
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException
{
return _wrapped.list(location, packageName, kinds, recurse);
}
@Override
public String inferBinaryName(Location location, JavaFileObject file)
{
return _wrapped.inferBinaryName(location, file);
}
@Override
public boolean isSameFile(FileObject a, FileObject b)
{
return _wrapped.isSameFile(a, b);
}
@Override
public boolean handleOption(String current, Iterator<String> remaining)
{
return _wrapped.handleOption(current, remaining);
}
@Override
public boolean hasLocation(Location location)
{
return _wrapped.hasLocation(location);
}
@Override
public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException
{
return _wrapped.getJavaFileForInput(location, className, kind);
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException
{
if (kind != Kind.CLASS)
{
return _wrapped.getJavaFileForOutput(location, className, kind, sibling);
}
if (className.contains("/"))
{
className = className.replace('/', '.');
}
ScriptingOutputFileObject fileObject;
if (sibling != null)
{
fileObject = new ScriptingOutputFileObject(Paths.get(sibling.getName()), className, className.substring(className.lastIndexOf('.') + 1));
}
else
{
fileObject = new ScriptingOutputFileObject(null, className, className.substring(className.lastIndexOf('.') + 1));
}
_classOutputs.add(fileObject);
return fileObject;
}
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException
{
return _wrapped.getFileForInput(location, packageName, relativeName);
}
@Override
public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException
{
return _wrapped.getFileForOutput(location, packageName, relativeName, sibling);
}
@Override
public void flush() throws IOException
{
_wrapped.flush();
}
@Override
public void close() throws IOException
{
_wrapped.close();
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files)
{
return _wrapped.getJavaFileObjectsFromFiles(files);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files)
{
return _wrapped.getJavaFileObjects(files);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names)
{
return _wrapped.getJavaFileObjectsFromStrings(names);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names)
{
return _wrapped.getJavaFileObjects(names);
}
@Override
public void setLocation(Location location, Iterable<? extends File> path) throws IOException
{
_wrapped.setLocation(location, path);
}
@Override
public Iterable<? extends File> getLocation(Location location)
{
return _wrapped.getLocation(location);
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardJavaFileManager;
/**
* @author HorridoJoho
*/
final class ScriptingFileManager implements StandardJavaFileManager
{
private final StandardJavaFileManager _wrapped;
private final LinkedList<ScriptingOutputFileObject> _classOutputs = new LinkedList<>();
public ScriptingFileManager(StandardJavaFileManager wrapped)
{
_wrapped = wrapped;
}
Iterable<ScriptingOutputFileObject> getCompiledClasses()
{
return Collections.unmodifiableCollection(_classOutputs);
}
@Override
public int isSupportedOption(String option)
{
return _wrapped.isSupportedOption(option);
}
@Override
public ClassLoader getClassLoader(Location location)
{
return _wrapped.getClassLoader(location);
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException
{
return _wrapped.list(location, packageName, kinds, recurse);
}
@Override
public String inferBinaryName(Location location, JavaFileObject file)
{
return _wrapped.inferBinaryName(location, file);
}
@Override
public boolean isSameFile(FileObject a, FileObject b)
{
return _wrapped.isSameFile(a, b);
}
@Override
public boolean handleOption(String current, Iterator<String> remaining)
{
return _wrapped.handleOption(current, remaining);
}
@Override
public boolean hasLocation(Location location)
{
return _wrapped.hasLocation(location);
}
@Override
public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException
{
return _wrapped.getJavaFileForInput(location, className, kind);
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException
{
if (kind != Kind.CLASS)
{
return _wrapped.getJavaFileForOutput(location, className, kind, sibling);
}
if (className.contains("/"))
{
className = className.replace('/', '.');
}
ScriptingOutputFileObject fileObject;
if (sibling != null)
{
fileObject = new ScriptingOutputFileObject(Paths.get(sibling.getName()), className, className.substring(className.lastIndexOf('.') + 1));
}
else
{
fileObject = new ScriptingOutputFileObject(null, className, className.substring(className.lastIndexOf('.') + 1));
}
_classOutputs.add(fileObject);
return fileObject;
}
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException
{
return _wrapped.getFileForInput(location, packageName, relativeName);
}
@Override
public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException
{
return _wrapped.getFileForOutput(location, packageName, relativeName, sibling);
}
@Override
public void flush() throws IOException
{
_wrapped.flush();
}
@Override
public void close() throws IOException
{
_wrapped.close();
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files)
{
return _wrapped.getJavaFileObjectsFromFiles(files);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files)
{
return _wrapped.getJavaFileObjects(files);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names)
{
return _wrapped.getJavaFileObjectsFromStrings(names);
}
@Override
public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names)
{
return _wrapped.getJavaFileObjects(names);
}
@Override
public void setLocation(Location location, Iterable<? extends File> path) throws IOException
{
_wrapped.setLocation(location, path);
}
@Override
public Iterable<? extends File> getLocation(Location location)
{
return _wrapped.getLocation(location);
}
}

View File

@ -1,147 +1,147 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.nio.file.Path;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.tools.JavaFileObject;
/**
* @author HorridoJoho
*/
final class ScriptingOutputFileObject implements JavaFileObject
{
private final Path _sourcePath;
private final String _javaName;
private final String _javaSimpleName;
private final ByteArrayOutputStream _out;
public ScriptingOutputFileObject(Path sourcePath, String javaName, String javaSimpleName)
{
_sourcePath = sourcePath;
_javaName = javaName;
_javaSimpleName = javaSimpleName;
_out = new ByteArrayOutputStream();
}
public Path getSourcePath()
{
return _sourcePath;
}
public String getJavaName()
{
return _javaName;
}
public String getJavaSimpleName()
{
return _javaSimpleName;
}
public byte[] getJavaData()
{
return _out.toByteArray();
}
@Override
public URI toUri()
{
return null;
}
@Override
public String getName()
{
return null;
}
@Override
public InputStream openInputStream()
{
return null;
}
@Override
public OutputStream openOutputStream()
{
return _out;
}
@Override
public Reader openReader(boolean ignoreEncodingErrors)
{
return null;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
{
return null;
}
@Override
public Writer openWriter()
{
return null;
}
@Override
public long getLastModified()
{
return 0;
}
@Override
public boolean delete()
{
return false;
}
@Override
public Kind getKind()
{
return Kind.CLASS;
}
@Override
public boolean isNameCompatible(String simpleName, Kind kind)
{
return (kind == Kind.CLASS) && (_javaSimpleName == simpleName);
}
@Override
public NestingKind getNestingKind()
{
return NestingKind.TOP_LEVEL;
}
@Override
public Modifier getAccessLevel()
{
return null;
}
}
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.scripting.java;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.nio.file.Path;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.tools.JavaFileObject;
/**
* @author HorridoJoho
*/
final class ScriptingOutputFileObject implements JavaFileObject
{
private final Path _sourcePath;
private final String _javaName;
private final String _javaSimpleName;
private final ByteArrayOutputStream _out;
public ScriptingOutputFileObject(Path sourcePath, String javaName, String javaSimpleName)
{
_sourcePath = sourcePath;
_javaName = javaName;
_javaSimpleName = javaSimpleName;
_out = new ByteArrayOutputStream();
}
public Path getSourcePath()
{
return _sourcePath;
}
public String getJavaName()
{
return _javaName;
}
public String getJavaSimpleName()
{
return _javaSimpleName;
}
public byte[] getJavaData()
{
return _out.toByteArray();
}
@Override
public URI toUri()
{
return null;
}
@Override
public String getName()
{
return null;
}
@Override
public InputStream openInputStream()
{
return null;
}
@Override
public OutputStream openOutputStream()
{
return _out;
}
@Override
public Reader openReader(boolean ignoreEncodingErrors)
{
return null;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
{
return null;
}
@Override
public Writer openWriter()
{
return null;
}
@Override
public long getLastModified()
{
return 0;
}
@Override
public boolean delete()
{
return false;
}
@Override
public Kind getKind()
{
return Kind.CLASS;
}
@Override
public boolean isNameCompatible(String simpleName, Kind kind)
{
return (kind == Kind.CLASS) && (_javaSimpleName == simpleName);
}
@Override
public NestingKind getNestingKind()
{
return NestingKind.TOP_LEVEL;
}
@Override
public Modifier getAccessLevel()
{
return null;
}
}

View File

@ -47,7 +47,6 @@ import com.l2jmobius.gameserver.taskmanager.tasks.TaskOlympiadSave;
import com.l2jmobius.gameserver.taskmanager.tasks.TaskRaidPointsReset;
import com.l2jmobius.gameserver.taskmanager.tasks.TaskRecom;
import com.l2jmobius.gameserver.taskmanager.tasks.TaskRestart;
import com.l2jmobius.gameserver.taskmanager.tasks.TaskScript;
import com.l2jmobius.gameserver.taskmanager.tasks.TaskSevenSignsUpdate;
import com.l2jmobius.gameserver.taskmanager.tasks.TaskShutdown;
@ -184,7 +183,6 @@ public final class TaskManager
registerTask(new TaskRaidPointsReset());
registerTask(new TaskRecom());
registerTask(new TaskRestart());
registerTask(new TaskScript());
registerTask(new TaskSevenSignsUpdate());
registerTask(new TaskShutdown());
}

View File

@ -1,51 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* 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 com.l2jmobius.gameserver.taskmanager.tasks;
import java.nio.file.Paths;
import java.util.logging.Level;
import com.l2jmobius.gameserver.scripting.ScriptEngineManager;
import com.l2jmobius.gameserver.taskmanager.Task;
import com.l2jmobius.gameserver.taskmanager.TaskManager.ExecutedTask;
/**
* @author janiii
*/
public class TaskScript extends Task
{
public static final String NAME = "script";
@Override
public String getName()
{
return NAME;
}
@Override
public void onTimeElapsed(ExecutedTask task)
{
try
{
ScriptEngineManager.getInstance().executeScript(Paths.get("cron", task.getParams()[2]));
}
catch (Exception e)
{
_log.log(Level.WARNING, "Script execution failed!", e);
}
}
}