Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.spi / src / main / java / org / gvsig / fmap / dal / spi / AbstractDataParameters.java @ 45535

History | View | Annotate | Download (11.6 KB)

1 40559 jjdelcerro
/**
2
 * gvSIG. Desktop Geographic Information System.
3 40435 jjdelcerro
 *
4 40559 jjdelcerro
 * Copyright (C) 2007-2013 gvSIG Association.
5 40435 jjdelcerro
 *
6 42611 jjdelcerro
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10 40435 jjdelcerro
 *
11 42611 jjdelcerro
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15 40435 jjdelcerro
 *
16 42611 jjdelcerro
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 40435 jjdelcerro
 *
20 42611 jjdelcerro
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22 40435 jjdelcerro
 */
23
package org.gvsig.fmap.dal.spi;
24
25 44816 jjdelcerro
import java.io.ByteArrayInputStream;
26 44304 jjdelcerro
import java.io.ByteArrayOutputStream;
27 43758 jjdelcerro
import java.io.File;
28
import java.io.IOException;
29 40435 jjdelcerro
import java.util.Iterator;
30 43758 jjdelcerro
import java.util.List;
31 45425 jjdelcerro
import javax.json.JsonObject;
32 43758 jjdelcerro
import org.apache.commons.io.FileUtils;
33
import org.apache.commons.io.FilenameUtils;
34
import org.apache.commons.lang3.StringUtils;
35 44750 jjdelcerro
import org.apache.commons.lang3.mutable.MutableInt;
36 43758 jjdelcerro
import org.cresques.cts.ICRSFactory;
37
import org.cresques.cts.IProjection;
38
import org.gvsig.fmap.crs.CRSFactory;
39 40435 jjdelcerro
40 42566 fdiaz
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42
43 40435 jjdelcerro
import org.gvsig.fmap.dal.DataParameters;
44
import org.gvsig.fmap.dal.exception.CopyParametersException;
45
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
46 45425 jjdelcerro
import org.gvsig.json.Json;
47
import org.gvsig.json.JsonObjectBuilder;
48 42611 jjdelcerro
import org.gvsig.tools.ToolsLocator;
49 40435 jjdelcerro
import org.gvsig.tools.dynobject.DelegatedDynObject;
50
import org.gvsig.tools.dynobject.DynClass;
51
import org.gvsig.tools.dynobject.DynField;
52
import org.gvsig.tools.dynobject.DynObject;
53 42611 jjdelcerro
import org.gvsig.tools.dynobject.DynObjectEncoder;
54
import org.gvsig.tools.dynobject.DynObjectManager;
55 40435 jjdelcerro
import org.gvsig.tools.dynobject.exception.DynMethodException;
56
import org.gvsig.tools.dynobject.exception.DynObjectValidateException;
57 44816 jjdelcerro
import org.gvsig.tools.persistence.PersistenceFactory;
58 44304 jjdelcerro
import org.gvsig.tools.persistence.PersistenceManager;
59 40435 jjdelcerro
import org.gvsig.tools.persistence.PersistentState;
60
import org.gvsig.tools.persistence.exception.PersistenceException;
61 44750 jjdelcerro
import org.gvsig.tools.persistence.xml.XMLPersistenceManager;
62 45535 fdiaz
import org.gvsig.tools.util.Validator;
63 40435 jjdelcerro
64
/**
65
 * @author jmvivo
66
 *
67
 */
68 44304 jjdelcerro
@SuppressWarnings("UseSpecificCatch")
69 45535 fdiaz
public abstract class AbstractDataParameters implements DataParameters, Validator {
70 40435 jjdelcerro
71 44304 jjdelcerro
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDataParameters.class);
72 45535 fdiaz
    private Exception validateException;
73 40435 jjdelcerro
74 42611 jjdelcerro
    @Override
75
    public Object getDynValue(String name) {
76
        return getDelegatedDynObject().getDynValue(name);
77
    }
78 42103 jjdelcerro
79 44318 jjdelcerro
    public String getProviderName() {
80
        return (String) this.getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME);
81
    }
82
83 43400 jjdelcerro
    public String getDataStoreName() {
84
        return (String) this.getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME);
85
    }
86
87
    public String getDescription() {
88
        return this.getDynClass().getDescription();
89
    }
90
91 42611 jjdelcerro
    @Override
92
    public String toString() {
93
        DynObjectEncoder encoder = ToolsLocator.getDynObjectManager().createSimpleDynObjectEncoder();
94
        return encoder.encode(this);
95
    }
96 40435 jjdelcerro
97 42611 jjdelcerro
    @Override
98
    public void setDynValue(String name, Object value) {
99
        DelegatedDynObject delegated = getDelegatedDynObject();
100
        if (delegated.getDynClass().getDynField(name) != null) {
101
            delegated.setDynValue(name, value);
102
        } else {
103
            try {
104
                throw new IllegalArgumentException(name);
105
            } catch (IllegalArgumentException ex) {
106 44304 jjdelcerro
                LOGGER.warn("Attribute '" + name + "' is not defined in "
107 42611 jjdelcerro
                        + delegated.getDynClass().getFullName() + " definition", ex);
108
            }
109
        }
110
    }
