Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / EditableAdapter.java @ 28367

History | View | Annotate | Download (50.1 KB)

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

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

    
11
import com.hardcode.driverManager.Driver;
12
import com.hardcode.driverManager.DriverLoadException;
13
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
14
import com.hardcode.gdbms.driver.exceptions.ReloadDriverException;
15
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
16
import com.hardcode.gdbms.engine.data.DataSourceFactory;
17
import com.hardcode.gdbms.engine.data.NoSuchTableException;
18
import com.hardcode.gdbms.engine.data.driver.AlphanumericDBDriver;
19
import com.hardcode.gdbms.engine.data.driver.DriverException;
20
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
21
import com.hardcode.gdbms.engine.data.edition.DataWare;
22
import com.hardcode.gdbms.engine.values.Value;
23
import com.iver.cit.gvsig.exceptions.commands.EditionCommandException;
24
import com.iver.cit.gvsig.exceptions.expansionfile.CloseExpansionFileException;
25
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
26
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileWriteException;
27
import com.iver.cit.gvsig.exceptions.layers.CancelEditingLayerException;
28
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
29
import com.iver.cit.gvsig.exceptions.validate.ValidateRowException;
30
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
31
import com.iver.cit.gvsig.exceptions.visitors.StopWriterVisitorException;
32
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
33
import com.iver.cit.gvsig.fmap.core.DefaultRow;
34
import com.iver.cit.gvsig.fmap.core.IRow;
35
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
36
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
37
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
38
import com.iver.cit.gvsig.fmap.drivers.TableDefinition;
39
import com.iver.cit.gvsig.fmap.edition.commands.AddFieldCommand;
40
import com.iver.cit.gvsig.fmap.edition.commands.AddRowCommand;
41
import com.iver.cit.gvsig.fmap.edition.commands.Command;
42
import com.iver.cit.gvsig.fmap.edition.commands.CommandCollection;
43
import com.iver.cit.gvsig.fmap.edition.commands.CommandRecord;
44
import com.iver.cit.gvsig.fmap.edition.commands.MemoryCommandRecord;
45
import com.iver.cit.gvsig.fmap.edition.commands.ModifyRowCommand;
46
import com.iver.cit.gvsig.fmap.edition.commands.RemoveFieldCommand;
47
import com.iver.cit.gvsig.fmap.edition.commands.RemoveRowCommand;
48
import com.iver.cit.gvsig.fmap.edition.commands.RenameFieldCommand;
49
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AbstractFieldManager;
50
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
51
import com.iver.cit.gvsig.fmap.layers.FBitSet;
52
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
53
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
54
import com.iver.cit.gvsig.fmap.operations.Cancel;
55

    
56
/**
57
 * DOCUMENT ME!
58
 *
59
 * @author Vicente Caballero Navarro
60
 */
61
public class EditableAdapter implements IEditableSource, IWriteable {
62
        protected boolean isEditing = false;
63

    
64
        private SelectableDataSource ds = null;
65

    
66
        protected FBitSet delRows = new FBitSet();
67

    
68
        private CommandRecord cr;
69

    
70
        protected IWriter writer;
71

    
72
        /**
73
         * Flag que indica que hay que tomar las siguientes operaciones como una
74
         * operaci?n at?mica
75
         */
76
        private boolean complex = false;
77

    
78
        private CommandCollection commands = null;
79

    
80
        protected ArrayList listFields = new ArrayList();
81

    
82
        protected ArrayList listInternalFields = new ArrayList();
83

    
84
        protected boolean bFieldsHasBeenChanged = false;
85

    
86
        /**
87
         * La clave ser? el fieldId. Para buscar si un value de una row ha de ser
88
         * rellenado con defaultValue o con lo que venga del expansion file,
89
         * miraremos si existe en este hash. Si existe, usamos el value del
90
         * expansion file. Si no existe, usamos el defaultValue del campo busc?ndolo
91
         * en la lista internalFields. Por cierto, en listInternalFields NO se
92
         * borran campos. Solo se van a?adiendo nuevos actualFields.
93
         */
94
        protected TreeMap actualFields; // la clave ser? el fieldId.
95

    
96
        protected ArrayList fastAccessFields = new ArrayList();
97

    
98
        protected class MyFieldManager extends AbstractFieldManager {
99

    
100
                public boolean alterTable() throws WriteDriverException {
101
                        return getFieldManager().alterTable();
102
                }
103

    
104
                public void addField(FieldDescription fieldDesc) {
105
                        super.addField(fieldDesc);
106
                }
107

    
108
                public FieldDescription removeField(String fieldName) {
109
                        // TODO Auto-generated method stub
110
                        return super.removeField(fieldName);
111
                }
112

    
113
                public void renameField(String antName, String newName) {
114
                        // TODO Auto-generated method stub
115
                        super.renameField(antName, newName);
116
                }
117

    
118
        }
119

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

    
135
        /*
136
         * Fichero en el que se guardan las nuevas geometr?as, producto de adiciones
137
         * o de modificaciones
138
         */
139
        protected ExpansionFile expansionFile;
140

    
141
        protected int numAdd = 0;
142

    
143
        private ObjectDriver editingDriver = new myObjectDriver();
144

    
145
        private SelectableDataSource ods;
146

    
147
        private ArrayList editionListeners = new ArrayList();
148

    
149
        private ArrayList rules = new ArrayList();
150

    
151
        protected int actualIndexFields;
152

    
153
        protected boolean isFullExtentDirty = false;
154

    
155
        private ArrayList fieldEvents=new ArrayList();
156
        private ArrayList rowEvents=new ArrayList();
157

    
158
        /**
159
         * Crea un nuevo EditableAdapter.
160
         */
161
        public EditableAdapter() {
162
                expansionFile = new MemoryExpansionFile(this);
163
                cr = new MemoryCommandRecord();
164
        }
165

    
166
        /**
167
         * DOCUMENT ME!
168
         *
169
         * @param ds
170
         *            DOCUMENT ME!
171
         * @throws DriverException
172
         */
173
        public void setOriginalDataSource(SelectableDataSource ds) throws ReadDriverException {
174
                this.ods = ds;
175
                initalizeFields(ds);
176
                Driver drv = ods.getDriver();
177
                if (drv instanceof IWriteable) {
178
                        setWriter(((IWriteable) drv).getWriter());
179
                }
180

    
181

    
182
        }
183

    
184
        /**
185
         * @param ds
186
         * @throws ReadDriverException
187
         * @throws DriverException
188
         */
189
        private void initalizeFields(SelectableDataSource ds) throws ReadDriverException {
190
                FieldDescription[] fields = ds.getFieldsDescription();
191
                listInternalFields.clear();
192
                actualIndexFields = 0;
193
                actualFields = new TreeMap();
194
//                fastAccessFields = new ArrayList();
195
                for (int i=0; i < fields.length; i++)
196
                {
197
                        InternalField field = new InternalField(fields[i], InternalField.ORIGINAL, new Integer(i));
198
                        listFields.add(field);
199
                        // field.setFieldIndex(i);
200
                        actualFields.put(field.getFieldId(), field);
201
//                        fastAccessFields.add(fields[i]);
202
                        System.out.println("INITIALIZEFIELDS: FIELD " + field.getFieldDesc().getFieldAlias());
203
                }
204
                        fieldsChanged();
205
                        bFieldsHasBeenChanged = false;
206
        }
207

    
208
        private TreeMap deepCloneInternalFields(TreeMap col)
209
        {
210
                TreeMap clonedFields = new TreeMap();
211
                for (Iterator iter = col.values().iterator(); iter.hasNext();) {
212
                        InternalField fld = (InternalField) iter.next();
213
                        InternalField clonedField = fld.cloneInternalField();
214
                        clonedFields.put(clonedField.getFieldId(), clonedField);
215
                }
216

    
217
                return clonedFields;
218
        }
219
        private void fieldsChanged() throws ReadDriverException {
220
                fastAccessFields= new ArrayList();
221
                int index = 0;
222
                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
223
                        InternalField fld = (InternalField) iter.next();
224
                        fastAccessFields.add(fld.getFieldDesc());
225
                        fld.setFieldIndex(index++);
226
                }
227

    
228
                listInternalFields.add(deepCloneInternalFields(actualFields));
229
                actualIndexFields = listInternalFields.size()-1;
230
                ds = null;
231
                getRecordset().mapExternalFields();
232
                bFieldsHasBeenChanged = true;
233
        }
