Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1000 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / EditableAdapter.java @ 11885

History | View | Annotate | Download (47.9 KB)

1
package com.iver.cit.gvsig.fmap.edition;
2

    
3
import java.io.IOException;
4
import java.util.ArrayList;
5
import java.util.Collection;
6
import java.util.HashMap;
7
import java.util.Iterator;
8
import java.util.TreeMap;
9

    
10
import com.hardcode.driverManager.Driver;
11
import com.hardcode.driverManager.DriverLoadException;
12
import com.hardcode.gdbms.engine.data.DataSourceFactory;
13
import com.hardcode.gdbms.engine.data.NoSuchTableException;
14
import com.hardcode.gdbms.engine.data.driver.AlphanumericDBDriver;
15
import com.hardcode.gdbms.engine.data.driver.DriverException;
16
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
17
import com.hardcode.gdbms.engine.data.edition.DataWare;
18
import com.hardcode.gdbms.engine.values.Value;
19
import com.iver.cit.gvsig.fmap.core.DefaultRow;
20
import com.iver.cit.gvsig.fmap.core.IRow;
21
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
22
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
23
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
24
import com.iver.cit.gvsig.fmap.drivers.TableDefinition;
25
import com.iver.cit.gvsig.fmap.edition.commands.AddFieldCommand;
26
import com.iver.cit.gvsig.fmap.edition.commands.AddRowCommand;
27
import com.iver.cit.gvsig.fmap.edition.commands.Command;
28
import com.iver.cit.gvsig.fmap.edition.commands.CommandCollection;
29
import com.iver.cit.gvsig.fmap.edition.commands.CommandRecord;
30
import com.iver.cit.gvsig.fmap.edition.commands.MemoryCommandRecord;
31
import com.iver.cit.gvsig.fmap.edition.commands.ModifyRowCommand;
32
import com.iver.cit.gvsig.fmap.edition.commands.RemoveFieldCommand;
33
import com.iver.cit.gvsig.fmap.edition.commands.RemoveRowCommand;
34
import com.iver.cit.gvsig.fmap.edition.commands.RenameFieldCommand;
35
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AbstractFieldManager;
36
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
37
import com.iver.cit.gvsig.fmap.layers.FBitSet;
38
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
39
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
40
import com.iver.cit.gvsig.fmap.operations.Cancel;
41

    
42
/**
43
 * DOCUMENT ME!
44
 *
45
 * @author Vicente Caballero Navarro
46
 */
47
public class EditableAdapter implements IEditableSource, IWriteable {
48
        protected boolean isEditing = false;
49

    
50
        private SelectableDataSource ds = null;
51

    
52
        protected FBitSet delRows = new FBitSet();
53

    
54
        private CommandRecord cr;
55

    
56
        protected IWriter writer;
57

    
58
        /**
59
         * Flag que indica que hay que tomar las siguientes operaciones como una
60
         * operaci?n at?mica
61
         */
62
        private boolean complex = false;
63

    
64
        private CommandCollection commands = null;
65

    
66
        protected ArrayList listFields = new ArrayList();
67

    
68
        protected ArrayList listInternalFields = new ArrayList();
69

    
70
        protected boolean bFieldsHasBeenChanged = false;
71

    
72
        /**
73
         * La clave ser? el fieldId. Para buscar si un value de una row ha de ser
74
         * rellenado con defaultValue o con lo que venga del expansion file,
75
         * miraremos si existe en este hash. Si existe, usamos el value del
76
         * expansion file. Si no existe, usamos el defaultValue del campo busc?ndolo
77
         * en la lista internalFields. Por cierto, en listInternalFields NO se
78
         * borran campos. Solo se van a?adiendo nuevos actualFields.
79
         */
80
        protected TreeMap actualFields; // la clave ser? el fieldId.
81

    
82
        protected ArrayList fastAccessFields = new ArrayList();
83

    
84
        protected class MyFieldManager extends AbstractFieldManager {
85

    
86
                public boolean alterTable() throws EditionException {
87
                        return getFieldManager().alterTable();
88
                }
89

    
90
                public void addField(FieldDescription fieldDesc) {
91
                        super.addField(fieldDesc);
92
                }
93

    
94
                public FieldDescription removeField(String fieldName) {
95
                        // TODO Auto-generated method stub
96
                        return super.removeField(fieldName);
97
                }
98

    
99
                public void renameField(String antName, String newName) {
100
                        // TODO Auto-generated method stub
101
                        super.renameField(antName, newName);
102
                }
103

    
104
        }
105

    
106
        /*
107
         * Establece una relaci?n entre los ?ndices de las geometr?as en el
108
         * EditableFeatureSource y los ?ndices en el fichero de expansi?n FJP:
109
         * CAMBIO: NECESITAMOS TRABAJAR CON FEATURE Y FEATUREITERATOR PARA IR
110
         * PREPARANDO EL CAMINO, GUARDAMOS EL FEATUREID (STRING) COMO CLAVE, Y COMO
111
         * VALOR, EL INDICE DENTRO DEL FICHERO DE EXPANSION (Integer). Lo de que
112
         * FeatureId sea un String es por compatibilidad con OGC. Seg?n OGC, una
113
         * Feature tiene que tener un Id string En el caso de los randomaccess,
114
         * ser?n el id de registro En los casos de base de datos espaciales, supongo
115
         * que siempre ser? num?rico tambi?n, pero lo tendremos que convertir a
116
         * string. Lo que est? claro es que NO se puede confiar nunca en que sea
117
         * algo correlativo (1, 2, 3, 4, 5, ... => FALSO!!)
118
         */
119
        protected HashMap relations = new HashMap();
120

    
121
        /*
122
         * Fichero en el que se guardan las nuevas geometr?as, producto de adiciones
123
         * o de modificaciones
124
         */
125
        protected ExpansionFile expansionFile;
126

    
127
        protected int numAdd = 0;
128

    
129
        private ObjectDriver editingDriver = new myObjectDriver();
130

    
131
        private SelectableDataSource ods;
132

    
133
        private ArrayList editionListeners = new ArrayList();
134

    
135
        private ArrayList rules = new ArrayList();
136

    
137
        protected int actualIndexFields;
138

    
139
        protected boolean isFullExtentDirty = false;
140

    
141
        private ArrayList fieldEvents=new ArrayList();
142
        private ArrayList rowEvents=new ArrayList();
143

    
144
        /**
145
         * Crea un nuevo EditableAdapter.
146
         */
147
        public EditableAdapter() {
148
                expansionFile = new MemoryExpansionFile(this);
149
                cr = new MemoryCommandRecord();
150
        }
151

    
152
        /**
153
         * DOCUMENT ME!
154
         *
155
         * @param ds
156
         *            DOCUMENT ME!
157
         * @throws DriverException
158
         */
159
        public void setOriginalDataSource(SelectableDataSource ds) throws DriverException {
160
                this.ods = ds;
161
                initalizeFields(ds);
162
                Driver drv = ods.getDriver();
163
                if (drv instanceof IWriteable) {
164
                        setWriter(((IWriteable) drv).getWriter());
165
                }
166

    
167

    
168
        }
169

    
170
        /**
171
         * @param ds
172
         * @throws DriverException
173
         */
174
        private void initalizeFields(SelectableDataSource ds) throws DriverException {
175
                FieldDescription[] fields = ds.getFieldsDescription();
176
                listInternalFields.clear();
177
                actualIndexFields = 0;
178
                actualFields = new TreeMap();
179
//                fastAccessFields = new ArrayList();
180
                for (int i=0; i < fields.length; i++)
181
                {
182
                        InternalField field = new InternalField(fields[i], InternalField.ORIGINAL, new Integer(i));
183
                        listFields.add(field);
184
                        // field.setFieldIndex(i);
185
                        actualFields.put(field.getFieldId(), field);
186
//                        fastAccessFields.add(fields[i]);
187
                        System.out.println("INITIALIZEFIELDS: FIELD " + field.getFieldDesc().getFieldAlias());
188
                }
189
                try {
190
                        fieldsChanged();
191
                        bFieldsHasBeenChanged = false;
192
                } catch (EditionException e) {
193
                        e.printStackTrace();
194
                        throw new DriverException(e);
195
                }
196
        }
197

    
198
        private TreeMap deepCloneInternalFields(TreeMap col)
199
        {
200
                TreeMap clonedFields = new TreeMap();
201
                for (Iterator iter = col.values().iterator(); iter.hasNext();) {
202
                        InternalField fld = (InternalField) iter.next();
203
                        InternalField clonedField = fld.cloneInternalField();
204
                        clonedFields.put(clonedField.getFieldId(), clonedField);
205
                }
206

    
207
                return clonedFields;
208
        }
209
        private void fieldsChanged() throws EditionException {
210
                fastAccessFields= new ArrayList();
211
                int index = 0;
212
                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
213
                        InternalField fld = (InternalField) iter.next();
214
                        fastAccessFields.add(fld.getFieldDesc());
215
                        fld.setFieldIndex(index++);
216
                }
217

    
218
                listInternalFields.add(deepCloneInternalFields(actualFields));
219
                actualIndexFields = listInternalFields.size()-1;
220
                try {
221
                        ds = null;
222
                        getRecordset().mapExternalFields();
223
                        bFieldsHasBeenChanged = true;
224
                } catch (DriverLoadException e) {
225
                        e.printStackTrace();
226
                        throw new EditionException(e);
227
                } catch (DriverException e) {
228
                        e.printStackTrace();
229
                        throw new EditionException(e);
230
                }
231
        }