111 40435 jjdelcerro
112 42611 jjdelcerro
    @Override
113
    public void clear() {
114
        DynObjectManager manager = ToolsLocator.getDynObjectManager();
115
        manager.clear(this);
116
    }
117 40435 jjdelcerro
118 44307 jjdelcerro
    protected void copyValuesTo(DataParameters target) {
119 42611 jjdelcerro
        DynObjectManager manager = ToolsLocator.getDynObjectManager();
120
        manager.copy(this, target);
121
    }
122 40435 jjdelcerro
123 42611 jjdelcerro
    @Override
124
    public DataParameters getCopy() {
125 44307 jjdelcerro
        DataParameters copy;
126 42611 jjdelcerro
        try {
127 44307 jjdelcerro
            if( this instanceof Cloneable ) {
128
                copy = (DataParameters) this.clone();
129
            } else {
130
                copy = (DataParameters) this.getClass().newInstance();
131
                this.copyValuesTo(copy);
132
            }
133
        } catch (Exception e) {
134 42611 jjdelcerro
            throw new CopyParametersException("data parameters", e);
135
        }
136
        return copy;
137
    }
138 40435 jjdelcerro
139 42611 jjdelcerro
    @Override
140
    public void saveToState(PersistentState state) throws PersistenceException {
141
        DynField[] fields = getDelegatedDynObject().getDynClass().getDynFields();
142 40435 jjdelcerro
143 42611 jjdelcerro
        for (DynField field : fields) {
144
            if (field.isPersistent()) {
145
                String name = field.getName();
146
                Object value = this.getDynValue(name);
147
                state.set(name, value);
148
            }
149
        }
150
    }
151 40435 jjdelcerro
152 42611 jjdelcerro
    @Override
153
    public void loadFromState(PersistentState state) throws PersistenceException {
154
        @SuppressWarnings("rawtypes")
155 42566 fdiaz
        Iterator it = state.getNames();
156 42611 jjdelcerro
        while (it.hasNext()) {
157
            String name = (String) it.next();
158
            try {
159
                Object value = state.get(name);
160
                this.setDynValue(name, value);
161
            } catch (Throwable t) {
162 44304 jjdelcerro
                LOGGER.warn("Can't load '" + name + "' property", t);
163 42611 jjdelcerro
            }
164
        }
165
    }
166 40435 jjdelcerro
167 42611 jjdelcerro
    @Override
168
    public void delegate(DynObject dynObject) {
169
        getDelegatedDynObject().delegate(dynObject);
170 40435 jjdelcerro
171 42611 jjdelcerro
    }
172 40435 jjdelcerro
173 42611 jjdelcerro
    @Override
174
    public DynClass getDynClass() {
175
        return getDelegatedDynObject().getDynClass();
176
    }
177 40435 jjdelcerro
178 42611 jjdelcerro
    @Override
179
    public boolean hasDynValue(String name) {
180
        return getDelegatedDynObject().hasDynValue(name);
181
    }
182 40435 jjdelcerro
183 42611 jjdelcerro
    @Override
184
    public void implement(DynClass dynClass) {
185
        getDelegatedDynObject().implement(dynClass);
186
    }
187 40435 jjdelcerro
188 42611 jjdelcerro
    @Override
189 42775 jjdelcerro
    public Object invokeDynMethod(String name, Object[] args)
190 42611 jjdelcerro
            throws DynMethodException {
191 42775 jjdelcerro
        return getDelegatedDynObject().invokeDynMethod(this, name, args);
192 42611 jjdelcerro
    }
193 40435 jjdelcerro
194 42611 jjdelcerro
    @Override
195 42775 jjdelcerro
    public Object invokeDynMethod(int code, Object[] args)
196 42611 jjdelcerro
            throws DynMethodException {
197 42775 jjdelcerro
        return getDelegatedDynObject().invokeDynMethod(this, code, args);
198 42611 jjdelcerro
    }
199 40435 jjdelcerro
200 42611 jjdelcerro
    @Override
201
    public void validate() throws ValidateDataParametersException {
202
        try {
203 40435 jjdelcerro
            this.getDynClass().validate(this);
204
        } catch (DynObjectValidateException e) {
205
            throw new ValidateDataParametersException(e);
206
        }
207 42611 jjdelcerro
    }
208 40435 jjdelcerro
209 43758 jjdelcerro
    protected void loadPRJ(File file, String parameterName) {
210
        File prjFile = new File(FilenameUtils.removeExtension(file.getAbsolutePath()) + ".prj");
211
        if (prjFile.exists()) {
212
            try {
213
                String contentFile = FileUtils.readFileToString(prjFile);
214
                if (StringUtils.isNotEmpty(contentFile)) {
215
                    IProjection crs = CRSFactory.getCRSFactory().get(ICRSFactory.FORMAT_WKT_ESRI, contentFile);
216
                    this.setDynValue(parameterName, crs);
217
                }
218
            } catch (IOException e) {
219 44304 jjdelcerro
                LOGGER.warn("Couldn't read prj file ''{}''", prjFile.getAbsolutePath());
220 43758 jjdelcerro
            }
221
        }
222
    }
