aboutsummaryrefslogtreecommitdiff
path: root/Week9/src/com/camilstaps/shop/Shell.java
blob: 7939963f0dadf10de389aff07e218f236d9ec08f (plain) (blame)
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/**
 * Copyright (c) 2015 Camil Staps <info@camilstaps.nl>
 * See the LICENSE file for copying permission.
 */

package com.camilstaps.shop;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Executing commands and providing output, using a UserInteraction and acting 
 * on a Database.
 * @author Camil Staps, s4498062
 */
public class Shell {
    
    /**
     * The Database to work with
     */
    private final Database database;
    /**
     * The UserInteraction to use
     */
    private final UserInteraction ui;
    
    /**
     * The current User, if logged in
     */
    private User user;
    
    public Shell(UserInteraction userInteraction) {
        this.database = Database.getInstance();
        this.ui = userInteraction;
    }
    
    /**
     * Request commands, execute them, and show the results
     */
    public void run() {
        while (true) {
            Command command = ui.getCommand();
            try {
                Method method = getClass().getMethod("exec" + command.getCommand().substring(0,1).toUpperCase() + command.getCommand().substring(1));
                method.invoke(this);
                
                if (command.getCommand().equalsIgnoreCase("exit")) {
                    return;
                }
            } catch (NoSuchMethodException ex) {
                ui.putStringln("Failure: no such command");
            } catch (InvocationTargetException ex) {
                ui.putStringln("Failure: " + ex.getCause().toString());
            } catch (SecurityException | IllegalAccessException | IllegalArgumentException ex) {
                ui.putStringln("Failure: unknown error");
            }
        }
    }
    
    /**
     * Require that the visitor logs in
     * @throws com.camilstaps.shop.Shell.LoginRequiredException if the visitor fails to login
     * @throws ItemNotFoundException if the visitor tries to login with a non-existing User number
     */
    public void requireLogin() throws LoginRequiredException, ItemNotFoundException {
        if (user == null) {
            ui.putStringln("You must login first.");
            
            try {
                execLogin();
            } catch (InputRequiredException ex) {
            }
            
            if (user == null) {
                throw new LoginRequiredException();
            }
        }
    }
    
    /**
     * Require that an administrator is logged in
     * @throws com.camilstaps.shop.Shell.AdminRequiredException if the visitor fails to login, or is not an administrator
     * @throws ItemNotFoundException if the visitor tries to login with a non-existing User number
     */
    public void requireAdmin() throws AdminRequiredException, ItemNotFoundException {
        if (user == null || !user.isAdmin()) {
            ui.putStringln("You must login as an administrator first.");
            
            try {
                execLogin();
            } catch (InputRequiredException ex) {
            }
                
            if (user == null || !user.isAdmin()) {
                throw new AdminRequiredException();
            }
        }
    }
    
    /**
     * Command: add an article
     * @throws DuplicateEntryException
     * @throws InputRequiredException
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException 
     */
    public void execAddArticle() throws DuplicateEntryException, InputRequiredException, LoginRequiredException, ItemNotFoundException {
        requireLogin();
        
        String name = ui.getRequiredString("Name: ");
        Category category = ui.getCategory();
        float price = ui.getFloat("Price: ");
        
        Article a = new Article(user, name, category, price);
        database.addItem(a);
    }
    
    /**
     * Command: set the article description
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException
     * @throws InputRequiredException 
     */
    public void execSetArticleDescription() throws LoginRequiredException, ItemNotFoundException, InputRequiredException {
        requireLogin();
        
        Article a;
        if (user.isAdmin()) {
            a = ui.getArticle();
        } else {
            a = ui.getArticle(user);
        }
        
        a.setDescription(ui.getRequiredString("Description: "));
    }
    
    /**
     * Command: set the multimedia linked to an article
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException
     * @throws InputRequiredException 
     */
    public void execSetArticleMultimedia() throws LoginRequiredException, ItemNotFoundException, InputRequiredException {
        requireLogin();
        
        Article a;
        if (user.isAdmin()) {
            a = ui.getArticle();
        } else {
            a = ui.getArticle(user);
        }
        
        a.setMultimedia(new File(ui.getRequiredString("Multimedia: ")));
    }
    