234

    
235
        /**
236
         * DOCUMENT ME!
237
         * @throws StartEditionLayerException
238
         * @throws StartWriterVisitorException
239
         *
240
         * @throws EditionException
241
         *             DOCUMENT ME!
242
         */
243
        public void startEdition(int sourceType) throws StartWriterVisitorException {
244
                isEditing = true;
245

    
246
                fireStartEditionEvent(sourceType);
247
        }
248

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

    
271
        public void saveEdits(IWriter writer, int sourceType)
272
                        throws StopWriterVisitorException {
273

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

    
286
                        TreeMap ancientFields = (TreeMap) listInternalFields
287
                                        .get(0);
288
                        Collection aux = ancientFields.values();
289
                        Iterator it = aux.iterator();
290
                        while (it.hasNext()) {
291
                                InternalField fld = (InternalField) it.next();
292
                                // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
293
                                if (actualFields.containsKey(fld.getFieldId())) {
294
                                        // Es un original
295
                                        String f1 = fld.getFieldDesc().getFieldName();
296
                                        String f2 = fld.getFieldDesc().getFieldAlias();
297
                                        if (f1.compareTo(f2) != 0)
298
                                        {
299
                                                getFieldManager().renameField(f1, f2);
300
                                        }
301
                                }
302
                                else
303
                                {        // No est?, hay que borrarlo
304
                                        getFieldManager().removeField(fld.getFieldDesc().getFieldAlias());
305
                                }
306
                        }
307
                        Collection aux2= actualFields.values();
308
                        Iterator it2 = aux2.iterator();
309
                        while (it2.hasNext()) {
310
                                InternalField fld = (InternalField) it2.next();
311
                                // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
312
                                if (!ancientFields.containsKey(fld.getFieldId())) {
313
                                        // Es uno a?adido
314
                                        getFieldManager().addField(fld.getFieldDesc());
315
                                }
316
                        }
317
                        // getFieldManager().alterTable(); // Se llama dentro del preprocess()
318
                }
319
                try {
320
                        writer.preProcess();
321
                        // Procesamos primero los borrados.
322
                        // Cuando se genere un tema nuevo, no se les debe hacer caso
323
                        // a estos registros
324

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

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

    
349
                        }
350

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

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

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

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

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

    
397
                } catch (ReadDriverException e) {
398
                        throw new StopWriterVisitorException(writer.getName(),e);
399
                } catch (StartWriterVisitorException e) {
400
                        throw new StopWriterVisitorException(writer.getName(),e);
401
                } catch (VisitorException e) {
402
                        throw new StopWriterVisitorException(writer.getName(),e);
403
                }
404

    
405
        }
406

    
407
        /**
408
         * DOCUMENT ME!
409
         *
410
         * @throws IOException
411
         *             DOCUMENT ME!
412
         */
413
        public void cancelEdition(int sourceType) throws CancelEditingLayerException {
414
                isEditing = false;
415
                try {
416
                        ds= null;
417
                        clean();
418
                        cr.clearAll();
419
                } catch (ReadDriverException e) {
420
                        throw new CancelEditingLayerException(writer.getName(),e);
421
                }
422
                fireCancelEditionEvent(sourceType);
423
        }
424

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

    
451
                // return expansionFile.getRow(num);
452
                // ExpansionFile ya entrega el registro formateado como debe
453
                IRowEdited rowFromExpansion;
454
                rowFromExpansion = expansionFile.getRow(num);
455
                // ?Habr?a que hacer aqu? setID(index + "")?
456
                edRow = new DefaultRowEdited(rowFromExpansion.getLinkedRow()
457
                                .cloneRow(), rowFromExpansion.getStatus(), index);
458
                return edRow;
459

    
460

    
461

    
462
        }
463

    
464
        /**
465
         * DOCUMENT ME!
466
         *
467
         * @return DOCUMENT ME!
468
         * @throws ReadDriverException
469
         *
470
         * @throws DriverIOException
471
         *             DOCUMENT ME!
472
         * @throws IOException
473
         *             DOCUMENT ME!
474
         */
475
        public int getRowCount() throws ReadDriverException {
476
                        return (int) (ods.getRowCount() + numAdd) - delRows.cardinality();// -
477
                        // expansionFile.getInvalidRows().cardinality();
478
        }