232

    
233
        /**
234
         * DOCUMENT ME!
235
         *
236
         * @throws EditionException
237
         *             DOCUMENT ME!
238
         */
239
        public void startEdition(int sourceType) throws EditionException {
240
                isEditing = true;
241

    
242
                fireStartEditionEvent(sourceType);
243
        }
244

    
245
        /**
246
         * Se ejecuta preProcess() del IWriter, luego se itera por los registros
247
         * borrados por si el IWriter los quiere borrar (solo ser? necesario cuando
248
         * escribimos sobre la misma tabla) y luego se itera por los nuevos
249
         * registros llamando a process con el registro correcto. (A?adidos,
250
         * modificados). Para finalizar, se ejecuta PostProcess
251
         *
252
         * @param writer
253
         *            IWriter que recibir? las llamadas.
254
         *
255
         * @throws EditionException
256
         *             DOCUMENT ME!
257
         *
258
         */
259
        public void stopEdition(IWriter writer, int sourceType)
260
                        throws EditionException {
261
                saveEdits(writer, sourceType);
262
                isEditing = false;
263
                cr.clearAll();
264
                fireStopEditionEvent(sourceType);
265
        }
266

    
267
        public void saveEdits(IWriter writer, int sourceType)
268
                        throws EditionException {
269

    
270
                // TODO: ARREGLAR ESTO PARA QUE CUANDO HA HABIDO CAMBIOS
271
                // EN LOS CAMPOS, PODAMOS CAMBIAR LO QUE TOQUE (A SER POSIBLE
272
                // SIN TENER QUE REESCRIBIR TODA LA TABLA CON POSTGIS)
273
                if (bFieldsHasBeenChanged)
274
                {
275
                        // Para cada campo de los originales, miramos si no est? en
276
                        // los actuales. Si no est?, le decimos al fieldManager
277
                        // que lo borre. Si est?, pero le hemos cambiado el nombre
278
                        // le pedimos al fieldManager que le cambie el nombre.
279
                        // Luego recorremos los campos actuales para ver cuales
280
                        // son nuevos, y los a?adimos.
281

    
282
                        TreeMap ancientFields = (TreeMap) listInternalFields
283
                                        .get(0);
284
                        Collection aux = ancientFields.values();
285
                        Iterator it = aux.iterator();
286
                        while (it.hasNext()) {
287
                                InternalField fld = (InternalField) it.next();
288
                                // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
289
                                if (actualFields.containsKey(fld.getFieldId())) {
290
                                        // Es un original
291
                                        String f1 = fld.getFieldDesc().getFieldName();
292
                                        String f2 = fld.getFieldDesc().getFieldAlias();
293
                                        if (f1.compareTo(f2) != 0)
294
                                        {
295
                                                getFieldManager().renameField(f1, f2);
296
                                        }
297
                                }
298
                                else
299
                                {        // No est?, hay que borrarlo
300
                                        getFieldManager().removeField(fld.getFieldDesc().getFieldAlias());
301
                                }
302
                        }
303
                        Collection aux2= actualFields.values();
304
                        Iterator it2 = aux2.iterator();
305
                        while (it2.hasNext()) {
306
                                InternalField fld = (InternalField) it2.next();
307
                                // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
308
                                if (!ancientFields.containsKey(fld.getFieldId())) {
309
                                        // Es uno a?adido
310
                                        getFieldManager().addField(fld.getFieldDesc());
311
                                }
312
                        }
313
                        // getFieldManager().alterTable(); // Se llama dentro del preprocess()
314
                }
315

    
316
                writer.preProcess();
317

    
318
                try {
319

    
320
                        // Procesamos primero los borrados.
321
                        // Cuando se genere un tema nuevo, no se les debe hacer caso
322
                        // a estos registros
323

    
324
                        for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
325
                                        .nextSetBit(i + 1)) {
326
                                int calculatedIndex = i;
327
                                Integer integer = new Integer(calculatedIndex);
328
                                // Si no est? en el fichero de expansi?n, es de los originales
329
                                // y hay que borrarlo
330
                                DefaultRowEdited edRow = null;
331
                                if (!relations.containsKey(integer)) {
332
                                        edRow = new DefaultRowEdited(new DefaultRow(ods
333
                                                        .getRow(calculatedIndex)),
334
                                                        DefaultRowEdited.STATUS_DELETED, calculatedIndex);
335
                                        writer.process(edRow);
336
                                } else {
337
                                        int num = ((Integer) relations.get(integer)).intValue();
338

    
339
                                        // return expansionFile.getRow(num);
340
                                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
341
                                        // ?Habr?a que hacer aqu? setID(index + "")?
342
                                        edRow = new DefaultRowEdited(rowFromExpansion
343
                                                        .getLinkedRow().cloneRow(),
344
                                                        DefaultRowEdited.STATUS_DELETED, calculatedIndex);
345
                                        writer.process(edRow);
346
                                }
347

    
348
                        }
349

    
350
                        int rowCount = getRowCount();
351
                        if (writer.isWriteAll())
352
                        {
353
                                for (int i = 0; i < rowCount; i++) {
354
                                        IRowEdited rowEdited = getRow(i);
355

    
356
                                        if (rowEdited != null) {
357
                                                writer.process(rowEdited);
358
                                        }
359
                                }
360
                        }
361
                        else
362
                        {
363
                                // Escribimos solo aquellos registros que han cambiado
364
                                for (int i = 0; i < rowCount; i++) {
365
                                        int calculatedIndex = getCalculatedIndex(i);
366
                                        Integer integer = new Integer(calculatedIndex);
367
                                        DefaultRowEdited edRow = null;
368
                                        // Si est? en el fichero de expansi?n hay que modificar
369
                                        if (relations.containsKey(integer)) {
370
                                                int num = ((Integer) relations.get(integer)).intValue();
371

    
372
                                                // return expansionFile.getRow(num);
373
                                                // ExpansionFile ya entrega el registro formateado como debe
374
                                                IRowEdited rowFromExpansion = expansionFile.getRow(num);
375
                                                // ?Habr?a que hacer aqu? setID(index + "")?
376
                                                edRow = new DefaultRowEdited(rowFromExpansion.getLinkedRow()
377
                                                                .cloneRow(), rowFromExpansion.getStatus(), i);
378
                                                writer.process(edRow);
379
                                        }
380
                                }
381
                        }
382
                        writer.postProcess();
383

    
384
                        // Hacemos que el escritor se entere de los nuevos campos
385
                        // que tiene. El escritor debe guardar una referencia
386
                        // a los campos con los que trabaja el drier, de forma
387
                        // que al recargar la capa (por ejemplo en el caso de
388
                        // PostGIS, se haga un setData con los campos que se hayan
389
                        // a?adido, borrado o renombrado).
390
                        writer.getTableDefinition().setFieldsDesc(getRecordset().getFieldsDescription());
391

    
392
                        ods.reload();
393
                        ds = null;
394
                        clean();
395

    
396
                } catch (DriverIOException e) {
397
                        e.printStackTrace();
398
                        throw new EditionException(e);
399
                } catch (IOException e) {
400
                        e.printStackTrace();
401
                        throw new EditionException(e);
402
                } catch (DriverException e) {
403
                        e.printStackTrace();
404
                        throw new EditionException(e);
405
                }
