PageRenderTime 826ms CodeModel.GetById 162ms app.highlight 456ms RepoModel.GetById 114ms app.codeStats 1ms

/src/enoa/handler/TemplateHandler.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 609 lines | 353 code | 78 blank | 178 comment | 38 complexity | 42a2b1b011b19294b4b811c2559b8f20 MD5 | raw file
  1package enoa.handler;
  2
  3import java.awt.Color;
  4import java.io.File;
  5import java.util.HashMap;
  6import java.util.Iterator;
  7import javax.swing.JComponent;
  8import mpv5.db.common.Context;
  9import mpv5.db.common.DatabaseObject;
 10import mpv5.db.common.NodataFoundException;
 11import mpv5.db.common.QueryHandler;
 12import mpv5.db.common.ReturnValue;
 13import mpv5.db.common.SaveString;
 14import mpv5.db.common.Templateable;
 15import mpv5.db.objects.*;
 16import mpv5.globals.LocalSettings;
 17import mpv5.globals.Messages;
 18import mpv5.handler.MPEnum;
 19import mpv5.logging.Log;
 20import mpv5.ui.panels.DataPanel;
 21import mpv5.usermanagement.MPSecurityManager;
 22import mpv5.utils.export.ODTFile;
 23import mpv5.utils.export.PDFFile;
 24
 25import static mpv5.globals.Constants.*;
 26
 27/**
 28 * This class provides {@link Template} loading and caching functionality, thread-safe
 29 */
 30public class TemplateHandler {
 31    
 32    /**
 33     * Return true if the Template for the currently logged in user, with the given type, and matching the targets group is loaded
 34     * @param group
 35     * @param type
 36     * @return
 37     */
 38    public static synchronized boolean isLoaded(Long group, int type) {
 39        String key = null;
 40        if (group != null) {
 41            key = mpv5.db.objects.User.getCurrentUser() + "@" + type + "@" + group;
 42        } else {
 43            key = mpv5.db.objects.User.getCurrentUser() + "@" + type + "@" + 1;
 44        }
 45
 46        if (TEMPLATE_CACHE.containsKey(key)) {
 47            return true;
 48        } else {
 49            return false;
 50        }
 51    }
 52
 53    /**
 54     * Return true if the Template for the currently logged in user, with the given type, and matching the targets group is loaded
 55     * @param target
 56     * @param type
 57     * @return
 58     */
 59    public static synchronized boolean isLoaded(Templateable target) {
 60        String key = null;
 61        if (target != null) {
 62            key = mpv5.db.objects.User.getCurrentUser() + "@" + target.templateType() + "@" + target.templateGroupIds();
 63        } else {
 64            key = mpv5.db.objects.User.getCurrentUser() + "@" + target.templateType() + "@" + 1;
 65        }
 66
 67        if (TEMPLATE_CACHE.containsKey(key)) {
 68            return true;
 69        } else {
 70            return false;
 71        }
 72    }
 73
 74    /**
 75     * Loads a template including neccesary files, target's group
 76     * @param target
 77     * @param typ
 78     * @return
 79     */
 80    public static synchronized Template loadTemplate(Templateable target) {
 81
 82        int groupsids = 0;
 83        if (target != null) {
 84            groupsids = target.templateGroupIds();
 85        } else {
 86            groupsids = 1;
 87        }
 88
 89        return loadTemplate(groupsids, target.templateType());
 90    }
 91
 92    /**
 93     *
 94     * @param t
 95     * @return
 96     */
 97    public static synchronized Template loadTemplate(Template t) {
 98        return loadTemplate(t.__getGroupsids(), Integer.valueOf(t.__getMimetype()));
 99    }
100
101    /**
102     * 
103     * @param group
104     * @param typ
105     * @return
106     */
107    public static synchronized Template loadTemplate(int group, int typ) {
108        return loadTemplate(Long.valueOf(group), typ);
109    }
110
111    /**
112     * Loads a template including necessary files
113     * @param target
114     * @param groupsids
115     * @param typ
116     * @return
117     */
118    public static synchronized Template loadTemplate(long groupsids, int typ) {
119        ReturnValue data;
120        if (LocalSettings.getBooleanProperty(LocalSettings.OFFICE_USE)) {
121            Integer type = new Integer(typ);
122
123            if (groupsids < 0) {
124                groupsids = 1;
125            }
126
127            String key = mpv5.db.objects.User.getCurrentUser() + "@" + type + "@" + groupsids;
128            if (TEMPLATE_CACHE.containsKey(key)) {
129                return TEMPLATE_CACHE.get(key);
130            } else {
131
132                if (type != null) {
133                    data = TemplateHandler.getDefinedTemplatesFor(groupsids, type);
134                    Template preloadedTemplate = null;
135                    if (data.hasData()) {
136                        try {
137                            preloadedTemplate = (Template) DatabaseObject.getObject(Context.getTemplate(), Integer.valueOf(data.getData()[data.getData().length - 1][0].toString()));
138                            Log.Debug(TemplateHandler.class, preloadedTemplate.getFile());
139                            if (preloadedTemplate.getFile().getName().endsWith("odt")) {
140                                if (LocalSettings.getBooleanProperty(LocalSettings.OFFICE_USE)) {
141                                    preloadedTemplate.defineExFile(new ODTFile(preloadedTemplate.getFile().getPath()));
142                                    Log.Debug(Template.class, "Loaded template: " + preloadedTemplate);
143                                    mpv5.YabsViewProxy.instance().addMessage(preloadedTemplate + Messages.LOADED.toString(), Color.GREEN);
144                                } else {
145//                                Popup.notice(Messages.NOT_POSSIBLE + "\n" + Messages.OOCONNERROR);
146                                    return null;
147                                }
148                            } else {
149                                preloadedTemplate.defineExFile(new PDFFile(preloadedTemplate.getFile().getPath()));
150                            }
151                            TEMPLATE_CACHE.put(key, preloadedTemplate);
152                        } catch (Exception ex) {
153                            Log.Debug(Template.class, "Invalid template: " + data.getData()[data.getData().length - 1][0].toString());
154                            try {
155                                Log.Debug(TemplateHandler.class, "Not removing invalid template " + preloadedTemplate);
156                                //preloadedTemplate.delete();
157                            } catch (Exception e) {
158                                Log.Debug(e);
159                            }
160                            return null;
161                        }
162                    } else {
163                        try {
164                            if (!(TEMPLATE_MISSING_NOTIFICATIONS.containsKey(type.toString()) && TEMPLATE_MISSING_NOTIFICATIONS.get(type.toString()).equals(Group.getObject(Context.getGroup(), (int) groupsids)))) {
165                                mpv5.YabsViewProxy.instance().addMessage(Messages.OO_NO_TEMPLATE + ": " + TemplateHandler.getName(type) + " [" + mpv5.db.objects.User.getCurrentUser() + "] [" + Group.getObject(Context.getGroup(), (int) groupsids) + "]", Color.YELLOW);
166                                Log.Debug(Template.class, "No template found for type: " + type + " for user: " + mpv5.db.objects.User.getCurrentUser() + " in GROUP " + Group.getObject(Context.getGroup(), (int) groupsids));
167                                TEMPLATE_MISSING_NOTIFICATIONS.put(type.toString(), (Group) Group.getObject(Context.getGroup(), (int) groupsids));
168                            }
169                        } catch (NodataFoundException nodataFoundException) {
170                            Log.Debug(Template.class, nodataFoundException.getMessage());
171                        }
172                    }
173                    return preloadedTemplate;
174                } else {
175                    return null;
176                }
177            }
178        } else {
179            return null;
180        }
181    }
182
183    private static ReturnValue getDefinedTemplatesFor(long groupsids, Integer type) {
184        ReturnValue data = QueryHandler.getConnection().freeQuery(
185                "SELECT templatesids FROM templatestousers  LEFT OUTER JOIN templates AS templates0 ON "
186                + "templates0.ids = templatestousers.templatesids WHERE templatestousers.usersids="
187                + mpv5.db.objects.User.getCurrentUser().__getIDS()
188                + " AND "
189                + "templates0.mimetype='" + type
190                + "' AND templatestousers.IDS>0 "
191                + "AND templates0.groupsids = " + groupsids, MPSecurityManager.VIEW, null);
192        if (!data.hasData()) {
193            data = QueryHandler.getConnection().freeQuery(
194                    "SELECT templatesids FROM templatestousers  LEFT OUTER JOIN templates AS templates0 ON "
195                    + "templates0.ids = templatestousers.templatesids WHERE templatestousers.usersids="
196                    + mpv5.db.objects.User.getCurrentUser().__getIDS()
197                    + " AND "
198                    + "templates0.mimetype='" + type
199                    + "' AND templatestousers.IDS>0 "
200                    + "AND templates0.groupsids = 1", MPSecurityManager.VIEW, null);
201        }
202        Log.Debug(TemplateHandler.class, "gefundene Daten: " + data.hasData());
203        return data;
204    }
205
206    /**
207     * An enum over the available template types and their String representation
208     * @return
209     */
210    public static MPEnum[] getTypes() {
211        MPEnum[] types = new MPEnum[15];
212        types[0] = new MPEnum() {
213
214            public Integer getId() {
215                return TYPE_BILL;
216            }
217
218            public String getName() {
219                return Messages.TYPE_BILL.toString();
220            }
221        };
222
223        types[1] = new MPEnum() {
224
225            public Integer getId() {
226                return TYPE_OFFER;
227            }
228
229            public String getName() {
230                return Messages.TYPE_OFFER.toString();
231            }
232        };
233
234        types[2] = new MPEnum() {
235
236            public Integer getId() {
237                return TYPE_ORDER;
238            }
239
240            public String getName() {
241                return Messages.TYPE_ORDER.toString();
242            }
243        };
244
245        types[3] = new MPEnum() {
246
247            public Integer getId() {
248                return TYPE_CONTACT;
249            }
250
251            public String getName() {
252                return Messages.TYPE_CONTACT.toString();
253            }
254        };
255
256        types[4] = new MPEnum() {
257
258            public Integer getId() {
259                return TYPE_DELIVERY_NOTE;
260            }
261
262            public String getName() {
263                return Messages.TYPE_DELIVERY.toString();
264            }
265        };
266
267        types[5] = new MPEnum() {
268
269            public Integer getId() {
270                return TYPE_ORDER_CONFIRMATION;
271            }
272
273            public String getName() {
274                return Messages.TYPE_CONFIRMATION.toString();
275            }
276        };
277
278        types[6] = new MPEnum() {
279
280            public Integer getId() {
281                return TYPE_PRODUCT;
282            }
283
284            public String getName() {
285                return Messages.TYPE_PRODUCT.toString();
286            }
287        };
288
289        types[7] = new MPEnum() {
290
291            public Integer getId() {
292                return TYPE_SERVICE;
293            }
294
295            public String getName() {
296                return Messages.TYPE_SERVICE.toString();
297            }
298        };
299
300        types[8] = new MPEnum() {
301
302            public Integer getId() {
303                return TYPE_REMINDER;
304            }
305
306            public String getName() {
307                return Messages.TYPE_REMINDER.toString();
308            }
309        };
310
311        types[9] = new MPEnum() {
312
313            public Integer getId() {
314                return TYPE_JOURNAL;
315            }
316
317            public String getName() {
318                return Messages.TYPE_JOURNAL.toString();
319            }
320        };
321
322        types[10] = new MPEnum() {
323
324            public Integer getId() {
325                return TYPE_PRODUCT_ORDER;
326            }
327
328            public String getName() {
329                return Messages.TYPE_PRODUCT_ORDER.toString();
330            }
331        };
332
333        types[11] = new MPEnum() {
334
335            public Integer getId() {
336                return TYPE_CONTACT;
337            }
338
339            public String getName() {
340                return Messages.TYPE_CONTRACT.toString();
341            }
342        };
343            
344        types[12] = new MPEnum() {
345
346            public Integer getId() {
347                return TYPE_CONVERSATION;
348            }
349
350            public String getName() {
351                return Messages.TYPE_CONVERSATION.toString();
352            }            
353        };
354        
355        types[13] = new MPEnum() {
356
357            public Integer getId() {
358                return TYPE_MASSPRINT;
359            }
360
361            public String getName() {
362                return Messages.TYPE_MASSPRINT.toString();
363            }            
364        };
365
366        types[14] = new MPEnum() {
367
368            public Integer getId() {
369                return TYPE_ACTIVITY;
370            }
371
372            public String getName() {
373                return Messages.TYPE_ACTIVITY.toString();
374            }
375        };
376        return types;
377    }
378
379//    /**
380//     * (P)reload the template files
381//     * @deprecated performance..
382//     */
383//    public static synchronized void cacheTemplates() {
384//        TEMPLATE_CACHE.clear();
385//        final List<Group> groups = new ArrayList<Group>();
386//        try {
387//            ArrayList<DatabaseObject> tlist = Group.getObjects(Context.getGroup(), true);
388//            for (int i = 0; i < tlist.size(); i++) {
389//                DatabaseObject databaseObject = tlist.get(i);
390//                groups.add((Group) databaseObject);
391//            }
392//        } catch (NodataFoundException ex) {
393//        }
394//
395//        List<Templateable> targets = new ArrayList<Templateable>();
396//        List<Integer> typs = new ArrayList<Integer>();
397//        Item it1 = new Item();
398//        it1.setInttype(Item.TYPE_BILL);
399//        targets.add(it1);
400//        typs.add(TYPE_BILL);
401//
402//        Item it2 = new Item();
403//        it2.setInttype(Item.TYPE_OFFER);
404//        targets.add(it2);
405//        typs.add(TYPE_OFFER);
406//
407//        Item it3 = new Item();
408//        it3.setInttype(Item.TYPE_ORDER);
409//        targets.add(it3);
410//        typs.add(TYPE_ORDER);
411//
412//        Item it4 = new Item();
413//        it4.setInttype(TYPE_DELIVERY_NOTE);
414//        targets.add(it4);
415//        typs.add(TYPE_DELIVERY_NOTE);
416//
417//        Product it5 = new Product();
418//        it5.setInttype(Product.TYPE_PRODUCT);
419//        targets.add(it5);
420//        typs.add(TYPE_PRODUCT);
421//
422//        Product it6 = new Product();
423//        it6.setInttype(Product.TYPE_SERVICE);
424//        targets.add(it6);
425//        typs.add(TYPE_SERVICE);
426//
427//        Reminder it7 = new Reminder();
428//        targets.add(it7);
429//        typs.add(TYPE_REMINDER);
430//
431//        Contact it8 = new Contact();
432//        targets.add(it8);
433//        typs.add(TYPE_CONTACT);
434//
435//        targets.add(null);
436//        typs.add(TYPE_JOURNAL);
437//
438//        for (int i = 0; i < targets.size(); i++) {
439////            final Templateable databaseObject = targets.get(i);
440//            final int type = typs.get(i);
441//            Runnable runnable = new Runnable() {
442//
443//                public void run() {
444//                    for (int j = 0; j < groups.size(); j++) {
445//                        Group group = groups.get(j);
446////                        if (databaseObject != null && group != null) {
447////                            ((DatabaseObject)databaseObject).setGroupsids(group.__getIDS());
448////                        }
449//                        loadTemplate(group.__getIDS(), type);
450//                    }
451//                }
452//            };
453//            new Thread(runnable).start();
454//        }
455//    }
456
457    /**
458     * The cache of the templates
459     */
460    public static HashMap<String, Template> TEMPLATE_CACHE = new HashMap<String, Template>();
461    public static HashMap<String, Group> TEMPLATE_MISSING_NOTIFICATIONS = new HashMap<String, Group>();
462
463    /**
464     * Load a template (if not already done) and enable the given button after loading.
465     * @param button
466     * @param dataOwner
467     */
468    public static void loadTemplateFor(final JComponent button, final Templateable dataOwner) {
469        loadTemplate(dataOwner.templateGroupIds(), dataOwner.templateType());
470    }
471
472    /**
473     * Load a template for a specific GROUP rather than the dataOwners group (if not already done) and enable the given button after loading.
474     * @param button
475     * @param typ
476     * @param groupsids
477     */
478    public static void loadTemplateFor(final JComponent button, final long groupsids, final int typ) {
479        button.setEnabled(false);
480        Runnable runnable = new Runnable() {
481
482            @Override
483            public void run() {
484                loadTemplate(groupsids, typ);
485                button.setEnabled(isLoaded(groupsids, typ));
486            }
487        };
488        new Thread(runnable).start();
489    }
490
491    /**
492     * Gets the String representation of the given template type
493     * @param type
494     * @return
495     */
496    public static String getName(int type) {
497        MPEnum[] e = getTypes();
498        for (int i = 0; i < e.length; i++) {
499            MPEnum mPEnum = e[i];
500            if (mPEnum.getId().intValue() == type) {
501                return mPEnum.getName();
502            }
503        }
504        return "<undefined> [" + type + "]";
505    }
506
507    /**
508     * Load a template (if not already done) and enable the given button after loading.
509     * @param jComponent
510     * @param dataOwner
511     * @param TYPE
512     */
513    public static void loadTemplateFor(final JComponent[] jComponent, final Templateable dataOwner) {
514        for (int i = 0; i < jComponent.length; i++) {
515            JComponent jComponent1 = jComponent[i];
516            jComponent1.setEnabled(false);
517        }
518        Runnable runnable = new Runnable() {
519
520            public void run() {
521                loadTemplate(dataOwner);
522                for (int i = 0; i < jComponent.length; i++) {
523                    JComponent jComponent1 = jComponent[i];
524                    jComponent1.setEnabled(isLoaded(dataOwner));
525                }
526            }
527        };
528        new Thread(runnable).start();
529    }
530
531    /**
532     * Load a template (if not already done) and enable the given button after loading.
533     * @param jComponent
534     * @param typ
535     * @param groupsids
536     */
537    public static void loadTemplateFor(final JComponent[] jComponent, final long groupsids, final int typ) {
538        for (int i = 0; i < jComponent.length; i++) {
539            JComponent jComponent1 = jComponent[i];
540            jComponent1.setEnabled(false);
541        }
542        Runnable runnable = new Runnable() {
543
544            @Override
545            public void run() {
546                loadTemplate(groupsids, typ);
547                for (int i = 0; i < jComponent.length; i++) {
548                    JComponent jComponent1 = jComponent[i];
549                    jComponent1.setEnabled(isLoaded(groupsids, typ));
550                }
551            }
552        };
553        new Thread(runnable).start();
554    }
555
556    /**
557     * Imports a template file
558     * @param file
559     * @return
560     */
561    public static boolean importTemplate(File file) {
562        Template t = new Template();
563
564        return QueryHandler.instanceOf().clone(Context.getFiles(), (DataPanel) null).insertFile(file, t, new SaveString(file.getName(), true));
565
566//                User object = mpv5.db.objects.User.getCurrentUser();
567//
568//                QueryCriteria d = new QueryCriteria();
569//                d.add("cname", dataOwner.__getIDS() + "@" + object.__getIDS() + "@" + mpv5.db.objects.User.getCurrentUser().__getGroupsids());
570//                QueryHandler.instanceOf().clone(Context.getTemplatesToUsers()).delete(d);
571//
572//                QueryData c = new QueryData();
573//                c.add("usersids", object.__getIDS());
574//                c.add("templatesids", dataOwner.__getIDS());
575//                c.add("groupsids", mpv5.db.objects.User.getCurrentUser().__getGroupsids());
576//                c.add("cname", dataOwner.__getIDS() + "@" + object.__getIDS() + "@" + mpv5.db.objects.User.getCurrentUser().__getGroupsids());
577//                QueryHandler.instanceOf().clone(Context.getTemplatesToUsers()).insert(c, null);
578
579    }
580    
581   /**
582     * Exports all template Objects for give template-Type
583     * @param Type - the templatetype 
584     * @return template[] - the template assoziated to the give templatetype 
585     */
586    public static Template[] getTemplatesForType(long groupsids, int typ) { 
587        String key = mpv5.db.objects.User.getCurrentUser() + "@" + new Integer(typ) + "@" + groupsids;
588        ReturnValue data = TemplateHandler.getDefinedTemplatesFor(groupsids, new Integer(typ));
589        Iterator<Object[]> it = data.getDataIterator();
590        Template[] templates = new Template[data.getData().length];
591        int i = 0;
592        while (it.hasNext()) {
593            Object[] ret = it.next();
594            try {
595                templates[i++] = (Template) DatabaseObject.getObject(Context.getTemplate(), Integer.valueOf(ret[0].toString()));
596            } catch (Exception ex) {
597                Log.Debug(Template.class, ex);
598            }
599        }
600        return templates;
601    }
602
603    /**
604     * Clear the template cache
605     */
606    public static void clearCache() {
607        TEMPLATE_CACHE.clear();
608    }
609}