479

    
480
        /*
481
         * (non-Javadoc)
482
         *
483
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#addRow(com.iver.cit.gvsig.fmap.core.IRow,
484
         *      java.lang.String)
485
         */
486
        public int addRow(IRow row, String descrip, int sourceType) throws ValidateRowException, ReadDriverException, ExpansionFileWriteException{
487
                validateRow(row,sourceType);
488

    
489
                int calculatedIndex = doAddRow(row, sourceType);
490
                Command command = new AddRowCommand(this, row, calculatedIndex,
491
                                sourceType);
492
                command.setDescription(descrip);
493
                if (complex) {
494
                        commands.add(command);
495
                } else {
496
                        cr.pushCommand(command);
497
                }
498

    
499
                return calculatedIndex;
500
        }
501

    
502
        /**
503
         * DOCUMENT ME!
504
         * @throws EditionCommandException
505
         *
506
         * @throws DriverIOException
507
         *             DOCUMENT ME!
508
         * @throws IOException
509
         *             DOCUMENT ME!
510
         */
511
        public void undo() throws EditionCommandException{
512
                // seleccion.clear();
513
                if (cr.moreUndoCommands()) {
514
                        cr.undoCommand();
515
                }
516
        }
517

    
518
        /**
519
         * DOCUMENT ME!
520
         * @throws EditionCommandException
521
         *
522
         * @throws DriverIOException
523
         *             DOCUMENT ME!
524
         * @throws IOException
525
         *             DOCUMENT ME!
526
         */
527
        public void redo() throws EditionCommandException {
528
                // seleccion.clear();
529
                if (cr.moreRedoCommands()) {
530
                        cr.redoCommand();
531
                }
532
        }
533

    
534
        /*
535
         * (non-Javadoc)
536
         *
537
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#removeRow(int)
538
         */
539
        public void removeRow(int index, String descrip, int sourceType) throws ReadDriverException, ExpansionFileReadException {
540

    
541
                int calculatedIndex = getCalculatedIndex(index);
542
                Command command = new RemoveRowCommand(this, calculatedIndex,
543
                                sourceType);
544
                command.setDescription(descrip);
545
                if (complex) {
546
                        commands.add(command);
547
                } else {
548
                        cr.pushCommand(command);
549
                }
550
                doRemoveRow(calculatedIndex, sourceType);
551

    
552
        }
553

    
554
        /*
555
         * (non-Javadoc)
556
         *
557
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#modifyRow(int,
558
         *      com.iver.cit.gvsig.fmap.core.IRow)
559
         */
560
        public int modifyRow(int index, IRow row, String descrip, int sourceType) throws ValidateRowException, ExpansionFileWriteException, ReadDriverException, ExpansionFileReadException {
561
                validateRow(row,sourceType);
562
                int calculatedIndex = getCalculatedIndex(index);
563
                int pos = doModifyRow(calculatedIndex, row, sourceType);
564
                Command command = new ModifyRowCommand(this, calculatedIndex, pos, row,
565
                                sourceType);
566
                command.setDescription(descrip);
567
                if (complex) {
568
                        commands.add(command);
569
                } else {
570
                        cr.pushCommand(command);
571
                }
572

    
573
                return pos;
574
        }
575

    
576
        /**
577
         * DOCUMENT ME!
578
         */
579
        public void compact() {
580
                expansionFile.compact(relations);
581
        }
582

    
583
        /**
584
         * DOCUMENT ME!
585
         */
586
        public void startComplexRow() {
587
                complex = true;
588
                commands = new CommandCollection();
589
        }
590

    
591
        /**
592
         * DOCUMENT ME!
593
         *
594
         * @throws IOException
595
         *             DOCUMENT ME!
596
         * @throws DriverIOException
597
         *             DOCUMENT ME!
598
         */
599
        public void endComplexRow(String description) {
600
                commands.setDescription(description);
601
                cr.pushCommand(commands);
602
                complex = false;
603
                for (int j = 0; j < editionListeners.size(); j++) {
604
                        for (int i = 0; i < fieldEvents.size(); i++) {
605
                                IEditionListener listener = (IEditionListener) editionListeners
606
                                        .get(j);
607
                                listener.afterFieldEditEvent((AfterFieldEditEvent)fieldEvents.get(i));
608
                        }
609
                        for (int i = 0; i < rowEvents.size(); i++) {
610
                                IEditionListener listener = (IEditionListener) editionListeners
611
                                                .get(j);
612
                                listener.afterRowEditEvent(null,(AfterRowEditEvent)rowEvents.get(i));
613
                        }
614
                }
615
                fieldEvents.clear();
616
                rowEvents.clear();
617
        }
618

    
619
        /**
620
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
621
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
622
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
623
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
624
         * expansion file a justo despues de la penultima geometr?a
625
         *
626
         * @param geometryIndex
627
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
628
         * @param previousExpansionFileIndex
629
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
630
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
631
         *            original y por tanto no hay que actualizar el mapa de indices
632
         *            sino eliminar su entrada.
633
         * @throws IOException
634
         * @throws DriverIOException
635
         */
636
        public int undoModifyRow(int geometryIndex,
637
                        int previousExpansionFileIndex, int sourceType) throws EditionCommandException  {
638

    
639
                if (previousExpansionFileIndex == -1) {
640
                        DefaultRowEdited edRow = null;
641
                        try {
642
                                edRow = new DefaultRowEdited(new DefaultRow(ods
643
                                                        .getRow(geometryIndex)),
644
                                                        IRowEdited.STATUS_ORIGINAL, geometryIndex);
645
                        } catch (ReadDriverException e) {
646
                                throw new EditionCommandException(writer.getName(),e);
647
                        }
648
                        boolean cancel=true;
649
                        try {
650
                                cancel = fireBeforeModifyRow(edRow, geometryIndex,
651
                                                sourceType);
652
                        } catch (ReadDriverException e) {
653
                                throw new EditionCommandException(writer.getName(),e);
654
                        }
655
                        if (cancel)
656
                                return -1;
657
                        // Se elimina de las relaciones y del fichero de expansi?n
658
                        relations.remove(new Integer(geometryIndex));
659
                        expansionFile.deleteLastRow();
660
                } else {
661
                        boolean cancel=true;
662
                        try {
663
                                cancel = fireBeforeModifyRow(expansionFile
664
                                                .getRow(previousExpansionFileIndex), geometryIndex,
665
                                                sourceType);
666
                        } catch (ExpansionFileReadException e) {
667
                                throw new EditionCommandException(writer.getName(),e);
668
                        } catch (ReadDriverException e) {
669
                                throw new EditionCommandException(writer.getName(),e);
670
                        }
671
                        if (cancel)
672
                                return -1;
673
                        int numAnt=((Integer)relations.get(new Integer(geometryIndex))).intValue();
674
                        // Se actualiza la relaci?n de ?ndices
675
                        relations.put(new Integer(geometryIndex), new Integer(
676
                                        previousExpansionFileIndex));
677
                        return numAnt;
678
                }
679
                //fireAfterModifyRow(geometryIndex, sourceType);
680
                return -1;
681
        }