406

    
407
        }
408

    
409
        /**
410
         * DOCUMENT ME!
411
         *
412
         * @throws IOException
413
         *             DOCUMENT ME!
414
         */
415
        public void cancelEdition(int sourceType) throws IOException {
416
                isEditing = false;
417
                try {
418
                        ds= null;
419
                        clean();
420
                        cr.clearAll();
421
                } catch (DriverException e) {
422
                        e.printStackTrace();
423
                        throw new IOException("Error: " + e.getMessage());
424
                }
425
                fireCancelEditionEvent(sourceType);
426
        }
427

    
428
        /*
429
         * (non-Javadoc)
430
         *
431
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
432
         */
433
        public IRowEdited getRow(int index) throws DriverIOException, IOException {
434
                int calculatedIndex = getCalculatedIndex(index);
435
                Integer integer = new Integer(calculatedIndex);
436
                DefaultRowEdited edRow = null;
437
                // Si no est? en el fichero de expansi?n
438
                if (!relations.containsKey(integer)) {
439
                        try {
440
                                /*
441
                                 * edRow = new DefaultRowEdited(new
442
                                 * DefaultRow(ods.getRow(calculatedIndex), "" + index),
443
                                 * DefaultRowEdited.STATUS_ORIGINAL, index);
444
                                 */
445
                                DefaultRow auxR = new DefaultRow(ods.getRow(calculatedIndex));
446
                                edRow = new DefaultRowEdited(auxR,
447
                                                DefaultRowEdited.STATUS_ORIGINAL, index);
448
                                return createExternalRow(edRow, 0);
449
//                                edRow = new DefaultRowEdited(new DefaultRow(ods
450
//                                                .getRow(calculatedIndex)),
451
//                                                DefaultRowEdited.STATUS_ORIGINAL, index);
452
                        } catch (DriverException e) {
453
                                throw new DriverIOException(e);
454
                        }
455
                } else {
456
                        int num = ((Integer) relations.get(integer)).intValue();
457

    
458
                        // return expansionFile.getRow(num);
459
                        // ExpansionFile ya entrega el registro formateado como debe
460
                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
461
                        // ?Habr?a que hacer aqu? setID(index + "")?
462
                        edRow = new DefaultRowEdited(rowFromExpansion.getLinkedRow()
463
                                        .cloneRow(), rowFromExpansion.getStatus(), index);
464
                        return edRow;
465
                }
466

    
467

    
468

    
469
        }
470

    
471
        /**
472
         * DOCUMENT ME!
473
         *
474
         * @return DOCUMENT ME!
475
         *
476
         * @throws DriverIOException
477
         *             DOCUMENT ME!
478
         * @throws IOException
479
         *             DOCUMENT ME!
480
         */
481
        public int getRowCount() throws DriverIOException, IOException {
482
                try {
483
                        return (int) (ods.getRowCount() + numAdd) - delRows.cardinality();// -
484
                        // expansionFile.getInvalidRows().cardinality();
485
                } catch (DriverException e) {
486
                        throw new DriverIOException(e);
487
                }
488

    
489
        }
490

    
491
        /*
492
         * (non-Javadoc)
493
         *
494
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#addRow(com.iver.cit.gvsig.fmap.core.IRow,
495
         *      java.lang.String)
496
         */
497
        public int addRow(IRow row, String descrip, int sourceType)
498
                        throws DriverIOException, IOException {
499

    
500
                try {
501
                        validateRow(row,sourceType);
502
                } catch (EditionException e) {
503
                        e.printStackTrace();
504
                        throw new IOException(e.getMessage());
505
                }
506

    
507
                int calculatedIndex = doAddRow(row, sourceType);
508
                Command command = new AddRowCommand(this, row, calculatedIndex,
509
                                sourceType);
510
                command.setDescription(descrip);
511
                if (complex) {
512
                        commands.add(command);
513
                } else {
514
                        cr.pushCommand(command);
515
                }
516

    
517
                return calculatedIndex;
518
        }
519

    
520
        /**
521
         * DOCUMENT ME!
522
         *
523
         * @throws DriverIOException
524
         *             DOCUMENT ME!
525
         * @throws IOException
526
         *             DOCUMENT ME!
527
         */
528
        public void undo() throws DriverIOException, IOException {
529
                // seleccion.clear();
530
                if (cr.moreUndoCommands()) {
531
                        cr.undoCommand();
532
                }
533
        }
534

    
535
        /**
536
         * DOCUMENT ME!
537
         *
538
         * @throws DriverIOException
539
         *             DOCUMENT ME!
540
         * @throws IOException
541
         *             DOCUMENT ME!
542
         */
543
        public void redo() throws DriverIOException, IOException {
544
                // seleccion.clear();
545
                if (cr.moreRedoCommands()) {
546
                        cr.redoCommand();
547
                }
548
        }
549

    
550
        /*
551
         * (non-Javadoc)
552
         *
553
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#removeRow(int)
554
         */
555
        public void removeRow(int index, String descrip, int sourceType)
556
                        throws IOException, DriverIOException {
557

    
558
                int calculatedIndex = getCalculatedIndex(index);
559
                Command command = new RemoveRowCommand(this, calculatedIndex,
560
                                sourceType);
561
                command.setDescription(descrip);
562
                if (complex) {
563
                        commands.add(command);
564
                } else {
565
                        cr.pushCommand(command);
566
                }
567
                doRemoveRow(calculatedIndex, sourceType);
568

    
569
        }
570

    
571
        /*
572
         * (non-Javadoc)
573
         *
574
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#modifyRow(int,
575
         *      com.iver.cit.gvsig.fmap.core.IRow)
576
         */
577
        public int modifyRow(int index, IRow row, String descrip, int sourceType)
578
                        throws IOException, DriverIOException {
579

    
580
                try {
581
                        validateRow(row,sourceType);
582
                } catch (EditionException e) {
583
                        e.printStackTrace();
584
                        throw new IOException(e.getMessage());
585
                }
586

    
587
                int calculatedIndex = getCalculatedIndex(index);
588
                int pos = doModifyRow(calculatedIndex, row, sourceType);
589
                Command command = new ModifyRowCommand(this, calculatedIndex, pos, row,
590
                                sourceType);
591
                command.setDescription(descrip);
592
                if (complex) {
593
                        commands.add(command);
594
                } else {
595
                        cr.pushCommand(command);
596
                }
597

    
598
                return pos;
599
        }
600

    
601
        /**
602
         * DOCUMENT ME!
603
         */
604
        public void compact() {
605
                expansionFile.compact(relations);
606
        }
