Expression.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.gameserver.script;
  16. import java.util.logging.Level;
  17. import java.util.logging.Logger;
  18. import javax.script.ScriptContext;
  19. import com.l2jserver.gameserver.scripting.L2ScriptEngineManager;
  20. public class Expression
  21. {
  22. protected static final Logger _log = Logger.getLogger(Expression.class.getName());
  23. private final ScriptContext _context;
  24. @SuppressWarnings("unused")
  25. private final String _lang;
  26. @SuppressWarnings("unused")
  27. private final String _code;
  28. public static Object eval(String lang, String code)
  29. {
  30. try
  31. {
  32. return L2ScriptEngineManager.getInstance().eval(lang, code);
  33. }
  34. catch (Exception e)
  35. {
  36. _log.log(Level.WARNING, "", e);
  37. return null;
  38. }
  39. }
  40. public static Object eval(ScriptContext context, String lang, String code)
  41. {
  42. try
  43. {
  44. return L2ScriptEngineManager.getInstance().eval(lang, code, context);
  45. }
  46. catch (Exception e)
  47. {
  48. _log.log(Level.WARNING, "", e);
  49. return null;
  50. }
  51. }
  52. public static Expression create(ScriptContext context, String lang, String code)
  53. {
  54. try
  55. {
  56. return new Expression(context, lang, code);
  57. }
  58. catch (Exception e)
  59. {
  60. _log.log(Level.WARNING, "", e);
  61. return null;
  62. }
  63. }
  64. private Expression(ScriptContext pContext, String pLang, String pCode)
  65. {
  66. _context = pContext;
  67. _lang = pLang;
  68. _code = pCode;
  69. }
  70. public <T> void addDynamicVariable(String name, T value)
  71. {
  72. try
  73. {
  74. _context.setAttribute(name, value, ScriptContext.ENGINE_SCOPE);
  75. }
  76. catch (Exception e)
  77. {
  78. _log.log(Level.WARNING, "", e);
  79. }
  80. }
  81. public void removeDynamicVariable(String name)
  82. {
  83. try
  84. {
  85. _context.removeAttribute(name, ScriptContext.ENGINE_SCOPE);
  86. }
  87. catch (Exception e)
  88. {
  89. _log.log(Level.WARNING, "", e);
  90. }
  91. }
  92. }