682

    
683
        /**
684
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
685
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
686
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
687
         * una futura compactaci?n termine con ella.
688
         *
689
         * @param index
690
         *            ?ndice de la geometr?a.
691
         * @throws ReadDriverException
692
         * @throws ExpansionFileReadException
693
         *
694
         * @throws DriverIOException
695
         * @throws IOException
696
         */
697
        public IRow doRemoveRow(int index, int sourceType) throws ReadDriverException, ExpansionFileReadException{
698
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
699
                if (cancel)
700
                        return null;
701
                // Llega un calculatedIndex
702
                delRows.set(index, true);
703
                System.err.println("Elimina una Row en la posici?n: " + index);
704
                // TODO: Con tablas no es necesario devolver la anterior feature. Por
705
                // ahora.
706
                isFullExtentDirty = true;
707
                fireAfterRemoveRow(index, sourceType);
708
                return null;
709
        }
710

    
711
        /**
712
         ** Si se intenta modificar una geometr?a original de la capa en edici?n se
713
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
714
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
715
         * fichero de expansi?n, ?sta puede estar ah? (en el ExpansionFile
716
         * por haber sido a?adida o modificada. Si ha sido a?adida, entonces hay
717
         * que respetar su estatus para que los writers puedan saber que es
718
         * un registro NUEVO).
719
         *
720
         * @param index
721
         *            DOCUMENT ME!
722
         * @param feat
723
         *            DOCUMENT ME!
724
         *
725
         * @return DOCUMENT ME!
726
         * @throws ExpansionFileWriteException
727
         * @throws ReadDriverException
728
         * @throws ExpansionFileReadException
729
         *
730
         */
731
        public int doModifyRow(int index, IRow feat, int sourceType) throws ExpansionFileWriteException, ReadDriverException, ExpansionFileReadException {
732
                boolean cancel = fireBeforeModifyRow(feat, index, sourceType);
733
                if (cancel)
734
                        return -1;
735

    
736
                int pos = -1;
737
                Integer integer = new Integer(index);
738
//                System.err.println("Modifica una Row en la posici?n: " + index);
739
                // Si la geometr?a no ha sido modificada
740
                if (!relations.containsKey(integer)) {
741
                        int expansionIndex = expansionFile.addRow(feat,
742
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
743
                        relations.put(integer, new Integer(expansionIndex));
744
                } else {
745
                        // Obtenemos el ?ndice en el fichero de expansi?n
746
                        int num = ((Integer) relations.get(integer)).intValue();
747
                        pos = num;
748

    
749
                        /*
750
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
751
                         * fichero de expansi?n en el que se encuentra la geometr?a
752
                         * modificada
753
                         */
754
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
755

    
756
                        /*
757
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
758
                         * fichero de expansi?n.
759
                         */
760
                        relations.put(integer, new Integer(num));
761
                }
762
                isFullExtentDirty = true;
763
                //fireAfterModifyRow(index, sourceType);
764
                return pos;
765
        }
766

    
767
        /**
768
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
769
         * en la tabla relations.
770
         *
771
         * @param feat
772
         *            geometr?a a guardar.
773
         *
774
         * @return calculatedIndex
775
         * @throws ExpansionFileWriteException
776
         * @throws DriverIOException
777
         * @throws IOException
778
         */
779
        public int doAddRow(IRow feat, int sourceType) throws ReadDriverException, ExpansionFileWriteException  {
780
                boolean cancel = fireBeforeRowAdded(sourceType,feat.getID());
781
                if (cancel)
782
                        return -1;
783
                // A?ade la geometr?a
784
                // int virtualIndex = 0;
785
                int calculatedIndex = -1;
786

    
787
                calculatedIndex = (int) ods.getRowCount() + numAdd;
788

    
789
                int pos = expansionFile.addRow(feat, IRowEdited.STATUS_ADDED, actualIndexFields);
790
                relations.put(new Integer(calculatedIndex), new Integer(pos));
791
                numAdd++;
792
                System.err.println("A?ade una Row en la posici?n: " + calculatedIndex);
793
                isFullExtentDirty = true;
794
                fireAfterRowAdded(feat,calculatedIndex, sourceType);
795
                return calculatedIndex;
796
        }
797

    
798
        /**
799
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
800
         * en el fichero original
801
         *
802
         * @param index
803
         *            DOCUMENT ME!
804
         */
805
        public void undoRemoveRow(int index, int sourceType) throws EditionCommandException {
806
                delRows.set(index, false);
807
                String fid;
808
                try {
809
                        fid = getRow(index).getID();
810

    
811
                boolean cancel = fireBeforeRowAdded(sourceType,fid);
812
                if (cancel){
813
                        delRows.set(index,true);
814
                        return;
815
                }
816
                } catch (ExpansionFileReadException e) {
817
                        throw new EditionCommandException(getOriginalDriver().getName(),e);
818
                } catch (ReadDriverException e) {
819
                        throw new EditionCommandException(getOriginalDriver().getName(),e);
820
                }
821
                fireAfterRowAdded(null,index, sourceType);
822
        }
823

    
824
        /**
825
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
826
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
827
         * relaci?n del mapa de relaciones
828
         *
829
         * @param fmapSpatialIndex
830
         *            ?ndice de la geometr?a que se a?adi?
831
         * @throws DriverIOException
832
         * @throws IOException
833
         */
834
        public void undoAddRow(int calculatedIndex, int sourceType)
835
                        throws EditionCommandException {
836
                boolean cancel;
837
                try {
838
                        cancel = fireBeforeRemoveRow(calculatedIndex, sourceType);
839
                } catch (ReadDriverException e) {
840
                        throw new EditionCommandException(getOriginalDriver().getName(),e);
841
                }
842
                if (cancel)
843
                        return;
844
                expansionFile.deleteLastRow();
845
                relations.remove(new Integer(calculatedIndex));
846
                numAdd--;
847
                fireAfterRemoveRow(calculatedIndex, sourceType);
848
        }
849

    
850
        /*
851
         * (non-Javadoc)
852
         *
853
         * @see com.iver.cit.gvsig.fmap.layers.VectorialAdapter#getRecordset()
854
         */
855
        public SelectableDataSource getRecordset() throws ReadDriverException  {
856
                if (isEditing) {
857
                        if (ds == null) {
858
                                String name = LayerFactory.getDataSourceFactory()
859
                                                .addDataSource(editingDriver);
860

    
861
                                try {
862

    
863
                                        ds = new SelectableDataSource(LayerFactory
864
                                                        .getDataSourceFactory().createRandomDataSource(
865
                                                                        name, DataSourceFactory.AUTOMATIC_OPENING));
866
                                        ds.start();
867
                                        ds.setSelectionSupport(ods.getSelectionSupport());
868

    
869
                                } catch (NoSuchTableException e) {
870
                                        throw new RuntimeException(e);
871
                                } catch (DriverLoadException e) {
872
                                        throw new ReadDriverException(name,e);
873
                                }
874
                        }
875

    
876
                        return ds;
877
                }
878
                return ods;
879
        }
880

    
881
        /**
882
         * Return always the original recordset (even when is editing,
883
         * nor the getRecorset() method)
884
         *
885
         * */
886
        public SelectableDataSource getOriginalRecordset(){
887
                return ods;
888
        }
889

    
890

    
891
        /**
892
         * DOCUMENT ME!
893
         *
894
         * @return
895
         * @throws ReadDriverException
896
         */
897
        public FBitSet getSelection() throws ReadDriverException {
898
                /*
899
                 * try { return getRecordset().getSelection(); } catch
900
                 * (DriverLoadException e) { // TODO Auto-generated catch block
901
                 * e.printStackTrace(); } return null;
902
                 */
903
                return getRecordset().getSelection();
904
        }
905

    
906
        public void setSelection(FBitSet selection) throws ReadDriverException {
907
                /*
908
                 * try { getRecordset().setSelection(selection); } catch
909
                 * (DriverLoadException e) { // TODO Auto-generated catch block
910
                 * e.printStackTrace(); }
911
                 */
912
                getRecordset().setSelection(selection);
913
        }
914

    
915
        /**
916
         * DOCUMENT ME!
917
         *
918
         * @return DOCUMENT ME!
919
         */
920
        public boolean isEditing() {
921
                return isEditing;
922
        }
923

    
924
        public int getInversedIndex(long rowIndex) {
925
                int intervalNotDeleted = 0;
926
                int antDeleted = -1;
927
                int idPedido = (int) rowIndex;
928
                int numNotDeleted = 0;
929
                int numBorradosAnt = 0;
930

    
931
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
932
                                .nextSetBit(i + 1)) {
933
                        intervalNotDeleted = i - antDeleted - 1;
934
                        numNotDeleted += intervalNotDeleted;
935
                        if (i > idPedido) {
936
                                numNotDeleted = numNotDeleted + (i - idPedido);
937
                                break;
938
                        }
939
                        numBorradosAnt++;
940
                        antDeleted = i;
941
                }
942
                numNotDeleted = idPedido - numBorradosAnt;
943
                // System.out.println("Piden Viejo : "+ rowIndex + " y devuelvo como
944
                // nuevo " + (numNotDeleted));
945
                return numNotDeleted;
946
        }
