Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.impl / src / main / java / org / gvsig / fmap / dal / impl / DefaultDataManager.java @ 45037

History | View | Annotate | Download (52.2 KB)

1 43020 jjdelcerro
package org.gvsig.fmap.dal.impl;
2
3
import java.io.File;
4
import java.io.InputStream;
5
import java.net.URL;
6
import java.net.URLClassLoader;
7
import java.util.ArrayList;
8 44128 jjdelcerro
import java.util.Collections;
9 43020 jjdelcerro
import java.util.HashMap;
10 44871 jjdelcerro
import java.util.HashSet;
11 43020 jjdelcerro
import java.util.List;
12
import java.util.Map;
13 44376 jjdelcerro
import java.util.Objects;
14 44871 jjdelcerro
import java.util.Set;
15 44409 jjdelcerro
import java.util.UUID;
16 44328 jjdelcerro
import org.apache.commons.io.IOUtils;
17 43450 jjdelcerro
import org.apache.commons.lang3.StringUtils;
18 43984 jjdelcerro
import org.gvsig.expressionevaluator.Expression;
19 44042 jjdelcerro
import org.gvsig.expressionevaluator.ExpressionBuilder;
20 44023 jjdelcerro
import org.gvsig.expressionevaluator.ExpressionEvaluatorLocator;
21 44376 jjdelcerro
import org.gvsig.expressionevaluator.MutableSymbolTable;
22 44750 jjdelcerro
import org.gvsig.expressionevaluator.impl.DefaultDALExpressionBuilder;
23 44738 jjdelcerro
import org.gvsig.expressionevaluator.impl.symboltable.FeatureSymbolTableImpl;
24 44304 jjdelcerro
import org.gvsig.fmap.dal.BaseStoresRepository;
25 44376 jjdelcerro
import org.gvsig.fmap.dal.DALLocator;
26 43205 fdiaz
27 43020 jjdelcerro
import org.gvsig.fmap.dal.DataFactory;
28
import org.gvsig.fmap.dal.DataManager;
29
import org.gvsig.fmap.dal.DataServerExplorer;
30
import org.gvsig.fmap.dal.DataServerExplorerFactory;
31
import org.gvsig.fmap.dal.DataServerExplorerParameters;
32
import org.gvsig.fmap.dal.DataServerExplorerPool;
33
import org.gvsig.fmap.dal.DataStore;
34
import org.gvsig.fmap.dal.DataStoreFactory_v2_4;
35 44871 jjdelcerro
import org.gvsig.fmap.dal.DataStoreNotification;
36 43020 jjdelcerro
import org.gvsig.fmap.dal.DataStoreParameters;
37
import org.gvsig.fmap.dal.DataStoreProviderFactory;
38
import org.gvsig.fmap.dal.DataTypes;
39 44304 jjdelcerro
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
40 43521 jjdelcerro
41 43020 jjdelcerro
import org.gvsig.fmap.dal.NewDataStoreParameters;
42
import org.gvsig.fmap.dal.OpenErrorHandler;
43
import org.gvsig.fmap.dal.Register;
44 44253 jjdelcerro
import org.gvsig.fmap.dal.StoresRepository;
45 43056 jjdelcerro
import org.gvsig.fmap.dal.exception.DataException;
46 43020 jjdelcerro
import org.gvsig.fmap.dal.exception.InitializeException;
47 43205 fdiaz
import org.gvsig.fmap.dal.exception.OpenException;
48 43020 jjdelcerro
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
49 43205 fdiaz
import org.gvsig.fmap.dal.exception.CreateFileStoreException;
50 43020 jjdelcerro
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
51 44750 jjdelcerro
import org.gvsig.fmap.dal.expressionevaluator.DALExpressionBuilder;
52 43989 jjdelcerro
import org.gvsig.fmap.dal.expressionevaluator.FeatureAttributeEmulatorExpression;
53 43983 jjdelcerro
import org.gvsig.fmap.dal.expressionevaluator.FeatureSymbolTable;
54 44128 jjdelcerro
import org.gvsig.fmap.dal.feature.DataProfile;
55 44753 omartinez
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
56 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.EditableFeatureType;
57 44376 jjdelcerro
import org.gvsig.fmap.dal.feature.Feature;
58 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
59
import org.gvsig.fmap.dal.feature.FeatureQuery;
60
import org.gvsig.fmap.dal.feature.FeatureStore;
61
import org.gvsig.fmap.dal.feature.FeatureType;
62 44376 jjdelcerro
import org.gvsig.fmap.dal.feature.ForeingKey;
63
import static org.gvsig.fmap.dal.feature.ForeingKey.MAX_AVAILABLE_VALUES;
64 44328 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.DALFile;
65 44753 omartinez
import org.gvsig.fmap.dal.feature.impl.DefaultEditableFeatureAttributeDescriptor;
66 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.DefaultEditableFeatureType;
67
import org.gvsig.fmap.dal.feature.impl.DefaultFeatureIndex;
68 44328 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.DefaultFeatureStore;
69 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.impl.FeatureStoreFactory;
70
import org.gvsig.fmap.dal.feature.paging.FeaturePagingHelper;
71
import org.gvsig.fmap.dal.feature.paging.impl.FeaturePagingHelperImpl;
72
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProvider;
73
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProviderServices;
74 43056 jjdelcerro
import org.gvsig.fmap.dal.feature.spi.cache.FeatureCacheProvider;
75
import org.gvsig.fmap.dal.feature.spi.cache.FeatureCacheProviderFactory;
76 43020 jjdelcerro
import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProvider;
77
import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProviderServices;
78 43984 jjdelcerro
import org.gvsig.fmap.dal.impl.expressionevaluator.DefaultExpressionEvaluator;
79 43989 jjdelcerro
import org.gvsig.fmap.dal.impl.expressionevaluator.DefaultFeatureAttributeEmulatorExpression;
80 43205 fdiaz
import org.gvsig.fmap.dal.raster.impl.RasterStoreFactory;
81 43020 jjdelcerro
import org.gvsig.fmap.dal.raster.impl.RasterStoreOldFactory;
82
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProvider;
83 44816 jjdelcerro
import org.gvsig.fmap.dal.spi.AbstractDataParameters;
84 43205 fdiaz
import org.gvsig.fmap.dal.spi.DALSPILocator;
85 43020 jjdelcerro
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
86
import org.gvsig.fmap.dal.spi.DataStoreProvider;
87
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
88
import org.gvsig.fmap.dal.store.memory.MemoryStoreParameters;
89
import org.gvsig.fmap.dal.store.memory.MemoryStoreProvider;
90
import org.gvsig.tools.ToolsLocator;
91
import org.gvsig.tools.dataTypes.DataType;
92
import org.gvsig.tools.dataTypes.DataTypesManager;
93
import org.gvsig.tools.dynobject.DynObject;
94 44376 jjdelcerro
import org.gvsig.tools.dynobject.DynObjectValueItem;
95 43020 jjdelcerro
import org.gvsig.tools.dynobject.DynStruct;
96
import org.gvsig.tools.dynobject.DynStruct_v2;
97
import org.gvsig.tools.dynobject.Tags;
98
import org.gvsig.tools.evaluator.Evaluator;
99
import org.gvsig.tools.exception.BaseException;
100 43056 jjdelcerro
import org.gvsig.tools.extensionpoint.ExtensionPoint;
101 43241 jjdelcerro
import org.gvsig.tools.folders.FoldersManager;
102 43020 jjdelcerro
import org.gvsig.tools.identitymanagement.SimpleIdentityManager;
103
import org.gvsig.tools.identitymanagement.UnauthorizedException;
104 44328 jjdelcerro
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
105 44419 jjdelcerro
import org.gvsig.tools.script.Script;
106
import org.gvsig.tools.script.ScriptManager;
107 43020 jjdelcerro
import org.gvsig.tools.service.spi.Services;
108 43450 jjdelcerro
import org.slf4j.Logger;
109
import org.slf4j.LoggerFactory;
110 44821 jjdelcerro
import org.gvsig.fmap.dal.DatabaseWorkspaceManager.DatabaseWorkspaceListener;
111 44871 jjdelcerro
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
112
import org.gvsig.tools.observer.Observer;
113 43020 jjdelcerro
114 44304 jjdelcerro
@SuppressWarnings("UseSpecificCatch")
115 43020 jjdelcerro
public class DefaultDataManager
116
        implements DataManager, DataManagerProviderServices, Services {
117 43205 fdiaz
118 44023 jjdelcerro
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDataManager.class);
119 43450 jjdelcerro
120 43056 jjdelcerro
    final static private String DATA_MANAGER_CACHE = "Data.manager.caches";