607

    
608
        /**
609
         * DOCUMENT ME!
610
         */
611
        public void startComplexRow() {
612
                complex = true;
613
                commands = new CommandCollection();
614
        }
615

    
616
        /**
617
         * DOCUMENT ME!
618
         *
619
         * @throws IOException
620
         *             DOCUMENT ME!
621
         * @throws DriverIOException
622
         *             DOCUMENT ME!
623
         */
624
        public void endComplexRow(String description) throws IOException,
625
                        DriverIOException {
626
                commands.setDescription(description);
627
                cr.pushCommand(commands);
628
                complex = false;
629
                for (int j = 0; j < editionListeners.size(); j++) {
630
                        for (int i = 0; i < fieldEvents.size(); i++) {
631
                                IEditionListener listener = (IEditionListener) editionListeners
632
                                        .get(j);
633
                                listener.afterFieldEditEvent((AfterFieldEditEvent)fieldEvents.get(i));
634
                        }
635
                        for (int i = 0; i < rowEvents.size(); i++) {
636
                                IEditionListener listener = (IEditionListener) editionListeners
637
                                                .get(j);
638
                                listener.afterRowEditEvent(null,(AfterRowEditEvent)rowEvents.get(i));
639
                        }
640
                }
641
                fieldEvents.clear();
642
                rowEvents.clear();
643
        }
644

    
645
        /**
646
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
647
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
648
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
649
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
650
         * expansion file a justo despues de la penultima geometr?a
651
         *
652
         * @param geometryIndex
653
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
654
         * @param previousExpansionFileIndex
655
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
656
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
657
         *            original y por tanto no hay que actualizar el mapa de indices
658
         *            sino eliminar su entrada.
659
         *
660
         * @throws IOException
661
         * @throws DriverIOException
662
         */
663
        public void undoModifyRow(int geometryIndex,
664
                        int previousExpansionFileIndex, int sourceType) throws IOException,
665
                        DriverIOException {
666

    
667
                if (previousExpansionFileIndex == -1) {
668
                        DefaultRowEdited edRow = null;
669
                        try {
670
                                edRow = new DefaultRowEdited(new DefaultRow(ods
671
                                                .getRow(geometryIndex)),
672
                                                DefaultRowEdited.STATUS_ORIGINAL, geometryIndex);
673
                        } catch (DriverException e) {
674
                                e.printStackTrace();
675
                        }
676
                        boolean cancel = fireBeforeModifyRow(edRow, geometryIndex,
677
                                        sourceType);
678
                        if (cancel)
679
                                return;
680
                        // Se elimina de las relaciones y del fichero de expansi?n
681
                        relations.remove(new Integer(geometryIndex));
682
                        expansionFile.deleteLastRow();
683
                } else {
684
                        boolean cancel = fireBeforeModifyRow(expansionFile
685
                                        .getRow(previousExpansionFileIndex), geometryIndex,
686
                                        sourceType);
687
                        if (cancel)
688
                                return;
689
                        // Se actualiza la relaci?n de ?ndices
690
                        relations.put(new Integer(geometryIndex), new Integer(
691
                                        previousExpansionFileIndex));
692
                }
693
                //fireAfterModifyRow(geometryIndex, sourceType);
694
        }
695

    
696
        /**
697
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
698
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
699
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
700
         * una futura compactaci?n termine con ella.
701
         *
702
         * @param index
703
         *            ?ndice de la geometr?a.
704
         *
705
         * @throws DriverIOException
706
         * @throws IOException
707
         */
708
        public IRow doRemoveRow(int index, int sourceType)
709
                        throws DriverIOException, IOException {
710
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
711
                if (cancel)
712
                        return null;
713
                // Llega un calculatedIndex
714
                delRows.set(index, true);
715
                System.err.println("Elimina una Row en la posici?n: " + index);
716
                // TODO: Con tablas no es necesario devolver la anterior feature. Por
717
                // ahora.
718
                isFullExtentDirty = true;
719
                fireAfterRemoveRow(index, sourceType);
720
                return null;
721
        }
722

    
723
        /**
724
         ** Si se intenta modificar una geometr?a original de la capa en edici?n se
725
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
726
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
727
         * fichero de expansi?n, ?sta puede estar ah? (en el ExpansionFile
728
         * por haber sido a?adida o modificada. Si ha sido a?adida, entonces hay
729
         * que respetar su estatus para que los writers puedan saber que es
730
         * un registro NUEVO).
731
         *
732
         * @param index
733
         *            DOCUMENT ME!
734
         * @param feat
735
         *            DOCUMENT ME!
736
         *
737
         * @return DOCUMENT ME!
738
         *
739
         * @throws IOException
740
         * @throws DriverIOException
741
         */
742
        public int doModifyRow(int index, IRow feat, int sourceType)