947

    
948
        /**
949
         * DOCUMENT ME!
950
         *
951
         * @param rowIndex
952
         *            DOCUMENT ME!
953
         *
954
         * @return DOCUMENT ME!
955
         */
956
        public int getCalculatedIndex(long rowIndex) {
957
                int numNotDeleted = 0;
958
                int intervalNotDeleted = 0;
959
                int antDeleted = -1;
960
                int calculatedIndex;
961
                int idPedido = (int) rowIndex;
962
                int numBorradosAnt = 0;
963

    
964
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
965
                                .nextSetBit(i + 1)) {
966
                        intervalNotDeleted = i - antDeleted - 1;
967
                        numNotDeleted += intervalNotDeleted;
968
                        if (numNotDeleted > idPedido) {
969
                                break;
970
                        }
971
                        numBorradosAnt++;
972
                        antDeleted = i;
973
                }
974
                calculatedIndex = numBorradosAnt + idPedido;
975
                // System.out.println("Piden Registro : "+ rowIndex + " y devuelvo el "
976
                // + (calculatedIndex));
977
                return calculatedIndex;
978
        }
979

    
980
        /**
981
         * DOCUMENT ME!
982
         *
983
         * @author Vicente Caballero Navarro
984
         */
985
        private class myObjectDriver implements ObjectDriver {
986
                /*
987
                 * (non-Javadoc)
988
                 *
989
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
990
                 */
991
                public int[] getPrimaryKeys() throws ReadDriverException {
992
                        return ods.getPrimaryKeys();
993
                        // int[] pk=new int[1];
994
                        /*
995
                         * for (int i=0;i<getRowCount();i++){ pk[i]=i; }
996
                         */
997
                        // pk[0]=1;
998
                        // return pk;
999
                }
1000

    
1001
                /*
1002
                 * (non-Javadoc)
1003
                 *
1004
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
1005
                 */
1006
                public void write(DataWare dataWare) throws ReadDriverException, WriteDriverException {
1007
                        DataWare dataWareOrig = ods
1008
                                        .getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
1009
                        dataWareOrig.commitTrans();
1010
                }
1011

    
1012
                /*
1013
                 * (non-Javadoc)
1014
                 *
1015
                 * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
1016
                 */
1017
                public void setDataSourceFactory(DataSourceFactory dsf) {
1018
                        ods.setDataSourceFactory(dsf);
1019
                }
1020

    
1021
                /*
1022
                 * (non-Javadoc)
1023
                 *
1024
                 * @see com.hardcode.driverManager.Driver#getName()
1025
                 */
1026
                public String getName() {
1027
                        return ods.getName();
1028
                }
1029

    
1030
                /*
1031
                 * (non-Javadoc)
1032
                 *
1033
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
1034
                 *      int)
1035
                 */
1036
                public Value getFieldValue(long rowIndex, int fieldId) throws ReadDriverException {
1037
                        // Si no est? en el fichero de expansi?n
1038
                        // Integer integer = new Integer(getCalculatedIndex(rowIndex));
1039

    
1040

    
1041
                        try {
1042
                                IRow row = getRow((int)rowIndex);
1043
                                return row.getAttribute(fieldId);
1044
//                                if (!relations.containsKey(integer)) {
1045
//                                        return ods.getFieldValue(rowIndex, fieldId);
1046
//                                } else {
1047
//                                        int num = ((Integer) relations.get(integer)).intValue();
1048
//                                        DefaultRowEdited feat = (DefaultRowEdited) expansionFile
1049
//                                                        .getRow(num);
1050
//
1051
//                                        if (feat == null) {
1052
//                                                return null;
1053
//                                        }
1054
//
1055
//                                        return feat.getAttribute(fieldId);
1056
//                                }
1057
//                        } catch (DriverException e) {
1058
//                                e.printStackTrace();
1059
//                                throw new DriverException(e);
1060
                        } catch (ExpansionFileReadException e) {
1061
                                throw new ReadDriverException(getRecordset().getDriver().getName(),e);
1062
                        }
1063

    
1064
                        /**
1065
                         * try { if (!relations.containsKey(integer)) { // Si ha sido
1066
                         * eliminada if (delRows.get(integer.intValue())) { return null; }
1067
                         * else { return ods.getFieldValue(rowIndex, fieldId); }} else { int
1068
                         * num = ((Integer) relations.get(integer)).intValue();
1069
                         * DefaultRowEdited feat = (DefaultRowEdited)
1070
                         * expansionFile.getRow(num); if (feat==null)return null; return
1071
                         * feat.getAttribute(fieldId); }} catch (DriverException e) {
1072
                         * e.printStackTrace(); throw new DriverException(e); } catch
1073
                         * (IOException e) { e.printStackTrace(); throw new
1074
                         * DriverException(e); }
1075
                         */
1076
                }
1077

    
1078
                /*
1079
                 * (non-Javadoc)
1080
                 *
1081
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
1082
                 */
1083
                public int getFieldCount() throws ReadDriverException {
1084
                        return fastAccessFields.size();
1085
                }
1086

    
1087
                /*
1088
                 * (non-Javadoc)
1089
                 *
1090
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
1091
                 */
1092
                public String getFieldName(int fieldId) throws ReadDriverException {
1093
//                        int i=0;
1094
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1095
//                                InternalField fld = (InternalField) iter.next();
1096
//                                if (i == fieldId)
1097
//                                        return fld.getFieldDesc().getFieldAlias();
1098
//                                i++;
1099
//
1100
//                        }
1101
//                        throw new DriverException("FieldId " + fieldId + " not found ");
1102
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1103
                        return aux.getFieldAlias();
1104
                        // return null;
1105
                        // return ods.getFieldName(fieldId);
1106
                }
1107

    
1108
                /*
1109
                 * (non-Javadoc)
1110
                 *
1111
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
1112
                 */
1113
                public long getRowCount() throws ReadDriverException {
1114
                        return (int) (ods.getRowCount() + numAdd)
1115
                                        - delRows.cardinality();// -
1116
                        // expansionFile.getInvalidRows().cardinality();
1117
                }
1118

    
1119
                /*
1120
                 * (non-Javadoc)
1121
                 *
1122
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
1123
                 */
1124
                public int getFieldType(int fieldId) throws ReadDriverException {
1125
//                        int i=0;
1126
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1127
//                                InternalField fld = (InternalField) iter.next();
1128
//                                if (i == fieldId)
1129
//                                        return fld.getFieldDesc().getFieldType();
1130
//                                i++;
1131
//
1132
//                        }
1133
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1134
                        return aux.getFieldType();
1135

    
1136
//                        return ods.getFieldType(i);
1137
                }
1138

    
1139
                public int getFieldWidth(int fieldId) throws ReadDriverException {
1140
//                        int i=0;
1141
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1142
//                                InternalField fld = (InternalField) iter.next();
1143
////                                if (fld.getFieldIndex() == i)
1144
////                                        return fld.getFieldDesc().getFieldLength();
1145
//                                if (i == fieldId)
1146
//                                        return fld.getFieldDesc().getFieldLength();
1147
//                                i++;
1148
//
1149
//                        }
1150
//
1151
//                        return ods.getFieldWidth(i);
1152
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1153
                        return aux.getFieldLength();
1154

    
1155
                }
1156

    
1157
                public void reload() throws ReloadDriverException {
1158
                        ods.reload();
1159

    
1160
                }
1161
        }
