Statistics
| Revision:

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

History | View | Annotate | Download (47.7 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
                                        ds = new SelectableDataSource(LayerFactory
872
                                                        .getDataSourceFactory().createRandomDataSource(
873
                                                                        name, DataSourceFactory.MANUAL_OPENING));
874
                                        ds.start();
875
                                        ds.setSelectionSupport(ods.getSelectionSupport());
876

    
877
                                } catch (NoSuchTableException e) {
878
                                        throw new RuntimeException(e);
879
                                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
880
                                        throw new RuntimeException(e);
881
                                }
882
                        }
883

    
884
                        return ds;
885
                } else {
886
                        return ods;
887
                }
888
        }
889

    
890
        /**
891
         * Return always the original recordset (even when is editing,
892
         * nor the getRecorset() method)
893
         *
894
         * */
895
        public SelectableDataSource getOriginalRecordset(){
896
                return ods;
897
        }
898

    
899

    
900
        /**
901
         * DOCUMENT ME!
902
         *
903
         * @return
904
         */
905
        public FBitSet getSelection() {
906
                /*
907
                 * try { return getRecordset().getSelection(); } catch
908
                 * (DriverLoadException e) { // TODO Auto-generated catch block
909
                 * e.printStackTrace(); } return null;
910
                 */
911
                return getRecordset().getSelection();
912
        }
913

    
914
        public void setSelection(FBitSet selection) {
915
                /*
916
                 * try { getRecordset().setSelection(selection); } catch
917
                 * (DriverLoadException e) { // TODO Auto-generated catch block
918
                 * e.printStackTrace(); }
919
                 */
920
                getRecordset().setSelection(selection);
921
        }
922

    
923
        /**
924
         * DOCUMENT ME!
925
         *
926
         * @return DOCUMENT ME!
927
         */
928
        public boolean isEditing() {
929
                return isEditing;
930
        }
931

    
932
        public int getInversedIndex(long rowIndex) {
933
                int intervalNotDeleted = 0;
934
                int antDeleted = -1;
935
                int idPedido = (int) rowIndex;
936
                int numNotDeleted = 0;
937
                int numBorradosAnt = 0;
938

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

    
956
        /**
957
         * DOCUMENT ME!
958
         *
959
         * @param rowIndex
960
         *            DOCUMENT ME!
961
         *
962
         * @return DOCUMENT ME!
963
         */
964
        public int getCalculatedIndex(long rowIndex) {
965
                int numNotDeleted = 0;
966
                int intervalNotDeleted = 0;
967
                int antDeleted = -1;
968
                int calculatedIndex;
969
                int idPedido = (int) rowIndex;
970
                int numBorradosAnt = 0;
971

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

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

    
1009
                /*
1010
                 * (non-Javadoc)
1011
                 *
1012
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
1013
                 */
1014
                public void write(DataWare dataWare) throws DriverException {
1015
                        DataWare dataWareOrig = ods
1016
                                        .getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
1017
                        dataWareOrig.commitTrans();
1018
                }
1019

    
1020
                /*
1021
                 * (non-Javadoc)
1022
                 *
1023
                 * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
1024
                 */
1025
                public void setDataSourceFactory(DataSourceFactory dsf) {
1026
                        ods.setDataSourceFactory(dsf);
1027
                }
1028

    
1029
                /*
1030
                 * (non-Javadoc)
1031
                 *
1032
                 * @see com.hardcode.driverManager.Driver#getName()
1033
                 */
1034
                public String getName() {
1035
                        return ods.getName();
1036
                }
1037

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

    
1049

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

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

    
1091
                /*
1092
                 * (non-Javadoc)
1093
                 *
1094
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
1095
                 */
1096
                public int getFieldCount() throws DriverException {
1097
                        return fastAccessFields.size();
1098
                }
1099

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

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

    
1136
                        return 0;
1137
                }
1138

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

    
1156
//                        return ods.getFieldType(i);
1157
                }
