View Javadoc

1   /********************************************************************************
2    * InternetCafe is a software solution that helps the management of Cybercafes 
3    * according with the ITALIAN DECREE LAW ON ANTI-TERROR MEASURES, 27 JULY 2005.
4    * Copyright (C) 2006  Guido Angelo Ingenito
5   
6    * This program is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU General Public License
8    * as published by the Free Software Foundation; either version 2
9    * of the License, or (at your option) any later version.
10  
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU General Public License for more details.
15   * 
16   * You should have received a copy of the GNU General Public License
17   * along with this program; if not, write to the Free Software
18   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19   *******************************************************************************/
20  package base;
21  
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.io.FileOutputStream;
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.io.OutputStream;
28  import java.util.Iterator;
29  import java.util.Observable;
30  
31  import org.apache.log4j.Logger;
32  
33  import base.backup.Backup;
34  import base.network.Network;
35  import base.network.NetworkManager;
36  import base.service.Service;
37  import base.session.Session;
38  import base.user.User;
39  
40  import com.db4o.Db4o;
41  import com.db4o.ObjectContainer;
42  import com.db4o.ObjectSet;
43  
44  public class InternetCafeManager extends Observable {
45  
46  	private static final transient Logger logger = Logger
47  			.getLogger(InternetCafeManager.class.getName());
48  
49  	private static InternetCafeManager instance;
50  
51  	public static InternetCafeManager getInstance() {
52  		return instance == null ? instance = new InternetCafeManager()
53  				: instance;
54  	}
55  
56  	private java.util.Hashtable<String, User> user = new java.util.Hashtable<String, User>();
57  
58  	private java.util.Hashtable<String, Session> session = new java.util.Hashtable<String, Session>();
59  
60  	private java.util.Hashtable<String, Service> service = new java.util.Hashtable<String, Service>();
61  
62  	private java.util.Hashtable<String, Backup> backup = new java.util.Hashtable<String, Backup>();
63  
64  	protected InternetCafeManager() {
65  
66  	}
67  
68  	private void deleteDB(ObjectContainer db) {
69  		ObjectSet result = db.get(new Object());
70  		while (result.hasNext())
71  			db.delete(result.next());
72  		db.commit();
73  	}
74  
75  	public void store() {
76  
77  		if (!new File(ConfigurationManager.getInstance().getDataBasePath())
78  				.exists()) {
79  			try {
80  				new File(ConfigurationManager.getInstance().getDataBasePath())
81  						.createNewFile();
82  			} catch (IOException e) {
83  				// TODO Auto-generated catch block
84  				e.printStackTrace();
85  			}
86  		}
87  		ObjectContainer db = Db4o.openFile(ConfigurationManager.getInstance()
88  				.getDataBasePath());
89  		try {
90  			// Here we will uppdate all the images...
91  			updateImageReferences();
92  
93  			// We must delete the current database and restore it to the fresh
94  			// values...
95  			deleteDB(db);
96  			// This will store in the db all the users...
97  			Iterator iterator = user.values().iterator();
98  			while (iterator.hasNext()) {
99  				User u = (User) iterator.next();
100 				if (u != null && u.getId() != -1)
101 					db.set(u);
102 			}
103 			// This will store in the db the entire network...
104 			db.set(NetworkManager.getInstance().getNetwork());
105 			// This will store in the db all the sessions...
106 			iterator = session.values().iterator();
107 			while (iterator.hasNext())
108 				db.set((Session) iterator.next());
109 
110 			// This will store in the db all the services...
111 			iterator = service.values().iterator();
112 			while (iterator.hasNext())
113 				db.set((Service) iterator.next());
114 
115 			// This will store in the db all the backups...
116 			iterator = backup.values().iterator();
117 			while (iterator.hasNext())
118 				db.set((Backup) iterator.next());
119 
120 			// This is the end of the operations on the db...
121 			db.commit();
122 
123 			logger.debug("Internet Cafe Successfully Stored.");
124 		} catch (Exception ex) {
125 			ex.printStackTrace();
126 		} finally {
127 			db.close();
128 		}
129 	}
130 
131 	private void updateImageReferences() {
132 		// Now we must store each user and document image
133 		File userImageDirectory = new File(ConfigurationManager.getInstance()
134 				.getUserImageDirectoryPath());
135 		File documentImageDirectory = new File(ConfigurationManager
136 				.getInstance().getDocumentImageDirectoryPath());
137 
138 		if (!userImageDirectory.exists()) {
139 			boolean success = userImageDirectory.mkdirs();
140 			if (!success)
141 				logger.error("Can't create the User's image directory!");
142 		}
143 
144 		if (!documentImageDirectory.exists()) {
145 			boolean success = documentImageDirectory.mkdirs();
146 			if (!success)
147 				logger.error("Can't create the Document's image directory!");
148 		}
149 
150 		// Here we must move all the new images to the correct directory...
151 		Iterator iterator = user.values().iterator();
152 		while (iterator.hasNext()) {
153 			User u = (User) iterator.next();
154 			if (u.getImagePath() != null && new File(u.getImagePath()).exists()) {
155 				File userImageFile = new File(u.getImagePath());
156 
157 				String extension = userImageFile.getName().substring(
158 						userImageFile.getName().lastIndexOf("."),
159 						userImageFile.getName().length());
160 				// This is the new file renamed according with the concat
161 				// pattern "User" + UserId + "Image" + extension
162 				File newUserImageFile = new File(userImageDirectory, "User"
163 						+ u.getId() + "Image" + extension);
164 
165 				// CASE 0 - The user's image directory doesn't contains the
166 				// user's file... copy it
167 				if (!contains(userImageDirectory.list(), userImageFile
168 						.getName())) {
169 					try {
170 						copy(userImageFile, newUserImageFile);
171 						u.setImagePath(ConfigurationManager.getInstance()
172 								.getUserImageDirectoryPath()
173 								+ File.separatorChar
174 								+ newUserImageFile.getName());
175 					} catch (IOException e) {
176 						logger
177 								.error("Can't move the User's image file to the Users's images directory!");
178 						// TODO Auto-generated catch block
179 						e.printStackTrace();
180 					}
181 				}// CASE 1 - The user's image directory contains the user's
182 				// file and it has the same length... discard changes,
183 				// nothing to do...
184 				else if (userImageFile.length() != newUserImageFile.length()) {
185 					// CASE 2 - The user's image directory contains the user's
186 					// file and it hasn't the same length... delete the previous
187 					// file and copy the new one
188 					try {
189 						newUserImageFile.delete();
190 						copy(userImageFile, newUserImageFile);
191 					} catch (IOException e) {
192 						logger
193 								.error("Can't move the User's image file to the Users's images directory!");
194 						// TODO Auto-generated catch block
195 						e.printStackTrace();
196 					}
197 				}
198 
199 			}
200 
201 			if (u.getDocument() != null
202 					&& u.getDocument().getImagePath() != null) {
203 				File documentImageFile = new File(u.getDocument()
204 						.getImagePath());
205 				if (documentImageFile.exists()
206 						&& !contains(documentImageDirectory.list(),
207 								documentImageFile.getName())) {
208 					String extension = documentImageFile.getName().substring(
209 							documentImageFile.getName().lastIndexOf("."),
210 							documentImageFile.getName().length());
211 
212 					File newDocumentImageFile = new File(
213 							documentImageDirectory, "Document" + u.getId()
214 									+ "Image" + extension);
215 					try {
216 						copy(documentImageFile, newDocumentImageFile);
217 
218 						u.getDocument().setImagePath(
219 								ConfigurationManager.getInstance()
220 										.getDocumentImageDirectoryPath()
221 										+ File.separatorChar
222 										+ newDocumentImageFile.getName());
223 					} catch (IOException e) {
224 						System.err
225 								.println("Can't move the User's document image file to the Users's documents image directory!");
226 						// TODO Auto-generated catch block
227 						e.printStackTrace();
228 					}
229 
230 				}
231 			}
232 
233 		}
234 	}
235 
236 	void copy(File src, File dst) throws IOException {
237 		InputStream in = new FileInputStream(src);
238 		OutputStream out = new FileOutputStream(dst);
239 
240 		// Transfer bytes from in to out
241 		byte[] buf = new byte[1024];
242 		int len;
243 		while ((len = in.read(buf)) > 0) {
244 			out.write(buf, 0, len);
245 		}
246 		in.close();
247 		out.close();
248 	}
249 
250 	public static boolean contains(String[] list, String text) {
251 		for (int i = 0; i < list.length; i++)
252 			if (list[i].equalsIgnoreCase(text))
253 				return true;
254 		return false;
255 	}
256 
257 	public void retrieve() {
258 
259 		if (!new File(ConfigurationManager.getInstance().getDataBasePath())
260 				.exists())
261 			return;
262 
263 		ObjectContainer db = Db4o.openFile(ConfigurationManager.getInstance()
264 				.getDataBasePath());
265 		try {
266 
267 			// This will retrieve all the users...
268 			user = new java.util.Hashtable<String, User>();
269 			ObjectSet os = db.get(User.class);
270 			while (os.hasNext()) {
271 				User u = (User) os.next();
272 				if (u != null && u.getId() != -1) {
273 					// We must set the correct imagePath for each user image and
274 					// document...
275 					if (!ConfigurationManager.debugMode) {
276 						if (u.getImagePath() != "" && u.getImagePath() != null
277 								&& u.getImagePath().contains("..")) {
278 							String imagePath = u.getImagePath().replace("..",
279 									".");
280 							u.setImagePath(imagePath);
281 						}
282 						if (u.getDocument() != null
283 								&& u.getDocument().getImagePath() != ""
284 								&& u.getDocument().getImagePath() != null
285 								&& u.getDocument().getImagePath()
286 										.contains("..")) {
287 							String imagePath = u.getDocument().getImagePath()
288 									.replace("..", ".");
289 							u.getDocument().setImagePath(imagePath);
290 						}
291 					}
292 					addUser(u);
293 				}
294 			}
295 
296 			// This will retrieve the entire network...
297 			os = db.get(Network.class);
298 			while (os.hasNext())
299 				NetworkManager.getInstance().setNetwork((Network) os.next());
300 
301 			// This will retrieve all the sessions...
302 			os = db.get(Session.class);
303 			while (os.hasNext())
304 				addSession((Session) os.next());
305 
306 			// This will retrieve all the services...
307 			os = db.get(Service.class);
308 			while (os.hasNext())
309 				addService((Service) os.next());
310 
311 			// This will retrieve all the backups...
312 			os = db.get(Backup.class);
313 			while (os.hasNext())
314 				addBackup((Backup) os.next());
315 
316 			logger.debug("Internet Cafe Successfully Retrieved.");
317 		} catch (Exception ex) {
318 			ex.printStackTrace();
319 		} finally {
320 			db.close();
321 		}
322 	}
323 
324 	/***
325 	 * This method simply adds a user.
326 	 * 
327 	 * @param user
328 	 *            The user to add.
329 	 */
330 	public void addUser(User user) {
331 		this.setChanged();
332 		this.user.put(userKey(user), user);
333 		this.notifyObservers(user);
334 	}
335 
336 	/***
337 	 * This method simply adds a backup.
338 	 * 
339 	 * @param backup
340 	 *            The backup to add.
341 	 */
342 	public void addBackup(Backup backup) {
343 		this.setChanged();
344 		this.backup.put(backupKey(backup), backup);
345 		this.notifyObservers(backup);
346 	}
347 
348 	/***
349 	 * This method simply adds a service.
350 	 * 
351 	 * @param service
352 	 *            The service to add.
353 	 */
354 	public void addService(Service service) {
355 		this.setChanged();
356 		this.service.put(serviceKey(service), service);
357 		this.notifyObservers(service);
358 	}
359 
360 	/***
361 	 * @return Returns the user.
362 	 */
363 	public User[] getUser() {
364 		return user.values().toArray(new User[0]);
365 	}
366 
367 	/***
368 	 * @return Returns the backup.
369 	 */
370 	public Backup[] getBackup() {
371 		return backup.values().toArray(new Backup[0]);
372 	}
373 
374 	/***
375 	 * @return Returns the user.
376 	 */
377 	public Service[] getService() {
378 		return service.values().toArray(new Service[0]);
379 	}
380 
381 	/***
382 	 * @return Returns the session.
383 	 */
384 	public Session[] getSession() {
385 		return session.values().toArray(new Session[0]);
386 	}
387 
388 	/***
389 	 * This method simply adds a session.
390 	 * 
391 	 * @param session
392 	 *            The session to add.
393 	 */
394 	public void addSession(Session session) {
395 		this.setChanged();
396 		this.session.put(sessionKey(session), session);
397 		this.notifyObservers(session);
398 	}
399 
400 	/***
401 	 * This method simply adds a set of sessions.
402 	 * 
403 	 * @param sessionSet
404 	 *            The session set to add.
405 	 */
406 	public void addSessionSet(Session[] sessionSet) {
407 		for (int i = 0; i < sessionSet.length; i++)
408 			addSession(sessionSet[i]);
409 	}
410 
411 	/***
412 	 * This method deletes the user.
413 	 * 
414 	 * @param user
415 	 *            The user to be deleted.
416 	 */
417 	public void deleteUser(User user) {
418 		this.setChanged();
419 		this.user.remove(userKey(user));
420 		this.notifyObservers(user);
421 	}
422 
423 	/***
424 	 * This method deletes the service.
425 	 * 
426 	 * @param service
427 	 *            The user to be deleted.
428 	 */
429 	public void deleteService(Service service) {
430 		this.setChanged();
431 		this.service.remove(serviceKey(service));
432 		this.notifyObservers(service);
433 	}
434 
435 	/***
436 	 * This method simply builds a key string for an instance of User.
437 	 * 
438 	 * @param user
439 	 *            The user from wich build the key.
440 	 * @return A key rappresentation for the user.
441 	 */
442 	protected static String userKey(User user) {
443 		String key = user.getId() + " " + user.getName() + " "
444 				+ user.getSurname() + " " + user.getBirthday();
445 		return key;
446 	}
447 
448 	/***
449 	 * This method simply builds a key string for an instance of Backup.
450 	 * 
451 	 * @param backup
452 	 *            The backup from wich build the key.
453 	 * @return A key rappresentation for the backup.
454 	 */
455 	protected static String backupKey(Backup backup) {
456 		String key = backup.getId() + " " + backup.getName() + " "
457 				+ backup.getDate();
458 		return key;
459 	}
460 
461 	/***
462 	 * This method simply builds a key string for an instance of Service.
463 	 * 
464 	 * @param service
465 	 *            The service from wich build the key.
466 	 * @return A key rappresentation for the service.
467 	 */
468 	protected static String serviceKey(Service service) {
469 		String key = service.getId() + " " + service.getName() + " "
470 				+ service.getRateType();
471 		return key;
472 	}
473 
474 	/***
475 	 * This method simply builds a key string for an instance of Session.
476 	 * 
477 	 * @param session
478 	 *            The session from wich build the key.
479 	 * @return A key rappresentation for the session.
480 	 */
481 	protected static String sessionKey(Session session) {
482 		String key = session.getId() + " " + session.getUser().getNickname()
483 				+ " " + session.getWorkstation().getName() + " "
484 				+ session.getStartTime();
485 		return key;
486 	}
487 
488 	/***
489 	 * This method deletes a session.
490 	 * 
491 	 * @param session
492 	 *            The session to delete.
493 	 */
494 	public void deleteSession(Session session) {
495 		this.setChanged();
496 		this.session.remove(sessionKey(session));
497 		this.notifyObservers(session);
498 	}
499 
500 	/***
501 	 * This method retrieves a user specifying his id.
502 	 * 
503 	 * @param userId
504 	 *            An id associated to the user to retrieve.
505 	 * @return A user with id equals to userId, null if the specified userId is
506 	 *         not a valid user's id.
507 	 */
508 	public User getUserById(int userId) {
509 		User[] user = getUser();
510 		for (int i = 0; i < user.length; i++)
511 			if (user[i].getId() == userId)
512 				return user[i];
513 		return null;
514 	}
515 
516 	/***
517 	 * This method retrieves a session specifying his id.
518 	 * 
519 	 * @param sessionId
520 	 *            An id associated to the session to retrieve.
521 	 * @return A session with id equals to sessionId, null if the specified
522 	 *         sessionId is not a valid session's id.
523 	 */
524 	public Session getSessionById(int sessionId) {
525 		Session[] session = getSession();
526 		for (int i = 0; i < session.length; i++)
527 			if (session[i].getId() == sessionId)
528 				return session[i];
529 		return null;
530 	}
531 
532 	/***
533 	 * This method retrieves a service specifying his id.
534 	 * 
535 	 * @param serviceId
536 	 *            An id associated to the service to retrieve.
537 	 * @return A service with id equals to serviceId, null if the specified
538 	 *         serviceId is not a valid service's id.
539 	 */
540 	public Service getServiceById(int serviceId) {
541 		Service[] service = getService();
542 		for (int i = 0; i < service.length; i++)
543 			if (service[i].getId() == serviceId)
544 				return service[i];
545 		return null;
546 	}
547 
548 	/***
549 	 * This method retrieves a backup specifying his id.
550 	 * 
551 	 * @param backupId
552 	 *            An id associated to the backup to retrieve.
553 	 * @return A backup with id equals to backupId, null if the specified
554 	 *         backupId is not a valid backup's id.
555 	 */
556 	public Backup getBackupById(int backupId) {
557 		Backup[] backup = getBackup();
558 		for (int i = 0; i < backup.length; i++)
559 			if (backup[i].getId() == backupId)
560 				return backup[i];
561 		return null;
562 	}
563 
564 	/***
565 	 * This method deletes a backup from the system.
566 	 * 
567 	 * @param backup
568 	 *            The backup to delete.
569 	 */
570 	public void deleteBackup(Backup backup) {
571 		this.setChanged();
572 		this.backup.remove(backupKey(backup));
573 		this.notifyObservers(backup);
574 	}
575 
576 	/***
577 	 * This method clears all the InternetCafe's data. Backups will not be
578 	 * deleted.
579 	 */
580 	public void clear() {
581 		user.clear();
582 		NetworkManager.getInstance().setNetwork(null);
583 		session.clear();
584 		service.clear();
585 	}
586 
587 	/***
588 	 * This method retrieves a user specifying his nickname.
589 	 * 
590 	 * @param userNickname
591 	 *            A nickname associated to the user to retrieve.
592 	 * @return A user with nickname equals to userNickname, null if the specified userNickname is
593 	 *         not a valid user's nickname.
594 	 */
595 	public User getUserByNickname(String userNickname) {
596 		User[] user = getUser();
597 		for (int i = 0; i < user.length; i++)
598 			if (user[i].getNickname().equals(userNickname))
599 				return user[i];
600 		return null;
601 	}
602 
603 }