1 package cz.cuni.amis.pogamut.defcon.utils;
2
3 import java.lang.reflect.Method;
4 import java.util.concurrent.CountDownLatch;
5 import java.util.concurrent.TimeUnit;
6
7 import javabot.PogamutJBotSupport;
8
9
10
11
12
13
14
15
16 public class SyncMethodExecContainer {
17 public volatile Method method;
18 public volatile Object[] parameters;
19 public volatile Object returnValue = null;
20 public volatile Object lock = new Object();
21 public volatile boolean used = false;
22
23 public SyncMethodExecContainer(Method method, Object[] parameters) {
24
25 if (method == null)
26 throw new IllegalArgumentException(
27 "method argument cannot be null.");
28
29 this.method = method;
30 this.parameters = parameters;
31 }
32
33
34
35
36
37 public void execute() {
38 synchronized (lock) {
39 try {
40 this.returnValue = method.invoke(null, parameters);
41 } catch (Exception e) {
42 e.printStackTrace();
43 } finally {
44 latch.countDown();
45 }
46 }
47 }
48
49 private final CountDownLatch latch = new CountDownLatch(1);
50
51
52
53
54
55
56
57 public Object syncCallInMainThread() {
58
59 synchronized (lock) {
60 if (used)
61 throw new RuntimeException(
62 "Called twice! Previous call must finish first!");
63 used = true;
64 }
65
66
67 PogamutJBotSupport.addQuery(this);
68 try {
69 latch.await(10000, TimeUnit.MILLISECONDS);
70 } catch (InterruptedException e) {
71 PogamutJBotSupport.writeToConsole("Intteruped waiting");
72 } catch (Exception e) {
73 PogamutJBotSupport.writeToConsole("Exception!");
74 e.printStackTrace();
75 e.getCause().printStackTrace();
76 }
77
78 return returnValue;
79 }
80
81 public Object getLock() {
82 return lock;
83 }
84 }