743
                        throws IOException, DriverIOException {
744
                boolean cancel = fireBeforeModifyRow(feat, index, sourceType);
745
                if (cancel)
746
                        return -1;
747

    
748
                int pos = -1;
749
                Integer integer = new Integer(index);
750
//                System.err.println("Modifica una Row en la posici?n: " + index);
751
                // Si la geometr?a no ha sido modificada
752
                if (!relations.containsKey(integer)) {
753
                        int expansionIndex = expansionFile.addRow(feat,
754
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
755
                        relations.put(integer, new Integer(expansionIndex));
756
                } else {
757
                        // Obtenemos el ?ndice en el fichero de expansi?n
758
                        int num = ((Integer) relations.get(integer)).intValue();
759
                        pos = num;
760

    
761
                        /*
762
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
763
                         * fichero de expansi?n en el que se encuentra la geometr?a
764
                         * modificada
765
                         */
766
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
767

    
768
                        /*
769
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
770
                         * fichero de expansi?n.
771
                         */
772
                        relations.put(integer, new Integer(num));
773
                }
774
                isFullExtentDirty = true;
775
                //fireAfterModifyRow(index, sourceType);
776
                return pos;
777
        }
778

    
779
        /**
780
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
781
         * en la tabla relations.
782
         *
783
         * @param feat
784
         *            geometr?a a guardar.
785
         *
786
         * @return calculatedIndex
787
         *
788
         * @throws DriverIOException
789
         * @throws IOException
790
         */
791
        public int doAddRow(IRow feat, int sourceType) throws DriverIOException,
792
                        IOException {
793
                boolean cancel = fireBeforeRowAdded(sourceType);
794
                if (cancel)
795
                        return -1;
796
                // A?ade la geometr?a
797
                // int virtualIndex = 0;
798
                int calculatedIndex = -1;
799

    
800
                try {
801
                        calculatedIndex = (int) ods.getRowCount() + numAdd;
802
                        // int externalIndex = getRowCount();
803
                        // calculatedIndex = getCalculatedIndex(externalIndex);
804
                } catch (DriverException e) {
805
                        throw new DriverIOException(e);
806
                }
807

    
808
                int pos = expansionFile.addRow(feat, IRowEdited.STATUS_ADDED, actualIndexFields);
809
                relations.put(new Integer(calculatedIndex), new Integer(pos));
810
                numAdd++;
811
                System.err.println("A?ade una Row en la posici?n: " + calculatedIndex);
812
                isFullExtentDirty = true;
813
                fireAfterRowAdded(feat,calculatedIndex, sourceType);
814
                return calculatedIndex;
815
        }
816

    
817
        /**
818
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
819
         * en el fichero original
820
         *
821
         * @param index
822
         *            DOCUMENT ME!
823
         *
824
         * @throws IOException
825
         * @throws DriverIOException
826
         */
827
        public void undoRemoveRow(int index, int sourceType) throws IOException,
828
                        DriverIOException {
829
                boolean cancel = fireBeforeRowAdded(sourceType);
830
                if (cancel)
831
                        return;
832
                delRows.set(index, false);
833
                fireAfterRowAdded(null,index, sourceType);
834
        }
835

    
836
        /**
837
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
838
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
839
         * relaci?n del mapa de relaciones
840
         *
841
         * @param index
842
         *            ?ndice de la geometr?a que se a?adi?
843
         *
844
         * @throws DriverIOException
845
         * @throws IOException
846
         */
847
        public void undoAddRow(int calculatedIndex, int sourceType)
848
                        throws DriverIOException, IOException {
849
                boolean cancel = fireBeforeRemoveRow(calculatedIndex, sourceType);
850
                if (cancel)
851
                        return;
852
                expansionFile.deleteLastRow();
853
                relations.remove(new Integer(calculatedIndex));
854
                numAdd--;
855
                fireAfterRemoveRow(calculatedIndex, sourceType);
856
        }
857

    
858
        /*
859
         * (non-Javadoc)
860
         *
861
         * @see com.iver.cit.gvsig.fmap.layers.VectorialAdapter#getRecordset()
862
         */
863
        public SelectableDataSource getRecordset() throws DriverLoadException {
864
                if (isEditing) {
865
                        if (ds == null) {
866
                                String name = LayerFactory.getDataSourceFactory()
867
                                                .addDataSource((ObjectDriver) editingDriver);
868

    
869
                                try {
870

    
871
                                        /*
872
                                        ds = new SelectableDataSource(LayerFactory
873
                                                        .getDataSourceFactory().createRandomDataSource(
874
                                                                        name, DataSourceFactory.MANUAL_OPENING));
875
                                        */
876
                                        // CHEMA: AUTOMATIC DATA SOURCE
877
                                        ds = new SelectableDataSource(LayerFactory
878
                                                        .getDataSourceFactory().createRandomDataSource(
879
                                                                        name, DataSourceFactory.AUTOMATIC_OPENING));
880
                                        ds.start();
881
                                        ds.setSelectionSupport(ods.getSelectionSupport());
882

    
883
                                } catch (NoSuchTableException e) {
884
                                        throw new RuntimeException(e);
885
                                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
886
                                        throw new RuntimeException(e);
887
                                }
888
                        }
889

    
890
                        return ds;
891
                } else {
892
                        return ods;
893
                }
894
        }
895

    
896
        /**
897
         * Return always the original recordset (even when is editing,
898
         * nor the getRecorset() method)
899
         *
900
         * */
901
        public SelectableDataSource getOriginalRecordset(){
902
                return ods;
903
        }
904

    
905

    
906
        /**
907
         * DOCUMENT ME!
908
         *
909
         * @return
910
         */
911
        public FBitSet getSelection() {
912
                /*
913
                 * try { return getRecordset().getSelection(); } catch
914
                 * (DriverLoadException e) { // TODO Auto-generated catch block
915
                 * e.printStackTrace(); } return null;
916
                 */
917
                return getRecordset().getSelection();
918
        }
919

    
920
        public void setSelection(FBitSet selection) {
921
                /*
922
                 * try { getRecordset().setSelection(selection); } catch
923
                 * (DriverLoadException e) { // TODO Auto-generated catch block
924
                 * e.printStackTrace(); }
925
                 */
926
                getRecordset().setSelection(selection);
927
        }
928

    
929
        /**
930
         * DOCUMENT ME!
931
         *
932
         * @return DOCUMENT ME!
933
         */
934
        public boolean isEditing() {
935
                return isEditing;
936
        }
937

    
938
        public int getInversedIndex(long rowIndex) {
939
                int intervalNotDeleted = 0;
940
                int antDeleted = -1;
941
                int idPedido = (int) rowIndex;
942
                int numNotDeleted = 0;
943
                int numBorradosAnt = 0;
944

    
945
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
946
                                .nextSetBit(i + 1)) {
947
                        intervalNotDeleted = i - antDeleted - 1;
948
                        numNotDeleted += intervalNotDeleted;
949
                        if (i > idPedido) {
950
                                numNotDeleted = numNotDeleted + (i - idPedido);
951
                                break;
952
                        }
953
                        numBorradosAnt++;
954
                        antDeleted = i;
955
                }
956
                numNotDeleted = idPedido - numBorradosAnt;
957
                // System.out.println("Piden Viejo : "+ rowIndex + " y devuelvo como
958
                // nuevo " + (numNotDeleted));
959
                return numNotDeleted;
960
        }
961

    
962
        /**
963
         * DOCUMENT ME!
964
         *
965
         * @param rowIndex
966
         *            DOCUMENT ME!
967
         *
968
         * @return DOCUMENT ME!
969
         */
970
        public int getCalculatedIndex(long rowIndex) {
971
                int numNotDeleted = 0;
972
                int intervalNotDeleted = 0;
973
                int antDeleted = -1;
974
                int calculatedIndex;
975
                int idPedido = (int) rowIndex;
976
                int numBorradosAnt = 0;
977

    
978
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
979
                                .nextSetBit(i + 1)) {
980
                        intervalNotDeleted = i - antDeleted - 1;
981
                        numNotDeleted += intervalNotDeleted;
982
                        if (numNotDeleted > idPedido) {
983
                                break;
984
                        }
985
                        numBorradosAnt++;
986
                        antDeleted = i;
987
                }
988
                calculatedIndex = numBorradosAnt + idPedido;
989
                // System.out.println("Piden Registro : "+ rowIndex + " y devuelvo el "
990
                // + (calculatedIndex));
991
                return calculatedIndex;
992
        }
993

    
994
        /**
995
         * DOCUMENT ME!
996
         *
997
         * @author Vicente Caballero Navarro
998
         */
