Statistics
| Revision:

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

History | View | Annotate | Download (49.1 KB)

1 3940 caballero
package com.iver.cit.gvsig.fmap.edition;
2
3 4061 caballero
import java.io.IOException;
4 4832 fjp
import java.util.ArrayList;
5 6212 fjp
import java.util.Collection;
6 4061 caballero
import java.util.HashMap;
7 6212 fjp
import java.util.Iterator;
8
import java.util.TreeMap;
9 3940 caballero
10 5569 jmvivo
import com.hardcode.driverManager.Driver;
11 4061 caballero
import com.hardcode.driverManager.DriverLoadException;
12 10627 caballero
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
13
import com.hardcode.gdbms.driver.exceptions.ReloadDriverException;
14
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
15 3940 caballero
import com.hardcode.gdbms.engine.data.DataSourceFactory;
16
import com.hardcode.gdbms.engine.data.NoSuchTableException;
17 9766 azabala
import com.hardcode.gdbms.engine.data.driver.AlphanumericDBDriver;
18 3940 caballero
import com.hardcode.gdbms.engine.data.driver.DriverException;
19
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
20
import com.hardcode.gdbms.engine.data.edition.DataWare;
21
import com.hardcode.gdbms.engine.values.Value;
22 10627 caballero
import com.iver.cit.gvsig.exceptions.commands.EditionCommandException;
23
import com.iver.cit.gvsig.exceptions.expansionfile.CloseExpansionFileException;
24
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
25
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileWriteException;
26
import com.iver.cit.gvsig.exceptions.layers.CancelEditingLayerException;
27
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
28
import com.iver.cit.gvsig.exceptions.layers.StopEditionLayerException;
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 4026 caballero
import com.iver.cit.gvsig.fmap.core.DefaultRow;
34 3940 caballero
import com.iver.cit.gvsig.fmap.core.IRow;
35
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
36 6212 fjp
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
37 5558 fjp
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
38
import com.iver.cit.gvsig.fmap.drivers.TableDefinition;
39 6212 fjp
import com.iver.cit.gvsig.fmap.edition.commands.AddFieldCommand;
40 3940 caballero
import com.iver.cit.gvsig.fmap.edition.commands.AddRowCommand;
41 4120 caballero
import com.iver.cit.gvsig.fmap.edition.commands.Command;
42 3940 caballero
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 6212 fjp
import com.iver.cit.gvsig.fmap.edition.commands.RemoveFieldCommand;
47 3940 caballero
import com.iver.cit.gvsig.fmap.edition.commands.RemoveRowCommand;
48 6212 fjp
import com.iver.cit.gvsig.fmap.edition.commands.RenameFieldCommand;
49
import com.iver.cit.gvsig.fmap.edition.fieldmanagers.AbstractFieldManager;
50 5886 fjp
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
51 3940 caballero
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 4832 fjp
import com.iver.cit.gvsig.fmap.operations.Cancel;
55 3940 caballero
56
/**
57
 * DOCUMENT ME!
58 7271 jaume
 *
59 3940 caballero
 * @author Vicente Caballero Navarro
60
 */
61 5595 fjp
public class EditableAdapter implements IEditableSource, IWriteable {
62 4792 fjp
        protected boolean isEditing = false;
63 3996 caballero
64 4792 fjp
        private SelectableDataSource ds = null;
65 3940 caballero
66 4792 fjp
        protected FBitSet delRows = new FBitSet();
67 3940 caballero
68 4792 fjp
        private CommandRecord cr;
69 6212 fjp
70 5549 fjp
        protected IWriter writer;
71 3940 caballero
72 4792 fjp
        /**
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 3940 caballero
78 4792 fjp
        private CommandCollection commands = null;
79 3940 caballero
80 6212 fjp
        protected ArrayList listFields = new ArrayList();
81
82
        protected ArrayList listInternalFields = new ArrayList();
83 7271 jaume
84 6483 fjp
        protected boolean bFieldsHasBeenChanged = false;
85 6212 fjp
86
        /**
87 6483 fjp
         * La clave ser? el fieldId. Para buscar si un value de una row ha de ser
88 6212 fjp
         * 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 6483 fjp
         * borran campos. Solo se van a?adiendo nuevos actualFields.
93 6212 fjp
         */
94 6483 fjp
        protected TreeMap actualFields; // la clave ser? el fieldId.
95 7271 jaume
96 6483 fjp
        protected ArrayList fastAccessFields = new ArrayList();
97 6212 fjp
98
        protected class MyFieldManager extends AbstractFieldManager {
99
100 10627 caballero
                public boolean alterTable() throws WriteDriverException {
101 6212 fjp
                        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 4792 fjp
        /*
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 3940 caballero
135 4792 fjp
        /*
136
         * Fichero en el que se guardan las nuevas geometr?as, producto de adiciones
137
         * o de modificaciones
138
         */
139
        protected ExpansionFile expansionFile;
140 3940 caballero
141 4792 fjp
        protected int numAdd = 0;
142 3940 caballero
143 4792 fjp
        private ObjectDriver editingDriver = new myObjectDriver();
144 3996 caballero
145 4792 fjp
        private SelectableDataSource ods;
146 4954 caballero
147 4832 fjp
        private ArrayList editionListeners = new ArrayList();
148 3940 caballero
149 5886 fjp
        private ArrayList rules = new ArrayList();
150
151 6212 fjp
        protected int actualIndexFields;
152
153 7271 jaume
        protected boolean isFullExtentDirty = false;
154
155 10342 caballero
        private ArrayList fieldEvents=new ArrayList();
156
        private ArrayList rowEvents=new ArrayList();
157 10207 caballero
158 4792 fjp
        /**
159
         * Crea un nuevo EditableAdapter.
160
         */
161
        public EditableAdapter() {
162 6212 fjp
                expansionFile = new MemoryExpansionFile(this);
163 4792 fjp
                cr = new MemoryCommandRecord();
164
        }
165 3940 caballero
166 4792 fjp
        /**
167
         * DOCUMENT ME!
168 7271 jaume
         *
169 4792 fjp
         * @param ds
170
         *            DOCUMENT ME!
171 7271 jaume
         * @throws DriverException
172 4792 fjp
         */
173 10627 caballero
        public void setOriginalDataSource(SelectableDataSource ds) throws ReadDriverException {
174 4792 fjp
                this.ods = ds;
175 6313 fjp
                initalizeFields(ds);
176 6856 fjp
                Driver drv = ods.getDriver();
177
                if (drv instanceof IWriteable) {
178
                        setWriter(((IWriteable) drv).getWriter());
179
                }
180
181 7271 jaume
182 6313 fjp
        }
183
184
        /**
185
         * @param ds
186 10627 caballero
         * @throws ReadDriverException
187 6313 fjp
         * @throws DriverException
188
         */
189 10627 caballero
        private void initalizeFields(SelectableDataSource ds) throws ReadDriverException {
190 6212 fjp
                FieldDescription[] fields = ds.getFieldsDescription();
191 6313 fjp
                listInternalFields.clear();
192 6326 fjp
                actualIndexFields = 0;
193 6212 fjp
                actualFields = new TreeMap();
194 6483 fjp
//                fastAccessFields = new ArrayList();
195 6212 fjp
                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 6384 fjp
                        // field.setFieldIndex(i);
200 6212 fjp
                        actualFields.put(field.getFieldId(), field);
201 6483 fjp
//                        fastAccessFields.add(fields[i]);
202 6326 fjp
                        System.out.println("INITIALIZEFIELDS: FIELD " + field.getFieldDesc().getFieldAlias());
203 6212 fjp
                }
204 6259 fjp
                        fieldsChanged();
205 6483 fjp
                        bFieldsHasBeenChanged = false;
206 4792 fjp
        }
207 3940 caballero
208 6839 fjp
        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 7271 jaume
217 6839 fjp
                return clonedFields;
218
        }
219 10627 caballero
        private void fieldsChanged() throws ReadDriverException {
220 6483 fjp
                fastAccessFields= new ArrayList();
221 6839 fjp
                int index = 0;
222 6483 fjp
                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
223
                        InternalField fld = (InternalField) iter.next();
224
                        fastAccessFields.add(fld.getFieldDesc());
225 6839 fjp
                        fld.setFieldIndex(index++);
226 6483 fjp
                }
227 6384 fjp
228 6839 fjp
                listInternalFields.add(deepCloneInternalFields(actualFields));
229 6212 fjp
                actualIndexFields = listInternalFields.size()-1;
230 10665 caballero
                ds = null;
231
                getRecordset().mapExternalFields();
232
                bFieldsHasBeenChanged = true;
233 6212 fjp
        }
