Statistics
| Revision:

gvsig-tools / org.gvsig.tools / library / trunk / org.gvsig.tools / org.gvsig.tools.lib / src / main / java / org / gvsig / tools / persistence / impl / AbstractPersistentState.java @ 1276

History | View | Annotate | Download (28.4 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
/*
25
 * AUTHORS (In addition to CIT):
26
 * 2009 IVER T.I   {{Task}}
27
 */
28

    
29
package org.gvsig.tools.persistence.impl;
30

    
31
import org.gvsig.tools.util.FileTools;
32
import java.io.File;
33
import java.lang.reflect.Array;
34
import java.net.MalformedURLException;
35
import java.net.URI;
36
import java.net.URISyntaxException;
37
import java.net.URL;
38
import java.util.ArrayList;
39
import java.util.Arrays;
40
import java.util.Collection;
41
import java.util.Collections;
42
import java.util.Date;
43
import java.util.HashMap;
44
import java.util.Iterator;
45
import java.util.LinkedHashMap;
46
import java.util.LinkedHashSet;
47
import java.util.List;
48
import java.util.Map;
49
import java.util.Map.Entry;
50
import java.util.Set;
51
import java.util.regex.Pattern;
52
import org.apache.commons.io.FileUtils;
53

    
54
import org.gvsig.tools.dataTypes.DataTypes;
55
import org.gvsig.tools.dynobject.DynField;
56
import org.gvsig.tools.dynobject.DynStruct;
57
import org.gvsig.tools.persistence.PersistenceFactory;
58
import org.gvsig.tools.persistence.PersistenceManager;
59
import org.gvsig.tools.persistence.Persistent;
60
import org.gvsig.tools.persistence.PersistentContext;
61
import org.gvsig.tools.persistence.PersistentState;
62
import org.gvsig.tools.persistence.exception.PersistenceException;
63
import org.gvsig.tools.persistence.exception.PersistenceTypeNotSupportedException;
64
import org.gvsig.tools.persistence.impl.exception.PersistenceIllegalStateTheClassNameNotSetException;
65
import org.gvsig.tools.persistence.impl.exception.PersistenceInvalidPropertyNameException;
66
import org.gvsig.tools.persistence.impl.exception.PersistenceInvalidTypeForPropertyException;
67
import org.gvsig.tools.persistence.impl.exception.PersistenceUnsuportedMapKeyTypeException;
68
import org.gvsig.tools.persistence.impl.exception.PersistenceValueNotFoundException;
69
import org.gvsig.tools.persistence.spi.PersistenceManagerServices;
70
import org.gvsig.tools.persistence.spi.PersistentContextServices;
71
import org.gvsig.tools.persistence.spi.PersistentContextServices.ObjectReference;
72
import org.gvsig.tools.persistence.spi.PersistentIdentifier;
73
import org.gvsig.tools.persistence.spi.PersistentStateServices;
74
import org.slf4j.Logger;
75
import org.slf4j.LoggerFactory;
76

    
77
public abstract class AbstractPersistentState implements
78
                PersistentStateServices {
79

    
80
        private static final Logger logger = LoggerFactory
81
                        .getLogger(PersistentState.class);
82

    
83
        private static final Pattern VALID_NAME_PATTERN = Pattern
84
                        .compile("[\\w][\\d\\w_]*");
85

    
86
        private static final List validStdTypeClasses = Collections
87
                        .unmodifiableList(Arrays.asList(new Class[] { // All need to be
88
                                                                                                                        // immutable
89
                                        Integer.class, Long.class, Float.class, Double.class,
90
                                                        Boolean.class, String.class, Date.class,
91
                                                        File.class, URL.class, URI.class }));
92

    
93
        private Map values = new LinkedHashMap();
94
        private PersistentContextServices context;
95
        private PersistentIdentifier id;
96
        private PersistenceManagerServices manager;
97
        private String theClassName = null;
98
        private PersistenceFactory factory;
99

    
100
        public AbstractPersistentState(PersistenceManagerServices manager,
101
                        PersistentContextServices context, PersistentIdentifier id) {
102
                this.manager = manager;
103
                this.context = context;
104
                this.id = id;
105
                values = new HashMap();
106
        }
107

    
108
        public void setFactory(PersistenceFactory factory) {
109
                this.factory = factory;
110
        }
111
        
112
        public DynStruct getDefinition() {
113
                DynStruct definition = this.factory.getDefinition(this.theClassName);
114
                return definition;
115
        }
116

    
117
        private DynStruct getDefinitionCheckNull() {
118
                DynStruct definition = getDefinition();
119
                if (definition == null) {
120
                        throw new NullPointerException(
121
                                        "Can't locate definition for the class '"
122
                                                        + this.theClassName + "' in the factory '"
123
                                                        + this.factory.getClass().getName()
124
                                                        + "', managed classes are '"
125
                                                        + this.factory.getManagedClasses().toString()
126
                                                        + "'.");
127
                }
128
                return definition;
129
        }
130

    
131
        public Object get(String name) throws PersistenceException {
132
                Object ret = values.get(name);
133
                if (ret == null) {
134
                        // We are asked for an attribute not defined in the dynstruct
135
                        if (!values.containsKey(name) && !definitionHasField(name)) {
136
                                throw new PersistenceValueNotFoundException(name);
137
                        }
138
                        return getDefaultValue(name);
139
                }
140
                return get(ret);
141
        }
142

    
143
        public List getList(String name) throws PersistenceException {
144
                return (List) get(name);
145
        }
146

    
147
        public Map getMap(String name) throws PersistenceException {
148
                return (Map) get(name);
149
        }
150

    
151
        public Set getSet(String name) throws PersistenceException {
152
                return (Set) get(name);
153
        }
154

    
155
        private Object get(Object obj) throws PersistenceException {
156
                if (obj instanceof ObjectReference) {
157
                        ObjectReference ref = (ObjectReference) obj;
158
                        return ref.getObject();
159
                }
160
                if (obj instanceof List) {
161
                        List result = new ArrayList(((List) obj).size());
162
                        getValues(result, (((List) obj).iterator()));
163
                        return result;
164
                }
165
                return obj;
166
        }
167

    
168
        private void getValues(List result, Iterator iterator)
169
                        throws PersistenceException {
170
                while (iterator.hasNext()) {
171
                        result.add(get(iterator.next()));
172
                }
173
        }
174

    
175
        public boolean getBoolean(String name) throws PersistenceException {
176
                return ((Boolean) get(name)).booleanValue();
177
        }
178

    
179
        public double getDouble(String name) throws PersistenceException {
180
                return ((Double) get(name)).doubleValue();
181
        }
182

    
183
        public File getFile(String name) throws PersistenceException {
184
                return (File) get(name);
185
        }
186

    
187
        public URL getURL(String name) throws PersistenceException {
188
                return (URL) get(name);
189
        }
190

    
191
        public URI getURI(String name) throws PersistenceException {
192
                return (URI) get(name);
193
        }
194

    
195
        public Date getDate(String name) throws PersistenceException {
196
                return (Date) get(name);
197
        }
198

    
199
        public float getFloat(String name) throws PersistenceException {
200
                return ((Float) get(name)).floatValue();
201
        }
202

    
203
        public int getInt(String name) throws PersistenceException {
204
                return ((Integer) get(name)).intValue();
205
        }
206

    
207
        public Iterator getIterator(String name) throws PersistenceException {
208
                Collection collection = (Collection) get(name);
209
                return collection.iterator();
210
        }
211

    
212
        public long getLong(String name) throws PersistenceException {
213
                return ((Long) get(name)).longValue();
214
        }
215

    
216
        public Object[] getArray(String name, Class valueClass)
217
                        throws PersistenceException {
218
                List valueList = getList(name);
219
                if (valueList == null) {
220
                        return null;
221
                }
222
                Object array = Array.newInstance(valueClass, valueList.size());
223
                return valueList.toArray((Object[]) array);
224
        }
225

    
226
        public boolean[] getBooleanArray(String name) throws PersistenceException {
227
                List valueList = getList(name);
228
                if (valueList == null) {
229
                        return null;
230
                }
231
                boolean[] values = new boolean[valueList.size()];
232
                for (int i = 0; i < values.length; i++) {
233
                        values[i] = ((Boolean) valueList.get(i)).booleanValue();
234
                }
235
                return values;
236
        }
237

    
238
        public int[] getIntArray(String name) throws PersistenceException {
239
                List valueList = getList(name);
240
                if (valueList == null) {
241
                        return null;
242
                }
243
                int[] values = new int[valueList.size()];
244
                for (int i = 0; i < values.length; i++) {
245
                        values[i] = ((Number) valueList.get(i)).intValue();
246
                }
247
                return values;
248
        }
249

    
250
        public long[] getLongArray(String name) throws PersistenceException {
251
                List valueList = getList(name);
252
                if (valueList == null) {
253
                        return null;
254
                }
255
                long[] values = new long[valueList.size()];
256
                for (int i = 0; i < values.length; i++) {
257
                        values[i] = ((Number) valueList.get(i)).longValue();
258
                }
259
                return values;
260
        }
261

    
262
        public float[] getFloatArray(String name) throws PersistenceException {
263
                List valueList = getList(name);
264
                if (valueList == null) {
265
                        return null;
266
                }
267
                float[] values = new float[valueList.size()];
268
                for (int i = 0; i < values.length; i++) {
269
                        values[i] = ((Number) valueList.get(i)).floatValue();
270
                }
271
                return values;
272
        }
273

    
274
        public double[] getDoubleArray(String name) throws PersistenceException {
275
                List valueList = getList(name);
276
                if (valueList == null) {
277
                        return null;
278
                }
279
                double[] values = new double[valueList.size()];
280
                for (int i = 0; i < values.length; i++) {
281
                        values[i] = ((Number) valueList.get(i)).doubleValue();
282
                }
283
                return values;
284
        }
285

    
286
        public Date[] getDateArray(String name) throws PersistenceException {
287
                return (Date[]) this.getArray(name, Date.class);
288
        }
289

    
290
        public String[] getStringArray(String name) throws PersistenceException {
291
                return (String[]) this.getArray(name, String.class);
292
        }
293

    
294
        public Iterator getNames() {
295
                return values.keySet().iterator();
296
        }
297

    
298
        public String getString(String name) throws PersistenceException {
299
                return ((String) get(name));
300
        }
301

    
302
        public void setNull(String name) throws PersistenceException {
303
                setValue(name, null);
304
        }
305

    
306
        public void set(String name, String value) throws PersistenceException {
307
                setValue(name, value);
308
        }
309

    
310
        public void set(String name, File value) throws PersistenceException {
311
                setValue(name, value);
312
        }
313

    
314
        public void set(String name, URL value) throws PersistenceException {
315
                setValue(name, value);
316
        }
317

    
318
        public void set(String name, URI value) throws PersistenceException {
319
                setValue(name, value);
320
        }
321

    
322
        public void set(String name, int value) throws PersistenceException {
323
                setValue(name, new Integer(value));
324
        }
325

    
326
        public void set(String name, long value) throws PersistenceException {
327
                setValue(name, new Long(value));
328
        }
329

    
330
        public void set(String name, double value) throws PersistenceException {
331
                setValue(name, new Double(value));
332

    
333
        }
334

    
335
        public void set(String name, float value) throws PersistenceException {
336
                setValue(name, new Float(value));
337

    
338
        }
339

    
340
        public void set(String name, boolean value) throws PersistenceException {
341
                setValue(name, new Boolean(value));
342
        }
343

    
344
        public void set(String name, Persistent obj) throws PersistenceException {
345
                setValue(name, getObjectToPersist(obj, name));
346
        }
347

    
348
        public void set(String name, Object obj) throws PersistenceException {
349
                setValue(name, getObjectToPersist(obj, name));
350
        }
351

    
352
        public void set(String name, Map obj) throws PersistenceException {
353
                setValue(name, getObjectToPersist(obj, name));
354
        }
355

    
356
        public void set(String name, List obj) throws PersistenceException {
357
                setValue(name, getObjectToPersist(obj, name));
358
        }
359

    
360
        public void set(String name, Iterator obj) throws PersistenceException {
361
                setValue(name, getObjectToPersist(obj, name));
362
        }
363

    
364
        public void set(String name, Object[] values) throws PersistenceException {
365
                set(name, values == null ? null : Arrays.asList(values));
366
        }
367

    
368
        public void set(String name, Date[] values) throws PersistenceException {
369
                set(name, values == null ? null : Arrays.asList(values));
370
        }
371

    
372
        public void set(String name, String[] values) throws PersistenceException {
373
                set(name, values == null ? null : Arrays.asList(values));
374
        }
375

    
376
        public void set(String name, boolean[] value) throws PersistenceException {
377
                if (value == null) {
378
                        setValue(name, null);
379
                } else {
380
                        List valueList = new ArrayList(value.length);
381
                        for (int i = 0; i < value.length; i++) {
382
                                valueList.add(value[i] ? Boolean.TRUE : Boolean.FALSE);
383
                        }
384
                        set(name, valueList);
385
                }
386
        }
387

    
388
        public void set(String name, int[] value) throws PersistenceException {
389
                if (value == null) {
390
                        setValue(name, null);
391
                } else {
392
                        List valueList = new ArrayList(value.length);
393
                        for (int i = 0; i < value.length; i++) {
394
                                valueList.add(new Integer(value[i]));
395
                        }
396
                        set(name, valueList);
397
                }
398
        }
399

    
400
        public void set(String name, long[] value) throws PersistenceException {
401
                if (value == null) {
402
                        setValue(name, null);
403
                } else {
404
                        List valueList = new ArrayList(value.length);
405
                        for (int i = 0; i < value.length; i++) {
406
                                valueList.add(new Long(value[i]));
407
                        }
408
                        set(name, valueList);
409
                }
410
        }
411

    
412
        public void set(String name, float[] value) throws PersistenceException {
413
                if (value == null) {
414
                        setValue(name, null);
415
                } else {
416
                        List valueList = new ArrayList(value.length);
417
                        for (int i = 0; i < value.length; i++) {
418
                                valueList.add(new Float(value[i]));
419
                        }
420
                        set(name, valueList);
421
                }
422
        }
423

    
424
        public void set(String name, double[] value) throws PersistenceException {
425
                if (value == null) {
426
                        setValue(name, null);
427
                } else {
428
                        List valueList = new ArrayList(value.length);
429
                        for (int i = 0; i < value.length; i++) {
430
                                valueList.add(new Double(value[i]));
431
                        }
432
                        set(name, valueList);
433
                }
434
        }
435

    
436
        public void set(String name, Set obj) throws PersistenceException {
437
                setValue(name, getObjectToPersist(obj, name));
438
        }
439

    
440
        public void set(String name, Boolean obj) throws PersistenceException {
441
                setValue(name, getObjectToPersist(obj, name));
442
        }
443

    
444
        public void set(String name, Integer obj) throws PersistenceException {
445
                setValue(name, getObjectToPersist(obj, name));
446
        }
447

    
448
        public void set(String name, Long obj) throws PersistenceException {
449
                setValue(name, getObjectToPersist(obj, name));
450
        }
451

    
452
        public void set(String name, Float obj) throws PersistenceException {
453
                setValue(name, getObjectToPersist(obj, name));
454
        }
455

    
456
        public void set(String name, Double obj) throws PersistenceException {
457
                setValue(name, getObjectToPersist(obj, name));
458
        }
459

    
460
        public void set(String name, Date obj) throws PersistenceException {
461
                setValue(name, getObjectToPersist(obj, name));
462
        }
463

    
464
        protected Object getObjectToPersist(Object theOriginal)
465
                        throws PersistenceException {
466
                return getObjectToPersist(theOriginal, null);
467
        }
468

    
469
        /**
470
         * Checks class of <code>theOriginal</code> and transforms it if is
471
         * necessary.<br>
472
         * 
473
         * @param theOriginal
474
         * @return
475
         * @throws PersistenceException
476
         */
477
        private Object getObjectToPersist(Object theOriginal, String propName)
478
                        throws PersistenceException {
479
                DynStruct definition = null;
480
                DynField field = null;
481
                try {
482
                        if (theOriginal == null) {
483
                                return null;
484
                        } else if (validStdTypeClasses.contains(theOriginal.getClass())) {
485
                                // FIXME: No esta comprobando que el tipo sea el correcto
486
                                return theOriginal;
487
                        }
488
                        if (theOriginal instanceof File) {
489
                                // File no es una clase final, asi que convertimos
490
                                // a File para curarnos en salud.
491
                                // FIXME: No esta comprobando que el tipo sea el correcto
492
                                return new File(((File) theOriginal).toURI());
493
                        }
494
                        definition = this.getDefinitionCheckNull();
495
                        if (propName != null) {
496
                                field = definition.getDynField(propName);
497
                        }
498
                        if (theOriginal instanceof Persistent) {
499
                                if (field != null) {
500
                                        Class classOfValue = field.getClassOfValue();
501
                                        if (classOfValue == null) {
502
                                                throw new NullPointerException(
503
                                                                "Class of value for field '"
504
                                                                                + definition.getFullName() + "' of '"
505
                                                                                + field.getName() + "' can't be null.");
506
                                        }
507
                                        if (!classOfValue.isAssignableFrom(theOriginal.getClass())) {
508
                                                throw new PersistenceInvalidTypeForPropertyException(
509
                                                                propName, definition, field, theOriginal);
510
                                        }
511
                                }
512
                                ObjectReference ref = context.get(theOriginal);
513
                                if (ref == null) {
514
                                        PersistentStateServices state = manager.createState(
515
                                                        theOriginal, context);
516
                                        ref = context.get(state);
517
                                }
518
                                return ref;
519

    
520
                        } else if ((manager.getFactories().get(theOriginal)) != null) {
521
                                if (field != null) {
522
                                        Class classOfValue = field.getClassOfValue();
523
                                        if (classOfValue == null) {
524
                                                throw new NullPointerException(
525
                                                                "Class of value for field '"
526
                                                                                + definition.getFullName() + "' of '"
527
                                                                                + field.getName() + "' can't be null.");
528
                                        }
529
                                        if (!classOfValue.isAssignableFrom(theOriginal.getClass())) {
530
                                                throw new PersistenceInvalidTypeForPropertyException(
531
                                                                propName, definition, field, theOriginal);
532
                                        }
533
                                }
534
                                ObjectReference ref = context.get(theOriginal);
535
                                if (ref == null) {
536
                                        PersistentStateServices state = manager.createState(
537
                                                        theOriginal, context);
538
                                        ref = context.get(state);
539
                                }
540
                                return ref;
541

    
542
                        } else if (theOriginal instanceof Map) {
543
                                if (field != null && field.getType() != DataTypes.MAP) {
544
                                        throw new PersistenceInvalidTypeForPropertyException(
545
                                                        propName, definition, field, theOriginal);
546
                                }
547
                                Map result = new LinkedHashMap(((Map) theOriginal).size());
548
                                storeValues(result, (Map) theOriginal);
549
                                return result;
550

    
551
                        } else if (theOriginal instanceof Set) {
552
                                if (field != null && field.getType() != DataTypes.SET) {
553
                                        throw new PersistenceInvalidTypeForPropertyException(
554
                                                        propName, definition, field, theOriginal);
555
                                }
556
                                Set result = new LinkedHashSet(((Set) theOriginal).size());
557
                                storeValues(result, ((Set) theOriginal).iterator());
558
                                return result;
559

    
560
                        } else if (theOriginal instanceof List) {
561
                                if (field != null
562
                                                && !(field.getType() == DataTypes.LIST || field
563
                                                                .getType() == DataTypes.ARRAY)) {
564
                                        throw new PersistenceInvalidTypeForPropertyException(
565
                                                        propName, definition, field, theOriginal);
566
                                }
567
                                List result = new ArrayList(((List) theOriginal).size());
568
                                storeValues(result, (((List) theOriginal).iterator()));
569
                                return result;
570

    
571
                        } else if (theOriginal instanceof Iterator) {
572
                                if (field != null
573
                                                && !(field.getType() == DataTypes.LIST || field
574
                                                                .getType() == DataTypes.ARRAY)) {
575
                                        throw new PersistenceInvalidTypeForPropertyException(
576
                                                        propName, definition, field, theOriginal);
577
                                }
578
                                List result = new ArrayList();
579

    
580
                                storeValues(result, (Iterator) theOriginal);
581
                                return result;
582

    
583
                        } else {
584
                                if (this.manager.getAutoValidation() == PersistenceManager.MANDATORY) {
585
                                        throw new PersistenceTypeNotSupportedException(
586
                                                        theOriginal.getClass(), propName);
587
                                } else {
588
                                        logger.error("Persistence type '"
589
                                                        + theOriginal.getClass().getName()
590
                                                        + "' not supported.");
591
                                        return null;
592
                                }
593
                        }
594
                } catch (PersistenceException ex) {
595
                        PersistentContextServices context = (PersistentContextServices) this
596
                                        .getContext();
597
                        if (!context.getCollectErrors()) {
598
                                throw ex;
599
                        }
600
                        context.addError(ex);
601
                        return null;
602
                } catch (Exception ex) {
603
                        PersistentContextServices context = (PersistentContextServices) this
604
                                        .getContext();
605
                        if (!context.getCollectErrors()) {
606
                                throw new PersistenceException(ex);
607
                        }
608
                        context.addError(ex);
609
                        return null;
610
                }
611
        }
612

    
613
        /*
614
         * (non-Javadoc)
615
         * 
616
         * @see
617
         * org.gvsig.tools.persistence.impl.ImplementationPersistentState#getId()
618
         */
619
        public PersistentIdentifier getId() {
620
                return id;
621
        }
622

    
623
        public void setValue(String name, Object value) throws PersistenceException {
624
                try {
625
                        if (this.theClassName == null) {
626
                                throw new PersistenceIllegalStateTheClassNameNotSetException();
627
                        }
628
                        if (!VALID_NAME_PATTERN.matcher(name).matches()) {
629
                                throw new PersistenceInvalidPropertyNameException(name);
630
                        }
631
                        this.values.put(name, value);
632

    
633
                } catch (PersistenceException ex) {
634
                        PersistentContextServices context = (PersistentContextServices) this
635
                                        .getContext();
636
                        if (!context.getCollectErrors()) {
637
                                throw ex;
638
                        }
639
                        context.addError(ex);
640
                } catch (Exception ex) {
641
                        PersistentContextServices context = (PersistentContextServices) this
642
                                        .getContext();
643
                        if (!context.getCollectErrors()) {
644
                                throw new PersistenceException(ex);
645
                        }
646
                        context.addError(ex);
647
                }
648
        }
649

    
650
        public String getTheClassName() {
651
                return theClassName;
652
        }
653

    
654
        /*
655
         * (non-Javadoc)
656
         * 
657
         * @see org.gvsig.tools.persistence.impl.ImplementationPersistentState#
658
         * setTheClassName(java.lang.String)
659
         */
660
        public void setTheClassName(String className) {
661
                theClassName = className;
662
        }
663
        
664
        private void storeValues(Collection storage, Iterator iter)
665
                        throws PersistenceException {
666
                while (iter.hasNext()) {
667
                        storage.add(getObjectToPersist(iter.next()));
668
                }
669

    
670
        }
671

    
672
        private void storeValues(Map storage, Map originalStorage)
673
                        throws PersistenceException {
674
                Iterator iter = originalStorage.entrySet().iterator();
675
                Entry orgEntry;
676
                Object key;
677
                Object value;
678

    
679
                while (iter.hasNext()) {
680
                        orgEntry = (Entry) iter.next();
681
                        key = orgEntry.getKey();
682

    
683
                        if (key == null) {
684
                                // Nothing to do
685
                        } else if (key instanceof String) {
686
                                // Nothing to do
687
                        } else if (key instanceof Number) {
688
                                // Nothing to do
689
                        } else if (key instanceof Boolean) {
690
                                // Nothing to do
691
                        } else if (key instanceof Persistent) {
692
                                key = getObjectToPersist(key);
693
                        } else {
694
                                throw new PersistenceUnsuportedMapKeyTypeException(orgEntry
695
                                                .getKey().getClass());
696
                        }
697

    
698
                        value = getObjectToPersist(orgEntry.getValue());
699

    
700
                        storage.put(key, value);
701
                }
702

    
703
        }
704

    
705
        /*
706
         * (non-Javadoc)
707
         * 
708
         * @see
709
         * org.gvsig.tools.persistence.impl.ImplementationPersistentState#getContext
710
         * ()
711
         */
712
        public PersistentContext getContext() {
713
                return context;
714
        }
715

    
716
        // private int size() {
717
        // return this.values.size();
718
        // }
719
        //
720
        /*
721
         * (non-Javadoc)
722
         * 
723
         * @see
724
         * org.gvsig.tools.persistence.impl.ImplementationPersistentState#hasValue
725
         * (java.lang.String)
726
         */
727
        public boolean hasValue(String name) {
728
                return this.values.containsKey(name);
729
        }
730

    
731
        public Object getValue(String name) {
732
                return values.get(name);
733
        }
734

    
735
        //
736
        // private ObjectReference createReference(Integer id) {
737
        // return new DefaultObjectReference(id);
738
        // }
739

    
740
        /**
741
         * Returns if the definition related to this state has a defined field
742
         */
743
        private boolean definitionHasField(String name) {
744
                DynStruct definition = manager.getDefinition(getTheClassName());
745
                return definition != null && definition.getDynField(name) != null;
746
        }
747
        
748
        private Object getDefaultValue(String name) {
749
                DynStruct definition = manager.getDefinition(getTheClassName());
750
                if( definition == null ) {
751
                    return null;
752
                }
753
                if( definition.getDynField(name)==null ) {
754
                    return null;
755
                }
756
                return definition.getDynField(name).getDefaultValue();
757
        }
758
        
759
        public void relativizeFiles(File rootFolder) {
760
                PersistentContext context = this.getContext();
761

    
762
                URI cwd = new File(System.getProperty("user.dir")).toURI();
763
                Iterator statesIterator = context.iterator();
764
                while (statesIterator.hasNext()) {
765
                        PersistentState aState = (PersistentState) statesIterator.next();
766
                        DynStruct definition = aState.getDefinition();
767
                        DynField[] fields = definition.getDynFields();
768
                        for( int i=0; i<fields.length; i++) {
769
                                DynField field = fields[i];
770
                                if (field.getType() == DataTypes.FILE
771
                                                || field.getType() == DataTypes.FOLDER) {
772
                                        try {
773
                                                File value = aState.getFile(field.getName());
774
                                                value = FileTools.relativizeFile(rootFolder, value);
775
                                                aState.set(field.getName(), value);
776
                                        } catch (PersistenceException e) {
777
                                                logger.warn(
778
                                                                "Can't relativice field '" + field.getName()
779
                                                                                + "' for class '"
780
                                                                                + definition.getName() + "'.", e);
781
                                        }
782
                                } else if (field.getType() == DataTypes.URL) {
783
                                        try {
784
                                                URL value = aState.getURL(field.getName());
785
                                                if ("FILE".equalsIgnoreCase(value.getProtocol())) {
786
                                                        File file = FileUtils.toFile(value);
787
                                                        if (FileTools.isInDifferentDrive(rootFolder,file)) {
788
                                /*
789
                                 * Different drives
790
                                 * (should happen only in Windows)
791
                                 */
792
                                value = file.toURI().toURL();
793
                                                        } else {
794
                                /*
795
                                * Both in the Same drive (C: D: etc) or Unix-style
796
                                */
797
                                file = FileTools.relativizeFile(rootFolder,file);
798
                                value = new URL("file","",file.toURI().toString().substring(cwd.toString().length()));
799
                                                        }
800
                                                        aState.set(field.getName(), value);
801
                                                }
802
                                        } catch (PersistenceException e) {
803
                                                // do nothind
804
                                        } catch (MalformedURLException e) {
805
                                                // do nothind
806
                                        }
807
                                } else if (field.getType() == DataTypes.URI) {
808
                                        try {
809
                                                URI value = aState.getURI(field.getName());
810
                                                if (value.getScheme() == null || "FILE".equalsIgnoreCase(value.getScheme())) {
811
                                                        File file = new File(value.getPath());
812
                                                        if (FileTools.isInDifferentDrive(rootFolder,file)) {
813
                                /*
814
                                 * Different drives
815
                                 * (should happen only in Windows)
816
                                 */
817
                                value = file.toURI();
818
                                                        } else {
819
                                /*
820
                                * Both in the Same drive (C: D: etc) or Unix-style
821
                                */
822
                                file = FileTools.relativizeFile(rootFolder,file);
823
                                value = new URI(file.getPath());
824
                                                        }
825
                                                        aState.set(field.getName(), value);
826
                                                }
827
                                        } catch (PersistenceException e) {
828
                                                // do nothind
829
                                        } catch (URISyntaxException e) {
830
                                                // do nothind
831
                                        }
832
                                }
833
                        }
834
                }
835
        }
836
        
837
    public void derelativizeFiles(File rootFolder) {
838
        PersistentContext context = this.getContext();
839
        //URI cwd = new File(System.getProperty("user.dir")).toURI();
840

    
841
        Iterator statesIterator = context.iterator();
842
        String className = null;
843

    
844
        while (statesIterator.hasNext()) {
845
            PersistentState aState = (PersistentState) statesIterator.next();
846
            try {
847
                className = aState.getTheClassName();
848
            } catch (Throwable e) {
849
                className = "Unknown";
850
            }
851
            try {
852
                DynStruct definition = aState.getDefinition();
853
                DynField[] fields = definition.getDynFields();
854
                for (int i = 0; i < fields.length; i++) {
855
                    DynField field = fields[i];
856
                    if (field.getType() == DataTypes.FILE
857
                            || field.getType() == DataTypes.FOLDER) {
858
                        try {
859
                            File value = aState.getFile(field.getName());
860
                            value = FileTools.derelativizeFile(rootFolder, value);
861
                            aState.set(field.getName(), value);
862
                        } catch (PersistenceException e) {
863
                            logger.warn(
864
                                    "Can't fix field '" + field.getName()
865
                                    + "' for class '"
866
                                    + definition.getName() + "'.", e);
867
                        }
868
                    } else if (field.getType() == DataTypes.URL) {
869
                        try {
870
                            URL value = aState.getURL(field.getName());
871
                            if ("FILE".equalsIgnoreCase(value.getProtocol())) {
872
                                if (!value.getFile().startsWith("/")) {
873
                                    File file = FileUtils.toFile(value);
874
                                    file = FileTools.derelativizeFile(rootFolder, file);
875
                                    value = file.toURI().toURL();
876
                                    aState.set(field.getName(), value);
877
                                }
878
                            }
879
                        } catch (PersistenceException e) {
880
                            // do nothing
881
                        } catch (MalformedURLException e) {
882
                            // do nothing
883
                        }
884

    
885
                    } else if (field.getType() == DataTypes.URI) {
886
                        try {
887
                            URI value = aState.getURI(field.getName());
888
                            if (value.getScheme() == null || "FILE".equalsIgnoreCase(value.getScheme())) {
889
                                if (!value.getPath().startsWith("/")) {
890
                                    File file = FileUtils.toFile(value.toURL());
891
                                    file = FileTools.derelativizeFile(rootFolder, file);
892
                                    aState.set(field.getName(), file.toURI());
893
                                }
894
                            }
895
                        } catch (PersistenceException e) {
896
                            // do nothing
897
                        } catch (MalformedURLException ex) {
898
                            // do nothing
899
                        }
900
                    }
901
                }
902
            } catch (RuntimeException e) {
903
                logger.info("Can't fix relative paths in " + className, e);
904
            }
905
        }
906
    }
907

    
908

    
909
}