1158

    
1159
                public int getFieldWidth(int fieldId) throws DriverException {
1160
//                        int i=0;
1161
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1162
//                                InternalField fld = (InternalField) iter.next();
1163
////                                if (fld.getFieldIndex() == i)
1164
////                                        return fld.getFieldDesc().getFieldLength();
1165
//                                if (i == fieldId)
1166
//                                        return fld.getFieldDesc().getFieldLength();
1167
//                                i++;
1168
//
1169
//                        }
1170
//
1171
//                        return ods.getFieldWidth(i);
1172
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1173
                        return aux.getFieldLength();
1174

    
1175
                }
1176

    
1177
                public void reload() throws IOException, DriverException {
1178
                        ods.reload();
1179

    
1180
                }
1181
        }
1182

    
1183
        public CommandRecord getCommandRecord() {
1184
                return cr;
1185
        }
1186

    
1187
        protected void fireAfterRemoveRow(int index, int sourceType) {
1188
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1189
                                EditionEvent.CHANGE_TYPE_DELETE, sourceType);
1190
                if (complex){
1191
                        rowEvents.add(event);
1192
                        return;
1193
                }
1194
                for (int i = 0; i < editionListeners.size(); i++) {
1195
                        IEditionListener listener = (IEditionListener) editionListeners
1196
                                        .get(i);
1197
                        listener.afterRowEditEvent(null, event);
1198
                }
1199

    
1200
        }
1201

    
1202
        protected boolean fireBeforeRemoveRow(int index, int sourceType) {
1203
                Cancel cancel = new Cancel();
1204
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1205
                                EditionEvent.CHANGE_TYPE_DELETE, cancel, sourceType);
1206
                for (int i = 0; i < editionListeners.size(); i++) {
1207
                        IEditionListener listener = (IEditionListener) editionListeners
1208
                                        .get(i);
1209
                        listener.beforeRowEditEvent(null, event);
1210
                        if (cancel.isCanceled())
1211
                                return true;
1212
                }
1213
                return false;
1214
        }
1215

    
1216
        protected void fireAfterRowAdded(IRow feat,int calculatedIndex, int sourceType) {
1217
                AfterRowEditEvent event = new AfterRowEditEvent(this, calculatedIndex,
1218
                                EditionEvent.CHANGE_TYPE_ADD, sourceType);
1219
                if (complex){
1220
                        rowEvents.add(event);
1221
                        return;
1222
                }
1223
                for (int i = 0; i < editionListeners.size(); i++) {
1224
                        IEditionListener listener = (IEditionListener) editionListeners
1225
                                        .get(i);
1226
                        listener.afterRowEditEvent(feat, event);
1227
                }
1228
        }
1229

    
1230
        protected void fireAfterFieldAdded(FieldDescription field) {
1231
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1232
                                EditionEvent.CHANGE_TYPE_ADD);
1233
                if (complex) {
1234
                        fieldEvents.add(event);
1235
                        return;
1236
                }
1237
                for (int i = 0; i < editionListeners.size(); i++) {
1238
                        IEditionListener listener = (IEditionListener) editionListeners
1239
                                        .get(i);
1240
                        listener.afterFieldEditEvent(event);
1241

    
1242
                }
1243
        }
1244

    
1245
        protected void fireAfterFieldRemoved(FieldDescription field) {
1246
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1247
                                EditionEvent.CHANGE_TYPE_DELETE);
1248
                if (complex) {
1249
                        fieldEvents.add(event);
1250
                        return;
1251
                }
1252
                for (int i = 0; i < editionListeners.size(); i++) {
1253
                        IEditionListener listener = (IEditionListener) editionListeners
1254
                                        .get(i);
1255
                        listener.afterFieldEditEvent(event);
1256
                }
1257
        }
1258

    
1259
        protected void fireAfterFieldModified(FieldDescription field) {
1260
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1261
                                EditionEvent.CHANGE_TYPE_MODIFY);
1262
                if (complex) {
1263
                        fieldEvents.add(event);
1264
                        return;
1265
                }
1266
                for (int i = 0; i < editionListeners.size(); i++) {
1267
                        IEditionListener listener = (IEditionListener) editionListeners
1268
                                        .get(i);
1269
                        listener.afterFieldEditEvent(event);
1270
                }
1271
        }
1272

    
1273

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

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

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

    
1319

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

    
1334
        protected void fireAfterModifyRow(int index, int sourceType) {
1335
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1336
                                EditionEvent.CHANGE_TYPE_MODIFY, sourceType);