234
235 4792 fjp
        /**
236
         * DOCUMENT ME!
237 10627 caballero
         * @throws StartEditionLayerException
238
         * @throws StartWriterVisitorException
239 7271 jaume
         *
240 4792 fjp
         * @throws EditionException
241
         *             DOCUMENT ME!
242
         */
243 10627 caballero
        public void startEdition(int sourceType) throws StartWriterVisitorException {
244 4792 fjp
                isEditing = true;
245 5986 caballero
246 5184 caballero
                fireStartEditionEvent(sourceType);
247 4792 fjp
        }
248 3996 caballero
249 4792 fjp
        /**
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 7271 jaume
         *
256 4792 fjp
         * @param writer
257
         *            IWriter que recibir? las llamadas.
258 7271 jaume
         *
259 4792 fjp
         * @throws EditionException
260
         *             DOCUMENT ME!
261 7271 jaume
         *
262 4792 fjp
         */
263 6212 fjp
        public void stopEdition(IWriter writer, int sourceType)
264 10627 caballero
                        throws StopWriterVisitorException {
265 6212 fjp
                saveEdits(writer, sourceType);
266 6227 fjp
                isEditing = false;
267 6356 fjp
                cr.clearAll();
268 6212 fjp
                fireStopEditionEvent(sourceType);
269
        }
270
271
        public void saveEdits(IWriter writer, int sourceType)
272 10627 caballero
                        throws StopWriterVisitorException {
273 7271 jaume
274 6579 fjp
                // 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 7271 jaume
                        // Para cada campo de los originales, miramos si no est? en
280 6579 fjp
                        // 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 7271 jaume
286 6579 fjp
                        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 7271 jaume
                                        }
301 6579 fjp
                                }
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 4792 fjp
                try {
320 10627 caballero
                        writer.preProcess();
321 4792 fjp
                        // Procesamos primero los borrados.
322
                        // Cuando se genere un tema nuevo, no se les debe hacer caso
323
                        // a estos registros
324 3996 caballero
325 6212 fjp
                        for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
326
                                        .nextSetBit(i + 1)) {
327 4792 fjp
                                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 10627 caballero
                                                        IRowEdited.STATUS_DELETED, calculatedIndex);
336 4792 fjp
                                        writer.process(edRow);
337
                                } else {
338
                                        int num = ((Integer) relations.get(integer)).intValue();
339 4061 caballero
340 4792 fjp
                                        // return expansionFile.getRow(num);
341
                                        IRowEdited rowFromExpansion = expansionFile.getRow(num);
342
                                        // ?Habr?a que hacer aqu? setID(index + "")?
343
                                        edRow = new DefaultRowEdited(rowFromExpansion
344 6212 fjp
                                                        .getLinkedRow().cloneRow(),
345 10627 caballero
                                                        IRowEdited.STATUS_DELETED, calculatedIndex);
346 4792 fjp
                                        writer.process(edRow);
347
                                }
348 3940 caballero
349 4792 fjp
                        }
350 3940 caballero
351 4792 fjp
                        int rowCount = getRowCount();
352 9834 fjp
                        if (writer.isWriteAll())
353
                        {
354
                                for (int i = 0; i < rowCount; i++) {
355
                                        IRowEdited rowEdited = getRow(i);
356 10207 caballero
357 9834 fjp
                                        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 3940 caballero
373 9834 fjp
                                                // 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 4792 fjp
                                }
382
                        }
383 5668 fjp
                        writer.postProcess();
384 5986 caballero
385 6580 fjp
                        // 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 6323 fjp
                        ods.reload();
394 6326 fjp
                        ds = null;
395
                        clean();
396 7271 jaume
397 10627 caballero
                } catch (ReadDriverException e) {
398
                        throw new StopWriterVisitorException(writer.getName(),e);
399
                } catch (ExpansionFileReadException e) {
400
                        throw new StopWriterVisitorException(writer.getName(),e);
401
                } catch (StartWriterVisitorException e) {
402
                        throw new StopWriterVisitorException(writer.getName(),e);
403
                } catch (VisitorException e) {
404
                        throw new StopWriterVisitorException(writer.getName(),e);
405 4792 fjp
                }
406 3940 caballero
407 4792 fjp
        }
408 3940 caballero
409 4792 fjp
        /**
410
         * DOCUMENT ME!
411 7271 jaume
         *
412 4792 fjp
         * @throws IOException
413
         *             DOCUMENT ME!
414
         */
415 10627 caballero
        public void cancelEdition(int sourceType) throws CancelEditingLayerException {
416 4792 fjp
                isEditing = false;
417 6313 fjp
                try {
418 6341 fjp
                        ds= null;
419 6313 fjp
                        clean();
420 6356 fjp
                        cr.clearAll();
421 10627 caballero
                } catch (ReadDriverException e) {
422
                        throw new CancelEditingLayerException(writer.getName(),e);
423 6313 fjp
                }
424 5184 caballero
                fireCancelEditionEvent(sourceType);
425 4792 fjp
        }
426 3940 caballero
427 4792 fjp
        /*
428
         * (non-Javadoc)
429 7271 jaume
         *
430 4792 fjp
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
431
         */
432 10627 caballero
        public IRowEdited getRow(int index) throws ReadDriverException, ExpansionFileReadException {
433 4792 fjp
                int calculatedIndex = getCalculatedIndex(index);
434
                Integer integer = new Integer(calculatedIndex);
435
                DefaultRowEdited edRow = null;
436
                // Si no est? en el fichero de expansi?n
437
                if (!relations.containsKey(integer)) {
438
                                /*
439
                                 * edRow = new DefaultRowEdited(new
440
                                 * DefaultRow(ods.getRow(calculatedIndex), "" + index),
441
                                 * DefaultRowEdited.STATUS_ORIGINAL, index);
442
                                 */
443 6313 fjp
                                DefaultRow auxR = new DefaultRow(ods.getRow(calculatedIndex));
444
                                edRow = new DefaultRowEdited(auxR,
445 10627 caballero
                                                IRowEdited.STATUS_ORIGINAL, index);
446 6313 fjp
                                return createExternalRow(edRow, 0);
447
//                                edRow = new DefaultRowEdited(new DefaultRow(ods
448
//                                                .getRow(calculatedIndex)),
449
//                                                DefaultRowEdited.STATUS_ORIGINAL, index);
450 4792 fjp
                }
451 10627 caballero
                int num = ((Integer) relations.get(integer)).intValue();
452 6313 fjp
453 10627 caballero
                // return expansionFile.getRow(num);
454
                // ExpansionFile ya entrega el registro formateado como debe
455
                IRowEdited rowFromExpansion;
456
                rowFromExpansion = expansionFile.getRow(num);
457
                // ?Habr?a que hacer aqu? setID(index + "")?
458
                edRow = new DefaultRowEdited(rowFromExpansion.getLinkedRow()
459
                                .cloneRow(), rowFromExpansion.getStatus(), index);
460
                return edRow;
461 7271 jaume
462
463 10627 caballero
464 4792 fjp
        }
465 3940 caballero
466 4792 fjp
        /**
467
         * DOCUMENT ME!
468 7271 jaume
         *
469 4792 fjp
         * @return DOCUMENT ME!
470 10627 caballero
         * @throws ReadDriverException
471 7271 jaume
         *
472 4792 fjp
         * @throws DriverIOException
473
         *             DOCUMENT ME!
474
         * @throws IOException
475
         *             DOCUMENT ME!
476
         */
477 10627 caballero
        public int getRowCount() throws ReadDriverException {
478 4792 fjp
                        return (int) (ods.getRowCount() + numAdd) - delRows.cardinality();// -
479 6212 fjp
                        // expansionFile.getInvalidRows().cardinality();
480 4637 caballero
        }
481 3940 caballero
482 6212 fjp
        /*
483
         * (non-Javadoc)
484 7271 jaume
         *
485 6212 fjp
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#addRow(com.iver.cit.gvsig.fmap.core.IRow,
486
         *      java.lang.String)
487 4792 fjp
         */
488 10627 caballero
        public int addRow(IRow row, String descrip, int sourceType) throws ValidateRowException, ReadDriverException, ExpansionFileWriteException{
489
                validateRow(row,sourceType);
490 6071 caballero
491 5184 caballero
                int calculatedIndex = doAddRow(row, sourceType);
492 6212 fjp
                Command command = new AddRowCommand(this, row, calculatedIndex,
493
                                sourceType);
494 4792 fjp
                command.setDescription(descrip);
495
                if (complex) {
496
                        commands.add(command);
497
                } else {
498
                        cr.pushCommand(command);
499
                }
500 5077 caballero
501 4792 fjp
                return calculatedIndex;
502
        }
