Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / main / java / org / gvsig / fmap / dal / store / jdbc2 / spi / JDBCResourcesStorage.java @ 45065

History | View | Annotate | Download (14.7 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 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 3
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
package org.gvsig.fmap.dal.store.jdbc2.spi;
25

    
26
import java.io.ByteArrayInputStream;
27
import java.io.ByteArrayOutputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.FileOutputStream;
32
import java.io.IOException;
33
import java.io.InputStream;
34
import java.io.OutputStream;
35
import java.net.URL;
36
import java.security.MessageDigest;
37
import java.util.ArrayList;
38
import java.util.List;
39
import org.apache.commons.codec.digest.DigestUtils;
40
import org.apache.commons.io.FileUtils;
41
import org.apache.commons.io.IOUtils;
42
import org.apache.commons.lang3.StringUtils;
43
import org.apache.commons.lang3.tuple.ImmutablePair;
44
import org.apache.commons.lang3.tuple.Pair;
45
import org.gvsig.expressionevaluator.ExpressionBuilder;
46
import org.gvsig.expressionevaluator.ExpressionUtils;
47
import org.gvsig.fmap.dal.DALLocator;
48
import org.gvsig.fmap.dal.DataManager;
49
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.FIELD_RESOURCES_NAME;
50
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.FIELD_RESOURCES_RESOURCE;
51
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_RESOURCES_NAME;
52
import org.gvsig.fmap.dal.feature.EditableFeature;
53
import org.gvsig.fmap.dal.feature.Feature;
54
import org.gvsig.fmap.dal.feature.FeatureStore;
55
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
56
import org.gvsig.tools.ToolsLocator;
57
import org.gvsig.tools.dispose.DisposeUtils;
58
import org.gvsig.tools.folders.FoldersManager;
59
import org.gvsig.tools.resourcesstorage.AbstractResourcesStorage;
60
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
61
import org.slf4j.Logger;
62
import org.slf4j.LoggerFactory;
63

    
64
/**
65
 *
66
 * @author jjdelcerro
67
 */
68
@SuppressWarnings("UseSpecificCatch")
69
public class JDBCResourcesStorage extends AbstractResourcesStorage {
70

    
71
    private static final Logger LOGGER = LoggerFactory.getLogger(JDBCResourcesStorage.class);
72

    
73
    private static class DataBaseResource implements Resource {
74

    
75
        private class ResourceInputStream extends InputStream {
76

    
77
            @Override
78
            public int read() throws IOException {
79
                return in.read();
80
            }
81

    
82
            @Override
83
            public void close() throws IOException {
84
                DataBaseResource.this.close();
85
            }
86
        }
87

    
88
        private class ResourceOutputStream extends OutputStream {
89

    
90
            @Override
91
            public void write(int b) throws IOException {
92
                out.write(b);
93
            }
94

    
95
            @Override
96
            public void flush() throws IOException {
97
                out.flush();
98
            }
99

    
100
            @Override
101
            public void close() throws IOException {
102
                DataBaseResource.this.close();
103
            }
104
        }
105

    
106
        private final JDBCStoreParameters storeParameters;
107
        private final String tableName;
108
        private final String name;
109

    
110
        private InputStream in;
111
        private ByteArrayOutputStream out;
112

    
113
        public DataBaseResource(JDBCStoreParameters storeParameters, String tableName, String name) {
114
            this.storeParameters = storeParameters;
115
            this.tableName = tableName;
116
            this.name = name;
117
        }
118

    
119
        @Override
120
        public String getName() {
121
          return name;
122
        }
123
        
124
        @Override
125
        public boolean isReadOnly() {
126
            return false;
127
        }
128
        @Override
129
        public URL getURL() {
130
            try {
131
                String url = this.storeParameters.getUrl();
132
                return new URL(url + "&tableName=" + this.tableName + "&resourceName=" + this.name);
133
            } catch (Throwable ex) {
134
                return null;
135
            }
136
        }
137

    
138
        @Override
139
        public boolean exists() {
140
            FeatureStore store = null;
141
            try {
142
                FoldersManager fm = ToolsLocator.getFoldersManager();
143
                Pair<String, String> key = this.getCacheID();
144
                File f = fm.getTemporaryFile("resources-storage","jdbc", key.getLeft(), key.getRight());
145
                if( f.exists() ) {
146
                  return true;
147
                }
148
                DataManager dataManager = DALLocator.getDataManager();
149
                store = (FeatureStore) dataManager.openStore(
150
                        this.storeParameters.getDataStoreName(),
151
                        this.storeParameters
152
                );
153
                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
154
                String filter = builder.eq(
155
                        builder.column(FIELD_RESOURCES_NAME),
156
                        builder.constant(this.tableName+"."+this.name)
157
                ).toString();
158
                Feature feature = store.findFirst(filter);
159
                return feature!=null;
160
            } catch (Throwable ex) {
161
                LOGGER.warn("Can't access to the resoure '" + this.getURL() + "'.", ex);
162
            } finally {
163
                DisposeUtils.disposeQuietly(store);
164
            }
165
            return false;
166
        }
167

    
168
        private Pair<String,String> getCacheID() {
169
          byte[] data = this.storeParameters.toByteArray();
170
          ImmutablePair<String, String> r = new ImmutablePair<>(
171
                  DigestUtils.md5Hex(data), 
172
                  this.tableName+"."+this.name
173
          );
174
          return r;
175
        }
176
        
177
        private InputStream getInputStreamFromCache() {
178
          FoldersManager fm = ToolsLocator.getFoldersManager();
179
          Pair<String, String> key = this.getCacheID();
180
          File f = fm.getTemporaryFile("resources-storage","jdbc", key.getLeft(), key.getRight());
181
          if( !f.exists() ) {
182
            InputStream is = null;
183
            FileOutputStream os = null;
184
            try {
185
              is = this.getInputStream();
186
              FileUtils.forceMkdir(f.getParentFile());
187
              os = new FileOutputStream(f);
188
              IOUtils.copy(is, os);              
189
              
190
              File f2 = fm.getTemporaryFile("resources-storage","jdbc", key.getLeft(), "parameters");              
191
              byte[] data = this.storeParameters.toByteArray();
192
              os = new FileOutputStream(f2);
193
              IOUtils.write(data, os);
194
            } catch (IOException ex) {
195
              return null;
196
            } finally {
197
              IOUtils.closeQuietly(is);
198
              IOUtils.closeQuietly(os);
199
            }
200
          }
201
          InputStream is = null;
202
          try {
203
            is = new FileInputStream(f);
204
          } catch (FileNotFoundException ex) {
205
          }
206
          return is;
207
        }
208
        
209
        private InputStream getInputStream() throws IOException {
210
            FeatureStore store = null;
211
            try {
212
                DataManager dataManager = DALLocator.getDataManager();
213
                store = (FeatureStore) dataManager.openStore(
214
                        this.storeParameters.getDataStoreName(),
215
                        this.storeParameters
216
                );
217
                ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
218
                String filter = builder.eq(
219
                        builder.column(FIELD_RESOURCES_NAME),
220
                        builder.constant(this.tableName+"."+this.name)
221
                ).toString();
222
                Feature feature = store.findFirst(filter);
223
                if (feature == null) {
224
                    return null;
225
                }
226
                byte[] resource = feature.getByteArray(FIELD_RESOURCES_RESOURCE);
227
                InputStream is = new ByteArrayInputStream(resource);
228
                return is;
229
            } catch (Throwable ex) {
230
                LOGGER.warn("Can't access to the resoure '" + this.getURL() + "'.", ex);
231
            } finally {
232
                DisposeUtils.disposeQuietly(store);
233
            }
234
            return null;
235
        }
236

    
237
        @Override
238
        public InputStream asInputStream() throws IOException {
239
            if (this.in != null || this.out != null) {
240
                throw new IllegalStateException("Resource is already open (" + this.getURL() + ")");
241
            }
242
            InputStream is = this.getInputStreamFromCache();
243
            if( is==null ) {
244
              is = this.getInputStream();
245
            }
246
            this.in = is;
247
            return new ResourceInputStream();
248
        }
249

    
250
        @Override
251
        public OutputStream asOutputStream() throws IOException {
252
            if (this.in != null || this.out != null) {
253
                throw new IllegalStateException("Resource is already open (" + this.getURL() + ").");
254
            }
255
            this.out = new ByteArrayOutputStream();
256
            return new ResourceOutputStream();
257
        }
258

    
259
        @Override
260
        public void close() {
261
            if (this.in != null) {
262
                IOUtils.closeQuietly(this.in);
263
                this.in = null;
264
            }
265
            if (this.out != null) {
266
                FeatureStore store = null;
267
                try {
268
                    DataManager dataManager = DALLocator.getDataManager();
269
                    store = (FeatureStore) dataManager.openStore(
270
                            this.storeParameters.getDataStoreName(),
271
                            this.storeParameters
272
                    );
273
                    store.edit();
274
                    ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
275
                    String filter = builder.eq(
276
                            builder.column(FIELD_RESOURCES_NAME),
277
                            builder.constant(this.tableName+"."+this.name)
278
                    ).toString();
279
                    Feature feature = store.findFirst(filter);
280
                    EditableFeature efeature;
281
                    if (feature == null) {
282
                        efeature = store.createNewFeature();
283
                        efeature.set(FIELD_RESOURCES_NAME, this.tableName+"."+this.name);
284
                        efeature.set(FIELD_RESOURCES_RESOURCE, this.out.toByteArray());
285
                        store.insert(efeature);
286
                    } else {
287
                        efeature = feature.getEditable();
288
                        efeature.set(FIELD_RESOURCES_RESOURCE, this.out.toByteArray());
289
                        store.update(efeature);
290
                    }
291
                    store.finishEditing();
292

    
293
                } catch (Throwable ex) {
294
                    LOGGER.warn("Can't write the resoure '" + this.getURL() + "'.", ex);
295
                } finally {
296
                    DisposeUtils.disposeQuietly(store);
297
                }
298
            }
299
        }
300
    }
301

    
302
    private final ResourcesStorage alternativeStorge;
303
    private final JDBCStoreParameters resourcesStoreParameters;
304
    private final String tableName;
305

    
306
    public JDBCResourcesStorage(ResourcesStorage alternativeStorge, JDBCStoreParameters resourcesStoreParameters, String tableName) {
307
        this.alternativeStorge = alternativeStorge;
308
        if( StringUtils.equals(TABLE_RESOURCES_NAME, tableName) ) {
309
            // No podemos buscar recursos de la tabla de recursos, ya que si no
310
            // al abrise la tabla de recursos entraria en bucle.
311
            this.resourcesStoreParameters = null;
312
        } else {
313
            this.resourcesStoreParameters = resourcesStoreParameters;
314
        }
315
        this.tableName = tableName;
316
    }
317

    
318
    @Override
319
    public boolean isEmpty() {
320
        return this.resourcesStoreParameters == null;
321
    }
322

    
323
    @Override
324
    public Resource getResource(String name) {
325
        if( this.alternativeStorge!=null ) {
326
            Resource r = this.alternativeStorge.getResource(name);
327
            if( r.exists() ) {
328
                return r;
329
            }
330
        }
331
        if (this.resourcesStoreParameters == null) {
332
            return null;
333
        }
334
        return new DataBaseResource(
335
                this.resourcesStoreParameters, 
336
                this.tableName, 
337
                name
338
        );
339
    }
340

    
341
    @Override
342
    public List<Resource> getResources(String name) {
343
        if (this.resourcesStoreParameters == null) {
344
            return null;
345
        }
346
        if( this.alternativeStorge!=null ) {
347
            List<Resource> r = this.alternativeStorge.getResources(name);
348
            if( r!=null && !r.isEmpty() ) {
349
                return r;
350
            }
351
        }
352
        FeatureStore store = null;
353
        try {
354
            DataManager dataManager = DALLocator.getDataManager();
355
            store = (FeatureStore) dataManager.openStore(
356
                    this.resourcesStoreParameters.getDataStoreName(),
357
                    this.resourcesStoreParameters
358
            );
359
            ExpressionBuilder builder = ExpressionUtils.createExpressionBuilder();
360
            List<ResourcesStorage.Resource> ress = new ArrayList<>();
361
            int n = 0;
362
            while (true) {
363
                String multiresourceName;
364
                if (n == 0) {
365
                    multiresourceName = name;
366
                } else {
367
                    multiresourceName = String.valueOf(n) + "." + name ;
368
                }
369
                String filter = builder.eq(
370
                        builder.column(FIELD_RESOURCES_NAME),
371
                        builder.constant(this.tableName+"."+multiresourceName)
372
                ).toString();
373
                Feature feature = store.findFirst(filter);
374
                if( feature==null ) {
375
                    break;
376
                }
377
                ress.add(new DataBaseResource(
378
                        this.resourcesStoreParameters, 
379
                        this.tableName,
380
                        multiresourceName
381
                    )
382
                );
383
                n++;
384
            }
385
            if (ress.isEmpty()) {
386
                return null;
387
            }
388
            return ress;
389
        } catch (Throwable ex) {
390
            LOGGER.warn("Can't get resources for '" + this.resourcesStoreParameters.getUrl()+"&resourceName="+name + "'.", ex);
391
            return null;
392
            
393
        } finally {
394
            DisposeUtils.disposeQuietly(store);
395
        }
396

    
397
    }
398

    
399
}