OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 139 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
74 ilm 1
package org.openconcerto.modules.extensionbuilder;
2
 
3
import java.io.BufferedOutputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.IOException;
6
import java.io.StringReader;
7
import java.io.UnsupportedEncodingException;
8
import java.math.BigDecimal;
9
import java.sql.SQLException;
10
import java.util.ArrayList;
11
import java.util.Collection;
12
import java.util.Collections;
13
import java.util.Comparator;
14
import java.util.HashSet;
15
import java.util.LinkedHashSet;
16
import java.util.List;
86 ilm 17
import java.util.Locale;
74 ilm 18
import java.util.Set;
19
import java.util.logging.Level;
20
 
21
import javax.swing.JFrame;
22
import javax.swing.JOptionPane;
23
import javax.swing.event.ChangeEvent;
24
import javax.swing.event.ChangeListener;
25
 
26
import org.jdom.Document;
27
import org.jdom.Element;
28
import org.jdom.input.SAXBuilder;
29
import org.jdom.output.Format;
30
import org.jdom.output.XMLOutputter;
31
import org.openconcerto.erp.action.CreateFrameAbstractAction;
32
import org.openconcerto.erp.config.ComptaPropsConfiguration;
33
import org.openconcerto.erp.config.Log;
34
import org.openconcerto.erp.config.MenuAndActions;
35
import org.openconcerto.erp.config.MenuManager;
36
import org.openconcerto.erp.modules.MenuContext;
37
import org.openconcerto.modules.extensionbuilder.component.ComponentDescritor;
38
import org.openconcerto.modules.extensionbuilder.list.ColumnDescriptor;
39
import org.openconcerto.modules.extensionbuilder.list.ListDescriptor;
40
import org.openconcerto.modules.extensionbuilder.menu.mainmenu.MenuDescriptor;
41
import org.openconcerto.modules.extensionbuilder.meu.actions.ActionDescriptor;
42
import org.openconcerto.modules.extensionbuilder.table.AllTableListModel;
43
import org.openconcerto.modules.extensionbuilder.table.ElementDescriptor;
44
import org.openconcerto.modules.extensionbuilder.table.FieldDescriptor;
45
import org.openconcerto.modules.extensionbuilder.table.TableDescritor;
46
import org.openconcerto.modules.extensionbuilder.translation.Translation;
47
import org.openconcerto.modules.extensionbuilder.translation.action.ActionTranslation;
48
import org.openconcerto.modules.extensionbuilder.translation.field.FieldTranslation;
49
import org.openconcerto.modules.extensionbuilder.translation.field.TableTranslation;
50
import org.openconcerto.modules.extensionbuilder.translation.menu.MenuTranslation;
51
import org.openconcerto.sql.element.GroupSQLComponent;
52
import org.openconcerto.sql.element.SQLElement;
53
import org.openconcerto.sql.model.DBRoot;
54
import org.openconcerto.sql.model.FieldPath;
55
import org.openconcerto.sql.model.SQLBase;
56
import org.openconcerto.sql.model.SQLField;
57
import org.openconcerto.sql.model.SQLName;
58
import org.openconcerto.sql.model.SQLRowAccessor;
59
import org.openconcerto.sql.model.SQLRowValues;
60
import org.openconcerto.sql.model.SQLTable;
86 ilm 61
import org.openconcerto.sql.model.graph.PathBuilder;
74 ilm 62
import org.openconcerto.sql.request.ListSQLRequest;
139 ilm 63
import org.openconcerto.sql.request.RowItemDesc;
153 ilm 64
import org.openconcerto.sql.request.SQLFieldTranslator;
74 ilm 65
import org.openconcerto.sql.utils.AlterTable;
66
import org.openconcerto.sql.utils.ChangeTable;
67
import org.openconcerto.sql.utils.SQLCreateTable;
68
import org.openconcerto.sql.view.EditFrame;
69
import org.openconcerto.sql.view.EditPanel;
70
import org.openconcerto.sql.view.EditPanel.EditMode;
71
import org.openconcerto.sql.view.IListFrame;
72
import org.openconcerto.sql.view.ListeAddPanel;
73
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
74
import org.openconcerto.sql.view.list.IListe;
75
import org.openconcerto.sql.view.list.IListeAction;
76
import org.openconcerto.sql.view.list.RowAction;
77
import org.openconcerto.sql.view.list.SQLTableModelColumn;
78
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
79
import org.openconcerto.ui.group.Group;
80
import org.openconcerto.ui.group.Item;
81
import org.openconcerto.ui.group.LayoutHints;
82
import org.openconcerto.ui.group.modifier.AddGroupModifier;
83
import org.openconcerto.ui.group.modifier.AddItemModifier;
84
import org.openconcerto.ui.group.modifier.MoveToGroupModifier;
85
import org.openconcerto.utils.CollectionUtils;
153 ilm 86
import org.openconcerto.utils.i18n.Grammar;
87
import org.openconcerto.utils.i18n.Grammar_fr;
88
import org.openconcerto.utils.i18n.NounClass;
89
import org.openconcerto.utils.i18n.Phrase;
86 ilm 90
import org.openconcerto.utils.i18n.TranslationManager;
74 ilm 91
 