503 3940 caballero
504 4792 fjp
        /**
505
         * DOCUMENT ME!
506 10627 caballero
         * @throws EditionCommandException
507 7271 jaume
         *
508 4792 fjp
         * @throws DriverIOException
509
         *             DOCUMENT ME!
510
         * @throws IOException
511
         *             DOCUMENT ME!
512
         */
513 10627 caballero
        public void undo() throws EditionCommandException{
514 4792 fjp
                // seleccion.clear();
515 6127 fjp
                if (cr.moreUndoCommands()) {
516 4792 fjp
                        cr.undoCommand();
517
                }
518
        }
519 3940 caballero
520 4792 fjp
        /**
521
         * DOCUMENT ME!
522 10627 caballero
         * @throws EditionCommandException
523 7271 jaume
         *
524 4792 fjp
         * @throws DriverIOException
525
         *             DOCUMENT ME!
526
         * @throws IOException
527
         *             DOCUMENT ME!
528
         */
529 10627 caballero
        public void redo() throws EditionCommandException {
530 4792 fjp
                // seleccion.clear();
531 6127 fjp
                if (cr.moreRedoCommands()) {
532 4792 fjp
                        cr.redoCommand();
533
                }
534
        }
535 3940 caballero
536 6212 fjp
        /*
537 4792 fjp
         * (non-Javadoc)
538 7271 jaume
         *
539 4792 fjp
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#removeRow(int)
540
         */
541 10627 caballero
        public void removeRow(int index, String descrip, int sourceType) throws ReadDriverException, ExpansionFileReadException {
542 5077 caballero
543 4792 fjp
                int calculatedIndex = getCalculatedIndex(index);
544 6212 fjp
                Command command = new RemoveRowCommand(this, calculatedIndex,
545
                                sourceType);
546 4792 fjp
                command.setDescription(descrip);
547
                if (complex) {
548
                        commands.add(command);
549
                } else {
550
                        cr.pushCommand(command);
551
                }
552 5184 caballero
                doRemoveRow(calculatedIndex, sourceType);
553 5077 caballero
554 4792 fjp
        }
555 3940 caballero
556 4792 fjp
        /*
557
         * (non-Javadoc)
558 7271 jaume
         *
559 4792 fjp
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#modifyRow(int,
560
         *      com.iver.cit.gvsig.fmap.core.IRow)
561
         */
562 10627 caballero
        public int modifyRow(int index, IRow row, String descrip, int sourceType) throws ValidateRowException, ExpansionFileWriteException, ReadDriverException, ExpansionFileReadException {
563
                validateRow(row,sourceType);
564 4792 fjp
                int calculatedIndex = getCalculatedIndex(index);
565 5184 caballero
                int pos = doModifyRow(calculatedIndex, row, sourceType);
566 6212 fjp
                Command command = new ModifyRowCommand(this, calculatedIndex, pos, row,
567
                                sourceType);
568 4792 fjp
                command.setDescription(descrip);
569
                if (complex) {
570
                        commands.add(command);
571
                } else {
572
                        cr.pushCommand(command);
573
                }
574 5077 caballero
575 4792 fjp
                return pos;
576
        }
577 3940 caballero
578 4792 fjp
        /**
579
         * DOCUMENT ME!
580
         */
581
        public void compact() {
582
                expansionFile.compact(relations);
583
        }
584 3996 caballero
585 4792 fjp
        /**
586
         * DOCUMENT ME!
587
         */
588
        public void startComplexRow() {
589
                complex = true;
590
                commands = new CommandCollection();
591
        }
592 3996 caballero
593 4792 fjp
        /**
594
         * DOCUMENT ME!
595 7271 jaume
         *
596 4792 fjp
         * @throws IOException
597
         *             DOCUMENT ME!
598
         * @throws DriverIOException
599
         *             DOCUMENT ME!
600
         */
601 10627 caballero
        public void endComplexRow(String description) {
602 6071 caballero
                commands.setDescription(description);
603 4792 fjp
                cr.pushCommand(commands);
604
                complex = false;
605 10394 caballero
                for (int j = 0; j < editionListeners.size(); j++) {
606
                        for (int i = 0; i < fieldEvents.size(); i++) {
607
                                IEditionListener listener = (IEditionListener) editionListeners
608
                                        .get(j);
609
                                listener.afterFieldEditEvent((AfterFieldEditEvent)fieldEvents.get(i));
610
                        }
611
                        for (int i = 0; i < rowEvents.size(); i++) {
612
                                IEditionListener listener = (IEditionListener) editionListeners
613
                                                .get(j);
614
                                listener.afterRowEditEvent(null,(AfterRowEditEvent)rowEvents.get(i));
615
                        }
616 10207 caballero
                }
617 10342 caballero
                fieldEvents.clear();
618
                rowEvents.clear();
619 4792 fjp
        }
620 3940 caballero
621 4792 fjp
        /**
622
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
623
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
624
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
625
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
626
         * expansion file a justo despues de la penultima geometr?a
627 7271 jaume
         *
628 4792 fjp
         * @param geometryIndex
629
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
630
         * @param previousExpansionFileIndex
631
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
632
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
633
         *            original y por tanto no hay que actualizar el mapa de indices
634
         *            sino eliminar su entrada.
635
         * @throws IOException
636
         * @throws DriverIOException
637
         */
638 6212 fjp
        public void undoModifyRow(int geometryIndex,
639 10627 caballero
                        int previousExpansionFileIndex, int sourceType) throws EditionCommandException  {
640 5197 caballero
641 4792 fjp
                if (previousExpansionFileIndex == -1) {
642 6212 fjp
                        DefaultRowEdited edRow = null;
643 5197 caballero
                        try {
644
                                edRow = new DefaultRowEdited(new DefaultRow(ods
645 10627 caballero
                                                        .getRow(geometryIndex)),
646
                                                        IRowEdited.STATUS_ORIGINAL, geometryIndex);
647
                        } catch (ReadDriverException e) {
648
                                throw new EditionCommandException(writer.getName(),e);
649 5197 caballero
                        }
650 6212 fjp
                        boolean cancel = fireBeforeModifyRow(edRow, geometryIndex,
651
                                        sourceType);
652 5197 caballero
                        if (cancel)
653
                                return;
654 4792 fjp
                        // Se elimina de las relaciones y del fichero de expansi?n
655
                        relations.remove(new Integer(geometryIndex));
656
                        expansionFile.deleteLastRow();
657
                } else {
658 10627 caballero
                        boolean cancel;
659
                        try {
660
                                cancel = fireBeforeModifyRow(expansionFile
661
                                                .getRow(previousExpansionFileIndex), geometryIndex,
662
                                                sourceType);
663
                        } catch (ExpansionFileReadException e) {
664
                                throw new EditionCommandException(writer.getName(),e);
665
                        }
666 5197 caballero
                        if (cancel)
667
                                return;
668 4792 fjp
                        // Se actualiza la relaci?n de ?ndices
669
                        relations.put(new Integer(geometryIndex), new Integer(
670
                                        previousExpansionFileIndex));
671
                }
672 10287 caballero
                //fireAfterModifyRow(geometryIndex, sourceType);
673 4792 fjp
        }
674 3940 caballero
675 4792 fjp
        /**
676
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
677
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
678
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
679
         * una futura compactaci?n termine con ella.
680 7271 jaume
         *
681 4792 fjp
         * @param index
682
         *            ?ndice de la geometr?a.
683 10627 caballero
         * @throws ReadDriverException
684
         * @throws ExpansionFileReadException
685 7271 jaume
         *
686 4792 fjp
         * @throws DriverIOException
687
         * @throws IOException
688
         */
689 10627 caballero
        public IRow doRemoveRow(int index, int sourceType) throws ReadDriverException, ExpansionFileReadException{
690 5184 caballero
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
691 5077 caballero
                if (cancel)
692
                        return null;
693 4792 fjp
                // Llega un calculatedIndex
694
                delRows.set(index, true);
695
                System.err.println("Elimina una Row en la posici?n: " + index);
696
                // TODO: Con tablas no es necesario devolver la anterior feature. Por
697
                // ahora.
698 7271 jaume
                isFullExtentDirty = true;
699 5184 caballero
                fireAfterRemoveRow(index, sourceType);
700 4792 fjp
                return null;
701
        }