1162

    
1163
        public CommandRecord getCommandRecord() {
1164
                return cr;
1165
        }
1166

    
1167
        protected void fireAfterRemoveRow(int index, int sourceType) {
1168
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1169
                                EditionEvent.CHANGE_TYPE_DELETE, sourceType);
1170
                if (complex){
1171
                        rowEvents.add(event);
1172
                        return;
1173
                }
1174
                for (int i = 0; i < editionListeners.size(); i++) {
1175
                        IEditionListener listener = (IEditionListener) editionListeners
1176
                                        .get(i);
1177
                        listener.afterRowEditEvent(null, event);
1178
                }
1179

    
1180
        }
1181

    
1182
        protected boolean fireBeforeRemoveRow(int index, int sourceType) throws ReadDriverException {
1183
                Cancel cancel = new Cancel();
1184
                String fid=null;
1185
                IRow row=null;
1186
                try {
1187
                        row=getRow(getInversedIndex(index));
1188
                        fid = row.getID();
1189
                } catch (ExpansionFileReadException e) {
1190
                        throw new ReadDriverException(getOriginalDriver().getName(),e);
1191
                }
1192
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, fid,
1193
                                EditionEvent.CHANGE_TYPE_DELETE, cancel, sourceType);
1194
                for (int i = 0; i < editionListeners.size(); i++) {
1195
                        IEditionListener listener = (IEditionListener) editionListeners
1196
                                        .get(i);
1197
                        listener.beforeRowEditEvent(row, event);
1198
                        if (cancel.isCanceled())
1199
                                return true;
1200
                }
1201
                return false;
1202
        }
