/
Manager.java
263 lines (233 loc) · 8.46 KB
/
Manager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import java.util.concurrent.locks.*;
import java.io.*;
import java.util.*;
/**
* Manager é a "capital" das classes é onde se guarda a referência para utilizadores, tarefas e armazém e onde
* são implementados os métodos que permitem o controlo de concorrência ao acesso desses recursos.
*
* @author Jorge Caldas, José Cortez, Marcelo Gonçalves, Ricardo Silva
* @version 2014.12.15
*/
public class Manager implements Serializable {
/* Contador para dar o ID ás tarefas */
private int countID;
/* Map com todos os utilizadores do sistema */
private HashMap<String, User> users;
/* Map com todas as tarefas definidas no sistema */
private HashMap<String, Task> tasks;
/* Map com todas as tarefas a decorrer no sistema */
private HashMap<Integer, String> tasksRunning;
/* Armazém com os objetos partilhados */
private Warehouse warehouse;
private Lock lock = new ReentrantLock();
public Manager(Warehouse wh) {
this.users = new HashMap<>();
this.tasks = new HashMap<>();
this.tasksRunning = new HashMap<>();
this.warehouse = wh;
this.countID = 0;
}
/* Retorna um Map com os utilizadores existentes no sistema */
public HashMap<String, User> getUsers() {
HashMap<String,User> r = new HashMap<>();
for(Map.Entry<String,User> entry : users.entrySet()){
r.put(entry.getKey(),entry.getValue());
}
return r;
}
/* Regista um novo utilizador no sistema */
public boolean registerUser(String nick, String pass) {
boolean res = false;
if(nick.equals("") || (pass.equals(""))) return res;
lock.lock();
try {
if (!this.users.containsKey(nick)) {
User u = new User(nick, pass);
this.users.put(nick, u);
res = true;
}
} finally { lock.unlock(); }
return res;
}
/* Valida a existencia e os dados de um Utilizador */
public boolean validateUser(String nick, String pass) {
boolean res = false;
lock.lock();
try {
if (this.users.containsKey(nick)) {
if (this.users.get(nick).getPassword().equals(pass)) {
this.users.get(nick).setAtivo(true);
res = true;
}
}
} finally { lock.unlock(); }
return res;
}
/* Termina a sessão de um utilizador */
public void logout(String nick) {
lock.lock();
try {
this.users.get(nick).setAtivo(false);
} finally { lock.unlock(); }
}
/*
* Cria uma nova Tarefa.
* Retorna true se foi criada com sucesso false caso contrário
*/
public boolean newTask(String type, Packet objects) {
if(type.equals("")) return false;
lock.lock();
try{
if(this.tasks.containsKey(type)){
return false;
}
else{
HashMap<String,String> aux = objects.getArgs();
HashMap<String,Integer> objs = new HashMap<>();
for(Map.Entry<String,String> entry : aux.entrySet()){
objs.put(entry.getKey(),Integer.parseInt((entry.getValue())));
}
Task t = new Task(type, objs,lock);
this.tasks.put(type,t);
return true;
}
} finally{ lock.unlock(); }
}
/*
* Inicia a realização de uma Tarefa.
* Retorna o ID se foi iniciada com sucesso -1 caso contrário
*/
public int beginTask(String type) {
Map<String,Integer> objectsToConsume;
lock.lock();
try{
if(!this.tasks.containsKey(type)) return -1;
else{
objectsToConsume = this.tasks.get(type).getObjects();
}
} finally{ lock.unlock(); }
try{ warehouse.consume(objectsToConsume); }
catch(Exception e){ return -1; }
lock.lock();
try{
countID++;
this.tasksRunning.put(countID,type);
return countID; // Retornar o ID da tarefa
} finally{ lock.unlock(); }
}
/*
* Termina a realização da Tarefa.
* Retorna true se foi terminada com sucesso false caso contrário
*/
public boolean endTask(String id) throws InterruptedException {
Map<String,Integer> objectsToSupply;
String type;
lock.lock();
try{
if(!this.tasksRunning.containsKey(Integer.valueOf(id))){
return false;
} else{
type = this.tasksRunning.get(Integer.valueOf(id));
objectsToSupply = this.tasks.get(type).getObjects();
}
} finally{ lock.unlock(); }
// Supply de todos os objetos
for(Map.Entry<String,Integer> entry : objectsToSupply.entrySet()){
warehouse.supply(entry.getKey(),entry.getValue());
}
lock.lock();
try{
this.tasksRunning.remove(Integer.valueOf(id));
this.tasks.get(type).signalP();
} finally{ lock.unlock(); }
return true;
}
/* Devolve lista com o tipo de tarefas */
public List<String> listTask() {
ArrayList<String> tasklist = new ArrayList<>();
lock.lock();
try{
for(Task task : this.tasks.values()){
tasklist.add(task.getType());
}
return tasklist;
} finally{ lock.unlock(); }
}
/*Devolve uma lista do stock corrente*/
public HashMap<String,Integer> listStock() {
HashMap<String,Integer> liststock = new HashMap<>();
lock.lock();
try{
for(Map.Entry<String,Product> entry : this.warehouse.getStock().entrySet()){
liststock.put(entry.getKey(), entry.getValue().getQuantity());
}
return liststock;
} finally{ lock.unlock(); }
}
/* Devolve lista com o tipo de tarefas em desenvolvimento */
public HashMap<Integer,String> listTaskRunnig() {
HashMap<Integer,String> tasklist = new HashMap<>();
lock.lock();
try{
for(Map.Entry<Integer,String> entry : this.tasksRunning.entrySet()){
tasklist.put(entry.getKey(),entry.getValue());
}
return tasklist;
} finally{ lock.unlock(); }
}
/* Abastece o armazém com o produto - name, e a quantidade - qtd */
public boolean supply(String name, String qtd) throws InterruptedException {
if(name.equals("") || qtd.equals("")) return false;
try{
warehouse.supply(name, Integer.parseInt(qtd));
return true;
} catch(InterruptedException ie){
return false;
}
}
int waitTasks(List<Integer> wL) throws InterruptedException {
lock.lock();
try{
boolean i = true;
while(i){
i = false;
for(Integer id : wL){
if(countID < id) return id;
String type = this.tasksRunning.get(id);
if(type!=null){
this.tasks.get(type).awaitP();
i = true; break;
}
}
}
return -1;
} finally{ lock.unlock(); }
}
public Warehouse getWarehouse(){return this.warehouse;}
public void saveManager() throws FileNotFoundException, IOException {
String workingDir = System.getProperty("user.dir");
FileOutputStream fos = new FileOutputStream(workingDir+"\\Manager.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
try{
oos.writeObject(this);
oos.close();
}
catch (IOException e){
System.out.println("\nerror saving file!\n");
}
}
public Manager loadManager() throws IOException, ClassNotFoundException{
try{
String workingDir = System.getProperty("user.dir");
FileInputStream fin=new FileInputStream(workingDir+"\\Manager.ser");
ObjectInputStream oin=new ObjectInputStream(fin);
Manager m = (Manager)oin.readObject();
if(m!=null) return m;
else return new Manager(new Warehouse());
}
catch (IOException e){
System.out.println("\nerror loading file!\n");
return new Manager(new Warehouse());
}
}
}