702 3940 caballero
703 4792 fjp
        /**
704 9800 azabala
         ** Si se intenta modificar una geometr?a original de la capa en edici?n se
705 4792 fjp
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
706
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
707 9800 azabala
         * fichero de expansi?n, ?sta puede estar ah? (en el ExpansionFile
708
         * por haber sido a?adida o modificada. Si ha sido a?adida, entonces hay
709
         * que respetar su estatus para que los writers puedan saber que es
710
         * un registro NUEVO).
711 7271 jaume
         *
712 4792 fjp
         * @param index
713
         *            DOCUMENT ME!
714
         * @param feat
715
         *            DOCUMENT ME!
716 7271 jaume
         *
717 4792 fjp
         * @return DOCUMENT ME!
718 10627 caballero
         * @throws ExpansionFileWriteException
719
         * @throws ReadDriverException
720
         * @throws ExpansionFileReadException
721 7271 jaume
         *
722 4792 fjp
         */
723 10627 caballero
        public int doModifyRow(int index, IRow feat, int sourceType) throws ExpansionFileWriteException, ReadDriverException, ExpansionFileReadException {
724 6212 fjp
                boolean cancel = fireBeforeModifyRow(feat, index, sourceType);
725 5077 caballero
                if (cancel)
726
                        return -1;
727
728 4792 fjp
                int pos = -1;
729
                Integer integer = new Integer(index);
730 10207 caballero
//                System.err.println("Modifica una Row en la posici?n: " + index);
731 4792 fjp
                // Si la geometr?a no ha sido modificada
732
                if (!relations.containsKey(integer)) {
733 6212 fjp
                        int expansionIndex = expansionFile.addRow(feat,
734
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
735 4792 fjp
                        relations.put(integer, new Integer(expansionIndex));
736
                } else {
737
                        // Obtenemos el ?ndice en el fichero de expansi?n
738
                        int num = ((Integer) relations.get(integer)).intValue();
739
                        pos = num;
740 3940 caballero
741 4792 fjp
                        /*
742
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
743
                         * fichero de expansi?n en el que se encuentra la geometr?a
744
                         * modificada
745
                         */
746 6212 fjp
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
747 3940 caballero
748 4792 fjp
                        /*
749
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
750
                         * fichero de expansi?n.
751
                         */
752
                        relations.put(integer, new Integer(num));
753
                }
754 7271 jaume
                isFullExtentDirty = true;
755 10287 caballero
                //fireAfterModifyRow(index, sourceType);
756 4792 fjp
                return pos;
757
        }
758 3940 caballero
759 4792 fjp
        /**
760
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
761
         * en la tabla relations.
762 7271 jaume
         *
763 4792 fjp
         * @param feat
764
         *            geometr?a a guardar.
765 7271 jaume
         *
766 4792 fjp
         * @return calculatedIndex
767 10627 caballero
         * @throws ExpansionFileWriteException
768 4792 fjp
         * @throws DriverIOException
769
         * @throws IOException
770
         */
771 10627 caballero
        public int doAddRow(IRow feat, int sourceType) throws ReadDriverException, ExpansionFileWriteException  {
772 5184 caballero
                boolean cancel = fireBeforeRowAdded(sourceType);
773 5077 caballero
                if (cancel)
774
                        return -1;
775 4792 fjp
                // A?ade la geometr?a
776
                // int virtualIndex = 0;
777
                int calculatedIndex = -1;
778
779 10627 caballero
                calculatedIndex = (int) ods.getRowCount() + numAdd;
780 4792 fjp
781 6212 fjp
                int pos = expansionFile.addRow(feat, IRowEdited.STATUS_ADDED, actualIndexFields);
782 4792 fjp
                relations.put(new Integer(calculatedIndex), new Integer(pos));
783
                numAdd++;
784
                System.err.println("A?ade una Row en la posici?n: " + calculatedIndex);
785 7271 jaume
                isFullExtentDirty = true;
786 7231 jorpiell
                fireAfterRowAdded(feat,calculatedIndex, sourceType);
787 4792 fjp
                return calculatedIndex;
788 4061 caballero
        }
789 3996 caballero
790 4792 fjp
        /**
791
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
792
         * en el fichero original
793 7271 jaume
         *
794 4792 fjp
         * @param index
795
         *            DOCUMENT ME!
796
         */
797 10627 caballero
        public void undoRemoveRow(int index, int sourceType) throws EditionCommandException {
798
                boolean cancel;
799
                try {
800
                        cancel = fireBeforeRowAdded(sourceType);
801
                } catch (ReadDriverException e) {
802
                        throw new EditionCommandException(writer.getName(),e);
803
                }
804 5077 caballero
                if (cancel)
805
                        return;
806 4792 fjp
                delRows.set(index, false);
807 7231 jorpiell
                fireAfterRowAdded(null,index, sourceType);
808 4792 fjp
        }
809 3996 caballero
810 4792 fjp
        /**
811
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
812
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
813
         * relaci?n del mapa de relaciones
814 7271 jaume
         *
815 4792 fjp
         * @param index
816
         *            ?ndice de la geometr?a que se a?adi?
817
         * @throws DriverIOException
818
         * @throws IOException
819
         */
820 6212 fjp
        public void undoAddRow(int calculatedIndex, int sourceType)
821 10627 caballero
                        throws EditionCommandException {
822 6212 fjp
                boolean cancel = fireBeforeRemoveRow(calculatedIndex, sourceType);
823 5077 caballero
                if (cancel)
824
                        return;
825 4792 fjp
                expansionFile.deleteLastRow();
826
                relations.remove(new Integer(calculatedIndex));
827
                numAdd--;
828 6212 fjp
                fireAfterRemoveRow(calculatedIndex, sourceType);
829 4792 fjp
        }
830 3996 caballero
831 4792 fjp
        /*
832
         * (non-Javadoc)
833 7271 jaume
         *
834 4792 fjp
         * @see com.iver.cit.gvsig.fmap.layers.VectorialAdapter#getRecordset()
835
         */
836 10627 caballero
        public SelectableDataSource getRecordset() throws ReadDriverException  {
837 4792 fjp
                if (isEditing) {
838
                        if (ds == null) {
839
                                String name = LayerFactory.getDataSourceFactory()
840 10627 caballero
                                                .addDataSource(editingDriver);
841 3996 caballero
842 4792 fjp
                                try {
843 7271 jaume
844 4792 fjp
                                        ds = new SelectableDataSource(LayerFactory
845
                                                        .getDataSourceFactory().createRandomDataSource(
846 6313 fjp
                                                                        name, DataSourceFactory.MANUAL_OPENING));
847
                                        ds.start();
848 4792 fjp
                                        ds.setSelectionSupport(ods.getSelectionSupport());
849 3940 caballero
850 4792 fjp
                                } catch (NoSuchTableException e) {
851
                                        throw new RuntimeException(e);
852 10665 caballero
                                } catch (DriverLoadException e) {
853
                                        throw new ReadDriverException(name,e);
854 4792 fjp
                                }
855
                        }
856 3940 caballero
857 4792 fjp
                        return ds;
858
                }
859 10627 caballero
                return ods;
860 4792 fjp
        }
861 10207 caballero
862 9766 azabala
        /**
863
         * Return always the original recordset (even when is editing,
864
         * nor the getRecorset() method)
865 10207 caballero
         *
866 9766 azabala
         * */
867
        public SelectableDataSource getOriginalRecordset(){
868
                return ods;
869
        }
870 3940 caballero
871
872 4792 fjp
        /**
873
         * DOCUMENT ME!
874 7271 jaume
         *
875 4792 fjp
         * @return
876 10627 caballero
         * @throws ReadDriverException
877 4792 fjp
         */
878 10627 caballero
        public FBitSet getSelection() throws ReadDriverException {
879 4792 fjp
                /*
880
                 * try { return getRecordset().getSelection(); } catch
881
                 * (DriverLoadException e) { // TODO Auto-generated catch block
882
                 * e.printStackTrace(); } return null;
883
                 */
884
                return getRecordset().getSelection();
885
        }
886 3940 caballero
887 10627 caballero
        public void setSelection(FBitSet selection) throws ReadDriverException {
888 4792 fjp
                /*
889
                 * try { getRecordset().setSelection(selection); } catch
890
                 * (DriverLoadException e) { // TODO Auto-generated catch block
891
                 * e.printStackTrace(); }
892
                 */
893
                getRecordset().setSelection(selection);
894
        }
895 3940 caballero
896 4792 fjp
        /**
897
         * DOCUMENT ME!
898 7271 jaume
         *
899 4792 fjp
         * @return DOCUMENT ME!
900
         */
901
        public boolean isEditing() {
902
                return isEditing;
903
        }
904 3996 caballero
905 5986 caballero
        public int getInversedIndex(long rowIndex) {
906 4792 fjp
                int intervalNotDeleted = 0;
907
                int antDeleted = -1;
908
                int idPedido = (int) rowIndex;
909
                int numNotDeleted = 0;
910
                int numBorradosAnt = 0;
911 3996 caballero
912 4792 fjp
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
913
                                .nextSetBit(i + 1)) {
914
                        intervalNotDeleted = i - antDeleted - 1;
915
                        numNotDeleted += intervalNotDeleted;
916
                        if (i > idPedido) {
917
                                numNotDeleted = numNotDeleted + (i - idPedido);
918
                                break;
919
                        }
920
                        numBorradosAnt++;
921
                        antDeleted = i;
922
                }
923
                numNotDeleted = idPedido - numBorradosAnt;
924
                // System.out.println("Piden Viejo : "+ rowIndex + " y devuelvo como
925
                // nuevo " + (numNotDeleted));
926
                return numNotDeleted;
927
        }