121
    final static private String DATA_MANAGER_CACHE_DESCRIPTION =
122
        "DAL cache providers";
123 43205 fdiaz
124
    public static final String FILESYSTEM_EXPLORER_NAME = "FilesystemExplorer";
125
126
127 43020 jjdelcerro
    private class Registers {
128
129
        private final Register store;
130
        private final Register storeProvider;
131
        private final Register serverExplorer;
132
        private final Register featureIndexProvider;
133
134
        public Registers() {
135
            this.store = new RegisterImpl(
136
                    "Data.manager.stores.factory",
137
                    "DAL store factories"
138
            );
139
            this.storeProvider = new RegisterImpl(
140
                    "Data.manager.providers.factory",
141
                    "DAL store provider factories"
142
            );
143
            this.serverExplorer = new RegisterImpl(
144
                    "Data.manager.servereexplorer.factory",
145
                    "DAL server explorer factories"
146
            );
147
            this.featureIndexProvider = new RegisterImpl(
148
                    "Data.manager.feature.index.factory",
149
                    "DAL feature index factories"
150
            );
151
152
            this.store.register(new FeatureStoreFactory());
153
        }
154
    }
155
    private static final String TAG_DAL_OPENSTORE = "dal.openstore.";
156
157
    private final Registers registers;
158
159
    private final Map<Integer, String> defaultDataIndexProviders;
160
161
    private OpenErrorHandler openErrorHandler = null;
162
163
    private DataServerExplorerPool dataServerExplorerPool = null;
164
165
    private List<DataType> dataTypes = null;
166
167
    private ClassLoader resourcesLoader = null;
168
169 44128 jjdelcerro
    private List<DataProfile> dataProfiles;
170
171 44346 jjdelcerro
    private final Map<String, DatabaseWorkspaceManager> databaseWorkspaces = new HashMap<>();
172 44419 jjdelcerro
173 44821 jjdelcerro
    private final Map<String,DatabaseWorkspaceListener> addDatabaseWorkspaceListeners = new HashMap<>();
174 44871 jjdelcerro
175
    private final Set<Observer>storeObservers = new HashSet<>();
176 44346 jjdelcerro
177 43020 jjdelcerro
    public DefaultDataManager() {
178
        this.registers = new Registers();
179
        this.defaultDataIndexProviders = new HashMap<>();
180
    }
181
182
    @Override
183
    public Register getStoreRegister() {
184
        return this.registers.store;
185
    }
186
187
    @Override
188
    public Register getStoreProviderRegister() {
189
        return this.registers.storeProvider;
190
    }
191
192
    @Override
193
    public Register getServerExplorerRegister() {
194
        return this.registers.serverExplorer;
195
    }
196
197
    @Override
198
    public Register getFeatureIndexRegister() {
199
        return this.registers.featureIndexProvider;
200
    }
201
202
    private String getStoreName(DataStoreParameters parameters) {
203
        for (DataFactory factory : this.getStoreRegister()) {
204
            DataStoreFactory_v2_4 storeFactory = (DataStoreFactory_v2_4) factory;
205
            if (storeFactory.canUse(parameters)) {
206
                return storeFactory.getName();
207
            }
208
        }
209
        return null;
210
    }
211
212
    /**
213
     * @deprecated
214
     */
215
    @Override
216
    public void registerDefaultRasterStore(Class rasterStoreClass) {
217
        // Metodo usado por el raster nuevo para regstrar su factoria de store
218
        this.getStoreRegister().register(new RasterStoreFactory(rasterStoreClass));
219
    }
220
221 44831 jjdelcerro
222
    private boolean oldRasterRegistered = false;
223 43020 jjdelcerro
    /**
224
     * @deprecated
225
     */
226
    @Override
227
    public void registerStoreFactory(String name, Class storeFactoryClass) {
228
        // Metodo usado por el raster viejo para registrar las factorias de sus stores
229
        this.getStoreRegister().register(new RasterStoreOldFactory(name, storeFactoryClass));
230 44831 jjdelcerro
        this.oldRasterRegistered = true;
231 43020 jjdelcerro
    }
232
233 44831 jjdelcerro
    @Override
234
    public boolean isTheOldRasterRegistered() {
235
      return this.oldRasterRegistered;
236
    }
237
238 43020 jjdelcerro
    /**
239
     * @param name
240
     * @param storeProviderClass
241
     * @param parametersClass
242
     * @deprecated use registerStoreProviderFactory
243
     */
244
    @Override
245
    public void registerStoreProvider(String name, Class storeProviderClass,
246
            Class parametersClass) {
247
        if (name == null || storeProviderClass == null || parametersClass == null) {
248
            throw new IllegalArgumentException("Any parameters can be null");
249
        }
250
251
        if (!DataStoreParameters.class.isAssignableFrom(parametersClass)) {
252
            throw new IllegalArgumentException(parametersClass.getName()
253
                    + " must implement org.gvsig.fmap.dal.DataStoreParameters");
254
        }
255
256
        if (CoverageStoreProvider.class.isAssignableFrom(storeProviderClass)) {
257
            // Envuelve al proveedor en una factoria por defecto.
258
            this.registerStoreProviderFactory(new DataStoreProviderToCoverageProviderFactoryWrapper(
259
                    name, "", storeProviderClass, parametersClass));
260
            return;
261
        }
262
263
        if (FeatureStoreProvider.class.isAssignableFrom(storeProviderClass)) {
264
            // Envuelve al proveedor en una factoria por defecto.
265
            this.registerStoreProviderFactory(new DataStoreProviderToFeatureStoreProviderFactoryWrapper(
266
                    name, "", storeProviderClass, parametersClass));
267
            return;
268
        }
269
270
        throw new IllegalArgumentException("Not supported implemtation: name="
271
                + name + " provider class=" + storeProviderClass.getName());
272
273
    }
274
275
    @Override
276
    public void registerExplorerProvider(String name, Class explorerClass, Class parametersClass) {
277
        if (name == null || explorerClass == null || parametersClass == null) {
278
            // FIXME Exception
279
            throw new IllegalArgumentException("Any parameters can be null");
280
        }
281
282
        if (!DataServerExplorerParameters.class
283
                .isAssignableFrom(parametersClass)) {
284
            // FIXME Exception
285
            throw new IllegalArgumentException(
286
                    parametersClass.getName()
287
                    + " must implement org.gvsig.fmap.dal.DataServerExplorerParameters");
288
        }
289
290
        if (!DataServerExplorer.class.isAssignableFrom(explorerClass)) {
291
            // FIXME Exception
292
            throw new IllegalArgumentException(explorerClass.getName()
293
                    + " must implement org.gvsig.fmap.dal.DataServerExplorer");
294
        }
295
296
        // Envuelve al proveedor en una factoria por defecto.
297
        this.registerServerExplorerFactory(
298
                new DataServerExplorerToDataExplorerFactoryWrapper(
299
                        name, "", explorerClass, parametersClass
300
                )
301
        );
302
303
    }