    /**
     * Command: remove an article
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException
     * @throws InputRequiredException 
     */
    public void execRemoveArticle() throws LoginRequiredException, ItemNotFoundException, InputRequiredException {
        requireLogin();
        
        Article a;
        if (user.isAdmin()) {
            a = ui.getArticle();
        } else {
            a = ui.getArticle(user);
        }
        
        database.removeItem(a);
    }
    
    /**
     * Command: show a list of articles
     */
    public void execListArticles() {
        for (Article a : database.getArticles()) {
            ui.putStringln(a.toString());
        }
    }
    
    /**
     * Command: search for an article
     */
    public void execSearchArticle() {
        String regex = ui.getString("Keywords: ");
        for (Article a : database.searchArticle(Pattern.compile(regex))) {
            ui.putStringln(a.toString());
        }
    }
    
    /**
     * Command: show detailed data about an article
     * @throws InputRequiredException
     * @throws ItemNotFoundException 
     */
    public void execShowArticle() throws InputRequiredException, ItemNotFoundException {
        Article a = ui.getArticle();
        ui.putStringln(a.toString());
        if (a.getDescription() != null) {
            ui.putStringln(a.getDescription());
        }
        File multimedia = a.getMultimedia();
        if (multimedia != null) {
            ui.putStringln("Multimedia: " + multimedia.getPath());
        }
        if (user != null && user.isAdmin()) {
            ui.putStringln("User: " + a.getOwner().toString(true));
        }
    }
    
    /**
     * Command: add a category
     * @throws DuplicateEntryException
     * @throws InputRequiredException
     * @throws com.camilstaps.shop.Shell.AdminRequiredException
     * @throws ItemNotFoundException 
     */
    public void execAddCategory() throws DuplicateEntryException, InputRequiredException, AdminRequiredException, ItemNotFoundException {
        requireAdmin();
        
        String name = ui.getRequiredString("Name: ");
        database.addItem(new Category(name));
    }
    
    /**
     * Command: list categories
     */
    public void execListCategories() {
        for (String c : database.getCategoryNames()) {
            ui.putStringln(c);
        }
    }
    
    /**
     * Command: list users
     * Administrators see a more detailed list
     */
    public void execListUsers() {
        for (User u : database.getUsers()) {
            ui.putStringln(u.toString(user != null && user.isAdmin()));
        }
    }
    
    /**
     * Command: register a new user
     * @throws DuplicateEntryException
     * @throws InputRequiredException 
     */
    public void execRegister() throws DuplicateEntryException, InputRequiredException {
        boolean addAsAdmin = false;
        
        if (database.getUsers().isEmpty()) {
            addAsAdmin = true;
            ui.putStringln("This is the first user and will therefore be added as administrator.");
        } else if (user != null && user.isAdmin()) {
            addAsAdmin = ui.getBoolean("Add user as administrator");
        }
        
        String nr = ui.getRequiredString("Number: ");
        String email = ui.getRequiredString("Email: ");
        
        User u = new User(nr, email, addAsAdmin);
        
        String password = u.setRandomPassword();
        ui.putStringln("Password: " + password);
        
        database.addItem(u);
    }
    
    /**
     * Command: login
     * @throws InputRequiredException
     * @throws ItemNotFoundException 
     */
    public void execLogin() throws InputRequiredException, ItemNotFoundException {
        if (user != null) {
            ui.putStringln("You are already logged in.");
            return;
        }
        
        User u = ui.getUser();
        String pw = ui.getRequiredString("Password: ");
        
        if (!u.verify(pw)) {
            ui.putStringln("Failed to login.");
            return;
        }
        
        if (u.isBlocked()) {
            ui.putStringln("You are blocked.");
            return;
        }
        
        user = u;
    }
    
    /**
     * Command: logout
     */
    public void execLogout() {
        user = null;
    }
    
    /**
     * Command: add an article to the cart
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException
     * @throws InputRequiredException 
     */
    public void execAddToCart() throws LoginRequiredException, ItemNotFoundException, InputRequiredException {
        requireLogin();
        
        user.getCart().add(ui.getArticle());
    }
    