928 3940 caballero
929 4792 fjp
        /**
930
         * DOCUMENT ME!
931 7271 jaume
         *
932 4792 fjp
         * @param rowIndex
933
         *            DOCUMENT ME!
934 7271 jaume
         *
935 4792 fjp
         * @return DOCUMENT ME!
936
         */
937 4954 caballero
        public int getCalculatedIndex(long rowIndex) {
938 4792 fjp
                int numNotDeleted = 0;
939
                int intervalNotDeleted = 0;
940
                int antDeleted = -1;
941
                int calculatedIndex;
942
                int idPedido = (int) rowIndex;
943
                int numBorradosAnt = 0;
944 3940 caballero
945 4792 fjp
                for (int i = delRows.nextSetBit(0); i >= 0; i = delRows
946
                                .nextSetBit(i + 1)) {
947
                        intervalNotDeleted = i - antDeleted - 1;
948
                        numNotDeleted += intervalNotDeleted;
949
                        if (numNotDeleted > idPedido) {
950
                                break;
951
                        }
952
                        numBorradosAnt++;
953
                        antDeleted = i;
954
                }
955
                calculatedIndex = numBorradosAnt + idPedido;
956
                // System.out.println("Piden Registro : "+ rowIndex + " y devuelvo el "
957
                // + (calculatedIndex));
958
                return calculatedIndex;
959
        }
960 3940 caballero
961 4792 fjp
        /**
962
         * DOCUMENT ME!
963 7271 jaume
         *
964 4792 fjp
         * @author Vicente Caballero Navarro
965
         */
966
        private class myObjectDriver implements ObjectDriver {
967
                /*
968
                 * (non-Javadoc)
969 7271 jaume
                 *
970 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#getPrimaryKeys()
971
                 */
972 10627 caballero
                public int[] getPrimaryKeys() throws ReadDriverException {
973 4792 fjp
                        return ods.getPrimaryKeys();
974
                        // int[] pk=new int[1];
975
                        /*
976
                         * for (int i=0;i<getRowCount();i++){ pk[i]=i; }
977
                         */
978
                        // pk[0]=1;
979
                        // return pk;
980
                }
981 3996 caballero
982 4792 fjp
                /*
983
                 * (non-Javadoc)
984 7271 jaume
                 *
985 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ObjectDriver#write(com.hardcode.gdbms.engine.data.edition.DataWare)
986
                 */
987 10627 caballero
                public void write(DataWare dataWare) throws ReadDriverException, WriteDriverException {
988 4792 fjp
                        DataWare dataWareOrig = ods
989
                                        .getDataWare(DataSourceFactory.DATA_WARE_DIRECT_MODE);
990
                        dataWareOrig.commitTrans();
991
                }
992 3940 caballero
993 4792 fjp
                /*
994
                 * (non-Javadoc)
995 7271 jaume
                 *
996 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.GDBMSDriver#setDataSourceFactory(com.hardcode.gdbms.engine.data.DataSourceFactory)
997
                 */
998
                public void setDataSourceFactory(DataSourceFactory dsf) {
999
                        ods.setDataSourceFactory(dsf);
1000
                }
1001
1002
                /*
1003
                 * (non-Javadoc)
1004 7271 jaume
                 *
1005 4792 fjp
                 * @see com.hardcode.driverManager.Driver#getName()
1006
                 */
1007
                public String getName() {
1008
                        return ods.getName();
1009
                }
1010
1011
                /*
1012
                 * (non-Javadoc)
1013 7271 jaume
                 *
1014 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldValue(long,
1015
                 *      int)
1016
                 */
1017 10627 caballero
                public Value getFieldValue(long rowIndex, int fieldId) throws ReadDriverException {
1018 4792 fjp
                        // Si no est? en el fichero de expansi?n
1019 6259 fjp
                        // Integer integer = new Integer(getCalculatedIndex(rowIndex));
1020 4792 fjp
1021 6259 fjp
1022 4792 fjp
                        try {
1023 6259 fjp
                                IRow row = getRow((int)rowIndex);
1024
                                return row.getAttribute(fieldId);
1025
//                                if (!relations.containsKey(integer)) {
1026
//                                        return ods.getFieldValue(rowIndex, fieldId);
1027
//                                } else {
1028
//                                        int num = ((Integer) relations.get(integer)).intValue();
1029
//                                        DefaultRowEdited feat = (DefaultRowEdited) expansionFile
1030
//                                                        .getRow(num);
1031
//
1032
//                                        if (feat == null) {
1033
//                                                return null;
1034
//                                        }
1035
//
1036
//                                        return feat.getAttribute(fieldId);
1037
//                                }
1038
//                        } catch (DriverException e) {
1039
//                                e.printStackTrace();
1040
//                                throw new DriverException(e);
1041 10627 caballero
                        } catch (ExpansionFileReadException e) {
1042
                                throw new ReadDriverException(getRecordset().getDriver().getName(),e);
1043 4792 fjp
                        }
1044
1045
                        /**
1046
                         * try { if (!relations.containsKey(integer)) { // Si ha sido
1047
                         * eliminada if (delRows.get(integer.intValue())) { return null; }
1048
                         * else { return ods.getFieldValue(rowIndex, fieldId); }} else { int
1049
                         * num = ((Integer) relations.get(integer)).intValue();
1050
                         * DefaultRowEdited feat = (DefaultRowEdited)
1051
                         * expansionFile.getRow(num); if (feat==null)return null; return
1052
                         * feat.getAttribute(fieldId); }} catch (DriverException e) {
1053
                         * e.printStackTrace(); throw new DriverException(e); } catch
1054
                         * (IOException e) { e.printStackTrace(); throw new
1055
                         * DriverException(e); }
1056
                         */
1057
                }
1058
1059
                /*
1060
                 * (non-Javadoc)
1061 7271 jaume
                 *
1062 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldCount()
1063
                 */
1064 10627 caballero
                public int getFieldCount() throws ReadDriverException {
1065 6483 fjp
                        return fastAccessFields.size();
1066 4792 fjp
                }
1067
1068
                /*
1069
                 * (non-Javadoc)
1070 7271 jaume
                 *
1071 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldName(int)
1072
                 */
1073 10627 caballero
                public String getFieldName(int fieldId) throws ReadDriverException {
1074 6483 fjp
//                        int i=0;
1075
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1076
//                                InternalField fld = (InternalField) iter.next();
1077
//                                if (i == fieldId)
1078 6384 fjp
//                                        return fld.getFieldDesc().getFieldAlias();
1079 6483 fjp
//                                i++;
1080 7271 jaume
//
1081 6483 fjp
//                        }
1082
//                        throw new DriverException("FieldId " + fieldId + " not found ");
1083
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1084
                        return aux.getFieldAlias();
1085 6259 fjp
                        // return null;
1086
                        // return ods.getFieldName(fieldId);
1087 4792 fjp
                }
1088
1089
                /*
1090
                 * (non-Javadoc)
1091 7271 jaume
                 *
1092 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getRowCount()
1093
                 */
1094 10627 caballero
                public long getRowCount() throws ReadDriverException {
1095
                        return (int) (ods.getRowCount() + numAdd)
1096
                                        - delRows.cardinality();// -
1097
                        // expansionFile.getInvalidRows().cardinality();
1098 4792 fjp
                }
1099
1100
                /*
1101
                 * (non-Javadoc)
1102 7271 jaume
                 *
1103 4792 fjp
                 * @see com.hardcode.gdbms.engine.data.driver.ReadAccess#getFieldType(int)
1104
                 */
1105 10627 caballero
                public int getFieldType(int fieldId) throws ReadDriverException {
1106 6483 fjp
//                        int i=0;
1107
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1108
//                                InternalField fld = (InternalField) iter.next();
1109
//                                if (i == fieldId)
1110 6384 fjp
//                                        return fld.getFieldDesc().getFieldType();
1111 6483 fjp
//                                i++;
1112 7271 jaume
//
1113 6483 fjp
//                        }
1114
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1115
                        return aux.getFieldType();
1116 7271 jaume
1117 6483 fjp
//                        return ods.getFieldType(i);
1118 4792 fjp
                }
1119 4863 fjp
1120 10627 caballero
                public int getFieldWidth(int fieldId) throws ReadDriverException {
1121 6483 fjp
//                        int i=0;
1122 7271 jaume
//                        for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1123 6483 fjp
//                                InternalField fld = (InternalField) iter.next();
1124
////                                if (fld.getFieldIndex() == i)
1125
////                                        return fld.getFieldDesc().getFieldLength();
1126
//                                if (i == fieldId)
1127 6384 fjp
//                                        return fld.getFieldDesc().getFieldLength();
1128 6483 fjp
//                                i++;
1129 7271 jaume
//
1130 6483 fjp
//                        }
1131
//
1132
//                        return ods.getFieldWidth(i);
1133
                        FieldDescription aux = (FieldDescription) fastAccessFields.get(fieldId);
1134
                        return aux.getFieldLength();
1135 6259 fjp
1136 4863 fjp
                }
1137 6323 fjp
1138 10627 caballero
                public void reload() throws ReloadDriverException {
1139 6323 fjp
                        ods.reload();
1140 7271 jaume
1141 6323 fjp
                }
1142 4792 fjp
        }