304
305
    @Override
306
    public void registerStoreFactory(DataStoreFactory_v2_4 factory) {
307
        this.getStoreRegister().register(factory);
308
    }
309
310
    @Override
311
    public void registerStoreProviderFactory(DataStoreProviderFactory factory) {
312
        this.getStoreProviderRegister().register(factory);
313
    }
314
315
    @Override
316
    public void registerServerExplorerFactory(DataServerExplorerFactory factory) {
317
        this.getServerExplorerRegister().register(factory);
318
    }
319
320
    @Override
321 44304 jjdelcerro
    public DataStoreParameters createStoreParameters(byte[] data) {
322 44816 jjdelcerro
        DataStoreParameters parameters = (DataStoreParameters) AbstractDataParameters.fromByteArray(data);
323
        return parameters;
324 44304 jjdelcerro
    }
325
326 44743 jjdelcerro
    public DataStoreParameters createStoreParameters(String providerName) throws InitializeException, ProviderNotRegisteredException {
327
      // Cuando desde python se llama a createStoreParameters con solo un argumento
328
      // acaba entrando por aqui en lugar de por
329
      //   createStoreParameters(String providerName, Object... arguments)
330
      return this.createStoreParameters(providerName, (Object[]) null);
331
    }
332
333 44304 jjdelcerro
    @Override
334 44738 jjdelcerro
    public DataStoreParameters createStoreParameters(String providerName, Object... arguments) throws InitializeException, ProviderNotRegisteredException {
335 43503 jjdelcerro
        if( providerName == null ) {
336
            String msg = "Provider name can't be null.";
337 44023 jjdelcerro
            LOGGER.warn(msg);
338 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
339
        }
340 44743 jjdelcerro
        if( arguments!=null && arguments.length>0 ) {
341
          if( arguments.length == 1 ) {
342
              // Desde jython entra por este metodo en lugar de los especificos
343
              // de DataStoreParameters o DynObject
344
              if( arguments[0] instanceof DataStoreParameters ) {
345
                  return this.createStoreParameters(providerName, (DataStoreParameters)(arguments[0]));
346
              } else if( arguments[0] instanceof DynObject ) {
347
                  return this.createStoreParameters(providerName, (DynObject)(arguments[0]));
348
              }
349
          }
350
          if( (arguments.length % 2)!= 0 ) {
351
              throw new IllegalArgumentException("The number of arguments must be even.");
352
          }
353 44738 jjdelcerro
        }
354
        if( providerName == null ) {
355
            String msg = "Provider name can't be null.";
356
            LOGGER.warn(msg);
357
            throw new IllegalArgumentException(msg);
358
        }
359 43020 jjdelcerro
        DataFactory providerFactory = this.getStoreProviderRegister().getFactory(providerName);
360 43503 jjdelcerro
        if( providerFactory == null ) {
361
            String msg = "Can't locate provider factory for '"+providerName+"'.";
362 44023 jjdelcerro
            LOGGER.warn(msg);
363 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
364
        }
365 44738 jjdelcerro
        DataStoreParameters parameters = (DataStoreParameters) providerFactory.createParameters();
366 44743 jjdelcerro
        if( arguments!=null && arguments.length>0 ) {
367
          for( int i=0; i<arguments.length; i+=2 ) {
368
              String name = (String) arguments[i];
369
              if( name.endsWith("=") ) {
370
                  name = name.substring(0, name.length()-1);
371
              }
372
              Object value = arguments[i+1];
373
              parameters.setDynValue(name, value);
374
          }
375 44738 jjdelcerro
        }
376
        return parameters;
377 43020 jjdelcerro
    }
378
379
    @Override
380
    public NewDataStoreParameters createNewStoreParameters(String explorerName, String providerName) throws InitializeException, ProviderNotRegisteredException {
381
        try {
382 43093 jjdelcerro
            DataServerExplorer explorer = this.openServerExplorer(explorerName, (DataServerExplorerParameters)null);
383 43020 jjdelcerro
            return explorer.getAddParameters(providerName);
384
        } catch (Exception ex) {
385
            throw new InitializeException(ex);
386
        }
387
    }
388
389
    @Override
390
    public DataServerExplorerParameters createServerExplorerParameters(String explorerName) throws InitializeException, ProviderNotRegisteredException {
391 43503 jjdelcerro
        if( explorerName == null ) {
392
            String msg = "Explorer name can't be null.";
393 44023 jjdelcerro
            LOGGER.warn(msg);
394 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
395
        }
396 43020 jjdelcerro
        DataFactory explorerFactory = this.getServerExplorerRegister().getFactory(explorerName);
397 43488 jjdelcerro
        if( explorerFactory == null ) {
398
            String msg = "Can't locate server explorer factory for '"+explorerName+"'.";
399 44023 jjdelcerro
            LOGGER.warn(msg);
400 43488 jjdelcerro
            throw new IllegalArgumentException(msg);
401
        }
402 43020 jjdelcerro
        DataServerExplorerParameters params = (DataServerExplorerParameters) explorerFactory.createParameters();
403
        return params;
404
    }
405
406
    @Override
407
    public DataStoreParameters createMemoryStoreParameters(String autoOrderAttributeName) throws InitializeException {
408
        try {
409
            DataStoreParameters parameters = createStoreParameters(MemoryStoreProvider.NAME);
410
            if (autoOrderAttributeName != null) {
411
                parameters.setDynValue(
412
                        MemoryStoreParameters.ORDER_PARAMETER_NAME,
413
                        autoOrderAttributeName);
414
            }
415
            return parameters;
416
        } catch (Exception ex) {
417
            throw new InitializeException(ex);
418
        }
419
    }
420
421
    @Override
422
    public DataServerExplorer openServerExplorer(String explorerName, DataServerExplorerParameters parameters) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
423 43503 jjdelcerro
        if( explorerName == null ) {
424
            String msg = "Explorer name can't be null.";
425 44023 jjdelcerro
            LOGGER.warn(msg);
426 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
427
        }
428 43020 jjdelcerro
        DataFactory explorerFactory = this.getServerExplorerRegister().getFactory(explorerName);
429 43450 jjdelcerro
        if( explorerFactory == null ) {
430
            String msg = "Can't locate server explorer factory for '"+explorerName+"'.";
431 44023 jjdelcerro
            LOGGER.warn(msg);
432 43450 jjdelcerro
            throw new IllegalArgumentException(msg);
433
        }
434 43020 jjdelcerro
        if (parameters == null) {
435
            parameters = (DataServerExplorerParameters) explorerFactory.createParameters();
436
        }
437
        DataServerExplorer explorer = (DataServerExplorer) explorerFactory.create(
438
                parameters,
439
                new DefaultDataServerExplorerProviderServices()
440
        );
441
        return explorer;
442
    }
443 43205 fdiaz
444 43093 jjdelcerro
    @Override
445
    public DataServerExplorer openServerExplorer(String explorerName, Object... arguments) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
446 43373 jjdelcerro
        if( arguments.length==1 && arguments[0] instanceof DataServerExplorerParameters ) {
447 44669 jjdelcerro
            // Esto hace falta ya que desde scripting si se invoca a openServerExplorer con solo
448 43373 jjdelcerro
            // un parametro de tipo DataServerExplorerParameters llama ha este metodo en lugar de
449
            // llamar al que toca.
450
            return openServerExplorer(explorerName, (DataServerExplorerParameters)(arguments[0]));
451
        }
452 43503 jjdelcerro
        if( explorerName == null ) {
453
            String msg = "Explorer name can't be null.";
454 44023 jjdelcerro
            LOGGER.warn(msg);
455 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
456
        }
457 43093 jjdelcerro
        if( (arguments.length % 2)!= 0 ) {
458
            throw new ValidateDataParametersException();
459
        }