92
public class Extension {
93
 
94
    // Descriptors of the extension
95
    private List<ElementDescriptor> elementList = new ArrayList<ElementDescriptor>();
96
    private List<TableDescritor> createTableList = new ArrayList<TableDescritor>();
97
    private List<TableDescritor> modifyTableList = new ArrayList<TableDescritor>();
98
    private List<ListDescriptor> createListList = new ArrayList<ListDescriptor>();
99
    private List<TableTranslation> tableTranslations = new ArrayList<TableTranslation>();
100
    private List<FieldTranslation> fieldTranslations = new ArrayList<FieldTranslation>();
101
    private List<MenuTranslation> menuTranslations = new ArrayList<MenuTranslation>();
102
    private List<ActionTranslation> actionTranslations = new ArrayList<ActionTranslation>();
103
    private List<ComponentDescritor> createComponentList = new ArrayList<ComponentDescritor>();
104
    private List<ComponentDescritor> modifyComponentList = new ArrayList<ComponentDescritor>();
105
    private List<MenuDescriptor> createMenuList = new ArrayList<MenuDescriptor>();
106
    private List<MenuDescriptor> removeMenuList = new ArrayList<MenuDescriptor>();
107
    private List<ActionDescriptor> createActionList = new ArrayList<ActionDescriptor>();
108
 
109
    // Listeners
110
    private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
111
 
112
    private String name;
113
    private boolean notSaved;
114
    private boolean autoStart;
115
    private boolean isStarted;
116
 
117
    public Extension(String name) {
118
        this.name = name;
119
        this.notSaved = true;
120
    }
121
 
122
    public void clearAll() {
123
        elementList.clear();
124
        createTableList.clear();
125
        modifyTableList.clear();
126
        createListList.clear();
127
        tableTranslations.clear();
128
        fieldTranslations.clear();
129
        menuTranslations.clear();
130
        actionTranslations.clear();
131
        createComponentList.clear();
132
        modifyComponentList.clear();
133
        createMenuList.clear();
134
        removeMenuList.clear();
135
        createActionList.clear();
136
        listeners.clear();
137
 
138
        notSaved = true;
139
        autoStart = false;
140
        isStarted = false;
141
 
142
    }
143
 
144
    boolean isStarted() {
145
        return this.isStarted;
146
    }
147
 
148
    public boolean isAutoStart() {
149
        return autoStart;
150
    }
151
 
86 ilm 152
    public void start(DBRoot root, boolean inModuleStart) throws SQLException {
74 ilm 153
 
154
        // Ensure that database is configured
155
        boolean databaseOk = setupDatabase(root);
156
        if (!databaseOk) {
157
            Log.get().severe("Extension " + this.getName() + " not started due to database error");
158
            return;
159
        }
160
        // Register translations
153 ilm 161
        registerTranslations(root);
74 ilm 162
        // Create menus
86 ilm 163
        if (!inModuleStart) {
164
            final MenuAndActions copy = MenuManager.getInstance().copyMenuAndActions();
165
            registerMenuActions(copy);
166
            MenuManager.getInstance().setMenuAndActions(copy);
167
        }
74 ilm 168
        Log.get().info("Extension " + this.getName() + " started");
169
        this.isStarted = true;
170
        this.autoStart = true;
171
        fireChanged();
172
    }
173
 
153 ilm 174
    private void registerTranslations(DBRoot root) {
86 ilm 175
        final String locale = Locale.getDefault().toString();
176
        for (MenuTranslation mTranslation : this.menuTranslations) {
177
            if (locale.equals(mTranslation.getLocale())) {
178
                TranslationManager.getInstance().setTranslationForMenu(mTranslation.getId(), mTranslation.getLabel());
179
            }
180
        }
181
        for (ActionTranslation mTranslation : this.actionTranslations) {
182
            if (locale.equals(mTranslation.getLocale())) {
183
                TranslationManager.getInstance().setTranslationForAction(mTranslation.getId(), mTranslation.getLabel());
184
            }
185
        }
186
        for (FieldTranslation mTranslation : this.fieldTranslations) {
187
            if (locale.equals(mTranslation.getLocale())) {
188
                TranslationManager.getInstance().setTranslationForItem(mTranslation.getTableName() + "." + mTranslation.getFieldName(), mTranslation.getLabel());
153 ilm 189
                // TODO: getDescFor SQLFieldTranslator
86 ilm 190
            }
191
        }
192
        for (TableTranslation mTranslation : this.tableTranslations) {
193
            if (locale.equals(mTranslation.getLocale())) {
153 ilm 194
                // FIXME voir avec Sylvain, impossible pour l'instant
195
                SQLElement e = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(mTranslation.getTableName());
196
                e.setDefaultName(createPhrase(mTranslation.getSingular(), mTranslation.getPlural()));
86 ilm 197
            }
198
        }
199
    }
200
 
153 ilm 201
    private static Phrase createPhrase(String singular, String plural) {
202
        final NounClass nounClass;
203
        final String base;
204
        if (singular.startsWith("une ")) {
205
            nounClass = NounClass.FEMININE;
206
            base = singular.substring(4);
207
        } else if (singular.startsWith("un ")) {
208
            nounClass = NounClass.MASCULINE;
209
            base = singular.substring(3);
210
        } else {
211
            nounClass = null;
212
            base = singular;
213
        }
214
        final Phrase res = new Phrase(Grammar_fr.getInstance(), base, nounClass);
215
        if (nounClass != null)
216
            res.putVariant(Grammar.INDEFINITE_ARTICLE_SINGULAR, singular);
217
        res.putVariant(Grammar.PLURAL, plural);
218
        return res;
219
    }
220
 
86 ilm 221
    private void registerMenuActions(MenuAndActions menuAndActions) {
74 ilm 222
        // register actions
153 ilm 223
        for (final MenuDescriptor menuDescriptor : getCreateMenuList()) {
224
            if (menuDescriptor.getType().equals(MenuDescriptor.CREATE)) {
225
                Log.get().info("Registering action for menu creation id:'" + menuDescriptor.getId() + "'");
74 ilm 226
 
86 ilm 227
                menuAndActions.putAction(new CreateFrameAbstractAction() {
228
 
74 ilm 229
                    @Override
230
                    public JFrame createFrame() {
231
 
232
                        JFrame editFrame = new JFrame();
153 ilm 233
                        String componentId = menuDescriptor.getComponentId();
86 ilm 234
                        if (componentId == null) {
153 ilm 235
                            throw new IllegalStateException("No ComponentId for menu " + menuDescriptor.getId());
86 ilm 236
                        }
74 ilm 237
                        ComponentDescritor n = getCreateComponentFromId(componentId);
86 ilm 238
                        if (n == null) {
239
                            throw new IllegalStateException("No ComponentDescritor for " + componentId);
240
                        }
74 ilm 241
                        final SQLTable t = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(n.getTable());
242
                        if (t == null) {
243
                            throw new IllegalStateException("No table  " + n.getTable());
244
                        }
245
                        final SQLElement element = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(t);
246
 
153 ilm 247
                        final GroupSQLComponent gComponent = new ExtensionGroupSQLComponent(element, n.getGroup());
74 ilm 248
                        editFrame.setTitle(EditFrame.getCreateMessage(element));
249
                        editFrame.setContentPane(new EditPanel(gComponent, EditMode.CREATION));
250
                        editFrame.pack();
251
                        return editFrame;
252
 
253
                    }
153 ilm 254
                }, menuDescriptor.getId(), true);
74 ilm 255
 
153 ilm 256
            } else if (menuDescriptor.getType().equals(MenuDescriptor.LIST)) {
257
                if (menuDescriptor.getListId() != null) {
139 ilm 258
                    menuAndActions.putAction(new CreateFrameAbstractAction() {
74 ilm 259
 
139 ilm 260
                        @Override
261
                        public JFrame createFrame() {
153 ilm 262
                            final String componentId = menuDescriptor.getListId();
139 ilm 263
                            if (componentId == null) {
153 ilm 264
                                throw new IllegalStateException("null ListId for MenuDescriptor " + menuDescriptor.getId());
139 ilm 265
                            }
266
                            final ListDescriptor listDesc = getCreateListFromId(componentId);
267
                            if (listDesc == null) {
268
                                throw new IllegalStateException("No ListDescriptor  " + componentId);
269
                            }
270
                            final SQLTable t = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(listDesc.getMainTable());
271
                            if (t == null) {
272
                                throw new IllegalStateException("No table  " + listDesc.getMainTable());
273
                            }
274
                            final SQLElement element = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElement(t);
275
                            final ListSQLRequest req = new ListSQLRequest(element.getTable(), new ArrayList<String>(0));
153 ilm 276
                            SQLTableModelSourceOnline source = createSource(element, req, listDesc);
86 ilm 277
 
139 ilm 278
                            final IListe list = new IListe(source);
279
                            final IListFrame editFrame = new IListFrame(new ListeAddPanel(element, list));
280
                            editFrame.pack();
281
                            return editFrame;
74 ilm 282
 
139 ilm 283
                        }
153 ilm 284
                    }, menuDescriptor.getId(), true);
139 ilm 285
                }
153 ilm 286
            } else if (menuDescriptor.getType().equals(MenuDescriptor.LIST)) {
74 ilm 287
                // No action to register
288
            } else {
153 ilm 289
                Log.get().warning("unknown type " + menuDescriptor.getType());
74 ilm 290
            }
291
        }
292
 
86 ilm 293
        // System.err.println("****" + MenuManager.getInstance().getActionForId("test1"));
294
        //
295
        // final MenuAndActions copy = MenuManager.getInstance().copyMenuAndActions();
296
        // // create group
297
        // final Group group = copy.getGroup();
298
        initMenuGroup(menuAndActions.getGroup());
299
        // MenuManager.getInstance().setMenuAndActions(copy);
300
        // System.err.println("*******" + MenuManager.getInstance().getActionForId("test1"));
74 ilm 301
    }
302
 
153 ilm 303
    public SQLTableModelSourceOnline createSource(SQLElement element, ListSQLRequest req, ListDescriptor listDesc) {
304
        final SQLTableModelSourceOnline source = new SQLTableModelSourceOnline(req, element);
305
        final List<SQLTableModelColumn> cols = new ArrayList<>();
306
        for (ColumnDescriptor cDesc : listDesc.getColumns()) {
307
            final String fieldspath = cDesc.getFieldsPaths();
308
            final String[] paths = fieldspath.split(",");
309
            final Set<FieldPath> fps = new LinkedHashSet<FieldPath>();
310
            for (int i = 0; i < paths.length; i++) {
311
                // LOCAL, id_batiment.id_site.nom
312
                final SQLName name = SQLName.parse(paths[i].trim());
313
 
314
                final PathBuilder p = new PathBuilder(element.getTable());
315
                final int stop = name.getItemCount() - 1;
316
                for (int j = 0; j < stop; j++) {
317
                    String it = name.getItem(j);
318
                    p.addForeignField(it);
319
                }
320
                final FieldPath fp = new FieldPath(p.build(), name.getName());
321
                fps.add(fp);
322
 
323
            }
324
            String columnName = cDesc.getId();
325
            if (!columnName.contains(".")) {
326
                columnName = element.getTable().getTable().getName() + "." + columnName;
327
            }
328
            String tranlatedName = TranslationManager.getInstance().getTranslationForItem(columnName);
329
            if (tranlatedName == null) {
330
                tranlatedName = SQLFieldTranslator.getDefaultDesc(fps.iterator().next().getField()).getTitleLabel();
331
            }
332
            if (tranlatedName == null) {
333
                tranlatedName = cDesc.getId();
334
            }
335
 
336
            cols.add(new BaseSQLTableModelColumn(tranlatedName, String.class) {
337
 
338
                @Override
339
                protected Object show_(SQLRowAccessor r) {
340
                    final List<String> l = new ArrayList<>();
341
                    for (final FieldPath fp : fps) {
342
                        final String string = fp.getString((SQLRowValues) r);
343
                        if (string != null)
344
                            l.add(string);
345
                    }
346
                    return CollectionUtils.join(l, " ");
347
                }
348
 
349
                @Override
350
                public Set<FieldPath> getPaths() {
351
                    return fps;
352
                }
353
            });
354
 
355
        }
356
 
357
        source.getColumns().addAll(cols);
358
        return source;
359
    }
360
 
74 ilm 361
    public void initMenuGroup(final Group group) {
362
        for (MenuDescriptor element : getCreateMenuList()) {
363
            if (element.getType().equals(MenuDescriptor.GROUP)) {
364
                AddGroupModifier add = new AddGroupModifier(element.getId());
365
                if (group.getDescFromID(element.getId()) == null) {
366
                    // only add if not exists
367
                    add.applyOn(group);
368
                }
369
                String menuId = element.getInsertInMenu();
370
                Group dest = (Group) group.getDescFromID(menuId);
371
                if (dest != null) {
372
                    MoveToGroupModifier mode = new MoveToGroupModifier(element.getId(), dest);
373
                    mode.applyOn(group);
374
                } else {
375
                    Log.get().severe("No group " + menuId + " found to move item " + element.getId());
376
                }
377
            }
378
        }
379
        // create items
380
        for (MenuDescriptor element : getCreateMenuList()) {
381
            if (!element.getType().equals(MenuDescriptor.GROUP)) {
382
                AddItemModifier add = new AddItemModifier(element.getId());
383
                if (group.getDescFromID(element.getId()) == null) {
384
                    // only add if not exists
385
                    add.applyOn(group);
386
                }
387
 
388
                String menuId = element.getInsertInMenu();
389
                Group dest = (Group) group.getDescFromID(menuId);
390
                if (dest != null) {
391
                    MoveToGroupModifier mode = new MoveToGroupModifier(element.getId(), dest);
392
                    mode.applyOn(group);
393
                } else {
394
                    Log.get().severe("No group " + menuId + " found to move group " + element.getId());
395
                }
396
            }
397
        }
398
        for (MenuDescriptor element : getRemoveMenuList()) {
399
            String eId = element.getId();
400
            Item item = group.getDescFromID(eId);
401
            if (item != null) {
402
                item.setLocalHint(item.getLocalHint().getBuilder().setVisible(false).build());
403
            } else {
404
                Log.get().severe("No Item " + eId + " found in group " + group.getId());
405
            }
406
        }
407
        System.err.println("Extension.initMenuGroup()" + group.printTree());
408
 
409
    }
410
 
411
    public ComponentDescritor getCreateComponentFromId(String id) {
412
        for (ComponentDescritor menuDescriptor : this.createComponentList) {
413
            if (menuDescriptor.getId().equals(id)) {
414
                return menuDescriptor;
415
            }
416
        }
417
        return null;
418
    }
419
 
420
    private boolean setupDatabase(DBRoot root) throws SQLException {
421
        List<ChangeTable<?>> changesToApply = new ArrayList<ChangeTable<?>>();
422
        List<SQLCreateTable> createToApply = new ArrayList<SQLCreateTable>();
423
        // Create fields and tables if needed
424
        final List<TableDescritor> t = new ArrayList<TableDescritor>();
425
        t.addAll(this.createTableList);
426
        t.addAll(this.modifyTableList);
427
        Set<String> tableNames = new HashSet<String>();
428
        for (TableDescritor tDesc : t) {
429
            String tableName = tDesc.getName();
430
            tableNames.add(tableName);
431
            final SQLTable table = root.getTable(tableName);
432
            final ChangeTable<?> createTable;
433
            if (table == null) {
434
                createTable = new SQLCreateTable(root, tableName);
435
                createToApply.add((SQLCreateTable) createTable);
436
            } else {
437
                createTable = new AlterTable(table);
438
 
439
            }
440
            // fields creation
441
            boolean mustAdd = false;
442
            for (FieldDescriptor fDesc : tDesc.getFields()) {
443
                final SQLField f = (table == null) ? null : table.getFieldRaw(fDesc.getName());
444
                if (f == null) {
445
                    final String type = fDesc.getType();
446
                    if (type.equals(FieldDescriptor.TYPE_STRING)) {
447
                        int l = 256;
448
                        try {
449
                            l = Integer.parseInt(fDesc.getLength());
450
                        } catch (Exception e) {
451
                            Log.get().log(Level.WARNING, "Extension: unable to parse length: " + fDesc.getLength(), e);
452
                        }
453
                        createTable.addVarCharColumn(fDesc.getName(), l);
454
                    } else if (type.equals(FieldDescriptor.TYPE_INTEGER)) {
455
                        int defaultVal = 0;
456
                        try {
457
                            defaultVal = Integer.parseInt(fDesc.getDefaultValue());
458
                        } catch (Exception e) {
459
                            Log.get().log(Level.WARNING, "Extension: unable to parse default integer value : " + fDesc.getDefaultValue(), e);
460
                        }
461
                        createTable.addIntegerColumn(fDesc.getName(), defaultVal);
462
                    } else if (type.equals(FieldDescriptor.TYPE_DECIMAL)) {
463
                        BigDecimal defaultVal = BigDecimal.ZERO;
464
                        try {
465
                            defaultVal = new BigDecimal(fDesc.getDefaultValue());
466
                        } catch (Exception e) {
467
                            Log.get().log(Level.WARNING, "Extension: unable to parse default bigdecimal value : " + fDesc.getDefaultValue(), e);
468
                        }
469
                        createTable.addNumberColumn(fDesc.getName(), BigDecimal.class, defaultVal, false);
470
                    } else if (type.equals(FieldDescriptor.TYPE_BOOLEAN)) {
471
                        String defaultValue = "false";
472
                        if (fDesc.getDefaultValue() != null && fDesc.getDefaultValue().equals("true")) {
473
                            defaultValue = "true";
474
                        }
475
                        createTable.addColumn(fDesc.getName(), "boolean", defaultValue, false);
476
                    } else if (type.equals(FieldDescriptor.TYPE_DATE)) {
477
                        createTable.addColumn(fDesc.getName(), "date");
478
                    } else if (type.equals(FieldDescriptor.TYPE_TIME)) {
479
                        createTable.addColumn(fDesc.getName(), "time");
480
                    } else if (type.equals(FieldDescriptor.TYPE_DATETIME)) {
481
                        createTable.addDateAndTimeColumn(fDesc.getName());
482
                    } else if (type.equals(FieldDescriptor.TYPE_REF)) {
483
                        // created later
484
                        mustAdd = false;
485
                    }
486
                    mustAdd = true;
487
                } else {
488
                    // Le champs existe, on ne fait rien
489
                    // checker les types
490
                }
491
            }
492
            if (mustAdd && !(createTable instanceof SQLCreateTable)) {
493
                changesToApply.add(createTable);
494
            }
495
        }
496
        // Let's do it
497
        // FIXME : if changesToApply create field that createToApply : bing
498
        if (!createToApply.isEmpty()) {
499
            root.createTables(createToApply);
500
        }
501
        if (!changesToApply.isEmpty()) {
502
            for (String change : ChangeTable.cat(changesToApply)) {
503
                root.getDBSystemRoot().getDataSource().execute(change);
504
            }
505
 
506
        }
507
        // Refetch if needed
508
        if (!changesToApply.isEmpty() || !createToApply.isEmpty()) {
509
            root.getSchema().updateVersion();
510
            root.refetch(tableNames);
511
            Log.get().info("Fetching table changes (" + changesToApply.size() + " fields and " + createToApply.size() + " tables)");
512
        }
513
        // Compute foreign keys to create
514
        changesToApply.clear();
515
        for (TableDescritor tDesc : t) {
516
            final SQLTable table = root.getTable(tDesc.getName());
517
            for (FieldDescriptor fDesc : tDesc.getFields()) {
518
                final SQLField f = (table == null) ? null : table.getFieldRaw(fDesc.getName());
519
                if (f == null && fDesc.getType().equals(FieldDescriptor.TYPE_REF)) {
520
                    final String fTableName = fDesc.getForeignTable();
521
                    final SQLTable fTable = root.getTable(fTableName);
522
                    if (fTable != null) {
523
                        final AlterTable mTable = new AlterTable(table);
524
                        mTable.addForeignColumn(fDesc.getName(), fTable);
525
                        changesToApply.add(mTable);
526
                    } else {
527
                        JOptionPane.showMessageDialog(new JFrame(), "L'extension ne peut pas s'installer car la table " + fTableName + " n'existe pas.");
528
                        return false;
529
                    }
530
                }
531
            }
532
        }
533
        // Create foreign keys
534
        if (!changesToApply.isEmpty()) {
535
            for (String change : ChangeTable.cat(changesToApply)) {
536
                root.getDBSystemRoot().getDataSource().execute(change);
537
            }
538
            root.getSchema().updateVersion();
539
            root.refetch(tableNames);
540
            Log.get().info("Fetching " + changesToApply.size() + " foreign fields creation");
541
        }
542
        // Create elements for created tables
543
        for (TableDescritor tDesc : t) {
544
 
545
            tDesc.createElement(this);
546
        }
547
        return true;
548
    }
549
 
550
    public void stop() {
551
        this.isStarted = false;
552
        this.autoStart = false;
553
        Log.get().info("Extension " + this.getName() + " stopped");
86 ilm 554
        // TODO : remove menu changes
74 ilm 555
        fireChanged();
556
    }
557
 
558
    public String getName() {
559
        return name;
560
    }
561
 
562
    @SuppressWarnings("unchecked")
563
    public void importFromXML(String xml) {
564
 
565
        System.out.println("Extension.importFromXML():" + xml);
566
        if (xml.length() > 0) {
567
            final SAXBuilder sxb = new SAXBuilder();
568
            try {
569
                final Document doc = sxb.build(new StringReader(xml));
570
                final Element root = doc.getRootElement();
571
                if (root.getAttributeValue("autostart", "false").equals("true")) {
572
                    this.autoStart = true;
573
                }
574
                // elements parsing
575
                final List<Element> elements = root.getChildren("element");
576
                for (Element eElement : elements) {
577
                    final String id = eElement.getAttributeValue("id");
578
                    final String tableName = eElement.getAttributeValue("tableName");
579
                    ElementDescriptor eDesc = new ElementDescriptor(id, tableName);
580
                    // TODO : fkeyaction
581
                    this.elementList.add(eDesc);
582
                }
583
                // tables parsing
584
                final List<Element> tables = root.getChildren("table");
585
                for (Element eTable : tables) {
586
                    final String type = eTable.getAttributeValue("type");
587
                    final String name = eTable.getAttributeValue("name");
588
                    final TableDescritor tDesc = new TableDescritor(name);
589
                    final List<Element> fields = eTable.getChildren("field");
590
                    for (Element field : fields) {
591
                        FieldDescriptor f = createFieldDescriptorFrom(name, field);
592
                        tDesc.add(f);
593
                    }
594
                    if (tDesc.getFields().size() > 0) {
595
                        if (type.equals("create")) {
596
                            this.createTableList.add(tDesc);
597
                        } else if (type.equals("modify")) {
598
                            this.modifyTableList.add(tDesc);
599
                        } else {
600
                            throw new IllegalStateException("Unknown table type: " + type);
601
                        }
602
                    }
603
 
604
                }
605
                // translations
606
                final List<Element> translations = root.getChildren("translation");
607
                for (Element eTranslation : translations) {
608
                    final String lang = eTranslation.getAttributeValue("locale");
609
                    if (lang == null) {
610
                        throw new IllegalArgumentException("no locale found in translation element");
611
                    }
612
                    final List<Element> tTables = eTranslation.getChildren("element");
613
                    for (Element element : tTables) {
614
                        final String tableName = element.getAttributeValue("refid");
615
                        final TableTranslation t = new TableTranslation(lang, tableName);
616
                        t.setSingular(element.getAttributeValue("singular"));
617
                        t.setPlural(element.getAttributeValue("plural"));
618
                        this.tableTranslations.add(t);
619
                        final List<Element> tFields = element.getChildren("item");
620
                        for (Element elementF : tFields) {
621
                            final FieldTranslation tF = new FieldTranslation(lang, tableName, elementF.getAttributeValue("id"));
622
                            tF.setLabel(elementF.getAttributeValue("label"));
623
                            tF.setDocumentation(elementF.getAttributeValue("doc"));
624
                            this.fieldTranslations.add(tF);
625
                        }
626
                    }
627
 
628
                    final List<Element> tMenu = eTranslation.getChildren("menu");
629
                    for (Element element : tMenu) {
630
                        final MenuTranslation t = new MenuTranslation(lang, element.getAttributeValue("refid"));
631
                        t.setLabel(element.getAttributeValue("label"));
632
                        this.menuTranslations.add(t);
633
                    }
634
                    final List<Element> tActions = eTranslation.getChildren("action");
635
                    for (Element element : tActions) {
636
                        final ActionTranslation t = new ActionTranslation(lang, element.getAttributeValue("refid"));
637
                        t.setLabel(element.getAttributeValue("label"));
638
                        this.actionTranslations.add(t);
639
                    }
640
                }
641
 
642
                // list parsing
643
                final List<Element> lists = root.getChildren("list");
644
                for (Element eList : lists) {
645
                    final String type = eList.getAttributeValue("type");
646
                    final String id = eList.getAttributeValue("id");
647
                    final String refid = eList.getAttributeValue("refid");
648
 
649
                    final ListDescriptor listDesc = new ListDescriptor(id);
650
                    String mainTable = this.getTableNameForElementId(refid);
651
                    if (mainTable == null) {
652
                        // fallback to table name
653
                        mainTable = refid;
654
                    }
655
                    listDesc.setMainTable(mainTable);
656
                    final List<Element> columns = eList.getChildren("column");
657
                    for (Element field : columns) {
658
                        ColumnDescriptor f = createColumnDescriptorFrom(mainTable, field);
659
                        listDesc.add(f);
660
                    }
661
                    if (listDesc.getColumnCount() > 0) {
662
                        if (type.equals("create")) {
663
                            this.createListList.add(listDesc);
664
                        } else {
665
                            throw new IllegalStateException("Unknown table type: " + type);
666
                        }
667
                    }
668
 
669
                } // component parsing
670
                final List<Element> components = root.getChildren("component");
671
                for (Element eList : components) {
672
                    final String type = eList.getAttributeValue("type");
673
                    if (type.equals("create")) {
674
                        final String id = eList.getAttributeValue("id");
675
                        final String table = eList.getAttributeValue("table");
676
                        final ComponentDescritor tDesc = new ComponentDescritor(id);
677
                        tDesc.setTable(table);
678
                        walkGroup(eList, tDesc.getGroup());
679
                        System.out.println("SimpleXMLAddon.importFromXML() " + tDesc);
680
                        this.createComponentList.add(tDesc);
681
                    }
682
                }
683
                // Menu
684
                final List<Element> menus = root.getChildren("menu");
685
                for (Element eList : menus) {
686
                    final String type = eList.getAttributeValue("type");
687
                    if (type.equals("create")) {
688
                        final List<Element> actions = eList.getChildren("action");
689
                        for (Element action : actions) {
690
                            final String id = action.getAttributeValue("id");
691
                            final String insertInMenu = action.getAttributeValue("insertInMenu");
692
                            final String actionType = action.getAttributeValue("type");
693
                            if (actionType.equals(MenuDescriptor.LIST)) {
694
                                // a list frame
695
                                final String listId = action.getAttributeValue("listId");
696
                                final MenuDescriptor mDesc = new MenuDescriptor(id);
697
                                mDesc.setInsertInMenu(insertInMenu);
698
                                mDesc.setType(actionType);
699
                                mDesc.setListId(listId);
700
                                this.createMenuList.add(mDesc);
701
                            } else if (actionType.equals(MenuDescriptor.CREATE)) {
702
                                // a create frame
703
                                final String componentId = action.getAttributeValue("componentId");
704
                                final MenuDescriptor mDesc = new MenuDescriptor(id);
705
                                mDesc.setInsertInMenu(insertInMenu);
706
                                mDesc.setType(actionType);
707
                                mDesc.setComponentId(componentId);
708
                                this.createMenuList.add(mDesc);
709
                            } else if (actionType.equals(MenuDescriptor.GROUP)) {
710
                                // a create frame
711
                                final MenuDescriptor mDesc = new MenuDescriptor(id);
712
                                mDesc.setInsertInMenu(insertInMenu);
713
                                mDesc.setType(actionType);
714
                                this.createMenuList.add(mDesc);
715
                            } else {
716
                                throw new IllegalStateException("Unknown action type " + actionType + " for action " + id);
717
                            }
718
 
719
                        }
720
                    } else if (type.equals("remove")) {
721
                        final List<Element> actions = eList.getChildren("action");
722
                        for (Element action : actions) {
723
                            final String id = action.getAttributeValue("id");
724
                            this.removeMenuList.add(new MenuDescriptor(id));
725
                        }
726
                    }
727
                }
728
 
729
                // Actions
730
                final List<Element> actions = root.getChildren("action");
731
                for (Element actionElement : actions) {
732
                    final String type = actionElement.getAttributeValue("type");
733
                    if (type.equals("create")) {
734
 
735
                        final String id = actionElement.getAttributeValue("id");
736
                        final String location = actionElement.getAttributeValue("location");
737
                        final String table = actionElement.getAttributeValue("table");
738
                        final String componentId = actionElement.getAttributeValue("componentId");
739
                        ActionDescriptor action = new ActionDescriptor(id);
740
                        action.setLocation(location);
741
                        action.setTable(table);
742
                        action.setComponentId(componentId);
743
                        this.createActionList.add(action);
744
 
745
                    } else {
746
                        // TODO: remove
747
                        throw new IllegalStateException("Unknown action type " + type);
748
                    }
749
 
750
                }
751
 
752
            } catch (Exception e) {
753
                System.err.println("SimpleXMLAddon.importFromXML(): parsing error :" + e.getMessage());
754
                e.printStackTrace();
755
            }
756
        }
757
        notSaved = false;
758
 
759
        fireChanged();
760
    }
761
 
762
    String toXML() {
763
        final Element rootElement = new Element("extension");
764
        rootElement.setAttribute("id", this.name);
765
        rootElement.setAttribute("autostart", String.valueOf(this.isStarted));
766
        rootElement.setAttribute("format", "1.0");
767
        final Document document = new Document(rootElement);
768
 
769
        // Element
770
        for (ElementDescriptor eDescriptor : this.elementList) {
771
            final Element eElement = new Element("element");
772
            eElement.setAttribute("tableName", eDescriptor.getTableName());
773
            eElement.setAttribute("id", eDescriptor.getId());
774
            // TODO: fkey action : <fkeyaction action="set_empty|cascade|restrict"
775
            // fields="id_language"/>
776
            rootElement.addContent(eElement);
777
        }
778
 
779
        // Table create
780
        for (TableDescritor tDescriptor : this.createTableList) {
781
            final Element eTable = new Element("table");
782
            eTable.setAttribute("type", "create");
783
            eTable.setAttribute("name", tDescriptor.getName());
784
            for (FieldDescriptor fDescriptor : tDescriptor.getFields()) {
785
                final Element eField = new Element("field");
786
                eField.setAttribute("name", fDescriptor.getName());
787
                eField.setAttribute("type", fDescriptor.getType());
788
                if (fDescriptor.getLength() != null) {
789
                    eField.setAttribute("length", fDescriptor.getLength());
790
                }
791
                if (fDescriptor.getDefaultValue() != null) {
792
                    eField.setAttribute("default", fDescriptor.getDefaultValue());
793
                }
794
                if (fDescriptor.getForeignTable() != null) {
795
                    eField.setAttribute("ftable", fDescriptor.getForeignTable());
796
                }
797
                eTable.addContent(eField);
798
            }
799
            rootElement.addContent(eTable);
800
        }
801
 
802
        // Table modify
803
        for (TableDescritor tDescriptor : this.modifyTableList) {
804
            final Element eTable = new Element("table");
805
            eTable.setAttribute("type", "modify");
806
            eTable.setAttribute("name", tDescriptor.getName());
807
            for (FieldDescriptor fDescriptor : tDescriptor.getFields()) {
808
                final Element eField = new Element("field");
809
                eField.setAttribute("name", fDescriptor.getName());
810
                eField.setAttribute("type", fDescriptor.getType());
811
                if (fDescriptor.getLength() != null) {
812
                    eField.setAttribute("length", fDescriptor.getLength());
813
                }
814
                if (fDescriptor.getDefaultValue() != null) {
815
                    eField.setAttribute("default", fDescriptor.getDefaultValue());
816
                }
817
                if (fDescriptor.getForeignTable() != null) {
818
                    eField.setAttribute("ftable", fDescriptor.getForeignTable());
819
                }
820
                eTable.addContent(eField);
821
            }
822
            rootElement.addContent(eTable);
823
        }
824
        // Translations
825
        final HashSet<String> locales = new HashSet<String>();
826
        for (Translation tr : tableTranslations) {
827
            locales.add(tr.getLocale());
828
        }
829
        for (Translation tr : fieldTranslations) {
830
            locales.add(tr.getLocale());
831
        }
832
        for (Translation tr : menuTranslations) {
833
            locales.add(tr.getLocale());
834
        }
835
        for (Translation tr : actionTranslations) {
836
            locales.add(tr.getLocale());
837
        }
838
        final List<String> lLocales = new ArrayList<String>(locales);
839
        Collections.sort(lLocales);
840
        for (String locale : lLocales) {
841
            final Element eTranslation = new Element("translation");
842
            eTranslation.setAttribute("locale", locale);
843
            rootElement.addContent(eTranslation);
844
            // Tables
845
            for (TableTranslation tTranslation : tableTranslations) {
846
                if (tTranslation.getLocale().equals(locale)) {
847
                    final Element eTable = new Element("element");
848
                    eTable.setAttribute("refid", tTranslation.getTableName());
849
                    final String singular = tTranslation.getSingular();
850
                    if (singular != null && !singular.isEmpty()) {
851
                        eTable.setAttribute("singular", singular);
852
                    }
853
                    final String plural = tTranslation.getPlural();
854
                    if (plural != null && !plural.isEmpty()) {
855
                        eTable.setAttribute("plural", plural);
856
                    }
857
                    for (FieldTranslation fTranslation : fieldTranslations) {
858
                        // Fields
859
                        if (fTranslation.getLocale().equals(locale) && fTranslation.getTableName().equals(tTranslation.getTableName())) {
860
                            final Element eField = new Element("item");
861
                            eField.setAttribute("id", fTranslation.getFieldName());
862
                            eField.setAttribute("label", fTranslation.getLabel());
863
                            if (fTranslation.getDocumentation() != null) {
864
                                eField.setAttribute("doc", fTranslation.getDocumentation());
865
                            }
866
                            eTable.addContent(eField);
867
                        }
868
                    }
869
                    eTranslation.addContent(eTable);
870
 
871
                }
872
            }
873
            // Menus
874
            for (MenuTranslation tMenu : menuTranslations) {
875
                if (tMenu.getLocale().equals(locale)) {
876
                    final Element eMenu = new Element("menu");
877
                    eMenu.setAttribute("refid", tMenu.getId());
878
                    eMenu.setAttribute("label", tMenu.getLabel());
879
                    eTranslation.addContent(eMenu);
880
                }
881
            }
882
 
883
            // Actions
884
            for (ActionTranslation tAction : actionTranslations) {
885
                if (tAction.getLocale().equals(locale)) {
886
                    final Element eMenu = new Element("action");
887
                    eMenu.setAttribute("refid", tAction.getId());
888
                    eMenu.setAttribute("label", tAction.getLabel());
889
                    eTranslation.addContent(eMenu);
890
                }
891
            }
892
        }
893
 
894
        // Actions
895
        for (ActionDescriptor action : this.createActionList) {
896
            final Element eAction = new Element("action");
897
            eAction.setAttribute("type", "create");
898
            eAction.setAttribute("id", action.getId());
899
            eAction.setAttribute("location", action.getLocation());
900
            eAction.setAttribute("table", action.getTable());
901
            eAction.setAttribute("componentId", action.getComponentId());
902
            rootElement.addContent(eAction);
903
        }
904
        // Menu create
905
        if (!this.createMenuList.isEmpty()) {
906
            final Element eMenu = new Element("menu");
907
            eMenu.setAttribute("type", "create");
908
            for (MenuDescriptor menu : this.createMenuList) {
909
                final Element eActionMenu = new Element("action");
910
                eActionMenu.setAttribute("id", menu.getId());
911
                eActionMenu.setAttribute("insertInMenu", menu.getInsertInMenu());
912
                final String type = menu.getType();
913
                eActionMenu.setAttribute("type", type);
914
                if (!type.equals(MenuDescriptor.CREATE) && !type.equals(MenuDescriptor.LIST) && !type.equals(MenuDescriptor.GROUP)) {
915
                    throw new IllegalStateException("Menu type " + type + " not supported");
916
                }
917
 
918
                if (type.endsWith("list") && menu.getListId() != null) {
919
                    eActionMenu.setAttribute("listId", menu.getListId());
920
                } else if (type.endsWith("create") && menu.getComponentId() != null) {
921
                    eActionMenu.setAttribute("componentId", menu.getComponentId());
922
                }
923
                eMenu.addContent(eActionMenu);
924
            }
925
            rootElement.addContent(eMenu);
926
 
927
        }
928
        // Menu remove
929
        if (!this.removeMenuList.isEmpty()) {
930
            final Element eMenu = new Element("menu");
931
            eMenu.setAttribute("type", "remove");
932
            for (MenuDescriptor menu : this.removeMenuList) {
933
                final Element eActionMenu = new Element("action");
934
                eActionMenu.setAttribute("id", menu.getId());
935
                eMenu.addContent(eActionMenu);
936
            }
937
            rootElement.addContent(eMenu);
938
        }
939
        // List create
940
        for (ListDescriptor listDescriptor : this.createListList) {
941
            final Element eList = new Element("list");
942
            eList.setAttribute("type", "create");
943
            eList.setAttribute("id", listDescriptor.getId());
944
            String refFromTable = getRefFromTable(listDescriptor.getMainTable());
945
            if (refFromTable == null) {
946
                refFromTable = listDescriptor.getMainTable();
947
            }
948
            if (refFromTable != null) {
949
                eList.setAttribute("refid", refFromTable);
950
                for (ColumnDescriptor fieldDescriptor : listDescriptor.getColumns()) {
951
                    final Element eField = new Element("column");
952
                    eField.setAttribute("id", fieldDescriptor.getId());
953
                    eField.setAttribute("fields", fieldDescriptor.getFieldsPaths());
954
                    eField.setAttribute("style", fieldDescriptor.getStyle());
955
                    eList.addContent(eField);
956
                }
957
 
958
                rootElement.addContent(eList);
959
            }
960
 
961
        }
962
        // Component create
963
        for (ComponentDescritor componentDescriptor : this.createComponentList) {
964
            final Element eComponent = new Element("component");
965
            eComponent.setAttribute("type", "create");
966
            eComponent.setAttribute("id", componentDescriptor.getId());
967
            eComponent.setAttribute("table", componentDescriptor.getTable());
968
            appendGroup(eComponent, componentDescriptor.getGroup());
969
 
970
            rootElement.addContent(eComponent);
971
        }
972
        // Component modify
973
        for (ComponentDescritor componentDescriptor : this.modifyComponentList) {
974
            System.out.println(componentDescriptor);
975
            throw new IllegalAccessError("Not yet implemented");
976
        }
977
        // Output
978
        XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
979
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
980
        final BufferedOutputStream oStream = new BufferedOutputStream(bOut);
981
        try {
982
            out.output(document, oStream);
983
        } catch (IOException e) {
984
            e.printStackTrace();
985
        } finally {
986
            try {
987
                oStream.close();
988
            } catch (IOException e) {
989
                e.printStackTrace();
990
            }
991
        }
992
        try {
993
            return bOut.toString("utf8");
994
        } catch (UnsupportedEncodingException e) {
995
            e.printStackTrace();
996
            return "";
997
        }
998
    }
999
 
1000
    private void appendGroup(Element eComponent, Group group) {
1001
        int size = group.getSize();
1002
        for (int i = 0; i < size; i++) {
1003
            Item it = group.getItem(i);
1004
            final Element gr;
1005
            if (it instanceof Group) {
1006
                gr = new Element("group");
1007
                appendGroup(gr, (Group) it);
1008
            } else {
1009
                gr = new Element("item");
1010
            }
1011
            gr.setAttribute("id", it.getId());
1012
            if (it.getLocalHint() != null) {
1013
                final LayoutHints hints = it.getLocalHint();
1014
                final String type;
1015
                if (hints.largeWidth()) {
1016
                    type = "verylarge";
1017
                } else if (hints.fillWidth()) {
1018
                    type = "large";
1019
                } else {
1020
                    type = "normal";
1021
                }
1022
                gr.setAttribute("type", type);
1023
                if (hints.isSeparated()) {
1024
                    gr.setAttribute("isSeparated", "true");
1025
                }
1026
                if (hints.showLabel()) {
1027
                    gr.setAttribute("showLabel", "true");
1028
                }
1029
            }
1030
 
1031
            eComponent.addContent(gr);
1032
 
1033
        }
1034
 
1035
    }
1036
 
1037
    private void walkGroup(Element e, Group group) {
1038
        @SuppressWarnings("unchecked")
1039
        final List<Element> elements = e.getChildren();
1040
        for (Element element : elements) {
1041
            String id = element.getAttributeValue("id", "unknown");
1042
            String type = element.getAttributeValue("type", "default");
1043
            String showLabel = element.getAttributeValue("showLabel", "true");
1044
            String isSeparated = element.getAttributeValue("isSeparated", "false");
1045
            if (element.getName().equals("item")) {
1046
                final Item it = new Item(id);
1047
                if (type.equals("large")) {
1048
                    it.setLocalHint(new LayoutHints(false, false, showLabel.equals("true"), isSeparated.equals("true"), true, false));
1049
                } else if (type.equals("verylarge")) {
1050
                    it.setLocalHint(new LayoutHints(true, false, showLabel.equals("true"), isSeparated.equals("true"), true, false));
1051
                } else {
1052
                    it.setLocalHint(new LayoutHints(false, false, showLabel.equals("true"), isSeparated.equals("true"), false, false));
1053
                }
1054
                System.out.println("Extension.walkGroup()" + it + " " + it.getLocalHint() + " from " + type);
1055
                group.add(it);
1056
 
1057
            } else if (element.getName().equals("group")) {
1058
                final Group g = new Group(id);
1059
                group.add(g);
1060
                walkGroup(element, g);
1061
            } else {
1062
                throw new IllegalStateException("Unknown element: " + element.getName());
1063
            }
1064
        }
1065
    }
1066
 
1067
    private FieldDescriptor createFieldDescriptorFrom(String table, Element field) {
1068
        FieldDescriptor f = new FieldDescriptor(table, field.getAttributeValue("name"), field.getAttributeValue("type"), field.getAttributeValue("default"), field.getAttributeValue("length"),
1069
                field.getAttributeValue("ftable"));
1070
        Element child = field.getChild("field");
1071
        if (child != null) {
1072
            f.setLink(createFieldDescriptorFrom(field.getAttributeValue("ftable"), child));
1073
        }
1074
        return f;
1075
    }
1076
 
1077
    private ColumnDescriptor createColumnDescriptorFrom(String table, Element field) {
1078
        final ColumnDescriptor f = new ColumnDescriptor(field.getAttributeValue("id"));
1079
        f.setFieldsPaths(field.getAttributeValue("fields"));
1080
        f.setStyle(field.getAttributeValue("style"));
1081
        return f;
1082
    }
1083
 
1084
    private void fireChanged() {
1085
        for (ChangeListener listener : listeners) {
1086
            listener.stateChanged(new ChangeEvent(this));
1087
        }
1088
 
1089
    }
1090
 
1091
    public List<TableDescritor> getCreateTableList() {
1092
        return createTableList;
1093
    }
1094
 
1095
    public void addCreateTable(TableDescritor value) {
1096
        this.createTableList.add(value);
1097
        setChanged();
1098
    }
1099
 
1100
    public void removeCreateTable(TableDescritor value) {
1101
        this.createTableList.remove(value);
1102
        setChanged();
1103
    }
1104
 
1105
    public List<TableDescritor> getModifyTableList() {
1106
        return modifyTableList;
1107
    }
1108
 
1109
    public List<ListDescriptor> getCreateListList() {
1110
        return createListList;
1111
    }
1112
 
1113
    public ListDescriptor getCreateListFromId(String id) {
1114
        for (ListDescriptor listDescriptor : this.createListList) {
1115
            if (listDescriptor.getId().equals(id)) {
1116
                return listDescriptor;
1117
            }
1118
        }
1119
        return null;
1120
    }
1121
 
1122
    public void addCreateList(ListDescriptor item) {
1123
        this.createListList.add(item);
1124
        setChanged();
1125
 
1126
    }
1127
 
1128
    public void removeCreateList(ListDescriptor item) {
1129
        this.createListList.remove(item);
1130
        setChanged();
1131
    }
1132
 
1133
    public void addChangeListener(ChangeListener listener) {
1134
        if (!this.listeners.contains(listener))
1135
            this.listeners.add(listener);
1136
 
1137
    }
1138
 
1139
    public TableDescritor getOrCreateTableDescritor(String tableName) {
1140
 
1141
        for (TableDescritor td : this.modifyTableList) {
1142
            if (td.getName().equalsIgnoreCase(tableName)) {
1143
                return td;
1144
            }
1145
        }
1146
        // create table descritor for the table
1147
        final TableDescritor td = new TableDescritor(tableName);
1148
        this.modifyTableList.add(td);
1149
        setChanged();
1150
        return td;
1151
    }
1152
 
1153
    public SQLTable getSQLTable(TableDescritor tableDesc) {
1154
        try {
1155
            SQLTable t = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(tableDesc.getName());
1156
            return t;
1157
        } catch (Exception e) {
1158
            return null;
1159
        }
1160
    }
1161
 
1162
    public boolean isNotSaved() {
1163
        return this.notSaved;
1164
    }
1165
 
1166
    public void setChanged() {
1167
        this.notSaved = true;
1168
        this.fireChanged();
1169
        String xml = this.toXML();
1170
        System.out.println(xml);
1171
    }
1172
 
1173
    // FIXME: filter textfield pour eviter les pb d'insert/update
1174
    // TODO: eviter les doublons lors du renommage
1175
 
1176
    public void save() {
1177
        String xml = this.toXML();
1178
        System.out.println(xml);
1179
        // insert new version
1180
        final SQLTable extensionTable = getExtensionTable();
1181
        SQLRowValues v = new SQLRowValues(extensionTable);
1182
        v.put("IDENTIFIER", this.getName());
153 ilm 1183
        v.put("XML", xml);
74 ilm 1184
        try {
153 ilm 1185
            // delete old version
1186
            deleteFromDB();
74 ilm 1187
            v.insert();
1188
            this.notSaved = false;
1189
        } catch (SQLException e) {
1190
            e.printStackTrace();
1191
            JOptionPane.showMessageDialog(new JFrame(), "Error while saving extension");
1192
        }
1193
 
1194
        this.fireChanged();
1195
    }
1196
 
1197
    private SQLTable getExtensionTable() {
1198
        return ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(ExtensionBuilderModule.TABLE_NAME);
1199
    }
1200
 
1201
    private void deleteFromDB() {
1202
        final SQLTable extensionTable = getExtensionTable();
1203
        String query = "DELETE FROM " + extensionTable.getSQL() + " WHERE \"IDENTIFIER\" = " + SQLBase.quoteStringStd(this.getName());
1204
        extensionTable.getDBSystemRoot().getDataSource().execute(query);
1205
    }
1206
 
1207
    public List<String> getAllKnownTableNames() {
1208
        final List<String> l = new ArrayList<String>();
1209
        final Set<String> s = new HashSet<String>();
1210
        for (SQLTable t : AllTableListModel.getAllDatabaseTables()) {
1211
            s.add(t.getName());
1212
        }
1213
        for (TableDescritor td : this.getCreateTableList()) {
1214
            s.add(td.getName());
1215
        }
1216
        s.remove("FWK_MODULE_METADATA");
1217
        s.remove("FWK_SCHEMA_METADATA");
1218
        s.remove("FWK_UNDEFINED_IDS");
1219
        s.remove(ExtensionBuilderModule.TABLE_NAME);
1220
        l.addAll(s);
1221
        Collections.sort(l, new Comparator<String>() {
1222
            @Override
1223
            public int compare(String o1, String o2) {
1224
                return o1.compareToIgnoreCase(o2);
1225
            }
1226
        });
1227
 
1228
        return l;
1229
    }
1230
 
1231
    public TableDescritor getTableListDescriptor(String tableName) {
1232
        for (TableDescritor td : this.createTableList) {
1233
            if (td.getName().equalsIgnoreCase(tableName)) {
1234
                return td;
1235
            }
1236
        }
1237
        return null;
1238
    }
1239
 
1240
    public List<String> getTranslatedFieldOfTable(String tableName) {
1241
        final List<String> l = new ArrayList<String>();
1242
        for (FieldTranslation tr : this.fieldTranslations) {
1243
            if (tr.getTableName().equals(tableName)) {
1244
                l.add(tr.getFieldName());
1245
            }
1246
        }
1247
        return l;
1248
    }
1249
 
1250
    public TableTranslation getTableTranslation(String lang, String tableName) {
1251
        for (TableTranslation tr : this.tableTranslations) {
1252
            if (tr.getLocale().equals(lang) && tr.getTableName().equals(tableName)) {
1253
                return tr;
1254
            }
1255
        }
1256
        return null;
1257
    }
1258
 
1259
    public String getFieldTranslation(String lang, String tableName, String fName) {
1260
        for (FieldTranslation tr : this.fieldTranslations) {
1261
            if (tr.getLocale().equals(lang) && tr.getTableName().equals(tableName) && tr.getFieldName().equals(fName)) {
1262
                return tr.getLabel();
1263
            }
1264
        }
1265
        return null;
1266
    }
1267
 
1268
    public List<ComponentDescritor> getCreateComponentList() {
1269
        return this.createComponentList;
1270
    }
1271
 
1272
    public void addCreateComponent(ComponentDescritor desc) {
1273
        this.createComponentList.add(desc);
1274
    }
1275
 
1276
    public void removeCreateComponent(ComponentDescritor desc) {
1277
        this.createComponentList.remove(desc);
1278
        setChanged();
1279
    }
1280
 
1281
    public List<MenuDescriptor> getCreateMenuList() {
1282
        return createMenuList;
1283
    }
1284
 
1285
    public void addCreateMenu(MenuDescriptor desc) {
1286
        this.createMenuList.add(desc);
1287
    }
1288
 
1289
    public MenuDescriptor getCreateMenuItemFromId(String id) {
1290
        for (MenuDescriptor menuDescriptor : this.createMenuList) {
1291
            if (menuDescriptor.getId().equals(id)) {
1292
                return menuDescriptor;
1293
            }
1294
        }
1295
        return null;
1296
    }
1297
 
1298
    public List<MenuDescriptor> getRemoveMenuList() {
1299
        return removeMenuList;
1300
    }
1301
 
1302
    public void addRemoveMenu(MenuDescriptor desc) {
1303
        this.removeRemoveMenuForId(desc.getId());
1304
        this.removeMenuList.add(desc);
1305
    }
1306
 
1307
    public List<String> getAllKnownFieldName(String tableName) {
1308
        final Set<String> l = new HashSet<String>();
1309
        // fields created in the extension
1310
 
1311
        final List<TableDescritor> desc = getCreateTableList();
1312
        for (TableDescritor tableDescritor : desc) {
1313
            if (tableDescritor.getName().equals(tableName)) {
1314
                final List<FieldDescriptor> fDescs = tableDescritor.getFields();
1315
                for (FieldDescriptor fieldDescriptor : fDescs) {
1316
                    l.add(fieldDescriptor.getName());
1317
                }
1318
            }
1319
        }
1320
        // + champs dans la base
1321
        final Set<SQLTable> tables = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTables();
1322
        for (SQLTable sqlTable : tables) {
1323
            final String tName = sqlTable.getName();
1324
            if (tName.equals(tableName)) {
1325
                Set<String> f = sqlTable.getFieldsName();
1326
                for (String string : f) {
1327
                    l.add(string);
1328
                }
1329
 
1330
            }
1331
        }
1332
 
1333
        return new ArrayList<String>(l);
1334
    }
1335
 
1336
    public List<String> getAllKnownActionNames() {
1337
        ArrayList<String> s = new ArrayList<String>();
1338
        Collection<SQLElement> elements = ComptaPropsConfiguration.getInstanceCompta().getDirectory().getElements();
1339
        for (SQLElement element : elements) {
1340
            Collection<IListeAction> actions = element.getRowActions();
1341
            for (IListeAction action : actions) {
1342
                if (action instanceof RowAction) {
1343
                    RowAction rAction = (RowAction) action;
1344
                    final String id = rAction.getID();
1345
                    if (id != null)
1346
                        s.add(id);
1347
                }
1348
            }
1349
        }
1350
        Collections.sort(s);
1351
        return s;
1352
    }
1353
 
1354
    public List<String> getActionNames() {
1355
        ArrayList<String> s = new ArrayList<String>();
1356
        for (ActionDescriptor action : this.createActionList) {
1357
            s.add(action.getId());
1358
        }
1359
        Collections.sort(s);
1360
        return s;
1361
    }
1362
 
1363
    public List<ActionDescriptor> getActionDescriptors() {
1364
        Collections.sort(this.createActionList, new Comparator<ActionDescriptor>() {
1365
 
1366
            @Override
1367
            public int compare(ActionDescriptor o1, ActionDescriptor o2) {
1368
                return o1.getId().compareTo(o2.getId());
1369
            }
1370
        });
1371
        return this.createActionList;
1372
    }
1373
 
1374
    public boolean isEmpty() {
1375
        return createTableList.isEmpty() && modifyTableList.isEmpty() && createListList.isEmpty() && tableTranslations.isEmpty() && fieldTranslations.isEmpty() && menuTranslations.isEmpty()
1376
                && actionTranslations.isEmpty() && createComponentList.isEmpty() && modifyComponentList.isEmpty() && createMenuList.isEmpty() && removeMenuList.isEmpty() && createActionList.isEmpty();
1377
    }
1378
 
1379
    public String getTableNameForElementId(String id) {
1380
        for (ElementDescriptor element : this.elementList) {
1381
            if (element.getId().equals(id)) {
1382
                return element.getTableName();
1383
            }
1384
        }
1385
        return null;
1386
    }
1387
 
1388
    private String getRefFromTable(String table) {
1389
        for (ElementDescriptor element : this.elementList) {
1390
            if (element.getTableName().equals(table)) {
1391
                return element.getId();
1392
            }
1393
        }
1394
        return null;
1395
    }
1396
 
1397
    public List<MenuTranslation> getMenuTranslations() {
1398
        return menuTranslations;
1399
    }
1400
 
1401
    public List<ActionTranslation> getActionTranslations() {
1402
        return actionTranslations;
1403
    }
1404
 
1405
    public List<FieldTranslation> getFieldTranslations() {
1406
        return fieldTranslations;
1407
    }
1408
 
1409
    public void removeChangeListener(ChangeListener listener) {
1410
        this.listeners.remove(listener);
1411
 
1412
    }
1413
 
1414
    public void setName(String name) {
1415
        if (!name.equals(this.name)) {
1416
            deleteFromDB();
1417
            this.name = name;
1418
            save();
1419
            setChanged();
1420
        }
1421
    }
1422
 
1423
    public void setupMenu(MenuContext ctxt) {
1424
        final Group group = ctxt.getMenuAndActions().getGroup();
1425
        initMenuGroup(group);
86 ilm 1426
        registerMenuActions(ctxt.getMenuAndActions());
74 ilm 1427
    }
1428
 
1429
    public void removeRemoveMenuForId(String id) {
1430
        for (int i = removeMenuList.size() - 1; i >= 0; i--) {
1431
            final MenuDescriptor m = removeMenuList.get(i);
1432
            if (m.getId().equals(id)) {
1433
                removeMenuList.remove(i);
1434
            }
1435
        }
1436
 
1437
    }
1438
 
1439
    public void removeCreateMenuForId(String id) {
1440
        for (int i = createMenuList.size() - 1; i >= 0; i--) {
1441
            final MenuDescriptor m = createMenuList.get(i);
1442
            if (m.getId().equals(id)) {
1443
                createMenuList.remove(i);
1444
            }
1445
        }
1446
 
1447
    }
1448
 
1449
    public MenuDescriptor getRemoveMenuItemFromId(String itemId) {
1450
        for (MenuDescriptor m : removeMenuList) {
1451
            if (m.getId().equals(itemId)) {
1452
                return m;
1453
            }
1454
        }
1455
        return null;
1456
    }
1457
 
1458
    public void renameMenuItem(String previousId, String newId) {
1459
        if (!previousId.equals(newId)) {
1460
            final List<MenuDescriptor> descs = new ArrayList<MenuDescriptor>(createMenuList.size() + removeMenuList.size());
1461
            descs.addAll(createMenuList);
1462
            descs.addAll(removeMenuList);
1463
            for (MenuDescriptor m : descs) {
1464
                if (m.getId().equals(previousId)) {
1465
                    m.setId(newId);
1466
                }
1467
            }
1468
 
1469
        }
1470
 
1471
    }
1472
 
1473
    public void moveMenuItem(String itemId, String parentId) {
1474
        for (MenuDescriptor m : createMenuList) {
1475
            if (m.getId().equals(itemId)) {
1476
                m.setInsertInMenu(parentId);
1477
            }
1478
        }
1479
 
1480
    }
86 ilm 1481
 
1482
    public void setMenuTranslation(String id, String text, Locale locale) {
1483
        MenuTranslation mTranslation = null;
1484
        for (MenuTranslation mTr : this.menuTranslations) {
1485
            if (mTr.getId().equals(id) && mTr.getLocale().equals(locale.toString())) {
1486
                mTranslation = mTr;
1487
                break;
1488
            }
1489
 
1490
        }
1491
        if (mTranslation == null) {
1492
            mTranslation = new MenuTranslation(locale.toString(), id);
1493
            this.menuTranslations.add(mTranslation);
1494
        }
1495
        mTranslation.setLabel(text);
1496
 
1497
    }
139 ilm 1498
 
1499
    private TableTranslation getTableTranslation(String tableName, Locale locale) {
1500
        TableTranslation tTranslation = null;
1501
        for (TableTranslation mTr : this.tableTranslations) {
1502
            if (mTr.getTableName().equals(tableName) && mTr.getLocale().equals(locale.toString())) {
1503
                tTranslation = mTr;
1504
                break;
1505
            }
1506
        }
1507
        if (tTranslation == null) {
1508
            tTranslation = new TableTranslation(locale.toString(), tableName);
1509
            this.tableTranslations.add(tTranslation);
1510
        }
1511
        return tTranslation;
1512
    }
1513
 
1514
    public void setTableSingularTranslation(String tableName, Locale locale, String text) {
1515
        TableTranslation mTranslation = getTableTranslation(tableName, locale);
1516
        mTranslation.setSingular(text);
1517
 
1518
    }
1519
 
1520
    public void setTablePluralTranslation(String tableName, Locale locale, String text) {
1521
        TableTranslation mTranslation = getTableTranslation(tableName, locale);
1522
        mTranslation.setPlural(text);
1523
 
1524
    }
1525
 
1526
    public void setFieldTranslation(String tableName, String fieldName, Locale locale, String text) {
1527
        FieldTranslation fTranslation = null;
1528
        for (FieldTranslation mTr : this.fieldTranslations) {
1529
            if (mTr.getTableName().equals(tableName) && mTr.getFieldName().equals(fieldName) && mTr.getLocale().equals(locale.toString())) {
1530
                fTranslation = mTr;
1531
                break;
1532
            }
1533
        }
1534
        if (fTranslation == null) {
1535
            fTranslation = new FieldTranslation(locale.toString(), tableName, fieldName);
1536
            this.fieldTranslations.add(fTranslation);
1537
        }
1538
        fTranslation.setLabel(text);
1539
 
1540
    }
74 ilm 1541
}