1143
1144
        public CommandRecord getCommandRecord() {
1145
                return cr;
1146
        }
1147 4832 fjp
1148 6212 fjp
        protected void fireAfterRemoveRow(int index, int sourceType) {
1149
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1150
                                EditionEvent.CHANGE_TYPE_DELETE, sourceType);
1151 10342 caballero
                if (complex){
1152
                        rowEvents.add(event);
1153 10207 caballero
                        return;
1154
                }
1155 6212 fjp
                for (int i = 0; i < editionListeners.size(); i++) {
1156
                        IEditionListener listener = (IEditionListener) editionListeners
1157
                                        .get(i);
1158 6689 caballero
                        listener.afterRowEditEvent(null, event);
1159 4832 fjp
                }
1160 4954 caballero
1161 4832 fjp
        }
1162
1163 6212 fjp
        protected boolean fireBeforeRemoveRow(int index, int sourceType) {
1164 4832 fjp
                Cancel cancel = new Cancel();
1165 6212 fjp
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1166
                                EditionEvent.CHANGE_TYPE_DELETE, cancel, sourceType);
1167
                for (int i = 0; i < editionListeners.size(); i++) {
1168
                        IEditionListener listener = (IEditionListener) editionListeners
1169
                                        .get(i);
1170
                        listener.beforeRowEditEvent(null, event);
1171 4832 fjp
                        if (cancel.isCanceled())
1172
                                return true;
1173
                }
1174
                return false;
1175
        }
1176
1177 7231 jorpiell
        protected void fireAfterRowAdded(IRow feat,int calculatedIndex, int sourceType) {
1178 6212 fjp
                AfterRowEditEvent event = new AfterRowEditEvent(this, calculatedIndex,
1179
                                EditionEvent.CHANGE_TYPE_ADD, sourceType);
1180 10342 caballero
                if (complex){
1181
                        rowEvents.add(event);
1182 10207 caballero
                        return;
1183
                }
1184 6212 fjp
                for (int i = 0; i < editionListeners.size(); i++) {
1185
                        IEditionListener listener = (IEditionListener) editionListeners
1186
                                        .get(i);
1187 7231 jorpiell
                        listener.afterRowEditEvent(feat, event);
1188 4954 caballero
                }
1189 4832 fjp
        }
1190
1191 6335 fjp
        protected void fireAfterFieldAdded(FieldDescription field) {
1192
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1193
                                EditionEvent.CHANGE_TYPE_ADD);
1194 10207 caballero
                if (complex) {
1195 10342 caballero
                        fieldEvents.add(event);
1196 10207 caballero
                        return;
1197
                }
1198 6335 fjp
                for (int i = 0; i < editionListeners.size(); i++) {
1199
                        IEditionListener listener = (IEditionListener) editionListeners
1200
                                        .get(i);
1201
                        listener.afterFieldEditEvent(event);
1202 10207 caballero
1203 6335 fjp
                }
1204
        }
1205
1206
        protected void fireAfterFieldRemoved(FieldDescription field) {
1207
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1208
                                EditionEvent.CHANGE_TYPE_DELETE);
1209 10207 caballero
                if (complex) {
1210 10342 caballero
                        fieldEvents.add(event);
1211 10207 caballero
                        return;
1212
                }
1213 6335 fjp
                for (int i = 0; i < editionListeners.size(); i++) {
1214
                        IEditionListener listener = (IEditionListener) editionListeners
1215
                                        .get(i);
1216
                        listener.afterFieldEditEvent(event);
1217
                }
1218
        }
1219
1220 6399 fjp
        protected void fireAfterFieldModified(FieldDescription field) {
1221
                AfterFieldEditEvent event = new AfterFieldEditEvent(this,field,
1222
                                EditionEvent.CHANGE_TYPE_MODIFY);
1223 10207 caballero
                if (complex) {
1224 10342 caballero
                        fieldEvents.add(event);
1225 10207 caballero
                        return;
1226
                }
1227 6399 fjp
                for (int i = 0; i < editionListeners.size(); i++) {
1228
                        IEditionListener listener = (IEditionListener) editionListeners
1229
                                        .get(i);
1230
                        listener.afterFieldEditEvent(event);
1231
                }
1232
        }
1233 7271 jaume
1234
1235 10627 caballero
        protected boolean fireBeforeRowAdded(int sourceType) throws ReadDriverException{
1236 4832 fjp
                Cancel cancel = new Cancel();
1237 12099 caballero
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, getNewIndex(),
1238 6212 fjp
                                EditionEvent.CHANGE_TYPE_ADD, cancel, sourceType);
1239
                for (int i = 0; i < editionListeners.size(); i++) {
1240
                        IEditionListener listener = (IEditionListener) editionListeners
1241
                                        .get(i);
1242
                        listener.beforeRowEditEvent(null, event);
1243 4832 fjp
                        if (cancel.isCanceled())
1244
                                return true;
1245
                }
1246
                return false;
1247
        }
1248
1249 10627 caballero
        protected boolean fireBeforeFieldAdded(FieldDescription field) {
1250 6335 fjp
                Cancel cancel = new Cancel();
1251
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1252
                EditionEvent.CHANGE_TYPE_ADD, cancel);
1253
                for (int i = 0; i < editionListeners.size(); i++) {
1254
                        IEditionListener listener = (IEditionListener) editionListeners
1255
                        .get(i);
1256
                        listener.beforeFieldEditEvent(event);
1257
                        if (cancel.isCanceled())
1258
                                return true;
1259
                }
1260
                return false;
1261
        }
1262
1263 10627 caballero
        protected boolean fireBeforeRemoveField(FieldDescription field){
1264 6335 fjp
                Cancel cancel = new Cancel();
1265
                BeforeFieldEditEvent event = new BeforeFieldEditEvent(this, field,
1266
                EditionEvent.CHANGE_TYPE_DELETE, cancel);
1267
                for (int i = 0; i < editionListeners.size(); i++) {
1268
                        IEditionListener listener = (IEditionListener) editionListeners
1269
                        .get(i);
1270
                        listener.beforeFieldEditEvent(event);
1271
                        if (cancel.isCanceled())
1272
                                return true;
1273
                }
1274
                return false;
1275
        }