999
        private class myObjectDriver implements ObjectDriver {
1000
                /*
1001
                 * (non-Javadoc)
1002
                 *
1003
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
1004
                 */
1005
                public int[] getPrimaryKeys() throws DriverException {
1006
                        return ods.getPrimaryKeys();
1007
                        // int[] pk=new int[1];
1008
                        /*
1009
                         * for (int i=0;i<getRowCount();i++){ pk[i]=i; }
1010
                         */
1011
                        // pk[0]=1;
1012
                        // return pk;
1013
                }
1014

    
1015
                /*
1016
                 * (non-Javadoc)
1017
                 *
1018
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
1019
                 */
1020
                public void write(DataWare dataWare) throws DriverException {
1021
                        DataWare dataWareOrig = ods
1022
                                        .getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
1023
                        dataWareOrig.commitTrans();
1024
                }
1025

    
1026
                /*
1027
                 * (non-Javadoc)
1028
                 *
1029
                 * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
1030
                 */
1031
                public void setDataSourceFactory(DataSourceFactory dsf) {
1032
                        ods.setDataSourceFactory(dsf);
1033
                }
1034

    
1035
                /*
1036
                 * (non-Javadoc)
1037
                 *
1038
                 * @see com.hardcode.driverManager.Driver#getName()
1039
                 */
1040
                public String getName() {
1041
                        return ods.getName();
1042
                }
1043

    
1044
                /*
1045
                 * (non-Javadoc)
1046
                 *
1047
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
1048
                 *      int)
1049
                 */
1050
                public Value getFieldValue(long rowIndex, int fieldId)
1051
                                throws DriverException {
1052
                        // Si no est? en el fichero de expansi?n
1053
                        // Integer integer = new Integer(getCalculatedIndex(rowIndex));
1054

    
1055

    
1056
                        try {
1057
                                IRow row = getRow((int)rowIndex);
1058
                                return row.getAttribute(fieldId);
1059
//                                if (!relations.containsKey(integer)) {
1060
//                                        return ods.getFieldValue(rowIndex, fieldId);
1061
//                                } else {
1062
//                                        int num = ((Integer) relations.get(integer)).intValue();
1063
//                                        DefaultRowEdited feat = (DefaultRowEdited) expansionFile
1064
//                                                        .getRow(num);
1065
//
1066
//                                        if (feat == null) {
1067
//                                                return null;
1068
//                                        }
1069
//
1070
//                                        return feat.getAttribute(fieldId);
1071
//                                }
1072
//                        } catch (DriverException e) {
1073
//                                e.printStackTrace();
1074
//                                throw new DriverException(e);
1075
                        } catch (IOException e) {
1076
                                e.printStackTrace();
1077
                                throw new DriverException(e);
1078
                        } catch (DriverIOException e) {
1079
                                e.printStackTrace();
1080
                                throw new DriverException(e);
1081
                        }
1082

    
1083
                        /**
1084
                         * try { if (!relations.containsKey(integer)) { // Si ha sido
1085
                         * eliminada if (delRows.get(integer.intValue())) { return null; }
1086
                         * else { return ods.getFieldValue(rowIndex, fieldId); }} else { int
1087
                         * num = ((Integer) relations.get(integer)).intValue();
1088
                         * DefaultRowEdited feat = (DefaultRowEdited)
1089
                         * expansionFile.getRow(num); if (feat==null)return null; return
1090
                         * feat.getAttribute(fieldId); }} catch (DriverException e) {
1091
                         * e.printStackTrace(); throw new DriverException(e); } catch
1092
                         * (IOException e) { e.printStackTrace(); throw new
1093
                         * DriverException(e); }
1094
                         */
1095
                }
1096

    
1097
                /*
1098
                 * (non-Javadoc)
1099
                 *
1100
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
1101
                 */
1102
                public int getFieldCount() throws DriverException {
1103
                        return fastAccessFields.size();
1104
                }
1105

    
1106
                /*
1107
                 * (non-Javadoc)
1108
                 *
1109
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
1110
                 */
1111
                public String getFieldName(int fieldId) throws DriverException {
1112
//                        int i=0;
1113
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1114
//                                InternalField fld = (InternalField) iter.next();
1115
//                                if (i == fieldId)
1116
//                                        return fld.getFieldDesc().getFieldAlias();
1117
//                                i++;
1118
//
1119
//                        }
1120
//                        throw new DriverException("FieldId " + fieldId + " not found ");
1121
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1122
                        return aux.getFieldAlias();
1123
                        // return null;
1124
                        // return ods.getFieldName(fieldId);
1125
                }
1126

    
1127
                /*
1128
                 * (non-Javadoc)
1129
                 *
1130
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
1131
                 */
1132
                public long getRowCount() {
1133
                        try {
1134
                                return (int) (ods.getRowCount() + numAdd)
1135
                                                - delRows.cardinality();// -
1136
                                // expansionFile.getInvalidRows().cardinality();
1137
                        } catch (DriverException e) {
1138
                                // TODO Auto-generated catch block
1139
                                e.printStackTrace();
1140
                        }
1141

    
1142
                        return 0;
1143
                }
1144

    
1145
                /*
1146
                 * (non-Javadoc)
1147
                 *
1148
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
1149
                 */
1150
                public int getFieldType(int fieldId) throws DriverException {
1151
//                        int i=0;
1152
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1153
//                                InternalField fld = (InternalField) iter.next();
1154
//                                if (i == fieldId)
1155
//                                        return fld.getFieldDesc().getFieldType();
1156
//                                i++;
1157
//
1158
//                        }
1159
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1160
                        return aux.getFieldType();
1161

    
1162
//                        return ods.getFieldType(i);
1163
                }
1164

    
1165
                public int getFieldWidth(int fieldId) throws DriverException {
1166
//                        int i=0;
1167
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1168
//                                InternalField fld = (InternalField) iter.next();
1169
////                                if (fld.getFieldIndex() == i)
1170
////                                        return fld.getFieldDesc().getFieldLength();
1171
//                                if (i == fieldId)
1172
//                                        return fld.getFieldDesc().getFieldLength();
1173
//                                i++;
1174
//
1175
//                        }
1176
//
1177
//                        return ods.getFieldWidth(i);
1178
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1179
                        return aux.getFieldLength();
1180

    
1181
                }
1182

    
1183
                public void reload() throws IOException, DriverException {
1184
                        ods.reload();
1185

    
1186
                }
1187
        }
1188

    
1189
        public CommandRecord getCommandRecord() {
1190
                return cr;
1191
        }
1192

    
1193
        protected void fireAfterRemoveRow(int index, int sourceType) {
1194
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1195
                                EditionEvent.CHANGE_TYPE_DELETE, sourceType);
1196
                if (complex){
1197
                        rowEvents.add(event);
1198
                        return;
1199
                }
1200
                for (int i = 0; i < editionListeners.size(); i++) {
1201
                        IEditionListener listener = (IEditionListener) editionListeners
1202
                                        .get(i);
1203
                        listener.afterRowEditEvent(null, event);
1204
                }
1205

    
1206
        }
1207

    
1208
        protected boolean fireBeforeRemoveRow(int index, int sourceType) {
1209
                Cancel cancel = new Cancel();
1210
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1211
                                EditionEvent.CHANGE_TYPE_DELETE, cancel, sourceType);
1212
                for (int i = 0; i < editionListeners.size(); i++) {
1213
                        IEditionListener listener = (IEditionListener) editionListeners
1214
                                        .get(i);
1215
                        listener.beforeRowEditEvent(null, event);
1216
                        if (cancel.isCanceled())
1217
                                return true;
1218
                }
1219
                return false;
1220
        }
1221

    
1222
        protected void fireAfterRowAdded(IRow feat,int calculatedIndex, int sourceType) {
1223
                AfterRowEditEvent event = new AfterRowEditEvent(this, calculatedIndex,
1224
                                EditionEvent.CHANGE_TYPE_ADD, sourceType);
1225
                if (complex){
1226
                        rowEvents.add(event);
1227
                        return;
1228
                }
1229
                for (int i = 0; i < editionListeners.size(); i++) {
1230
                        IEditionListener listener = (IEditionListener) editionListeners
1231
                                        .get(i);
1232
                        listener.afterRowEditEvent(feat, event);
1233
                }
1234
        }
1235

    
1236
        protected void fireAfterFieldAdded(FieldDescription field) {
1237
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1238
                                EditionEvent.CHANGE_TYPE_ADD);
1239
                if (complex) {
1240
                        fieldEvents.add(event);
1241
                        return;
1242
                }
1243
                for (int i = 0; i < editionListeners.size(); i++) {
1244
                        IEditionListener listener = (IEditionListener) editionListeners
1245
                                        .get(i);
1246
                        listener.afterFieldEditEvent(event);
1247

    
1248
                }
1249
        }
1250

    
1251
        protected void fireAfterFieldRemoved(FieldDescription field) {
1252
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1253
                                EditionEvent.CHANGE_TYPE_DELETE);
1254
                if (complex) {
1255
                        fieldEvents.add(event);
1256
                        return;
1257
                }
1258
                for (int i = 0; i < editionListeners.size(); i++) {
1259
                        IEditionListener listener = (IEditionListener) editionListeners
1260
                                        .get(i);
1261
                        listener.afterFieldEditEvent(event);
1262
                }
1263
        }
1264

    
1265
        protected void fireAfterFieldModified(FieldDescription field) {
1266
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1267
                                EditionEvent.CHANGE_TYPE_MODIFY);
1268
                if (complex) {
1269
                        fieldEvents.add(event);
1270
                        return;
1271
                }
1272
                for (int i = 0; i < editionListeners.size(); i++) {
1273
                        IEditionListener listener = (IEditionListener) editionListeners
1274
                                        .get(i);
1275
                        listener.afterFieldEditEvent(event);
1276
                }
1277
        }
1278

    
1279

    
1280
        protected boolean fireBeforeRowAdded(int sourceType)