460
        DataFactory explorerFactory = this.getServerExplorerRegister().getFactory(explorerName);
461
        DataServerExplorerParameters parameters = (DataServerExplorerParameters) explorerFactory.createParameters();
462
        for( int i=0; i<arguments.length; i+=2 ) {
463
            String name = (String) arguments[i];
464 44669 jjdelcerro
            if( name.endsWith("=") ) {
465
                name = name.substring(0, name.length()-1);
466
            }
467 43093 jjdelcerro
            Object value = arguments[i+1];
468
            parameters.setDynValue(name, value);
469
        }
470
        return this.openServerExplorer(explorerName, parameters);
471 43205 fdiaz
472 43093 jjdelcerro
    }
473 43205 fdiaz
474 43020 jjdelcerro
    /**
475
     * @param parameters
476
     * @return
477
     * @throws org.gvsig.fmap.dal.exception.InitializeException
478
     * @throws org.gvsig.fmap.dal.exception.ProviderNotRegisteredException
479
     * @throws org.gvsig.fmap.dal.exception.ValidateDataParametersException
480
     * @deprecated see openServerExplorer
481
     */
482
    @Override
483
    public DataServerExplorer createServerExplorer(
484
            DataServerExplorerParameters parameters) throws InitializeException,
485
            ProviderNotRegisteredException, ValidateDataParametersException {
486
        return openServerExplorer(parameters.getExplorerName(), parameters);
487
    }
488
489 43045 jjdelcerro
    /**
490
     * @deprecated use openStore
491
     * @param parameters
492
     * @return
493
     * @throws InitializeException
494
     * @throws ProviderNotRegisteredException
495 43205 fdiaz
     * @throws ValidateDataParametersException
496 43045 jjdelcerro
     */
497 43020 jjdelcerro
    @Override
498 43045 jjdelcerro
    public DataStore createStore(DataStoreParameters parameters)
499
        throws InitializeException, ProviderNotRegisteredException,
500
        ValidateDataParametersException {
501
        return openStore(parameters.getDataStoreName(), parameters);
502
    }
503 43205 fdiaz
504 43045 jjdelcerro
    @Override
505 43020 jjdelcerro
    public DataStore openStore(String providerName, DataStoreParameters parameters) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
506 43503 jjdelcerro
        if( providerName == null ) {
507
            String msg = "Provider name can't be null.";
508 44023 jjdelcerro
            LOGGER.warn(msg);
509 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
510
        }
511 43020 jjdelcerro
        SimpleIdentityManager identityManager = ToolsLocator.getIdentityManager();
512
        if (!identityManager.getCurrentIdentity().isAuthorized(READ_STORE_AUTHORIZATION, parameters, providerName)) {
513
            throw new UnauthorizedException(READ_STORE_AUTHORIZATION, parameters, providerName);
514
        }
515
516 43088 jjdelcerro
        parameters.validate();
517 43205 fdiaz
518 43020 jjdelcerro
        String storeName = this.getStoreName(parameters);
519 43450 jjdelcerro
        if( StringUtils.isEmpty(storeName) ) {
520
            String msg = "Can't locate the store name from the parameters. parameters=" + parameters.toString();
521 44023 jjdelcerro
            LOGGER.warn(msg);
522 43450 jjdelcerro
            throw new IllegalArgumentException(msg);
523
        }
524 43020 jjdelcerro
525
        DataStoreFactory_v2_4 storeFactory = (DataStoreFactory_v2_4) this.getStoreRegister().getFactory(storeName);
526 43450 jjdelcerro
        if( storeFactory == null ) {
527
            String msg = "Can't locate store factory for '"+storeName+"'.";
528 44023 jjdelcerro
            LOGGER.warn(msg);
529 43450 jjdelcerro
            throw new IllegalArgumentException(msg);
530
        }
531 43020 jjdelcerro
        DataFactory providerFactory = this.getStoreProviderRegister().getFactory(providerName);
532 43450 jjdelcerro
        if( providerFactory == null ) {
533
            String msg = "Can't locate provider factory for '"+providerName+"'.";
534 44023 jjdelcerro
            LOGGER.warn(msg);
535 43450 jjdelcerro
            throw new IllegalArgumentException(msg);
536
        }
537 43020 jjdelcerro
538
        DataStore store = (DataStore) storeFactory.create(parameters, this);
539
        DataStoreProvider provider = (DataStoreProvider) providerFactory.create(parameters, store);
540
541
        storeFactory.setProvider(store, provider);
542 44871 jjdelcerro
543
        for (Observer storeObserver : storeObservers) {
544
          if( storeObserver!=null) {
545
            store.addObserver(storeObserver);
546
          }
547
        }
548
        if( store instanceof FeatureStoreProviderServices ) {
549
          ((FeatureStoreProviderServices) store).notifyChange(DataStoreNotification.AFTER_OPEN);
550
        }
551 43020 jjdelcerro
        return store;
552
    }
553
554 44871 jjdelcerro
    @Override
555 44253 jjdelcerro
    public DataStore openStore(DataStoreParameters parameters, DataStoreProvider provider) {
556
        String storeName = this.getStoreName(parameters);
557
        if( StringUtils.isEmpty(storeName) ) {
558
            String msg = "Can't locate the store name from the parameters. parameters=" + parameters.toString();
559
            LOGGER.warn(msg);
560
            throw new IllegalArgumentException(msg);
561
        }
562
563
        DataStoreFactory_v2_4 storeFactory = (DataStoreFactory_v2_4) this.getStoreRegister().getFactory(storeName);
564
        if( storeFactory == null ) {
565
            String msg = "Can't locate store factory for '"+storeName+"'.";
566
            LOGGER.warn(msg);
567
            throw new IllegalArgumentException(msg);
568
        }
569
        DataStore store = (DataStore) storeFactory.create(parameters, this);
570
        storeFactory.setProvider(store, provider);
571 44871 jjdelcerro
        for (Observer storeObserver : storeObservers) {
572
          if( storeObserver!=null) {
573
            store.addObserver(storeObserver);
574
          }
575
        }
576
        if( store instanceof FeatureStoreProviderServices ) {
577
          ((FeatureStoreProviderServices) store).notifyChange(DataStoreNotification.AFTER_OPEN);
578
        }
579 44253 jjdelcerro
        return store;
580
    }
581
582 43020 jjdelcerro
    @Override
583
    public DataStore openStore(String provider, DynObject parameters) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
584
        DataStoreParameters params = toDataStoreParameters(provider, parameters);
585
        DataStore store = openStore(params.getDataStoreName(), params);
586
        return store;
587
    }
588
589
    @Override
590 43093 jjdelcerro
    public DataStore openStore(String providerName, Object... arguments) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
591 43239 jjdelcerro
        if( arguments.length == 1 ) {
592
            // Desde jython entra por este metodo en lugar de los especificos
593
            // de DataStoreParameters o DynObject
594
            if( arguments[0] instanceof DataStoreParameters ) {
595
                return this.openStore(providerName, (DataStoreParameters)(arguments[0]));
596
            } else if( arguments[0] instanceof DynObject ) {
597
                return this.openStore(providerName, (DynObject)(arguments[0]));
598
            }
599
        }
600 43093 jjdelcerro
        if( (arguments.length % 2)!= 0 ) {
601
            throw new ValidateDataParametersException();
602
        }
603 43503 jjdelcerro
        if( providerName == null ) {
604
            String msg = "Provider name can't be null.";
605 44023 jjdelcerro
            LOGGER.warn(msg);
606 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
607
        }
608 43093 jjdelcerro
        DataFactory providerFactory = this.getStoreProviderRegister().getFactory(providerName);
609
        DataStoreParameters parameters = (DataStoreParameters) providerFactory.createParameters();