1276
1277 7271 jaume
1278 6212 fjp
        protected boolean fireBeforeModifyRow(IRow feat, int index, int sourceType) {
1279 4832 fjp
                Cancel cancel = new Cancel();
1280 6212 fjp
                BeforeRowEditEvent event = new BeforeRowEditEvent(this, index,
1281
                                EditionEvent.CHANGE_TYPE_MODIFY, cancel, sourceType);
1282
                for (int i = 0; i < editionListeners.size(); i++) {
1283
                        IEditionListener listener = (IEditionListener) editionListeners
1284
                                        .get(i);
1285 5197 caballero
                        listener.beforeRowEditEvent(feat, event);
1286 4832 fjp
                        if (cancel.isCanceled())
1287
                                return true;
1288
                }
1289
                return false;
1290
        }
1291
1292 6212 fjp
        protected void fireAfterModifyRow(int index, int sourceType) {
1293
                AfterRowEditEvent event = new AfterRowEditEvent(this, index,
1294
                                EditionEvent.CHANGE_TYPE_MODIFY, sourceType);
1295 10342 caballero
                if (complex){
1296
                        rowEvents.add(event);
1297
                        return;
1298
                }
1299 6212 fjp
                for (int i = 0; i < editionListeners.size(); i++) {
1300
                        IEditionListener listener = (IEditionListener) editionListeners
1301
                                        .get(i);
1302 6689 caballero
                        listener.afterRowEditEvent(null, event);
1303 4954 caballero
                }
1304 4832 fjp
1305
        }
1306
1307 5184 caballero
        protected void fireStartEditionEvent(int sourceType) {
1308 6212 fjp
                EditionEvent ev = new EditionEvent(this, EditionEvent.START_EDITION,
1309
                                sourceType);
1310
                for (int i = 0; i < editionListeners.size(); i++) {
1311
                        IEditionListener listener = (IEditionListener) editionListeners
1312
                                        .get(i);
1313 4832 fjp
                        listener.processEvent(ev);
1314 4954 caballero
                }
1315
1316 4832 fjp
        }
1317
1318 5184 caballero
        protected void fireStopEditionEvent(int sourceType) {
1319 6212 fjp
                EditionEvent ev = new EditionEvent(this, EditionEvent.STOP_EDITION,
1320
                                sourceType);
1321
                for (int i = 0; i < editionListeners.size(); i++) {
1322
                        IEditionListener listener = (IEditionListener) editionListeners
1323
                                        .get(i);
1324 4832 fjp
                        listener.processEvent(ev);
1325 4954 caballero
                }
1326
1327 4832 fjp
        }
1328
1329 5184 caballero
        protected void fireCancelEditionEvent(int sourceType) {
1330 6212 fjp
                EditionEvent ev = new EditionEvent(this, EditionEvent.CANCEL_EDITION,
1331
                                sourceType);
1332
                for (int i = 0; i < editionListeners.size(); i++) {
1333
                        IEditionListener listener = (IEditionListener) editionListeners
1334
                                        .get(i);
1335 4832 fjp
                        listener.processEvent(ev);
1336 4954 caballero
                }
1337
1338 4832 fjp
        }
1339 4954 caballero
1340 6212 fjp
        public void addEditionListener(IEditionListener listener) {
1341 5111 caballero
                if (!editionListeners.contains(listener))
1342
                        editionListeners.add(listener);
1343 4832 fjp
        }
1344
1345 6212 fjp
        public void removeEditionListener(IEditionListener listener) {
1346 4832 fjp
                editionListeners.remove(listener);
1347
        }
1348 4954 caballero
1349 5549 fjp
        public IWriter getWriter() {
1350
                return writer;
1351
        }
1352
1353 6212 fjp
        protected void setWriter(IWriter writer) {
1354 5549 fjp
                this.writer = writer;
1355 5986 caballero
1356 5549 fjp
        }
1357 9766 azabala
        /*
1358
         * azabala: esto funciona para todos los drivers gdbms
1359
         * salvo para MySQL, que necesita que el ITableDefinition
1360
         * contenga el nombre de la tabla (y por tanto requiere
1361
         * DBLayerDefinition-en realidad hace falta DBTableDefinition)
1362
         * TODO REVISAR LA ARQUITECTURA DE ESTO
1363 10207 caballero
         *
1364 9766 azabala
         * */
1365 10627 caballero
        public ITableDefinition getTableDefinition() throws ReadDriverException {
1366 9766 azabala
                Driver originalDriver = getOriginalDriver();
1367
                if(! (originalDriver instanceof AlphanumericDBDriver)){
1368
                        TableDefinition tableDef = new TableDefinition();
1369
                        tableDef.setFieldsDesc(getRecordset().getFieldsDescription());
1370
                        tableDef.setName(getRecordset().getSourceInfo().name);
1371
                        return tableDef;
1372
                }
1373 10627 caballero
                AlphanumericDBDriver dbDriver = (AlphanumericDBDriver)originalDriver;
1374
                return dbDriver.getTableDefinition();
1375 10207 caballero
1376
1377 5558 fjp
        }
1378
1379 10627 caballero
        public void validateRow(IRow row,int sourceType) throws ValidateRowException  {
1380 6212 fjp
                for (int i = 0; i < rules.size(); i++) {
1381 5886 fjp
                        IRule rule = (IRule) rules.get(i);
1382 10207 caballero
                        boolean bAux = rule.validate(row,sourceType);
1383 6212 fjp
                        if (bAux == false) {
1384 10627 caballero
                                ValidateRowException ex = new ValidateRowException(writer.getName(),null);
1385 6002 fjp
                                // TODO: Lanzar una RuleException con datos como el registro
1386
                                // que no cumple, la regla que no lo ha cumplido, etc.
1387 6071 caballero
                                throw ex;
1388 6002 fjp
                        }
1389 5886 fjp
                }
1390
        }
1391
1392
        public ArrayList getRules() {
1393
                return rules;
1394
        }
1395
1396
        public void setRules(ArrayList rules) {
1397
                this.rules = rules;
1398
        }
1399 6212 fjp
1400 10627 caballero
        private void clean() throws ReadDriverException {
1401
                try {
1402
                        expansionFile.close();
1403
                } catch (CloseExpansionFileException e) {
1404
                        throw new ReadDriverException(getRecordset().getDriver().getName(),e);
1405
                }
1406 6127 fjp
                relations.clear();
1407
                numAdd = 0;
1408
                delRows.clear();
1409 6313 fjp
                // TODO: Es muy probable que necesitemos un reload de los datasources, al
1410
                // igual que lo tenemos en las capas. Por ahora, basta con retocar
1411
                // listInternalFields, pero casi seguro que lo correcto ser?a hacer un
1412
                // reload completo.
1413
                initalizeFields(ods);
1414 7271 jaume
1415 6313 fjp
//                listInternalFields.clear();
1416
//                listInternalFields.add(actualFields);
1417 6127 fjp
        }
1418 5886 fjp
1419 6212 fjp
        /*
1420
         * (non-Javadoc)
1421 7271 jaume
         *
1422 6212 fjp
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getFieldManager()
1423
         */
1424
        public IFieldManager getFieldManager() {
1425 6356 fjp
                if (ods.getDriver() instanceof IWriteable)
1426
                {
1427
                        IWriter writer = ((IWriteable)ods.getDriver()).getWriter();
1428
                        if ((writer != null) && (writer instanceof IFieldManager))
1429
                        {
1430 6628 fjp
                                IFieldManager fldManager = (IFieldManager) writer;
1431
                                return fldManager;
1432 6356 fjp
                        }
1433
                }
1434 6212 fjp
                return null;
1435
        }
1436
1437
        /**
1438
         * Tiene en cuenta los campos actuales para formatear una row con ellos. Le
1439
         * pasamos los campos que hab?a en el momento en que se cre? esa row.
1440 7271 jaume
         *
1441 6212 fjp
         * @param edRow
1442
         * @param indexInternalFields
1443
         * @return
1444
         */