1337
                if (complex){
1338
                        rowEvents.add(event);
1339
                        return;
1340
                }
1341
                for (int i = 0; i < editionListeners.size(); i++) {
1342
                        IEditionListener listener = (IEditionListener) editionListeners
1343
                                        .get(i);
1344
                        listener.afterRowEditEvent(null, event);
1345
                }
1346

    
1347
        }
1348

    
1349
        protected void fireStartEditionEvent(int sourceType) {
1350
                EditionEvent ev = new EditionEvent(this, EditionEvent.START_EDITION,
1351
                                sourceType);
1352
                for (int i = 0; i < editionListeners.size(); i++) {
1353
                        IEditionListener listener = (IEditionListener) editionListeners
1354
                                        .get(i);
1355
                        listener.processEvent(ev);
1356
                }
1357

    
1358
        }
1359

    
1360
        protected void fireStopEditionEvent(int sourceType) {
1361
                EditionEvent ev = new EditionEvent(this, EditionEvent.STOP_EDITION,
1362
                                sourceType);
1363
                for (int i = 0; i < editionListeners.size(); i++) {
1364
                        IEditionListener listener = (IEditionListener) editionListeners
1365
                                        .get(i);
1366
                        listener.processEvent(ev);
1367
                }
1368

    
1369
        }
1370

    
1371
        protected void fireCancelEditionEvent(int sourceType) {
1372
                EditionEvent ev = new EditionEvent(this, EditionEvent.CANCEL_EDITION,
1373
                                sourceType);
1374
                for (int i = 0; i < editionListeners.size(); i++) {
1375
                        IEditionListener listener = (IEditionListener) editionListeners
1376
                                        .get(i);
1377
                        listener.processEvent(ev);
1378
                }
1379

    
1380
        }
1381

    
1382
        public void addEditionListener(IEditionListener listener) {
1383
                if (!editionListeners.contains(listener))
1384
                        editionListeners.add(listener);
1385
        }
1386

    
1387
        public void removeEditionListener(IEditionListener listener) {
1388
                editionListeners.remove(listener);
1389
        }
1390

    
1391
        public IWriter getWriter() {
1392
                return writer;
1393
        }
1394

    
1395
        protected void setWriter(IWriter writer) {
1396
                this.writer = writer;
1397

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

    
1421

    
1422
        }
1423

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

    
1438
        public ArrayList getRules() {
1439
                return rules;
1440
        }
1441

    
1442
        public void setRules(ArrayList rules) {
1443
                this.rules = rules;
1444
        }
1445

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

    
1457
//                listInternalFields.clear();
1458
//                listInternalFields.add(actualFields);
1459
        }
1460

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

    
1479
        /**
1480
         * Tiene en cuenta los campos actuales para formatear una row con ellos. Le
1481
         * pasamos los campos que hab?a en el momento en que se cre? esa row.
1482
         *
1483
         * @param edRow
1484
         * @param indexInternalFields
1485
         * @return
1486
         */