610
        for( int i=0; i<arguments.length; i+=2 ) {
611
            String name = (String) arguments[i];
612 44669 jjdelcerro
            if( name.endsWith("=") ) {
613
                name = name.substring(0, name.length()-1);
614
            }
615 43093 jjdelcerro
            Object value = arguments[i+1];
616
            parameters.setDynValue(name, value);
617
        }
618
        return this.openStore(providerName, parameters);
619
    }
620 43205 fdiaz
621 43093 jjdelcerro
    @Override
622 43020 jjdelcerro
    public FeatureStore createMemoryStore(String autoOrderAttributeName) throws InitializeException {
623
        try {
624
            DataStoreParameters parameters = createMemoryStoreParameters(autoOrderAttributeName);
625
            DataStore store = openStore(MemoryStoreProvider.NAME, parameters);
626
            return (FeatureStore) store;
627
        } catch (Exception ex) {
628
            throw new InitializeException(ex);
629
        }
630
    }
631
632
    @Override
633
    public DataStoreProviderFactory getStoreProviderFactory(String providerName) {
634 43503 jjdelcerro
        if( providerName == null ) {
635
            String msg = "Provider name can't be null.";
636 44023 jjdelcerro
            LOGGER.warn(msg);
637 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
638
        }
639 43020 jjdelcerro
        DataFactory providerFactory = this.getStoreProviderRegister().getFactory(providerName);
640
        return (DataStoreProviderFactory) providerFactory;
641
    }
642
643
    @Override
644
    public List<String> getStoreProviders() {
645
        return this.getStoreProviderRegister().getFactoryNames();
646
    }
647
648
    @Override
649
    public List<String> getStoreProviders(String explorerName) {
650 43503 jjdelcerro
        if( explorerName == null ) {
651
            String msg = "Explorer name can't be null.";
652 44023 jjdelcerro
            LOGGER.warn(msg);
653 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
654
        }
655 43020 jjdelcerro
        try {
656 43093 jjdelcerro
            DataServerExplorer explorer = openServerExplorer(explorerName, (DataServerExplorerParameters)null);
657 43020 jjdelcerro
            List names = explorer.getDataStoreProviderNames();
658
            return names;
659
        } catch (Exception ex) {
660
            throw new RuntimeException("Can't get stores availables for explorer '" + explorerName + "'.", ex);
661
        }
662
    }
663
664
    @Override
665
    public List<String> getExplorerProviders() {
666
        List<String> names = this.getServerExplorerRegister().getFactoryNames();
667
        return names;
668
    }
669
670
    @Override
671
    public DataStoreProvider createProvider(DataStoreProviderServices providerServices, DataStoreParameters parameters) throws InitializeException, ProviderNotRegisteredException {
672
673
        String providerName = parameters.getDataStoreName();
674
        DataFactory providerFactory = this.getStoreProviderRegister().getFactory(providerName);
675
        if (providerFactory == null) {
676
            throw new ProviderNotRegisteredException(providerName);
677
        }
678
        while (true) {
679
            try {
680
                DataStoreProvider provider = (DataStoreProvider) providerFactory.create(
681
                        parameters, providerServices
682
                );
683
                return provider;
684
            } catch (Exception e) {
685
                if (openErrorHandler == null) {
686
                    throw new InitializeException(providerName, e);
687
                }
688
                boolean retry = openErrorHandler.canRetryOpen(e, parameters);
689
                if (!retry) {
690
                    throw new InitializeException(providerName, e);
691
                }
692
            }
693
        }
694
    }
695
696
    @Override
697
    public List<String> getFeatureIndexProviders() {
698
        List<String> names = this.getFeatureIndexRegister().getFactoryNames();
699
        return names;
700
    }
701
702
    @Override
703
    public void setDefaultFeatureIndexProviderName(int dataType, String name) {
704
        this.defaultDataIndexProviders.put(dataType, name);
705
    }
706
707
    @Override
708
    public String getDefaultFeatureIndexProviderName(int dataType) {
709
        return this.defaultDataIndexProviders.get(dataType);
710
    }
711
712
    @Override
713
    public FeatureIndexProviderServices createFeatureIndexProvider(
714
            String name,
715
            FeatureStore store,
716
            FeatureType type,
717
            String indexName,
718
            FeatureAttributeDescriptor attr
719
    ) throws InitializeException, ProviderNotRegisteredException {
720
721
        if (name == null) {
722
            name = getDefaultFeatureIndexProviderName(attr.getType());
723
        }
724
725
        if (name == null) {
726
            throw new InitializeException(
727
                    "There not any index provider registered.", null);
728
        }
729
        DataFactory indexfactory = this.getFeatureIndexRegister().getFactory(name);
730
        if (indexfactory == null) {
731
            throw new InitializeException(
732
                    "There not any index provider registered with name '" + name + "'.", null);
733
734
        }
735
        FeatureIndexProvider provider = (FeatureIndexProvider) indexfactory.create(null, null);
736
737
        FeatureIndexProviderServices services = new DefaultFeatureIndex(
738
                (FeatureStoreProviderServices) store,
739
                type,
740
                provider,
741
                attr.getName(),
742
                indexName
743
        );
744
        services.initialize();
745
        return services;
746
747
    }
748
749
    @Override
750
    public String getTemporaryDirectory() {
751 43241 jjdelcerro
        FoldersManager manager = ToolsLocator.getFoldersManager();
752
        File folder = manager.getUniqueTemporaryFile("_daltmp_");
753
        return folder.getAbsolutePath();
754 43020 jjdelcerro
    }
755
756
    @Override
757
    public DataStoreParameters createStoreParameters(DynStruct struct) throws InitializeException, ProviderNotRegisteredException {
758
        if (!(struct instanceof DynStruct_v2)) {
759
            throw new IllegalArgumentException("A DynStruct_v2 is required.");
760
        }
761
        Tags tags = ((DynStruct_v2) struct).getTags();
762
        return this.createStoreParameters(tags);
763
    }
764
765
    @Override
766
    public DataStoreParameters createStoreParameters(Tags tags) throws InitializeException, ProviderNotRegisteredException {
767
        String providerName = (String) tags.get(TAG_DAL_OPENSTORE + "provider");
768
        if (providerName == null) {
769
            throw new IllegalArgumentException("Tag DAL.OpenStore.provider is missing in struct.");
770
        }
771
        int prefixlen = TAG_DAL_OPENSTORE.length();
772
        DataStoreParameters parameters = this.createStoreParameters(providerName);
773
        for (String key : tags) {
774
            if (key.startsWith(TAG_DAL_OPENSTORE)) {
775
                parameters.setDynValue(key.substring(prefixlen), tags.get(key));
776
            }
777
        }
778
        return parameters;
779
    }
780
781
    @Override
782
    public DataStore openStore(DynStruct struct) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
783
        DataStoreParameters paramters = this.createStoreParameters(struct);
784
        DataStore store = this.openStore(paramters.getDataStoreName(), paramters);
785
        return store;
786
    }
787
788
    @Override
789
    public void newStore(String explorerName, String providerName, NewDataStoreParameters parameters, boolean overwrite) throws InitializeException, ProviderNotRegisteredException, ValidateDataParametersException {
790 43503 jjdelcerro
        if( explorerName == null ) {
791
            String msg = "Explorer name can't be null.";
792 44023 jjdelcerro
            LOGGER.warn(msg);
793 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
794
        }
795
        if( providerName == null ) {
796
            String msg = "Provider name can't be null.";
797 44023 jjdelcerro
            LOGGER.warn(msg);
798 43503 jjdelcerro
            throw new IllegalArgumentException(msg);
799
        }
800 43020 jjdelcerro
801
        SimpleIdentityManager identityManager = ToolsLocator.getIdentityManager();
802
        if (!identityManager.getCurrentIdentity().isAuthorized(CREATE_STORE_AUTHORIZATION, parameters, providerName)) {
803
            throw new UnauthorizedException(CREATE_STORE_AUTHORIZATION, parameters, providerName);
804
        }
805
        parameters.validate();
806
        try {
807
            DataServerExplorerParameters explorerParameters = this.createServerExplorerParameters(explorerName);
808
            DataServerExplorer server = this.openServerExplorer(explorerName, explorerParameters);
809
            server.add(providerName, parameters, overwrite);
810
        } catch (Exception e) {
811
            throw new InitializeException(e);
812
        }
813
    }
