Coverage details for base.InternetCafeManager

LineHitsSource
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  
445public class InternetCafeManager extends Observable {
45  
465    private static final transient Logger logger = Logger
475            .getLogger(InternetCafeManager.class.getName());
48  
49     private static InternetCafeManager instance;
50  
51     public static InternetCafeManager getInstance() {
5252        return instance == null ? instance = new InternetCafeManager()
5321                : instance;
54     }
55  
565    private java.util.Hashtable<String, User> user = new java.util.Hashtable<String, User>();
57  
585    private java.util.Hashtable<String, Session> session = new java.util.Hashtable<String, Session>();
59  
605    private java.util.Hashtable<String, Service> service = new java.util.Hashtable<String, Service>();
61  
625    private java.util.Hashtable<String, Backup> backup = new java.util.Hashtable<String, Backup>();
63  
645    protected InternetCafeManager() {
65  
665    }
67  
68     private void deleteDB(ObjectContainer db) {
690        ObjectSet result = db.get(new Object());
700        while (result.hasNext())
710            db.delete(result.next());
720        db.commit();
730    }
74  
75     public void store() {
76  
770        if (!new File(ConfigurationManager.getInstance().getDataBasePath())
780                .exists()) {
79             try {
800                new File(ConfigurationManager.getInstance().getDataBasePath())
810                        .createNewFile();
820            } catch (IOException e) {
83                 // TODO Auto-generated catch block
840                e.printStackTrace();
850            }
86         }
870        ObjectContainer db = Db4o.openFile(ConfigurationManager.getInstance()
880                .getDataBasePath());
89         try {
90             // Here we will uppdate all the images...
910            updateImageReferences();
92  
93             // We must delete the current database and restore it to the fresh
94             // values...
950            deleteDB(db);
96             // This will store in the db all the users...
970            Iterator iterator = user.values().iterator();
980            while (iterator.hasNext()) {
990                User u = (User) iterator.next();
1000                if (u != null && u.getId() != -1)
1010                    db.set(u);
1020            }
103             // This will store in the db the entire network...
1040            db.set(NetworkManager.getInstance().getNetwork());
105             // This will store in the db all the sessions...
1060            iterator = session.values().iterator();
1070            while (iterator.hasNext())
1080                db.set((Session) iterator.next());
109  
110             // This will store in the db all the services...
1110            iterator = service.values().iterator();
1120            while (iterator.hasNext())
1130                db.set((Service) iterator.next());
114  
115             // This will store in the db all the backups...
1160            iterator = backup.values().iterator();
1170            while (iterator.hasNext())
1180                db.set((Backup) iterator.next());
119  
120             // This is the end of the operations on the db...
1210            db.commit();
122  
1230            logger.debug("Internet Cafe Successfully Stored.");
1240        } catch (Exception ex) {
1250            ex.printStackTrace();
1260        } finally {
1270            db.close();
1280        }
1290    }
130  
131     private void updateImageReferences() {
132         // Now we must store each user and document image
1330        File userImageDirectory = new File(ConfigurationManager.getInstance()
1340                .getUserImageDirectoryPath());
1350        File documentImageDirectory = new File(ConfigurationManager
1360                .getInstance().getDocumentImageDirectoryPath());
137  
1380        if (!userImageDirectory.exists()) {
1390            boolean success = userImageDirectory.mkdirs();
1400            if (!success)
1410                logger.error("Can't create the User's image directory!");
142         }
143  
1440        if (!documentImageDirectory.exists()) {
1450            boolean success = documentImageDirectory.mkdirs();
1460            if (!success)
1470                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...
1510        Iterator iterator = user.values().iterator();
1520        while (iterator.hasNext()) {
1530            User u = (User) iterator.next();
1540            if (u.getImagePath() != null && new File(u.getImagePath()).exists()) {
1550                File userImageFile = new File(u.getImagePath());
156  
1570                String extension = userImageFile.getName().substring(
1580                        userImageFile.getName().lastIndexOf("."),
1590                        userImageFile.getName().length());
160                 // This is the new file renamed according with the concat
161                 // pattern "User" + UserId + "Image" + extension
1620                File newUserImageFile = new File(userImageDirectory, "User"
1630                        + u.getId() + "Image" + extension);
164  
165                 // CASE 0 - The user's image directory doesn't contains the
166                 // user's file... copy it
1670                if (!contains(userImageDirectory.list(), userImageFile
1680                        .getName())) {
169                     try {
1700                        copy(userImageFile, newUserImageFile);
1710                        u.setImagePath(ConfigurationManager.getInstance()
1720                                .getUserImageDirectoryPath()
1730                                + File.separatorChar
1740                                + newUserImageFile.getName());
1750                    } catch (IOException e) {
1760                        logger
1770                                .error("Can't move the User's image file to the Users's images directory!");
178                         // TODO Auto-generated catch block
1790                        e.printStackTrace();
1800                    }
1810                }// 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...
1840                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 {
1890                        newUserImageFile.delete();
1900                        copy(userImageFile, newUserImageFile);
1910                    } catch (IOException e) {
1920                        logger
1930                                .error("Can't move the User's image file to the Users's images directory!");
194                         // TODO Auto-generated catch block
1950                        e.printStackTrace();
1960                    }
197                 }
198  
199             }
200  
2010            if (u.getDocument() != null
2020                    && u.getDocument().getImagePath() != null) {
2030                File documentImageFile = new File(u.getDocument()
2040                        .getImagePath());
2050                if (documentImageFile.exists()
2060                        && !contains(documentImageDirectory.list(),
2070                                documentImageFile.getName())) {
2080                    String extension = documentImageFile.getName().substring(
2090                            documentImageFile.getName().lastIndexOf("."),
2100                            documentImageFile.getName().length());
211  
2120                    File newDocumentImageFile = new File(
2130                            documentImageDirectory, "Document" + u.getId()
2140                                    + "Image" + extension);
215                     try {
2160                        copy(documentImageFile, newDocumentImageFile);
217  
2180                        u.getDocument().setImagePath(
2190                                ConfigurationManager.getInstance()
2200                                        .getDocumentImageDirectoryPath()
2210                                        + File.separatorChar
2220                                        + newDocumentImageFile.getName());
2230                    } catch (IOException e) {
2240                        System.err
2250                                .println("Can't move the User's document image file to the Users's documents image directory!");
226                         // TODO Auto-generated catch block
2270                        e.printStackTrace();
2280                    }
229  
230                 }
231             }
232  
2330        }
2340    }
235  
236     void copy(File src, File dst) throws IOException {
2370        InputStream in = new FileInputStream(src);
2380        OutputStream out = new FileOutputStream(dst);
239  
240         // Transfer bytes from in to out
2410        byte[] buf = new byte[1024];
242         int len;
2430        while ((len = in.read(buf)) > 0) {
2440            out.write(buf, 0, len);
2450        }
2460        in.close();
2470        out.close();
2480    }
249  
250     public static boolean contains(String[] list, String text) {
2510        for (int i = 0; i < list.length; i++)
2520            if (list[i].equalsIgnoreCase(text))
2530                return true;
2540        return false;
255     }
256  
257     public void retrieve() {
258  
2590        if (!new File(ConfigurationManager.getInstance().getDataBasePath())
2600                .exists())
2610            return;
262  
2630        ObjectContainer db = Db4o.openFile(ConfigurationManager.getInstance()
2640                .getDataBasePath());
265         try {
266  
267             // This will retrieve all the users...
2680            user = new java.util.Hashtable<String, User>();
2690            ObjectSet os = db.get(User.class);
2700            while (os.hasNext()) {
2710                User u = (User) os.next();
2720                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                     }
2920                    addUser(u);
293                 }
2940            }
295  
296             // This will retrieve the entire network...
2970            os = db.get(Network.class);
2980            while (os.hasNext())
2990                NetworkManager.getInstance().setNetwork((Network) os.next());
300  
301             // This will retrieve all the sessions...
3020            os = db.get(Session.class);
3030            while (os.hasNext())
3040                addSession((Session) os.next());
305  
306             // This will retrieve all the services...
3070            os = db.get(Service.class);
3080            while (os.hasNext())
3090                addService((Service) os.next());
310  
311             // This will retrieve all the backups...
3120            os = db.get(Backup.class);
3130            while (os.hasNext())
3140                addBackup((Backup) os.next());
315  
3160            logger.debug("Internet Cafe Successfully Retrieved.");
3170        } catch (Exception ex) {
3180            ex.printStackTrace();
3190        } finally {
3200            db.close();
3210        }
3220    }
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) {
3310        this.setChanged();
3320        this.user.put(userKey(user), user);
3330        this.notifyObservers(user);
3340    }
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) {
3430        this.setChanged();
3440        this.backup.put(backupKey(backup), backup);
3450        this.notifyObservers(backup);
3460    }
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) {
3550        this.setChanged();
3560        this.service.put(serviceKey(service), service);
3570        this.notifyObservers(service);
3580    }
359  
360     /**
361      * @return Returns the user.
362      */
363     public User[] getUser() {
36426        return user.values().toArray(new User[0]);
365     }
366  
367     /**
368      * @return Returns the backup.
369      */
370     public Backup[] getBackup() {
3710        return backup.values().toArray(new Backup[0]);
372     }
373  
374     /**
375      * @return Returns the user.
376      */
377     public Service[] getService() {
3780        return service.values().toArray(new Service[0]);
379     }
380  
381     /**
382      * @return Returns the session.
383      */
384     public Session[] getSession() {
3850        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) {
3950        this.setChanged();
3960        this.session.put(sessionKey(session), session);
3970        this.notifyObservers(session);
3980    }
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) {
4070        for (int i = 0; i < sessionSet.length; i++)
4080            addSession(sessionSet[i]);
4090    }
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) {
4180        this.setChanged();
4190        this.user.remove(userKey(user));
4200        this.notifyObservers(user);
4210    }
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) {
4300        this.setChanged();
4310        this.service.remove(serviceKey(service));
4320        this.notifyObservers(service);
4330    }
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) {
4430        String key = user.getId() + " " + user.getName() + " "
4440                + user.getSurname() + " " + user.getBirthday();
4450        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) {
4560        String key = backup.getId() + " " + backup.getName() + " "
4570                + backup.getDate();
4580        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) {
4690        String key = service.getId() + " " + service.getName() + " "
4700                + service.getRateType();
4710        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) {
4820        String key = session.getId() + " " + session.getUser().getNickname()
4830                + " " + session.getWorkstation().getName() + " "
4840                + session.getStartTime();
4850        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) {
4950        this.setChanged();
4960        this.session.remove(sessionKey(session));
4970        this.notifyObservers(session);
4980    }
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) {
5090        User[] user = getUser();
5100        for (int i = 0; i < user.length; i++)
5110            if (user[i].getId() == userId)
5120                return user[i];
5130        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) {
5250        Session[] session = getSession();
5260        for (int i = 0; i < session.length; i++)
5270            if (session[i].getId() == sessionId)
5280                return session[i];
5290        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) {
5410        Service[] service = getService();
5420        for (int i = 0; i < service.length; i++)
5430            if (service[i].getId() == serviceId)
5440                return service[i];
5450        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) {
5570        Backup[] backup = getBackup();
5580        for (int i = 0; i < backup.length; i++)
5590            if (backup[i].getId() == backupId)
5600                return backup[i];
5610        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) {
5710        this.setChanged();
5720        this.backup.remove(backupKey(backup));
5730        this.notifyObservers(backup);
5740    }
575  
576     /**
577      * This method clears all the InternetCafe's data. Backups will not be
578      * deleted.
579      */
580     public void clear() {
5810        user.clear();
5820        NetworkManager.getInstance().setNetwork(null);
5830        session.clear();
5840        service.clear();
5850    }
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) {
5960        User[] user = getUser();
5970        for (int i = 0; i < user.length; i++)
5980            if (user[i].getNickname().equals(userNickname))
5990                return user[i];
6000        return null;
601     }
602  
603 }

this report was generated by version 1.0.5 of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.