1203

    
1204
        protected void fireAfterRowAdded(IRow feat,int calculatedIndex, int sourceType) {
1205
                AfterRowEditEvent event = new AfterRowEditEvent(this, calculatedIndex,
1206
                                EditionEvent.CHANGE_TYPE_ADD, sourceType);
1207
                if (complex){
1208
                        rowEvents.add(event);
1209
                        return;
1210
                }
1211
                for (int i = 0; i < editionListeners.size(); i++) {
1212
                        IEditionListener listener = (IEditionListener) editionListeners
1213
                                        .get(i);
1214
                        listener.afterRowEditEvent(feat, event);
1215
                }
1216
        }
1217

    
1218
        protected void fireAfterFieldAdded(FieldDescription field) {
1219
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1220
                                EditionEvent.CHANGE_TYPE_ADD);
1221
                if (complex) {
1222
                        fieldEvents.add(event);
1223
                        return;
1224
                }
1225
                for (int i = 0; i < editionListeners.size(); i++) {
1226
                        IEditionListener listener = (IEditionListener) editionListeners
1227
                                        .get(i);
1228
                        listener.afterFieldEditEvent(event);
1229

    
1230
                }
1231
        }
1232

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

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

    
1261

    
1262
        protected boolean fireBeforeRowAdded(int sourceType,String newFID) throws ReadDriverException{
1263
                Cancel cancel = new Cancel();
1264
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, newFID,
1265
                                EditionEvent.CHANGE_TYPE_ADD, cancel, sourceType);
1266
                for (int i = 0; i < editionListeners.size(); i++) {
1267
                        IEditionListener listener = (IEditionListener) editionListeners
1268
                                        .get(i);
1269
                        listener.beforeRowEditEvent(null, event);
1270
                        if (cancel.isCanceled())
1271
                                return true;
1272
                }
1273
                return false;
1274
        }
1275

    
1276
        protected boolean fireBeforeFieldAdded(FieldDescription field) {
1277
                Cancel cancel = new Cancel();
1278
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1279
                EditionEvent.CHANGE_TYPE_ADD, cancel);
1280
                for (int i = 0; i < editionListeners.size(); i++) {
1281
                        IEditionListener listener = (IEditionListener) editionListeners
1282
                        .get(i);
1283
                        listener.beforeFieldEditEvent(event);
1284
                        if (cancel.isCanceled())
1285
                                return true;
1286
                }
1287
                return false;
1288
        }
1289

    
1290
        protected boolean fireBeforeRemoveField(FieldDescription field){
1291
                Cancel cancel = new Cancel();
1292
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1293
                EditionEvent.CHANGE_TYPE_DELETE, 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

    
1305
        protected boolean fireBeforeModifyRow(IRow feat, int index, int sourceType) throws ReadDriverException {
1306
                Cancel cancel = new Cancel();
1307
                String fid=null;
1308
                try {
1309
                        fid = getRow(getInversedIndex(index)).getID();
1310
                } catch (ExpansionFileReadException e) {
1311
                        throw new ReadDriverException(getOriginalDriver().getName(),e);
1312
                }
1313
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, fid,
1314
                                EditionEvent.CHANGE_TYPE_MODIFY, cancel, sourceType);
1315
                for (int i = 0; i < editionListeners.size(); i++) {
1316
                        IEditionListener listener = (IEditionListener) editionListeners
1317
                                        .get(i);
1318
                        listener.beforeRowEditEvent(feat, event);
1319
                        if (cancel.isCanceled())
1320
                                return true;
1321
                }
1322
                return false;
1323
        }
1324

    
1325
        protected void fireAfterModifyRow(int index, int sourceType) {
1326
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1327
                                EditionEvent.CHANGE_TYPE_MODIFY, sourceType);
1328
                if (complex){
1329
                        rowEvents.add(event);
1330
                        return;
1331
                }
1332
                for (int i = 0; i < editionListeners.size(); i++) {
1333
                        IEditionListener listener = (IEditionListener) editionListeners
1334
                                        .get(i);
1335
                        listener.afterRowEditEvent(null, event);
1336
                }
1337

    
1338
        }
1339

    
1340
        protected void fireStartEditionEvent(int sourceType) {
1341
                EditionEvent ev = new EditionEvent(this, EditionEvent.START_EDITION,
1342
                                sourceType);
1343
                for (int i = 0; i < editionListeners.size(); i++) {
1344
                        IEditionListener listener = (IEditionListener) editionListeners
1345
                                        .get(i);
1346
                        listener.processEvent(ev);
1347
                }
1348

    
1349
        }
1350

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

    
1360
        }
1361

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

    
1371
        }
1372

    
1373
        public void addEditionListener(IEditionListener listener) {
1374
                if (!editionListeners.contains(listener))
1375
                        editionListeners.add(listener);
1376
        }
1377

    
1378
        public void removeEditionListener(IEditionListener listener) {
1379
                editionListeners.remove(listener);
1380
        }
1381

    
1382
        public IWriter getWriter() {
1383
                return writer;
1384
        }
1385

    
1386
        protected void setWriter(IWriter writer) {
1387
                this.writer = writer;
1388

    
1389
        }
1390
        /*
1391
         * azabala: esto funciona para todos los drivers gdbms
1392
         * salvo para MySQL, que necesita que el ITableDefinition
1393
         * contenga el nombre de la tabla (y por tanto requiere
1394
         * DBLayerDefinition-en realidad hace falta DBTableDefinition)
1395
         * TODO REVISAR LA ARQUITECTURA DE ESTO
1396
         *
1397
         * */
1398
        public ITableDefinition getTableDefinition() throws ReadDriverException {
1399
                Driver originalDriver = getOriginalDriver();
1400
                if(! (originalDriver instanceof AlphanumericDBDriver)){
1401
                        TableDefinition tableDef = new TableDefinition();
1402
                        tableDef.setFieldsDesc(getRecordset().getFieldsDescription());
1403
                        tableDef.setName(getRecordset().getSourceInfo().name);
1404
                        return tableDef;
1405
                }
1406
                AlphanumericDBDriver dbDriver = (AlphanumericDBDriver)originalDriver;
1407
                return dbDriver.getTableDefinition();
1408

    
1409

    
1410
        }