814
815
    @Override
816 44023 jjdelcerro
    @Deprecated
817
    public Evaluator createExpresion(String expression) throws InitializeException {
818
        Expression exp = ExpressionEvaluatorLocator.getManager().createExpression();
819
        exp.setPhrase(expression);
820
        return this.createExpresion(exp);
821 43020 jjdelcerro
    }
822
823
    @Override
824 44023 jjdelcerro
    @Deprecated
825
    public Evaluator createExpresion(Expression expression) throws InitializeException {
826
        DefaultExpressionEvaluator exp = new DefaultExpressionEvaluator(expression);
827
        return exp;
828 43020 jjdelcerro
    }
829
830 44023 jjdelcerro
831 43020 jjdelcerro
    @Override
832 44023 jjdelcerro
    public Evaluator createFilter(String expression) throws InitializeException {
833
        Expression exp = ExpressionEvaluatorLocator.getManager().createExpression();
834
        exp.setPhrase(expression);
835
        return this.createFilter(exp);
836
    }
837
838
    @Override
839
    public Evaluator createFilter(Expression expression) throws InitializeException {
840 43984 jjdelcerro
        DefaultExpressionEvaluator exp = new DefaultExpressionEvaluator(expression);
841
        return exp;
842
    }
843
844
    @Override
845 43020 jjdelcerro
    public FeaturePagingHelper createFeaturePagingHelper(
846
            FeatureStore featureStore, int pageSize) throws BaseException {
847
        return new FeaturePagingHelperImpl(featureStore, pageSize);
848
    }
849
850
    @Override
851
    public FeaturePagingHelper createFeaturePagingHelper(
852
            FeatureStore featureStore, FeatureQuery featureQuery, int pageSize)
853
            throws BaseException {
854
        return new FeaturePagingHelperImpl(featureStore, featureQuery, pageSize);
855
    }
856
857
    @Override
858
    public void setOpenErrorHandler(OpenErrorHandler handler) {
859
        openErrorHandler = handler;
860
    }
861
862
    @Override
863
    public OpenErrorHandler getOpenErrorHandler() {
864
        return this.openErrorHandler;
865
    }
866
867
    @Override
868
    public EditableFeatureType createFeatureType() {
869 43739 jjdelcerro
        return new DefaultEditableFeatureType(null);
870 43020 jjdelcerro
    }
871
872
    @Override
873
    public DataServerExplorerPool getDataServerExplorerPool() {
874
        if (this.dataServerExplorerPool == null) {
875
            this.dataServerExplorerPool = new DefaultDataServerExplorerPool();
876
        }
877
        return this.dataServerExplorerPool;
878
    }
879
880
    @Override
881
    public void setDataServerExplorerPool(DataServerExplorerPool pool) {
882
        this.dataServerExplorerPool = pool;
883
    }
884
885
    public DataStoreParameters toDataStoreParameters(String provider, DynObject params) throws InitializeException, ProviderNotRegisteredException {
886
        if (params instanceof DataStoreParameters) {
887
            return (DataStoreParameters) params;
888
        }
889
        String providerName;
890
        try {
891
            providerName = (String) params.getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME);
892
        } catch (Exception ex) {
893
            providerName = provider;
894
        }
895
        DataStoreParameters parameters = this.createStoreParameters(providerName);
896
        ToolsLocator.getDynObjectManager().copy(params, parameters);
897
        return parameters;
898
    }
899
900
    @Override
901
    public List<DataType> getDataTypes() {
902
        if (dataTypes == null) {
903
            DataTypesManager manager = ToolsLocator.getDataTypesManager();
904
            dataTypes = new ArrayList<>();
905
            dataTypes.add(manager.get(DataTypes.STRING));
906
            dataTypes.add(manager.get(DataTypes.BOOLEAN));
907
            dataTypes.add(manager.get(DataTypes.INT));
908
            dataTypes.add(manager.get(DataTypes.DOUBLE));
909
            dataTypes.add(manager.get(DataTypes.DATE));
910
            dataTypes.add(manager.get(DataTypes.GEOMETRY));
911
        }
912
        return dataTypes;
913
    }
914
915
    @Override
916
    public void setResourcesLoader(ClassLoader loader) {
917
        this.resourcesLoader = loader;
918
    }
919
920
    @Override
921
    public void setResourcesLoader(File folder) {
922
        if (folder == null) {
923
            this.resourcesLoader = null;
924
            return;
925
        }
926
        try {
927
            URL[] urls = new URL[]{folder.toURI().toURL()};
928
            this.resourcesLoader = new URLClassLoader(urls);
929
        } catch (Exception ex) {
930
            throw new IllegalArgumentException("Can't create a ClassLoader from '" + folder.toString() + "'.", ex);
931
        }
932
    }
933
934
    @Override
935
    public URL getResource(Object reourceLoader, String name) {
936
        URL x;
937
        if (this.resourcesLoader != null) {
938
            x = this.resourcesLoader.getResource(name);
939
            if (x != null) {
940
                return x;
941
            }
942
        }
943
        x = reourceLoader.getClass().getResource(name);
944
        return x;
945
    }
946
947
    @Override
948
    public InputStream getResourceAsStream(Object reourceLoader, String name) {
949
        InputStream x;
950
        if (this.resourcesLoader != null) {
951
            x = this.resourcesLoader.getResourceAsStream(name);
952
            if (x != null) {
953
                return x;
954
            }
955
        }
956
        x = reourceLoader.getClass().getResourceAsStream(name);
957
        return x;
958
    }
959 43205 fdiaz
960 43040 jjdelcerro
    @Override
961
    public ExpressionBuilder createExpressionBuilder() {
962 44042 jjdelcerro
        return ExpressionEvaluatorLocator.getManager().createExpressionBuilder();
963 43040 jjdelcerro
    }
964 43056 jjdelcerro
965
    public void registerFeatureCacheProvider(
966
        FeatureCacheProviderFactory providerFactory) {
967
        ToolsLocator.getExtensionPointManager()
968
            .add(DATA_MANAGER_CACHE, DATA_MANAGER_CACHE_DESCRIPTION)
969
            .append(providerFactory.getName(), "", providerFactory);
970
    }
971
972
    public FeatureCacheProvider createFeatureCacheProvider(String name,
973
        DynObject parameters) throws DataException {
974
        if (name == null) {
975
            throw new InitializeException(
976
                "It is necessary to provide a cache name", null);
977
        }
978
        if (parameters == null) {
979
            throw new InitializeException(
980
                "It is necessary to provide parameters to create the explorer",
981
                null);
982
        }
983
        FeatureCacheProviderFactory featureCacheProviderFactory;
984
        try {
985
            featureCacheProviderFactory =
986
                (FeatureCacheProviderFactory) ToolsLocator
987
                    .getExtensionPointManager().get(DATA_MANAGER_CACHE)
988
                    .create(name);
989
            if (featureCacheProviderFactory == null) {
990
                throw new ProviderNotRegisteredException(name);
991
            }
992
            return featureCacheProviderFactory.createCacheProvider(parameters);
993
        } catch (InstantiationException e) {
994
            throw new InitializeException(e);
995
        } catch (IllegalAccessException e) {
996
            throw new InitializeException(e);
997
        }
998
    }
