Middleware.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package API;
  7. import common.Instruction;
  8. import common.Log;
  9. import java.util.ArrayList;
  10. import java.util.HashMap;
  11. import java.util.LinkedHashMap;
  12. /**
  13. *
  14. * @author Eugenio
  15. */
  16. public class Middleware {
  17. // Todos os processors serão armazenados aqui, e cada evendo possui uma lista de processors separada por virgula
  18. protected static LinkedHashMap<String, API.MiddlewareInterface> processors = new LinkedHashMap<>();
  19. protected static HashMap<String, HashMap<String, ArrayList<String>>> events = new HashMap<>();
  20. public static void _init() {
  21. }
  22. public static void On(String selectors, String event, String processors) {
  23. HashMap<String, ArrayList<String>> s;
  24. ArrayList<String> processorsList = ProcToList(processors);
  25. for (String selector : selectors.split(",")) {
  26. if (!events.containsKey(selector)) {
  27. events.put(selector, new HashMap<>());
  28. }
  29. s = events.get(selector);
  30. if (!s.containsKey(event)) {
  31. s.put(event, new ArrayList<>());
  32. }
  33. s.get(event).addAll(processorsList);
  34. }
  35. }
  36. public static void Trigger(common.Code c, String selector, String event) throws Exception {
  37. // System.out.println("Try trigger:" + selector);
  38. if (events.containsKey(selector)) {
  39. HashMap<String, ArrayList<String>> t = events.get(selector);
  40. if (t.containsKey(event)) {
  41. ProcessorExecute(c, t.get(event));
  42. }
  43. }
  44. }
  45. public static void Add(String id, API.MiddlewareInterface p) throws Exception {
  46. if (processors.containsKey(id)) {
  47. Log.PrintWarning(
  48. "Code Processor",
  49. new Instruction().Set("msg", String.format("Tentativa de sobrescrita do processor %s.", id))
  50. );
  51. }
  52. processors.put(id, p);
  53. }
  54. protected static ArrayList<String> ProcToList(String events) {
  55. // System.out.println("events:" + events);
  56. ArrayList<String> r = new ArrayList<>();
  57. for (String p : events.replaceAll("\\s+", "").split(",")) {
  58. r.add(p);
  59. }
  60. return r;
  61. }
  62. public static void ProcessorExecute(common.Code c, ArrayList<String> eventList) throws Exception {
  63. for (String x : eventList) {
  64. if (x.equals("")) {
  65. continue;
  66. }
  67. if (!processors.containsKey(x)) {
  68. throw new Exception(String.format("Processador de código '%s' não definido!", x));
  69. }
  70. processors.get(x.trim()).Exec(c, processors);
  71. }
  72. }
  73. }