1281
                        throws DriverIOException, IOException {
1282
                Cancel cancel = new Cancel();
1283
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, getRowCount(),
1284
                                EditionEvent.CHANGE_TYPE_ADD, cancel, sourceType);
1285
                for (int i = 0; i < editionListeners.size(); i++) {
1286
                        IEditionListener listener = (IEditionListener) editionListeners
1287
                                        .get(i);
1288
                        listener.beforeRowEditEvent(null, event);
1289
                        if (cancel.isCanceled())
1290
                                return true;
1291
                }
1292
                return false;
1293
        }
1294

    
1295
        protected boolean fireBeforeFieldAdded(FieldDescription field)
1296
        throws EditionException {
1297
                Cancel cancel = new Cancel();
1298
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1299
                EditionEvent.CHANGE_TYPE_ADD, cancel);
1300
                for (int i = 0; i < editionListeners.size(); i++) {
1301
                        IEditionListener listener = (IEditionListener) editionListeners
1302
                        .get(i);
1303
                        listener.beforeFieldEditEvent(event);
1304
                        if (cancel.isCanceled())
1305
                                return true;
1306
                }
1307
                return false;
1308
        }
1309

    
1310
        protected boolean fireBeforeRemoveField(FieldDescription field)
1311
        throws EditionException {
1312
                Cancel cancel = new Cancel();
1313
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1314
                EditionEvent.CHANGE_TYPE_DELETE, cancel);
1315
                for (int i = 0; i < editionListeners.size(); i++) {
1316
                        IEditionListener listener = (IEditionListener) editionListeners
1317
                        .get(i);
1318
                        listener.beforeFieldEditEvent(event);
1319
                        if (cancel.isCanceled())
1320
                                return true;
1321
                }
1322
                return false;
1323
        }
1324

    
1325

    
1326
        protected boolean fireBeforeModifyRow(IRow feat, int index, int sourceType) {
1327
                Cancel cancel = new Cancel();
1328
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1329
                                EditionEvent.CHANGE_TYPE_MODIFY, cancel, sourceType);
1330
                for (int i = 0; i < editionListeners.size(); i++) {
1331
                        IEditionListener listener = (IEditionListener) editionListeners
1332
                                        .get(i);
1333
                        listener.beforeRowEditEvent(feat, event);
1334
                        if (cancel.isCanceled())
1335
                                return true;
1336
                }
1337
                return false;
1338
        }
1339

    
1340
        protected void fireAfterModifyRow(int index, int sourceType) {
1341
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1342
                                EditionEvent.CHANGE_TYPE_MODIFY, sourceType);
1343
                if (complex){
1344
                        rowEvents.add(event);
1345
                        return;
1346
                }
1347
                for (int i = 0; i < editionListeners.size(); i++) {
1348
                        IEditionListener listener = (IEditionListener) editionListeners
1349
                                        .get(i);
1350
                        listener.afterRowEditEvent(null, event);
1351
                }
1352

    
1353
        }
1354

    
1355
        protected void fireStartEditionEvent(int sourceType) {
1356
                EditionEvent ev = new EditionEvent(this, EditionEvent.START_EDITION,
1357
                                sourceType);
1358
                for (int i = 0; i < editionListeners.size(); i++) {
1359
                        IEditionListener listener = (IEditionListener) editionListeners
1360
                                        .get(i);
1361
                        listener.processEvent(ev);
1362
                }
1363

    
1364
        }
1365

    
1366
        protected void fireStopEditionEvent(int sourceType) {
1367
                EditionEvent ev = new EditionEvent(this, EditionEvent.STOP_EDITION,
1368
                                sourceType);
1369
                for (int i = 0; i < editionListeners.size(); i++) {
1370
                        IEditionListener listener = (IEditionListener) editionListeners
1371
                                        .get(i);
1372
                        listener.processEvent(ev);
1373
                }
1374

    
1375
        }
1376

    
1377
        protected void fireCancelEditionEvent(int sourceType) {
1378
                EditionEvent ev = new EditionEvent(this, EditionEvent.CANCEL_EDITION,
1379
                                sourceType);
1380
                for (int i = 0; i < editionListeners.size(); i++) {
1381
                        IEditionListener listener = (IEditionListener) editionListeners
1382
                                        .get(i);
1383
                        listener.processEvent(ev);
1384
                }
1385

    
1386
        }
1387

    
1388
        public void addEditionListener(IEditionListener listener) {
1389
                if (!editionListeners.contains(listener))
1390
                        editionListeners.add(listener);
1391
        }
1392

    
1393
        public void removeEditionListener(IEditionListener listener) {
1394
                editionListeners.remove(listener);
1395
        }
1396

    
1397
        public IWriter getWriter() {
1398
                return writer;
1399
        }
1400

    
1401
        protected void setWriter(IWriter writer) {
1402
                this.writer = writer;
1403

    
1404
        }
1405
        /*
1406
         * azabala: esto funciona para todos los drivers gdbms
1407
         * salvo para MySQL, que necesita que el ITableDefinition
1408
         * contenga el nombre de la tabla (y por tanto requiere
1409
         * DBLayerDefinition-en realidad hace falta DBTableDefinition)
1410
         * TODO REVISAR LA ARQUITECTURA DE ESTO
1411
         *
1412
         * */
1413
        public ITableDefinition getTableDefinition() throws DriverLoadException,
1414
                        DriverException {
1415
                Driver originalDriver = getOriginalDriver();
1416
//                if(! (originalDriver instanceof AlphanumericDBDriver)){
1417
                        TableDefinition tableDef = new TableDefinition();
1418
                        tableDef.setFieldsDesc(getRecordset().getFieldsDescription());
1419
                        tableDef.setName(getRecordset().getSourceInfo().name);
1420
                        return tableDef;
1421
//                }else{
1422
//                        AlphanumericDBDriver dbDriver = (AlphanumericDBDriver)originalDriver;
1423
//                        return dbDriver.getTableDefinition();
1424
//
1425
//                }
1426

    
1427

    
1428
        }
1429

    
1430
        public void validateRow(IRow row,int sourceType) throws EditionException {
1431
                for (int i = 0; i < rules.size(); i++) {
1432
                        IRule rule = (IRule) rules.get(i);
1433
                        boolean bAux = rule.validate(row,sourceType);
1434
                        if (bAux == false) {
1435
                                EditionException ex = new EditionException(
1436
                                                "NOT follow the rule: " + rule.getDescription());
1437
                                // TODO: Lanzar una RuleException con datos como el registro
1438
                                // que no cumple, la regla que no lo ha cumplido, etc.
1439
                                throw ex;
1440
                        }
1441
                }
1442
        }
1443

    
1444
        public ArrayList getRules() {
1445
                return rules;
1446
        }
1447

    
1448
        public void setRules(ArrayList rules) {
1449
                this.rules = rules;
1450
        }
1451

    
1452
        private void clean() throws IOException, DriverException {
1453
                expansionFile.close();
1454
                relations.clear();
1455
                numAdd = 0;
1456
                delRows.clear();
1457
                // TODO: Es muy probable que necesitemos un reload de los datasources, al
1458
                // igual que lo tenemos en las capas. Por ahora, basta con retocar
1459
                // listInternalFields, pero casi seguro que lo correcto ser?a hacer un
1460
                // reload completo.
1461
                initalizeFields(ods);
1462

    
1463
//                listInternalFields.clear();
1464
//                listInternalFields.add(actualFields);
1465
        }
1466

    
1467
        /*
1468
         * (non-Javadoc)
1469
         *
1470
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getFieldManager()
1471
         */