999
1000 43093 jjdelcerro
    @Override
1001 43056 jjdelcerro
    public List getFeatureCacheProviders() {
1002
        ExtensionPoint extensionPoint =
1003
            ToolsLocator.getExtensionPointManager().get(DATA_MANAGER_CACHE);
1004
        if (extensionPoint != null) {
1005
            return ToolsLocator.getExtensionPointManager()
1006
                .get(DATA_MANAGER_CACHE).getNames();
1007
        } else {
1008
            return new ArrayList();
1009
        }
1010
    }
1011
1012 43093 jjdelcerro
    @Override
1013 43056 jjdelcerro
    public DynObject createCacheParameters(String name)
1014
        throws InitializeException, ProviderNotRegisteredException {
1015
        if (name == null) {
1016
            throw new InitializeException(
1017
                "It is necessary to provide a cache name", null);
1018
        }
1019
        FeatureCacheProviderFactory featureCacheProviderFactory;
1020
        try {
1021
            featureCacheProviderFactory =
1022
                (FeatureCacheProviderFactory) ToolsLocator
1023
                    .getExtensionPointManager().get(DATA_MANAGER_CACHE)
1024
                    .create(name);
1025
            if (featureCacheProviderFactory == null) {
1026
                throw new ProviderNotRegisteredException(name);
1027
            }
1028
            return featureCacheProviderFactory.createParameters();
1029
        } catch (InstantiationException e) {
1030
            throw new InitializeException(e);
1031
        } catch (IllegalAccessException e) {
1032
            throw new InitializeException(e);
1033
        }
1034
    }
1035
1036 43205 fdiaz
    @Override
1037 43212 jjdelcerro
    public void createFileStore(String providerName, NewDataStoreParameters params, boolean overwrite) throws DataException {
1038 43205 fdiaz
        DataManagerProviderServices dataManager = DALSPILocator.getDataManagerProviderServices();
1039
        DataServerExplorerParameters eparams = null;
1040
        DataServerExplorer serverExplorer;
1041
        try {
1042
            serverExplorer = dataManager.openServerExplorer(FILESYSTEM_EXPLORER_NAME, eparams);
1043
        } catch (ValidateDataParametersException | InitializeException | ProviderNotRegisteredException e) {
1044
            throw new OpenException(FILESYSTEM_EXPLORER_NAME, e);
1045
        }
1046 43056 jjdelcerro
1047 43205 fdiaz
        try {
1048
            serverExplorer.add(providerName, params, overwrite);
1049
        } catch (DataException e) {
1050
            throw new CreateFileStoreException(e, providerName);
1051
        }
1052
    }
1053 43983 jjdelcerro
1054
    @Override
1055
    public FeatureSymbolTable createFeatureSymbolTable() {
1056 44738 jjdelcerro
        FeatureSymbolTable symbolTable = new FeatureSymbolTableImpl();
1057 43983 jjdelcerro
        return symbolTable;
1058
    }
1059
1060
    @Override
1061 43989 jjdelcerro
    public FeatureAttributeEmulatorExpression createFeatureAttributeEmulatorExpression(FeatureType type, Expression expression) {
1062
        FeatureAttributeEmulatorExpression emulator = new DefaultFeatureAttributeEmulatorExpression(type, expression);
1063
        return emulator;
1064
    }
1065
1066 44128 jjdelcerro
    @Override
1067
    public void registerDataProfile(DataProfile profile) {
1068
        if( profile==null ) {
1069
            return;
1070
        }
1071
        if( this.dataProfiles==null ) {
1072
            this.dataProfiles = new ArrayList<>();
1073
            this.dataProfiles.add(profile);
1074
            return;
1075
        }
1076
        for (DataProfile theProfile : this.dataProfiles) {
1077 44253 jjdelcerro
            if( theProfile.getID().equalsIgnoreCase(profile.getID()) ) {
1078 44128 jjdelcerro
                return;
1079
            }
1080
        }
1081
        this.dataProfiles.add(profile);
1082
    }
1083 43989 jjdelcerro
1084 44128 jjdelcerro
    @Override
1085
    public List<DataProfile> getDataProfiles() {
1086
        if( this.dataProfiles==null ) {
1087
            return null;
1088
        }
1089
        return Collections.unmodifiableList(this.dataProfiles);
1090
    }
1091
1092
    @Override
1093
    public DataProfile getDataProfile(String name) {
1094
        if( StringUtils.isBlank(name) ) {
1095
            return null;
1096
        }
1097
        for (DataProfile theProfile : this.dataProfiles) {
1098
            if( name.equalsIgnoreCase(theProfile.getName()) ) {
1099
                return theProfile;
1100
            }
1101
        }
1102
        return null;
1103
    }
1104
1105 44253 jjdelcerro
    private StoresRepository storesRepository;
1106
1107
    @Override
1108
    public StoresRepository getStoresRepository() {
1109
        if( this.storesRepository==null ) {
1110 44304 jjdelcerro
            this.storesRepository = new BaseStoresRepository("DAL");
1111 44253 jjdelcerro
        }
1112
        return this.storesRepository;
1113
    }
1114 44304 jjdelcerro
1115 44253 jjdelcerro
    @Override
1116 44304 jjdelcerro
    public DatabaseWorkspaceManager createDatabaseWorkspaceManager(DataServerExplorerParameters connection) {
1117
        DatabaseWorkspaceManager workspace = new DefaultDatabaseWorkspaceManager(connection);
1118
        return workspace;
1119 44253 jjdelcerro
    }
1120 44346 jjdelcerro
1121
    @Override
1122 44821 jjdelcerro
    public void removeDatabaseWorkspace(DatabaseWorkspaceManager databaseWorkspace) {
1123
        this.databaseWorkspaces.remove(databaseWorkspace.getId(),databaseWorkspace);
1124
        StoresRepository repo = databaseWorkspace.getStoresRepository();
1125
        this.getStoresRepository().removeRepository(repo.getID());
1126
        for (DatabaseWorkspaceListener listener : this.addDatabaseWorkspaceListeners.values()) {
1127
            if( listener!=null ) {
1128
                try {
1129
                    listener.onRemoveDatabaseWorkspace(databaseWorkspace);
1130
                } catch(Throwable th) {
1131
                    LOGGER.warn("Problems calling databaseworkspace listener '"+listener.getName()+"'.",th);
1132
                }
1133
            }
1134
        }
1135
        try {
1136
            ResourcesStorage resources = databaseWorkspace.getResourcesStorage();
1137
            ScriptManager scriptManager = ToolsLocator.getScriptManager();
1138
            Script script = scriptManager.loadScript(resources, "OnDisconnectToWorkspace.script");
1139
            if( script != null ) {
1140
                script.invokeFunction("main", new Object[] {databaseWorkspace});
1141
            }
1142
        } catch(Throwable th) {
1143
            LOGGER.warn("Problems executing 'OnDisconnectToWorkspace.script' from workspace '"+databaseWorkspace.getId()+"'.",th);
1144
        }
1145
    }
1146
1147
    @Override