1445
        public IRowEdited createExternalRow(IRowEdited edRow,
1446
                        int indexInternalFields) {
1447 7271 jaume
1448 6483 fjp
                // para acelerar
1449
                if (bFieldsHasBeenChanged == false)
1450
                        return edRow;
1451 7271 jaume
1452 6212 fjp
                Value[] att = edRow.getAttributes();
1453
                TreeMap ancientFields = (TreeMap) listInternalFields
1454
                                .get(indexInternalFields);
1455
                Value[] newAtt = new Value[actualFields.size()];
1456
                Collection aux = actualFields.values();
1457
                Iterator it = aux.iterator();
1458
                int i = 0;
1459
                Value val = null;
1460
                while (it.hasNext()) {
1461 6384 fjp
                        // Para cada campo de los actuales, miramos si ya estaba cuando
1462 7271 jaume
                        // el registro estaba guardado.
1463 6384 fjp
                        // Si estaba, cogemos el valor de ese campo en el registro
1464
                        // guardado. Si no estaba, ha sido a?adido despu?s y ponemos
1465
                        // su valor por defecto.
1466
                        // Nota importante: fieldIndex es el ?ndice del campo cuando
1467
                        // se guard?. NO es el ?ndice actual dentro de actualFields.
1468
                        // Se usa SOLO para recuperar el valor de los atributos
1469
                        // antiguos. Por eso no nos preocupamos de mantener actuallizados
1470
                        // el resto de campos cuando se borra o a?ade un nuevo campo.
1471 6212 fjp
                        InternalField fld = (InternalField) it.next();
1472 6483 fjp
                        // System.err.println("fld = " + fld.getFieldDesc().getFieldAlias() +  " id=" + fld.getFieldId());
1473 6212 fjp
                        if (ancientFields.containsKey(fld.getFieldId())) {
1474
                                InternalField ancientField = (InternalField) ancientFields
1475
                                                .get(fld.getFieldId());
1476 6839 fjp
                                val = att[ancientField.getFieldIndex()];
1477
                                // val = att[ancientField.getFieldId().intValue()];
1478 6483 fjp
                                // System.out.println("fld: " + fld.getFieldDesc().getFieldAlias() + " ancient:" + " val" + val);
1479 6212 fjp
                        } else
1480
                                val = fld.getFieldDesc().getDefaultValue();
1481 6227 fjp
                        newAtt[i++] = val;
1482 6212 fjp
                }
1483
                IRowEdited newRow = (IRowEdited) edRow.cloneRow();
1484
                newRow.setAttributes(newAtt);
1485
                return newRow;
1486
        }
1487
1488 10627 caballero
        public void removeField(String fieldName) throws WriteDriverException, ReadDriverException {
1489 6212 fjp
1490
                InternalField fld = findFieldByName(fieldName);
1491 6259 fjp
                if (fld == null)
1492 10627 caballero
                        throw new WriteDriverException(getRecordset().getDriver().getName(),null);
1493
                //throw new WriteDriverException("Field " + fieldName + " not found when removing field");
1494 6212 fjp
                Command command = new RemoveFieldCommand(this, fld);
1495
                if (complex) {
1496
                        commands.add(command);
1497
                } else {
1498
                        cr.pushCommand(command);
1499
                }
1500
                doRemoveField(fld);
1501
1502
        }
1503
1504
        private InternalField findFieldByName(String fieldName) {
1505
                Collection aux = actualFields.values();
1506
                Iterator it = aux.iterator();
1507
                while (it.hasNext()) {
1508
                        InternalField fld = (InternalField) it.next();
1509 6399 fjp
                        if (fld.getFieldDesc().getFieldAlias().compareToIgnoreCase(fieldName) == 0)
1510 6212 fjp
                                return fld;
1511
                }
1512 7271 jaume
1513 6212 fjp
                return null;
1514
        }
1515
1516 10627 caballero
        public void undoRemoveField(InternalField field) throws EditionCommandException {
1517 6384 fjp
                // field.setDeleted(false);
1518
//                field.setFieldIndex(actualFields.size());
1519 6212 fjp
                actualFields.put(field.getFieldId(), field);
1520 10627 caballero
                try {
1521
                        fieldsChanged();
1522
                } catch (ReadDriverException e) {
1523
                        throw new EditionCommandException(writer.getName(),e);
1524
                }
1525 6356 fjp
                fireAfterFieldAdded(field.getFieldDesc());
1526 6212 fjp
        }
1527
1528 10627 caballero
        public void doRemoveField(InternalField field) throws ReadDriverException {
1529 6335 fjp
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1530
                if (cancel) return;
1531 6212 fjp
                actualFields.remove(field.getFieldId());
1532
                fieldsChanged();
1533 6335 fjp
                fireAfterFieldRemoved(field.getFieldDesc());
1534 6212 fjp
        }
1535
1536 10627 caballero
        public void renameField(String antName, String newName) throws ReadDriverException{
1537 6212 fjp
1538
                InternalField fld = findFieldByName(antName);
1539
                Command command = new RenameFieldCommand(this, fld, newName);
1540
                if (complex) {
1541
                        commands.add(command);
1542
                } else {
1543
                        cr.pushCommand(command);
1544
                }
1545
                doRenameField(fld, newName);
1546
1547
        }
1548 7271 jaume
1549 10627 caballero
        public void undoRenameField(InternalField field, String antName) throws EditionCommandException{
1550 6621 fjp
                field.getFieldDesc().setFieldAlias(antName);
1551 10627 caballero
                try {
1552
                        fieldsChanged();
1553
                } catch (ReadDriverException e) {
1554
                        throw new EditionCommandException(writer.getName(),e);
1555
                }
1556 6399 fjp
                fireAfterFieldModified(field.getFieldDesc());
1557
1558 6212 fjp
        }
1559
1560 10627 caballero
        public void doRenameField(InternalField field, String newName) throws ReadDriverException{
1561 6621 fjp
                field.getFieldDesc().setFieldAlias(newName);
1562 6399 fjp
                fieldsChanged();
1563
                fireAfterFieldModified(field.getFieldDesc());
1564
1565 6212 fjp
        }
1566
1567
1568 10627 caballero
        public void addField(FieldDescription field) throws ReadDriverException {
1569 6212 fjp
1570
                InternalField fld = new InternalField(field, InternalField.ADDED, new Integer(listFields.size()));
1571
                Command command = new AddFieldCommand(this, fld);
1572
                if (complex) {
1573
                        commands.add(command);
1574
                } else {
1575
                        cr.pushCommand(command);
1576
                }
1577
                listFields.add(fld);
1578
                doAddField(fld);
1579
1580
        }
1581
1582 10627 caballero
        public void undoAddField(InternalField field) throws EditionCommandException  {
1583 6335 fjp
                boolean cancel = fireBeforeRemoveField(field.getFieldDesc());
1584
                if (cancel)
1585
                        return;
1586
1587 6384 fjp
                // field.setDeleted(true);
1588 6227 fjp
                actualFields.remove(field.getFieldId());
1589 10627 caballero
                try {
1590
                        fieldsChanged();
1591
                } catch (ReadDriverException e) {
1592
                        throw new EditionCommandException(writer.getName(),e);
1593
                }
1594 6335 fjp
                fireAfterFieldRemoved(field.getFieldDesc());
1595 7271 jaume
1596 6212 fjp
        }
1597
1598 10627 caballero
        public int doAddField(InternalField field) throws ReadDriverException {
1599 6335 fjp
                boolean cancel;
1600
                cancel = fireBeforeFieldAdded(field.getFieldDesc());
1601
                if (cancel)
1602
                        return -1;
1603
1604 6384 fjp
                // field.setDeleted(false);
1605
//                field.setFieldIndex(actualFields.size());
1606 6227 fjp
                actualFields.put(field.getFieldId(), field);
1607 6212 fjp
                fieldsChanged();
1608 6335 fjp
                fireAfterFieldAdded(field.getFieldDesc());
1609 6384 fjp
//                return field.getFieldIndex();
1610
                return field.getFieldId().intValue();
1611 6212 fjp
        }
1612 7271 jaume
1613 6365 fjp
        public Driver getOriginalDriver()
1614 6356 fjp
        {
1615
                return ods.getDriver();
1616
        }
1617 7271 jaume
1618 6478 fjp
        /**
1619
         * Use it to be sure the recordset will have the right fields. It forces a new SelectableDataSource
1620
         * to be created next time it is needed
1621
         */
1622
        public void cleanSelectableDatasource() {
1623
                ds = null;
1624
        }
1625
1626 6628 fjp
        public FieldDescription[] getFieldsDescription() {
1627
                return (FieldDescription[]) fastAccessFields.toArray(new FieldDescription[0]);
1628
        }
1629 12099 caballero
        public int getNewIndex() throws ReadDriverException {
1630
                int index=(int)ods.getRowCount() + numAdd;
1631
                return index;
1632
        }
1633 6628 fjp
1634 6384 fjp
//        private InternalField getInternalFieldByIndex(int fieldId)
1635
//        {
1636
//                for (Iterator iter = actualFields.values().iterator(); iter.hasNext();) {
1637
//                        InternalField fld = (InternalField) iter.next();
1638
//                        if (fld.getFieldIndex() == fieldId)
1639
//                                return fld;
1640
//                }
1641
//                return null;
1642
//        }
1643 7271 jaume
1644 3940 caballero
}