1487
        public IRowEdited createExternalRow(IRowEdited edRow,
1488
                        int indexInternalFields) {
1489

    
1490
                // para acelerar
1491
                if (bFieldsHasBeenChanged == false)
1492
                        return edRow;
1493

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

    
1530
        public void removeField(String fieldName) throws EditionException {
1531

    
1532
                InternalField fld = findFieldByName(fieldName);
1533
                if (fld == null)
1534
                        throw new EditionException("Field " + fieldName + " not found when removing field");
1535
                Command command = new RemoveFieldCommand(this, fld);
1536
                if (complex) {
1537
                        commands.add(command);
1538
                } else {
1539
                        cr.pushCommand(command);
1540
                }
1541
                doRemoveField(fld);
1542

    
1543
        }
1544

    
1545
        private InternalField findFieldByName(String fieldName) {
1546
                Collection aux = actualFields.values();
1547
                Iterator it = aux.iterator();
1548
                while (it.hasNext()) {
1549
                        InternalField fld = (InternalField) it.next();
1550
                        if (fld.getFieldDesc().getFieldAlias().compareToIgnoreCase(fieldName) == 0)
1551
                                return fld;
1552
                }
1553

    
1554
                return null;
1555
        }
1556

    
1557
        public void undoRemoveField(InternalField field) throws EditionException {
1558
                // field.setDeleted(false);
1559
//                field.setFieldIndex(actualFields.size());
1560
                actualFields.put(field.getFieldId(), field);
1561
                fieldsChanged();
1562
                fireAfterFieldAdded(field.getFieldDesc());
1563
        }
1564

    
1565
        public void doRemoveField(InternalField field) throws EditionException {
1566
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1567
                if (cancel) return;
1568
                actualFields.remove(field.getFieldId());
1569
                fieldsChanged();
1570
                fireAfterFieldRemoved(field.getFieldDesc());
1571
        }
1572

    
1573
        public void renameField(String antName, String newName) throws EditionException {
1574

    
1575
                InternalField fld = findFieldByName(antName);
1576
                Command command = new RenameFieldCommand(this, fld, newName);
1577
                if (complex) {
1578
                        commands.add(command);
1579
                } else {
1580
                        cr.pushCommand(command);
1581
                }
1582
                doRenameField(fld, newName);
1583

    
1584
        }
1585

    
1586
        public void undoRenameField(InternalField field, String antName) throws EditionException  {
1587
                field.getFieldDesc().setFieldAlias(antName);
1588
                fieldsChanged();
1589
                fireAfterFieldModified(field.getFieldDesc());
1590

    
1591
        }
1592

    
1593
        public void doRenameField(InternalField field, String newName) throws EditionException  {
1594
                field.getFieldDesc().setFieldAlias(newName);
1595
                fieldsChanged();
1596
                fireAfterFieldModified(field.getFieldDesc());
1597

    
1598
        }
1599

    
1600

    
1601
        public void addField(FieldDescription field) throws EditionException {
1602

    
1603
                InternalField fld = new InternalField(field, InternalField.ADDED, new Integer(listFields.size()));
1604
                Command command = new AddFieldCommand(this, fld);
1605
                if (complex) {
1606
                        commands.add(command);
1607
                } else {
1608
                        cr.pushCommand(command);
1609
                }
1610
                listFields.add(fld);
1611
                doAddField(fld);
1612

    
1613
        }
1614

    
1615
        public void undoAddField(InternalField field) throws EditionException {
1616
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1617
                if (cancel)
1618
                        return;
1619

    
1620
                // field.setDeleted(true);
1621
                actualFields.remove(field.getFieldId());
1622
                fieldsChanged();
1623
                fireAfterFieldRemoved(field.getFieldDesc());
1624

    
1625
        }
1626

    
1627
        public int doAddField(InternalField field) throws EditionException {
1628
                boolean cancel;
1629
                cancel = fireBeforeFieldAdded(field.getFieldDesc());
1630
                if (cancel)
1631
                        return -1;
1632

    
1633
                // field.setDeleted(false);
1634
//                field.setFieldIndex(actualFields.size());
1635
                actualFields.put(field.getFieldId(), field);
1636
                fieldsChanged();
1637
                fireAfterFieldAdded(field.getFieldDesc());
1638
//                return field.getFieldIndex();
1639
                return field.getFieldId().intValue();
1640
        }
1641

    
1642
        public Driver getOriginalDriver()
1643
        {
1644
                return ods.getDriver();
1645
        }
1646

    
1647
        /**
1648
         * Use it to be sure the recordset will have the right fields. It forces a new SelectableDataSource
1649
         * to be created next time it is needed
1650
         */
1651
        public void cleanSelectableDatasource() {
1652
                ds = null;
1653
        }
1654

    
1655
        public FieldDescription[] getFieldsDescription() {
1656
                return (FieldDescription[]) fastAccessFields.toArray(new FieldDescription[0]);
1657
        }
1658

    
1659

    
1660
//        private InternalField getInternalFieldByIndex(int fieldId)
1661
//        {
1662
//                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1663
//                        InternalField fld = (InternalField) iter.next();
1664
//                        if (fld.getFieldIndex() == fieldId)
1665
//                                return fld;
1666
//                }
1667
//                return null;
1668
//        }
1669

    
1670
}