    /**
     * Command: remove an article from the cart
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException 
     */
    public void execRemoveFromCart() throws LoginRequiredException, ItemNotFoundException {
        requireLogin();
        
        user.getCart().remove(ui.getArticle(user.getCart().getArticles()));
    }
    
    /**
     * Command: list articles in the cart
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException 
     */
    public void execListCart() throws LoginRequiredException, ItemNotFoundException {
        requireLogin();
        
        for (Article a : user.getCart().getArticles()) {
            ui.putStringln(a.toString());
        }
        
        ui.putStringln("Total value: " + user.getCart().getTotalAmount());
    }
    
    /**
     * Command: remove all articles from the cart
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException 
     */
    public void execClearCart() throws LoginRequiredException, ItemNotFoundException {
        requireLogin();
        
        if (ui.getBoolean("Are you sure?")) user.getCart().reset();
    }
    
    /**
     * Command: checkout (create an Order using the current Cart)
     * @throws ItemNotFoundException
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws DuplicateEntryException 
     */
    public void execCheckout() throws ItemNotFoundException, LoginRequiredException, DuplicateEntryException {
        requireLogin();
        
        if (user.getCart().getArticles().isEmpty()) {
            throw new ItemNotFoundException();
        }
        
        ui.putStringln("By checking out, you agree to pay the total amount.");
        if (!ui.getBoolean("Do you agree?"))
            return;
        
        Order order = new Order(user);
        database.addItem(order);
        
        ui.putStringln("Your order has been added as " + order.toString());
    }
    
    /**
     * Command: list orders
     * @throws ItemNotFoundException
     * @throws com.camilstaps.shop.Shell.LoginRequiredException 
     */
    public void execListOrders() throws ItemNotFoundException, LoginRequiredException {
        requireLogin();
        
        Set<Order> orders;
        if (user.isAdmin()) {
            orders = database.getOrders();
        } else {
            orders = user.getOrders();
        }
        for (Order o : orders) {
            ui.putStringln(o.toString());
        }
    }
    
    /**
     * Command: show detailed information about an order
     * @throws com.camilstaps.shop.Shell.LoginRequiredException
     * @throws ItemNotFoundException
     * @throws InputRequiredException 
     */
    public void execShowOrder() throws LoginRequiredException, ItemNotFoundException, InputRequiredException {
        requireLogin();
        
        Order o;
        if (user.isAdmin()) {
            o = ui.getOrder();
        } else {
            o = ui.getOrder(user);
        }
        ui.putStringln(o.toString());
        for (Article a : o.getArticles()) {
            ui.putStringln("  " + a.toString());
        }
        ui.putStringln("Total amount: " + o.getTotalAmount());
        ui.putStringln("Paid: " + (o.isPaid() ? "yes" : "no"));
    }
    
    /**
     * Command: set the paid status of an Order to true
     * @throws com.camilstaps.shop.Shell.AdminRequiredException
     * @throws ItemNotFoundException
     * @throws InputRequiredException 
     */
    public void execSetOrderPaid() throws AdminRequiredException, ItemNotFoundException, InputRequiredException {
        requireAdmin();
        ui.getOrder().setPaid(true);
    }
    
    /**
     * Command: block a user
     * @throws InputRequiredException
     * @throws ItemNotFoundException
     * @throws com.camilstaps.shop.Shell.AdminRequiredException 
     */
    public void execBlockUser() throws InputRequiredException, ItemNotFoundException, AdminRequiredException {
        requireAdmin();
        ui.getUser().setBlocked(true);
    }
    
    /**
     * Command: unblock a user
     * @throws InputRequiredException
     * @throws ItemNotFoundException
     * @throws com.camilstaps.shop.Shell.AdminRequiredException 
     */
    public void execUnblockUser() throws InputRequiredException, ItemNotFoundException, AdminRequiredException {
        requireAdmin();
        ui.getUser().setBlocked(false);
    }
    
    /**
     * Command: save the database
     */
    public void execExit() {
        database.write();
    }
    
    /**
     * This Exception is thrown when the visitor is required to login, but fails
     */
    private class LoginRequiredException extends Exception {
    }
    
    /**
     * This Exception is thrown when the visitor is required to login as an administrator, but fails
     */
    private class AdminRequiredException extends Exception {
    }
    
}