PageRenderTime 118ms CodeModel.GetById 30ms app.highlight 65ms RepoModel.GetById 15ms app.codeStats 1ms

/src/mpv5/db/objects/User.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 828 lines | 499 code | 91 blank | 238 comment | 53 complexity | 5d3207a4053cdccf54a0d89f8a4c088f MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.db.objects;
 18
 19import mpv5.usermanagement.*;
 20import java.awt.Font;
 21import java.io.File;
 22import java.util.ArrayList;
 23import java.util.Date;
 24import java.util.HashMap;
 25import java.util.Iterator;
 26import java.util.List;
 27import java.util.Locale;
 28import java.util.Map.Entry;
 29import java.util.Vector;
 30import javax.swing.JComponent;
 31import mpv5.Main;
 32import mpv5.data.PropertyStore;
 33import mpv5.db.common.Context;
 34import mpv5.db.common.DatabaseObject;
 35import mpv5.db.common.DatabaseObjectLock;
 36import mpv5.db.common.NodataFoundException;
 37import mpv5.db.common.QueryCriteria;
 38import mpv5.db.common.QueryHandler;
 39import mpv5.globals.LocalSettings;
 40import mpv5.globals.Messages;
 41import mpv5.handler.VariablesHandler;
 42import mpv5.i18n.LanguageManager;
 43import mpv5.logging.Log;
 44import mpv5.mail.MailConfiguration;
 45import mpv5.pluginhandling.YabsPluginLoader;
 46import mpv5.ui.dialogs.Popup;
 47import mpv5.ui.dialogs.subcomponents.ControlPanel_Fonts;
 48import dtaus.Konto;
 49import javax.swing.UIManager;
 50import mpv5.YabsViewProxy;
 51import mpv5.db.common.QueryCriteria2;
 52import mpv5.db.common.QueryParameter;
 53import mpv5.pluginhandling.YabsPlugin;
 54import mpv5.ui.dialogs.DialogForFile;
 55import mpv5.utils.text.TypeConversion;
 56
 57/**
 58 *
 59 *  
 60 */
 61public class User extends DatabaseObject {
 62
 63    private static User currentUser;
 64    private static final long serialVersionUID = 1L;
 65
 66    public static User getCurrentUser() {
 67        if (currentUser == null) {
 68            Log.Debug(User.class, "There is no user logged in here, using default user.");
 69            try {
 70                currentUser = User.DEFAULT;
 71                return currentUser;
 72            } catch (Exception ex) {
 73                Log.Debug(User.class, "Default user is missing.");
 74                return new User();
 75            }
 76        } else {
 77            return currentUser;
 78        }
 79    }
 80
 81    /**
 82     * Set the current logged in user
 83     * @param usern
 84     */
 85    public static void _setUser(User usern) {
 86        currentUser = usern;
 87//        predefTitle = (" (" + usern.getName() + ")");
 88    }
 89
 90    /**
 91     *
 92     * @param ford
 93     * @return The Users default save directory, if defined in the user properties. User.home instead.
 94     */
 95    public static File getSaveDir(DatabaseObject ford) {
 96
 97        String s = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("saveformat");
 98        String s2 = LocalSettings.getProperty(LocalSettings.BASE_DIR);
 99        File basedir = null;
100        if (s2 != null && !s2.equals("null")) {
101            basedir = new File(s2);
102        } else {
103            basedir = DialogForFile.CURRENT_DIR;
104        }
105
106        File subdirs = null;
107        if (s != null) {
108            if (s.contains("/")) {
109                subdirs = new File(s.substring(0, s.lastIndexOf("/")));
110            }
111        }
112
113        File savedir = basedir;
114        if (subdirs != null) {
115            savedir = new File(VariablesHandler.parse(basedir.getPath() + File.separator + subdirs.getPath(), ford));
116        }
117
118        savedir.mkdirs();
119        return savedir;
120    }
121    private String password = "";
122    private String fullname = "";
123    private String laf = "";
124    private String locale = "en_UK";
125    private String defcountry = "";
126    private String mail = "";
127    private String language = "buildin_en";
128    private int inthighestright = 4;
129    private int intdefaultaccount = 1;
130    private int intdefaultstatus = 1;
131    private int compsids = 0;
132    private boolean isenabled = true;
133    private boolean isloggedin = true;
134    private boolean isrgrouped = false;
135    public static int ADMIN_ID = 1;
136    private Date datelastlog = new Date();
137    public static User DEFAULT = new User("Default User", "nobody", MPSecurityManager.RIGHT_TO_VIEW, 4343);
138    public static HashMap<String, String> userCache = new HashMap<String, String>();
139    public static HashMap<String, String> userCache2 = new HashMap<String, String>();
140    private PropertyStore properties = new PropertyStore();
141    /**
142     * Properties added to this store will override the users properties stored in the database upon login
143     */
144    public static PropertyStore PROPERTIES_OVERRIDE = new PropertyStore();
145    private MailConfiguration mailConfiguration;
146    private DTAConfig dtaconf;
147
148    /**
149     * Caches all available usernames and IDs, no logins performed
150     */
151    public static void cacheUser() {
152        userCache.clear();
153        userCache.put(Integer.toBinaryString(DEFAULT.__getIDS()), DEFAULT.__getCname());
154        userCache2.clear();
155        userCache2.put(Integer.toBinaryString(DEFAULT.__getIDS()), DEFAULT.fullname);
156        try {
157            ArrayList<DatabaseObject> data = DatabaseObject.getObjects(Context.getUser());
158            for (int i = 0; i < data.size(); i++) {
159                DatabaseObject databaseObject = data.get(i);
160                userCache.put(Integer.toBinaryString(databaseObject.__getIDS()), databaseObject.__getCname());
161                userCache2.put(Integer.toBinaryString(databaseObject.__getIDS()), ((User) databaseObject).__getFullname());
162            }
163        } catch (NodataFoundException ex) {
164            Log.Debug(User.class, ex.getMessage());
165        }
166    }
167
168    /**
169     * Tries to find the given ID in the DB
170     * @param forId
171     * @return A username if existing, else "unknown"
172     */
173    public static String getUsername(int forId) {
174        if (userCache.containsKey(Integer.toBinaryString(forId))) {
175            return userCache.get(Integer.toBinaryString(forId));
176        } else {
177            Log.Debug(User.class, "User not found in cache: " + Integer.toBinaryString(forId));
178            return "unknown";
179        }
180    }
181
182    /**
183     * Tries to find the given ID in the DB
184     * @param forId
185     * @return A Fullname if existing, else "unknown"
186     */
187    public static String getFullName(int forId) {
188        if (userCache2.containsKey(Integer.toBinaryString(forId))) {
189            return userCache2.get(Integer.toBinaryString(forId));
190        } else {
191            Log.Debug(User.class, "User not found in cache: " + Integer.toBinaryString(forId));
192            return "unknown";
193        }
194    }
195
196    /**
197     * Tries to find an User with the given name
198     * @param username
199     * @return
200     */
201    public static int getUserId(String username) {
202
203        if (userCache.containsValue(username)) {
204            Iterator<Entry<String, String>> data = userCache.entrySet().iterator();
205
206            while (data.hasNext()) {
207                Entry<String, String> entry = data.next();
208                if (entry.getValue().equals(username)) {
209                    Log.Debug(User.class, "Cached user id found: " + Integer.parseInt(entry.getKey(), 2));
210                    return Integer.parseInt(entry.getKey(), 2);
211                }
212            }
213        } else {
214            cacheUser();
215            if (userCache.containsValue(username)) {
216                Iterator<Entry<String, String>> data = userCache.entrySet().iterator();
217
218                while (data.hasNext()) {
219                    Entry<String, String> entry = data.next();
220                    if (entry.getValue().equals(username)) {
221                        Log.Debug(User.class, "Cached user id found: " + Integer.parseInt(entry.getKey(), 2));
222                        return Integer.parseInt(entry.getKey(), 2);
223                    }
224                }
225            }
226        }
227        return DEFAULT.ids;
228    }
229
230    /**
231     * Tries to find the given ID in the DB
232     * @param userid
233     * @throws mpv5.db.common.NodataFoundException
234     */
235    public User(int userid) throws NodataFoundException {
236        this();
237        this.fetchDataOf(userid);
238        setProperties();
239    }
240
241    public User() {
242        setContext(Context.getUser());
243    }
244
245    private User(String fullname, String userid, int highright, int IDS) {
246        this();
247        this.fullname = fullname;
248        setCname(userid);
249        this.inthighestright = highright;
250        this.setIDS(IDS);
251
252    }
253
254    public Integer getID() {
255        return __getIDS();
256    }
257
258    public String getName() {
259        return getCname();
260    }
261
262    /**
263     * Return this users plugins
264     * @return 
265     */
266    public YabsPlugin[] getPlugins() {
267        return YabsPluginLoader.getPlugins();
268    }
269
270    /**
271     *
272     * @return True if this user IS User.DEFAULT
273     */
274    public boolean isDefault() {
275        if (getName().equals(DEFAULT.__getCname()) && __getIDS().intValue() == DEFAULT.__getIDS().intValue()) {
276            return true;
277        } else {
278            return false;
279        }
280    }
281
282    private boolean isAdmin() {
283        if (__getIDS().intValue() == 1) {
284            return true;
285        } else {
286            return false;
287        }
288    }
289
290    /**
291     * Logs in this user into yabs (sets user defined properties etc); does not check the authentication. Use
292     * {@link mpv5.usermanagement.MPSecurityManager#checkAuth(java.lang.String, java.lang.String) }
293     * before logging in the User.
294     */
295    public void login() {
296        Log.Debug(this, "releaseAllObjectsFor: " + this);
297        DatabaseObjectLock.releaseAllObjectsFor(this);
298        if (isenabled) {
299            _setUser(this);
300            setProperties();
301            try {
302                Locale.setDefault(TypeConversion.stringToLocale(__getLocale()));
303                Log.Debug(this, "Locale.setDefault() for: " + Locale.getDefault());
304                ControlPanel_Fonts.applyFont(Font.decode(LocalSettings.getProperty(LocalSettings.DEFAULT_FONT)));
305                if (UIManager.getLookAndFeel().getName() == null ? __getLaf() != null : !UIManager.getLookAndFeel().getName().equals(__getLaf())) {
306                    Main.setLaF(__getLaf());
307                }
308                defineMailConfig();
309                defineDTAConfig();
310                Log.Debug(this, "LanguageManager.getBundle() for: " + this);
311                LanguageManager.getBundle();
312            } catch (Exception e) {
313                Log.Debug(e);
314            }
315            final User t = this;
316
317            Runnable runnable = new Runnable() {
318
319                @Override
320                public void run() {
321//                    setTitle();
322                    setDatelastlog(new Date());
323                    setIsloggedin(true);
324                    save();
325                    DatabaseObject.cacheObjects();//re-cache for user
326                    YabsViewProxy.instance().addMessage(Messages.CACHED_OBJECTS);
327                    try {
328                        layoutinfo.putAll(ValueProperty.getProperty(t, "layoutinfo").getValue(new HashMap<String, String>()));
329                    } catch (Exception ex) {
330                        Log.Debug(this, ex.getMessage());
331                    }
332                }
333            };
334
335            new Thread(runnable).start();
336        } else {
337            Popup.warn(Messages.NOT_POSSIBLE.toString() + Messages.USER_DISABLED);
338        }
339    }
340
341    /**
342     * Logs out this user
343     */
344    public void logout() {
345        DatabaseObjectLock.releaseAllObjectsFor(this);
346        saveProperties();
347        _setUser(DEFAULT);
348        if (!isDefault()) {
349            setIsloggedin(false);
350            save();
351        }
352    }
353
354    @Override
355    public boolean save() {
356        if (!isDefault()) {
357            return super.save();
358        } else {
359            Popup.notice(Messages.DEFAULT_USER);
360            return false;
361        }
362    }
363
364    @Override
365    public boolean delete() {
366        if (!isAdmin()) {
367            return super.delete();
368        } else {
369            Popup.notice(Messages.ADMIN_USER);
370            return false;
371        }
372    }
373
374    /**
375     * @return the password
376     */
377    public String __getPassword() {
378        return password;
379    }
380
381    /**
382     * @param password the password to set
383     */
384    public void setPassword(String password) {
385        this.password = password;
386    }
387
388    /**
389     * @return the laf
390     */
391    public String __getLaf() {
392        return laf;
393    }
394
395    /**
396     * @param laf the laf to set
397     */
398    public void setLaf(String laf) {
399        this.laf = laf;
400    }
401
402    /**
403     * @return the locale
404     */
405    public String __getLocale() {
406        return locale;
407    }
408
409    /**
410     * @param locale the locale to set
411     */
412    public void setLocale(String locale) {
413        this.locale = locale;
414    }
415
416    /**
417     * @return the mail
418     */
419    public String __getMail() {
420        return mail;
421    }
422
423    /**
424     * @param mail the mail to set
425     */
426    public void setMail(String mail) {
427        this.mail = mail;
428    }
429
430    /**
431     * @return the language
432     */
433    public String __getLanguage() {
434        return language;
435    }
436
437    /**
438     * @param language the language to set
439     */
440    public void setLanguage(String language) {
441        this.language = language;
442    }
443
444    /**
445     * @return the isenabled
446     */
447    public boolean __getIsenabled() {
448        return isenabled;
449    }
450
451    /**
452     * @param isenabled the isenabled to set
453     */
454    public void setIsenabled(boolean isenabled) {
455        this.isenabled = isenabled;
456    }
457
458    @Override
459    public String toString() {
460        return getCname();
461    }
462
463    /**
464     * @return the lastlogdate
465     */
466    public Date __getDatelastlog() {
467        return datelastlog;
468    }
469
470    /**
471     * @param lastlogdate the lastlogdate to set
472     */
473    public void setDatelastlog(Date lastlogdate) {
474        this.datelastlog = lastlogdate;
475    }
476
477    /**
478     * @return the isloggedin
479     */
480    public boolean __getIsloggedin() {
481        return isloggedin;
482    }
483
484    /**
485     * @param isloggedin the isloggedin to set
486     */
487    public void setIsloggedin(boolean isloggedin) {
488        this.isloggedin = isloggedin;
489    }
490
491    /**
492     * @return the fullname
493     */
494    public String __getFullname() {
495        return fullname;
496    }
497
498    /**
499     * @param fullname the fullname to set
500     */
501    public void setFullname(String fullname) {
502        this.fullname = fullname;
503    }
504
505    /**
506     * @return the defcountry
507     */
508    public String __getDefcountry() {
509        return defcountry;
510    }
511
512    /**
513     * @param defcountry the defcountry to set
514     */
515    public void setDefcountry(String defcountry) {
516        this.defcountry = defcountry;
517    }
518
519    /**
520     * If the usernames & ids match, return true
521     * @param n
522     * @return
523     */
524    public boolean equalTo(User n) {
525        if ((n).__getCname().equals(this.__getCname()) && (n).__getIDS().intValue() == this.__getIDS().intValue()) {
526            return true;
527        } else {
528            return false;
529        }
530    }
531
532    @Override
533    public JComponent getView() {
534        return new mpv5.ui.dialogs.subcomponents.ControlPanel_Users(this);
535    }
536
537    /**
538     * Set a property for this user
539     * @param key
540     * @param value
541     */
542    public void changeProperty(String key, String value) {
543        properties.changeProperty(key, value);
544    }
545
546    /**
547     * Retrieve all properties from this user
548     * @return 
549     */
550    public PropertyStore getProperties() {
551        return properties;
552    }
553
554    /**
555     * Saves the user properties
556     */
557    public void saveProperties() {
558        synchronized (properties) {
559            List<String[]> l = properties.getList();
560
561            for (int i = 0; i < l.size(); i++) {
562                String[] d = l.get(i);
563                UserProperty p = new UserProperty();
564                p.setValue(d[1]);
565                p.setCname(d[0]);
566                p.setUsersids(getID());
567                p.setGroupsids(__getGroupsids());
568                p.save();
569            }
570        }
571    }
572
573    /**
574     * Delete the users properties
575     */
576    public void deleteProperties() {
577        QueryCriteria c = new QueryCriteria("usersids", __getIDS());
578        QueryHandler.instanceOf().clone(Context.getUserProperties()).delete(c);
579    }
580
581    /**
582     * Apply the user settings to this user (usually called during the login process)
583     */
584    public void setProperties() {
585
586        QueryCriteria2 criteria = new QueryCriteria2();
587        criteria.and(new QueryParameter(Context.getUserProperties(), "usersids", ids, QueryParameter.EQUALS),
588                     new QueryParameter(Context.getUserProperties(), "groupsids", __getGroupsids(), QueryParameter.EQUALS));
589        properties = new PropertyStore();
590        try {
591            properties.addAll(QueryHandler.instanceOf().clone(Context.getUserProperties()).select("cname, value", criteria).getData());
592            properties.addAll(PROPERTIES_OVERRIDE);
593            properties.setChanged(false);
594        } catch (NodataFoundException ex) {
595            Log.Debug(this, ex.getMessage());
596        }
597    }
598
599    @Override
600    public HashMap<String, Object> resolveReferences(HashMap<String, Object> map) {
601        super.resolveReferences(map);
602        List<Company> data;
603        try {
604            data = DatabaseObject.getReferencedObjects(this, Context.getCompany(), new Company());
605            //Presumably 0 or 1
606            for (int i = 0; i < data.size(); i++) {
607                map.put("company", data.get(i));
608            }
609        } catch (Exception ex) {
610            Log.Debug(this, ex.getMessage());
611        }
612//TODO  check for usage
613        return map;
614    }
615
616    /**
617     * @return the isrgrouped
618     */
619    public boolean __getIsrgrouped() {
620        return isrgrouped;
621    }
622
623    /**
624     * @param isrgrouped the isrgrouped to set
625     */
626    public void setIsrgrouped(boolean isrgrouped) {
627        this.isrgrouped = isrgrouped;
628    }
629
630    /**
631     * @return the inthighestright
632     */
633    public int __getInthighestright() {
634        return inthighestright;
635    }
636
637    /**
638     * @param inthighestright the inthighestright to set
639     */
640    public void setInthighestright(int inthighestright) {
641        this.inthighestright = inthighestright;
642    }
643
644    /**
645     * @return the intdefaultaccount
646     */
647    public int __getIntdefaultaccount() {
648        return intdefaultaccount;
649    }
650
651    /**
652     * @param intdefaultaccount the intdefaultaccount to set
653     */
654    public void setIntdefaultaccount(int intdefaultaccount) {
655        this.intdefaultaccount = intdefaultaccount;
656    }
657
658    @Override
659    public mpv5.utils.images.MPIcon getIcon() {
660        return null;
661    }
662
663    /**
664     * If this returns true, the User is only allowed to see, and use, data which belongs to the same Group as him
665     * <br/><b> and data from the Group with the ID 1.</b><br/><br/>
666     * Use this method to implement multi-client capability.
667     * @return
668     */
669    public boolean isGroupRestricted() {
670        return __getIsrgrouped();
671    }
672
673    /**
674     * @return the intdefaultstatus
675     */
676    public int __getIntdefaultstatus() {
677        return intdefaultstatus;
678    }
679
680    /**
681     * @param intdefaultstatus the intdefaultstatus to set
682     */
683    public void setIntdefaultstatus(int intdefaultstatus) {
684        this.intdefaultstatus = intdefaultstatus;
685    }
686
687    /**
688     * @return the compsids
689     */
690    public int __getCompsids() {
691        return compsids;
692    }
693
694    /**
695     * @param compsids the compsids to set
696     */
697    public void setCompsids(int compsids) {
698        this.compsids = compsids;
699    }
700
701    /**
702     * Define the mail config
703     */
704    public void defineMailConfig() {
705        if (getProperties().hasProperty("smtp.host")) {
706            defineMailConfiguration(new MailConfiguration());
707            mailConfiguration.setSmtpHost(getProperties().getProperty("smtp.host"));
708            mailConfiguration.setSenderAddress(mail);
709            mailConfiguration.setUsername(getProperties().getProperty("smtp.host.user"));
710            mailConfiguration.setPassword(getProperties().getProperty("smtp.host.password"));
711            mailConfiguration.setUseTls(Boolean.valueOf(getProperties().getProperty("smtp.host.usetls")));
712            mailConfiguration.setUseSmtps(Boolean.valueOf(getProperties().getProperty("smtp.host.usesmpts")));
713        } else {
714            Log.Debug(this, "Mail configuration not set.");
715        }
716    }
717
718    /**
719     * @return the mailConfiguration
720     */
721    public MailConfiguration getMailConfiguration() {
722        if (mailConfiguration.getSmtpHost() == null || mailConfiguration.getSmtpHost().length() == 0) {
723            mpv5.YabsViewProxy.instance().addMessage(Messages.NO_MAIL_CONFIG);
724            Log.Debug(this, "SMTP host configuration not set: " + mailConfiguration.getSmtpHost());
725        }
726        return mailConfiguration;
727    }
728
729    /**
730     * @param mailConfiguration the mailConfiguration to set
731     */
732    public void defineMailConfiguration(MailConfiguration mailConfiguration) {
733        this.mailConfiguration = mailConfiguration;
734    }
735
736    /**
737     * The configured banking account
738     * @return
739     */
740    public Konto getDTAAccount() {
741        return dtaconf.getBankAccount();
742    }
743
744    /**
745     * The configured banking account
746     * @return
747     */
748    public List<String> getDTAUsages() {
749        return dtaconf.getUsages();
750    }
751
752    public void defineDTAConfig() {
753        try {
754            Konto acc = new Konto(getProperties().getProperty("dtabankid"),
755                    getProperties().getProperty("dtabankaccount"),
756                    getProperties().getProperty("dtabankname"));
757            acc.name = __getFullname();
758            dtaconf = new DTAConfig();
759            dtaconf.setBankAccount(acc);
760            dtaconf.getUsages().add(getProperties().getProperty("dtausage0"));
761        } catch (Exception e) {
762            Log.Debug(this, "Unable to create DTA info");
763            dtaconf = null;
764        }
765    }
766    private HashMap<String, String> layoutinfo = new HashMap<String, String>();
767
768    /**
769     *
770     * @return
771     */
772    public HashMap<String, String> getLayoutProperties() {
773        return layoutinfo;
774    }
775
776    /**
777     * Delegates to getproperties().getproperty
778     * @param typ
779     * @param name
780     * @return
781     */
782    public boolean getProperty(String typ, String name) {
783        return getProperties().getProperty(typ, name);
784    }
785
786    /** Delegates to getproperties().getproperty
787     * @param name
788     * @return
789     */
790    public String getProperty(String name) {
791        return getProperties().getProperty(name);
792    }
793
794    /** Delegates to getproperties().setproperty
795     * @param name
796     * @return
797     */
798    public void setProperty(String key, String value) {
799        getProperties().changeProperty(key, value);
800    }
801}
802
803class DTAConfig {
804
805    private Konto bankAccount;
806    private List<String> usages = new Vector<String>();
807
808    /**
809     * @return the bankAccount
810     */
811    public Konto getBankAccount() {
812        return bankAccount;
813    }
814
815    /**
816     * @param bankAccount the bankAccount to set
817     */
818    public void setBankAccount(Konto bankAccount) {
819        this.bankAccount = bankAccount;
820    }
821
822    /**
823     * @return the usages
824     */
825    public List<String> getUsages() {
826        return usages;
827    }
828}