1472
        public IFieldManager getFieldManager() {
1473
                if (ods.getDriver() instanceof IWriteable)
1474
                {
1475
                        IWriter writer = ((IWriteable)ods.getDriver()).getWriter();
1476
                        if ((writer != null) && (writer instanceof IFieldManager))
1477
                        {
1478
                                IFieldManager fldManager = (IFieldManager) writer;
1479
                                return fldManager;
1480
                        }
1481
                }
1482
                return null;
1483
        }
1484

    
1485
        /**
1486
         * Tiene en cuenta los campos actuales para formatear una row con ellos. Le
1487
         * pasamos los campos que hab?a en el momento en que se cre? esa row.
1488
         *
1489
         * @param edRow
1490
         * @param indexInternalFields
1491
         * @return
1492
         */
1493
        public IRowEdited createExternalRow(IRowEdited edRow,
1494
                        int indexInternalFields) {
1495

    
1496
                // para acelerar
1497
                if (bFieldsHasBeenChanged == false)
1498
                        return edRow;
1499

    
1500
                Value[] att = edRow.getAttributes();
1501
                TreeMap ancientFields = (TreeMap) listInternalFields
1502
                                .get(indexInternalFields);
1503
                Value[] newAtt = new Value[actualFields.size()];
1504
                Collection aux = actualFields.values();
1505
                Iterator it = aux.iterator();
1506
                int i = 0;
1507
                Value val = null;
1508
                while (it.hasNext()) {
1509
                        // Para cada campo de los actuales, miramos si ya estaba cuando
1510
                        // el registro estaba guardado.
1511
                        // Si estaba, cogemos el valor de ese campo en el registro
1512
                        // guardado. Si no estaba, ha sido a?adido despu?s y ponemos
1513
                        // su valor por defecto.
1514
                        // Nota importante: fieldIndex es el ?ndice del campo cuando
1515
                        // se guard?. NO es el ?ndice actual dentro de actualFields.
1516
                        // Se usa SOLO para recuperar el valor de los atributos
1517
                        // antiguos. Por eso no nos preocupamos de mantener actuallizados
1518
                        // el resto de campos cuando se borra o a?ade un nuevo campo.
1519
                        InternalField fld = (InternalField) it.next();
1520
                        // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
1521
                        if (ancientFields.containsKey(fld.getFieldId())) {
1522
                                InternalField ancientField = (InternalField) ancientFields
1523
                                                .get(fld.getFieldId());
1524
                                val = att[ancientField.getFieldIndex()];
1525
                                // val = att[ancientField.getFieldId().intValue()];
1526
                                // System.out.println("fld: " + fld.getFieldDesc().getFieldAlias() + " ancient:" + " val" + val);
1527
                        } else
1528
                                val = fld.getFieldDesc().getDefaultValue();
1529
                        newAtt[i++] = val;
1530
                }
1531
                IRowEdited newRow = (IRowEdited) edRow.cloneRow();
1532
                newRow.setAttributes(newAtt);
1533
                return newRow;
1534
        }
1535

    
1536
        public void removeField(String fieldName) throws EditionException {
1537

    
1538
                InternalField fld = findFieldByName(fieldName);
1539
                if (fld == null)
1540
                        throw new EditionException("Field " + fieldName + " not found when removing field");
1541
                Command command = new RemoveFieldCommand(this, fld);
1542
                if (complex) {
1543
                        commands.add(command);
1544
                } else {
1545
                        cr.pushCommand(command);
1546
                }
1547
                doRemoveField(fld);
1548

    
1549
        }
1550

    
1551
        private InternalField findFieldByName(String fieldName) {
1552
                Collection aux = actualFields.values();
1553
                Iterator it = aux.iterator();
1554
                while (it.hasNext()) {
1555
                        InternalField fld = (InternalField) it.next();
1556
                        if (fld.getFieldDesc().getFieldAlias().compareToIgnoreCase(fieldName) == 0)
1557
                                return fld;
1558
                }
1559

    
1560
                return null;
1561
        }
1562

    
1563
        public void undoRemoveField(InternalField field) throws EditionException {
1564
                // field.setDeleted(false);
1565
//                field.setFieldIndex(actualFields.size());
1566
                actualFields.put(field.getFieldId(), field);
1567
                fieldsChanged();
1568
                fireAfterFieldAdded(field.getFieldDesc());
1569
        }
1570

    
1571
        public void doRemoveField(InternalField field) throws EditionException {
1572
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1573
                if (cancel) return;
1574
                actualFields.remove(field.getFieldId());
1575
                fieldsChanged();
1576
                fireAfterFieldRemoved(field.getFieldDesc());
1577
        }
1578

    
1579
        public void renameField(String antName, String newName) throws EditionException {
1580

    
1581
                InternalField fld = findFieldByName(antName);
1582
                Command command = new RenameFieldCommand(this, fld, newName);
1583
                if (complex) {
1584
                        commands.add(command);
1585
                } else {
1586
                        cr.pushCommand(command);
1587
                }
1588
                doRenameField(fld, newName);
1589

    
1590
        }
1591

    
1592
        public void undoRenameField(InternalField field, String antName) throws EditionException  {
1593
                field.getFieldDesc().setFieldAlias(antName);
1594
                fieldsChanged();
1595
                fireAfterFieldModified(field.getFieldDesc());
1596

    
1597
        }
1598

    
1599
        public void doRenameField(InternalField field, String newName) throws EditionException  {
1600
                field.getFieldDesc().setFieldAlias(newName);
1601
                fieldsChanged();
1602
                fireAfterFieldModified(field.getFieldDesc());
1603

    
1604
        }
1605

    
1606

    
1607
        public void addField(FieldDescription field) throws EditionException {
1608

    
1609
                InternalField fld = new InternalField(field, InternalField.ADDED, new Integer(listFields.size()));
1610
                Command command = new AddFieldCommand(this, fld);
1611
                if (complex) {
1612
                        commands.add(command);
1613
                } else {
1614
                        cr.pushCommand(command);
1615
                }
1616
                listFields.add(fld);
1617
                doAddField(fld);
1618

    
1619
        }
1620

    
1621
        public void undoAddField(InternalField field) throws EditionException {
1622
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1623
                if (cancel)
1624
                        return;
1625

    
1626
                // field.setDeleted(true);
1627
                actualFields.remove(field.getFieldId());
1628
                fieldsChanged();
1629
                fireAfterFieldRemoved(field.getFieldDesc());
1630

    
1631
        }
1632

    
1633
        public int doAddField(InternalField field) throws EditionException {
1634
                boolean cancel;
1635
                cancel = fireBeforeFieldAdded(field.getFieldDesc());
1636
                if (cancel)
1637
                        return -1;
1638

    
1639
                // field.setDeleted(false);
1640
//                field.setFieldIndex(actualFields.size());
1641
                actualFields.put(field.getFieldId(), field);
1642
                fieldsChanged();
1643
                fireAfterFieldAdded(field.getFieldDesc());
1644
//                return field.getFieldIndex();
1645
                return field.getFieldId().intValue();
1646
        }
1647

    
1648
        public Driver getOriginalDriver()
1649
        {
1650
                return ods.getDriver();
1651
        }
1652

    
1653
        /**
1654
         * Use it to be sure the recordset will have the right fields. It forces a new SelectableDataSource
1655
         * to be created next time it is needed
1656
         */
1657
        public void cleanSelectableDatasource() {
1658
                ds = null;
1659
        }
1660

    
1661
        public FieldDescription[] getFieldsDescription() {
1662
                return (FieldDescription[]) fastAccessFields.toArray(new FieldDescription[0]);
1663
        }
1664

    
1665

    
1666
//        private InternalField getInternalFieldByIndex(int fieldId)
1667
//        {
1668
//                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1669
//                        InternalField fld = (InternalField) iter.next();
1670
//                        if (fld.getFieldIndex() == fieldId)
1671
//                                return fld;
1672
//                }
1673
//                return null;
1674
//        }
1675

    
1676
}