2
0

Expression.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 javax.script.ScriptContext;
  17. import com.l2jserver.gameserver.scripting.L2ScriptEngineManager;
  18. public class Expression
  19. {
  20. private final ScriptContext _context;
  21. @SuppressWarnings("unused")
  22. private final String _lang;
  23. @SuppressWarnings("unused")
  24. private final String _code;
  25. public static Object eval(String lang, String code)
  26. {
  27. try
  28. {
  29. return L2ScriptEngineManager.getInstance().eval(lang, code);
  30. }
  31. catch (Exception e)
  32. {
  33. e.printStackTrace();
  34. return null;
  35. }
  36. }
  37. public static Object eval(ScriptContext context, String lang, String code)
  38. {
  39. try
  40. {
  41. return L2ScriptEngineManager.getInstance().eval(lang, code, context);
  42. }
  43. catch (Exception e)
  44. {
  45. e.printStackTrace();
  46. return null;
  47. }
  48. }
  49. public static Expression create(ScriptContext context, String lang, String code)
  50. {
  51. try
  52. {
  53. return new Expression(context, lang, code);
  54. }
  55. catch (Exception e)
  56. {
  57. e.printStackTrace();
  58. return null;
  59. }
  60. }
  61. private Expression(ScriptContext pContext, String pLang, String pCode)
  62. {
  63. _context = pContext;
  64. _lang = pLang;
  65. _code = pCode;
  66. }
  67. public <T> void addDynamicVariable(String name, T value)
  68. {
  69. try
  70. {
  71. _context.setAttribute(name, value, ScriptContext.ENGINE_SCOPE);
  72. }
  73. catch (Exception e)
  74. {
  75. e.printStackTrace();
  76. }
  77. }
  78. public void removeDynamicVariable(String name)
  79. {
  80. try
  81. {
  82. _context.removeAttribute(name, ScriptContext.ENGINE_SCOPE);
  83. }
  84. catch (Exception e)
  85. {
  86. e.printStackTrace();
  87. }
  88. }
  89. }