223
224
    protected void loadWLD(File file, String parameterName) {
225
        File wldFile = new File(FilenameUtils.removeExtension(file.getAbsolutePath()) + ".wld");
226
        if (wldFile.exists()) {
227
            try {
228
                List<String> lines = FileUtils.readLines(wldFile);
229
                if (lines != null && lines.size() == 6) {
230
                    this.setDynValue(parameterName, lines);
231
                }
232
233
            } catch (IOException e) {
234 44304 jjdelcerro
                LOGGER.warn("Couldn't read wld file ''{}''", wldFile.getAbsolutePath());
235 43758 jjdelcerro
            }
236
        }
237
    }
238
239 44304 jjdelcerro
    @Override
240
    public byte[] toByteArray() {
241
            try {
242 44750 jjdelcerro
//            PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
243
            PersistenceManager persistenceManager = new XMLPersistenceManager();
244 44304 jjdelcerro
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
245 44750 jjdelcerro
            PersistentState state = persistenceManager.getState(this, false, new MutableInt(1));
246 44304 jjdelcerro
            persistenceManager.saveState(state, stream);
247
            return stream.toByteArray();
248
        } catch (Exception ex) {
249
            LOGGER.warn("Can't get byte[] from parameters.",ex);
250
            return null;
251
        }
252
    }
253 44346 jjdelcerro
254 44816 jjdelcerro
    public static DataParameters fromByteArray(byte[] data) {
255
        Object x;
256
        PersistenceManager defaultPersistenceManager = ToolsLocator.getPersistenceManager();
257
        try {
258
            PersistenceManager xmlPersistenceManager = new XMLPersistenceManager();
259
            for (Iterator it = defaultPersistenceManager.getFactories().iterator(); it.hasNext();) {
260
              PersistenceFactory factory = (PersistenceFactory) it.next();
261
              xmlPersistenceManager.registerFactory(factory);
262
            }
263
            ByteArrayInputStream stream = new ByteArrayInputStream(data);
264
            x = xmlPersistenceManager.getObject(stream);
265
            DataParameters parameters = (DataParameters) x;
266
            return parameters;
267
        } catch (Exception ex) {
268
          LOGGER.debug("Can't get parameters from byte[] with XMLPersistenceManager.",ex);
269
          // Try with the default persistence manager for compatibility
270
        }
271
        try {
272
            ByteArrayInputStream stream = new ByteArrayInputStream(data);
273
            DataParameters parameters = (DataParameters) defaultPersistenceManager.getObject(stream);
274
            return parameters;
275
        } catch (Exception ex) {
276
            LOGGER.warn("Can't get parameters from byte[].",ex);
277
            return null;
278
        }
279
    }
280
281 44346 jjdelcerro
    @Override
282
    public boolean equals(Object obj) {
283
        if( !(obj instanceof DynObject) ) {
284
            return false;
285
        }
286
        DynObjectManager manager = ToolsLocator.getDynObjectManager();
287
        return manager.equals(this, (DynObject) obj);
288
    }
289
290
    @Override
291
    public int hashCode() {
292
        DynObjectManager manager = ToolsLocator.getDynObjectManager();
293
        return manager.hashCode(this);
294
    }
295
296 45425 jjdelcerro
    @Override
297
    public JsonObject toJson() {
298
        JsonObjectBuilder builder = this.toJsonBuilder();
299
        return builder.build();
300
    }
301
302
    @Override
303
    public JsonObjectBuilder toJsonBuilder() {
304
        JsonObjectBuilder builder = Json.createObjectBuilder();
305
        builder.add_class(this);
306
        builder.addAll(this);
307
        return builder;
308
    }
309
310
    @Override
311
    public void fromJson(JsonObject json) {
312
        Json.addAll(this, json);
313
    }
314
315
316 42611 jjdelcerro
    /**
317
     * Returns an instance of the {@link DynObject} to delegate to.
318
     *
319
     * @return the delegate {@link DynObject}
320
     */
321
    protected abstract DelegatedDynObject getDelegatedDynObject();
322 40435 jjdelcerro
323 45535 fdiaz
    @Override
324
    public boolean isValid(Object data, Object... args) {
325
        try {
326
            validate();
327
            return true;
328
        } catch (Exception e) {
329
            this.validateException = e;
330
            return false;
331
        }
332
    }
333
334
    @Override
335
    public String getMessage() {
336
        if(this.validateException == null){
337
            return null;
338
        }
339
        return this.validateException.getMessage();
340
    }
341
342
    @Override
343
    public Throwable getCause() {
344
        return this.validateException;
345
    }
346
347
348
349 40596 jjdelcerro
}