1411

    
1412
        public void validateRow(IRow row,int sourceType) throws ValidateRowException  {
1413
                for (int i = 0; i < rules.size(); i++) {
1414
                        IRule rule = (IRule) rules.get(i);
1415
                        boolean bAux = rule.validate(row,sourceType);
1416
                        if (bAux == false) {
1417
                                ValidateRowException ex = new ValidateRowException(writer.getName(),null);
1418
                                // TODO: Lanzar una RuleException con datos como el registro
1419
                                // que no cumple, la regla que no lo ha cumplido, etc.
1420
                                throw ex;
1421
                        }
1422
                }
1423
        }
1424

    
1425
        public ArrayList getRules() {
1426
                return rules;
1427
        }
1428

    
1429
        public void setRules(ArrayList rules) {
1430
                this.rules = rules;
1431
        }
1432

    
1433
        private void clean() throws ReadDriverException {
1434
                try {
1435
                        expansionFile.close();
1436
                } catch (CloseExpansionFileException e) {
1437
                        throw new ReadDriverException(getRecordset().getDriver().getName(),e);
1438
                }
1439
                relations.clear();
1440
                numAdd = 0;
1441
                delRows.clear();
1442
                // TODO: Es muy probable que necesitemos un reload de los datasources, al
1443
                // igual que lo tenemos en las capas. Por ahora, basta con retocar
1444
                // listInternalFields, pero casi seguro que lo correcto ser?a hacer un
1445
                // reload completo.
1446
                initalizeFields(ods);
1447

    
1448
//                listInternalFields.clear();
1449
//                listInternalFields.add(actualFields);
1450
        }
1451

    
1452
        /*
1453
         * (non-Javadoc)
1454
         *
1455
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getFieldManager()
1456
         */
1457
        public IFieldManager getFieldManager() {
1458
                if (ods.getDriver() instanceof IWriteable)
1459
                {
1460
                        IWriter writer = ((IWriteable)ods.getDriver()).getWriter();
1461
                        if ((writer != null) && (writer instanceof IFieldManager))
1462
                        {
1463
                                IFieldManager fldManager = (IFieldManager) writer;
1464
                                return fldManager;
1465
                        }
1466
                }
1467
                return null;
1468
        }
1469

    
1470
        /**
1471
         * Tiene en cuenta los campos actuales para formatear una row con ellos. Le
1472
         * pasamos los campos que hab?a en el momento en que se cre? esa row.
1473
         *
1474
         * @param edRow
1475
         * @param indexInternalFields
1476
         * @return
1477
         */
1478
        public IRowEdited createExternalRow(IRowEdited edRow,
1479
                        int indexInternalFields) {
1480

    
1481
                // para acelerar
1482
                if (bFieldsHasBeenChanged == false)
1483
                        return edRow;
1484

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

    
1521
        public void removeField(String fieldName) throws WriteDriverException, ReadDriverException {
1522

    
1523
                InternalField fld = findFieldByName(fieldName);
1524
                if (fld == null)
1525
                        throw new WriteDriverException(getRecordset().getDriver().getName(),null);
1526
                //throw new WriteDriverException("Field " + fieldName + " not found when removing field");
1527
                Command command = new RemoveFieldCommand(this, fld);
1528
                if (complex) {
1529
                        commands.add(command);
1530
                } else {
1531
                        cr.pushCommand(command);
1532
                }
1533
                doRemoveField(fld);
1534

    
1535
        }
1536

    
1537
        private InternalField findFieldByName(String fieldName) {
1538
                Collection aux = actualFields.values();
1539
                Iterator it = aux.iterator();
1540
                while (it.hasNext()) {
1541
                        InternalField fld = (InternalField) it.next();
1542
                        if (fld.getFieldDesc().getFieldAlias().compareToIgnoreCase(fieldName) == 0)
1543
                                return fld;
1544
                }
1545

    
1546
                return null;
1547
        }
1548

    
1549
        public void undoRemoveField(InternalField field) throws EditionCommandException {
1550
                // field.setDeleted(false);
1551
//                field.setFieldIndex(actualFields.size());
1552
                actualFields.put(field.getFieldId(), field);
1553
                try {
1554
                        fieldsChanged();
1555
                } catch (ReadDriverException e) {
1556
                        throw new EditionCommandException(writer.getName(),e);
1557
                }
1558
                fireAfterFieldAdded(field.getFieldDesc());
1559
        }
1560

    
1561
        public void doRemoveField(InternalField field) throws ReadDriverException {
1562
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1563
                if (cancel) return;
1564
                actualFields.remove(field.getFieldId());
1565
                fieldsChanged();
1566
                fireAfterFieldRemoved(field.getFieldDesc());
1567
        }
1568

    
1569
        public void renameField(String antName, String newName) throws ReadDriverException{
1570

    
1571
                InternalField fld = findFieldByName(antName);
1572
                Command command = new RenameFieldCommand(this, fld, newName);
1573
                if (complex) {
1574
                        commands.add(command);
1575
                } else {
1576
                        cr.pushCommand(command);
1577
                }
1578
                doRenameField(fld, newName);
1579

    
1580
        }
1581

    
1582
        public void undoRenameField(InternalField field, String antName) throws EditionCommandException{
1583
                field.getFieldDesc().setFieldAlias(antName);
1584
                try {
1585
                        fieldsChanged();
1586
                } catch (ReadDriverException e) {
1587
                        throw new EditionCommandException(writer.getName(),e);
1588
                }
1589
                fireAfterFieldModified(field.getFieldDesc());
1590

    
1591
        }
1592

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

    
1598
        }
1599

    
1600

    
1601
        public void addField(FieldDescription field) throws ReadDriverException {
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 EditionCommandException  {
1616
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1617
                if (cancel)
1618
                        return;
1619

    
1620
                // field.setDeleted(true);
1621
                actualFields.remove(field.getFieldId());
1622
                try {
1623
                        fieldsChanged();
1624
                } catch (ReadDriverException e) {
1625
                        throw new EditionCommandException(writer.getName(),e);
1626
                }
1627
                fireAfterFieldRemoved(field.getFieldDesc());
1628

    
1629
        }
1630

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

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

    
1646
        public Driver getOriginalDriver()
1647
        {
1648
                return ods.getDriver();
1649
        }
1650

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

    
1659
        public FieldDescription[] getFieldsDescription() {
1660
                return (FieldDescription[]) fastAccessFields.toArray(new FieldDescription[0]);
1661
        }
1662
        public String getNewFID() {
1663
                return "fid-" + (new UID()).toString();
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
}