1148 44346 jjdelcerro
    public void addDatabaseWorkspace(DatabaseWorkspaceManager databaseWorkspace) {
1149
        this.databaseWorkspaces.put(databaseWorkspace.getId(),databaseWorkspace);
1150
        StoresRepository repo = databaseWorkspace.getStoresRepository();
1151
        this.getStoresRepository().addRepository(repo);
1152 44419 jjdelcerro
1153 44821 jjdelcerro
        for (DatabaseWorkspaceListener listener : this.addDatabaseWorkspaceListeners.values()) {
1154 44419 jjdelcerro
            if( listener!=null ) {
1155
                try {
1156
                    listener.onAddDatabaseWorkspace(databaseWorkspace);
1157
                } catch(Throwable th) {
1158
                    LOGGER.warn("Problems calling databaseworkspace listener '"+listener.getName()+"'.",th);
1159
                }
1160
            }
1161
        }
1162
        try {
1163
            ResourcesStorage resources = databaseWorkspace.getResourcesStorage();
1164
            ScriptManager scriptManager = ToolsLocator.getScriptManager();
1165
            Script script = scriptManager.loadScript(resources, "OnConnectToWorkspace.script");
1166
            if( script != null ) {
1167
                script.invokeFunction("main", new Object[] {databaseWorkspace});
1168
            }
1169
        } catch(Throwable th) {
1170
            LOGGER.warn("Problems executing 'OnConnectToWorkspace.script' from workspace '"+databaseWorkspace.getId()+"'.",th);
1171
        }
1172 44346 jjdelcerro
    }
1173 44419 jjdelcerro
1174
    @Override
1175 44821 jjdelcerro
    public void addDatabaseWorkspaceListener(DatabaseWorkspaceListener listener) {
1176 44419 jjdelcerro
        this.addDatabaseWorkspaceListeners.put(listener.getName(), listener);
1177
    }
1178 44346 jjdelcerro
1179
    @Override
1180
    public DatabaseWorkspaceManager getDatabaseWorkspace(String name) {
1181 44821 jjdelcerro
        if( StringUtils.isBlank(name) ) {
1182
          return null;
1183
        }
1184 44346 jjdelcerro
        return this.databaseWorkspaces.get(name);
1185
    }
1186 44328 jjdelcerro
1187
    @Override
1188 44346 jjdelcerro
    public DatabaseWorkspaceManager getDatabaseWorkspace(DataStoreParameters params) {
1189
        for (DatabaseWorkspaceManager databaseWorkspace : this.databaseWorkspaces.values()) {
1190
            if( databaseWorkspace.getStoresRepository().contains(params) ) {
1191
                return databaseWorkspace;
1192
            }
1193
        }
1194
        return null;
1195
    }
1196
1197
    @Override
1198 44328 jjdelcerro
    public void writeDALResource(ResourcesStorage resources, DataStore store) {
1199
        ResourcesStorage.Resource resource = null;
1200
        try {
1201
            if( resources == null || resources.isReadOnly() ) {
1202
                return;
1203
            }
1204
            resource = resources.getResource("dal");
1205
            if( resource == null || resource.isReadOnly() ) {
1206
                return;
1207
            }
1208
            DALFile dalFile = DALFile.getDALFile();
1209
            dalFile.setStore((DefaultFeatureStore) store);
1210
            if( !dalFile.isEmpty() ) {
1211
                dalFile.write(resource);
1212
            }
1213
        } catch (Throwable ex) {
1214
            LOGGER.warn("Can't save DAL resource", ex);
1215
        } finally {
1216
            IOUtils.closeQuietly(resource);
1217
        }
1218
1219
1220
    }
1221
1222
    @Override
1223
    public void writeDALResource(ResourcesStorage resources, FeatureType featureType) {
1224
        ResourcesStorage.Resource resource = null;
1225
        try {
1226
            if( resources == null || resources.isReadOnly() ) {
1227
                return;
1228
            }
1229
            resource = resources.getResource("dal");
1230
            if( resource == null || resource.isReadOnly() ) {
1231
                return;
1232
            }
1233
            DALFile dalFile = DALFile.getDALFile();
1234
            dalFile.setFeatureType(featureType);
1235
            if( !dalFile.isEmpty() ) {
1236
                dalFile.write(resource);
1237
            }
1238
        } catch (Throwable ex) {
1239
            LOGGER.warn("Can't save DAL resource", ex);
1240
        } finally {
1241
            IOUtils.closeQuietly(resource);
1242
        }
1243
    }
1244 44376 jjdelcerro
1245
    private Map<String,DynObjectValueItem[]> availableValues = null;
1246
1247
    @Override
1248 44719 jjdelcerro
    public void clearAvailableValuesCache() {
1249
      this.availableValues = null;
1250
    }
1251
1252
    @Override
1253 44376 jjdelcerro
    public DynObjectValueItem[] getAvailableValues(FeatureStore myStore, FeatureAttributeDescriptor descriptor) {
1254
        String keyName = myStore.getFullName() + ":columnName=" + descriptor.getName();
1255
        if( this.availableValues==null ) {
1256
            this.availableValues = new HashMap<>();
1257
        }
1258
        DynObjectValueItem[] values = this.availableValues.get(keyName);
1259
        if( values != null ) {
1260
            return values;
1261
        }
1262
        if( !descriptor.isForeingKey() ) {
1263
            return null;
1264
        }
1265
        ForeingKey foreingKey = descriptor.getForeingKey();
1266
        try {
1267
            StoresRepository theStoresRepository;
1268
            FeatureStore store = descriptor.getStore();
1269
            if (store == null) {
1270
                theStoresRepository = DALLocator.getDataManager().getStoresRepository();
1271
1272
            } else {
1273
                theStoresRepository = store.getStoresRepository();
1274
            }
1275
            FeatureStore foreingStore = (FeatureStore) theStoresRepository.getStore(
1276
                foreingKey.getTableName()
1277
            );
1278
            Expression labelExpression = foreingKey.getLabelExpression(null);
1279
            String codeName = foreingKey.getCodeName();
1280
            FeatureSymbolTable featureSymbolTable = this.createFeatureSymbolTable();
1281
            MutableSymbolTable symbolTable = featureSymbolTable.createParent();
1282
1283
            int count = (int) foreingStore.getFeatureCount();
1284
            values = new DynObjectValueItem[Math.min(count, MAX_AVAILABLE_VALUES)];
1285
            int n = 0;
1286
            for (Feature feature : foreingStore.getFeatureSet()) {
1287
                Object code = feature.get(codeName);
1288
                Object value;
1289
                if (labelExpression == null) {
1290
                    value = code;
1291
                } else {
1292
                    featureSymbolTable.setFeature(feature);
1293
                    value = labelExpression.execute(symbolTable);
1294
                }
1295
                values[n++] = new DynObjectValueItem(code, Objects.toString(value, Objects.toString(code, "##ERROR##")));
1296
                if( n>=MAX_AVAILABLE_VALUES ) {
1297
                    break;
1298
                }
1299
            }
1300
            this.availableValues.put(keyName, values);
1301
            return values;
1302
        } catch (Exception ex) {
1303
            LOGGER.warn("Can't get available values for field '"+myStore.getName()+"."+descriptor.getName()+"' from table '" + foreingKey.getTableName() + "'.", ex);
1304
        }
1305
        return null;
1306
    }
1307
1308 44409 jjdelcerro
    @Override
1309
    public String createUniqueID() {
1310
        UUID x = UUID.randomUUID();
1311
        String s = x.toString();
1312
        return s;
1313
    }
1314 44750 jjdelcerro
1315 44753 omartinez
    @Override
1316
    public EditableFeatureAttributeDescriptor createFeatureAttributeDescriptor() {
1317
        DefaultEditableFeatureAttributeDescriptor edi = new DefaultEditableFeatureAttributeDescriptor(null, false);
1318
        return edi;
1319
    }
1320
1321 44750 jjdelcerro
  @Override
1322
  public DALExpressionBuilder createDALExpressionBuilder() {
1323
    return new DefaultDALExpressionBuilder();
1324
  }
1325
1326 44871 jjdelcerro
  @Override
1327
  public void addStoreObserver(Observer observer) {
1328
    this.storeObservers.add(observer);
1329
  }
1330
1331
  @Override
1332
  public void removeStoreObserver(Observer observer) {
1333
    this.storeObservers.remove(observer);
1334
  }
1335
1336 43020 jjdelcerro
}