OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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