Statistics
| Revision:

gvsig-projects-pool / org.gvsig.vcsgis / trunk / org.gvsig.vcsgis / org.gvsig.vcsgis.lib / org.gvsig.vcsgis.lib.impl / src / main / java / org / gvsig / vcsgis / lib / repository / localdb / VCSGisRepositoryLocaldb.java @ 3953

History | View | Annotate | Download (24.6 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, see <https://www.gnu.org/licenses/>. 
18
 * 
19
 * For any additional information, do not hesitate to contact us
20
 * at info AT gvsig.com, or visit our website www.gvsig.com.
21
 */
22

    
23
package org.gvsig.vcsgis.lib.repository.localdb;
24

    
25
import java.time.LocalDateTime;
26
import java.util.Date;
27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.Objects;
31
import java.util.zip.CRC32;
32
import javax.json.JsonObject;
33
import org.apache.commons.lang3.BooleanUtils;
34
import org.apache.commons.lang3.StringUtils;
35
import org.gvsig.fmap.dal.DALLocator;
36
import org.gvsig.fmap.dal.DataManager;
37
import org.gvsig.fmap.dal.DataServerExplorerParameters;
38
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
39
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.CONFIG_NAME_STORESREPOSITORYID;
40
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_CONFIGURATION;
41
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_REPOSITORY;
42
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_RESOURCES;
43
import org.gvsig.fmap.dal.feature.FeatureStore;
44
import org.gvsig.fmap.dal.feature.FeatureType;
45
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
46
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
47
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
48
import org.gvsig.fmap.dal.store.jdbc2.JDBCServerExplorer;
49
import org.gvsig.json.Json;
50
import org.gvsig.json.JsonObjectBuilder;
51
import org.gvsig.tools.ToolsLocator;
52
import static org.gvsig.tools.dataTypes.DataTypeUtils.toTimestamp;
53
import org.gvsig.tools.dispose.DisposeUtils;
54
import org.gvsig.tools.dispose.impl.AbstractDisposable;
55
import org.gvsig.tools.task.SimpleTaskStatus;
56
import org.gvsig.vcsgis.lib.VCSGisCodeGenerator;
57
import org.gvsig.vcsgis.lib.VCSGisEntity;
58
import org.gvsig.vcsgis.lib.VCSGisLocator;
59
import org.gvsig.vcsgis.lib.VCSGisManager;
60
import static org.gvsig.vcsgis.lib.VCSGisManager.ERR_AUTHENTICATION_EXPIRED;
61
import static org.gvsig.vcsgis.lib.VCSGisManager.ERR_INVALID_AUTHENTICATION_TOKEN;
62
import static org.gvsig.vcsgis.lib.VCSGisManager.ERR_INVALID_USERCODE;
63
import static org.gvsig.vcsgis.lib.VCSGisManager.ERR_OK;
64
import static org.gvsig.vcsgis.lib.VCSGisManager.ERR_USER_NOT_AUTHORIZED;
65
import org.gvsig.vcsgis.lib.VCSGisRuntimeException;
66
import org.gvsig.vcsgis.lib.VCSGisUser;
67
import org.gvsig.vcsgis.lib.VCSGisUtils;
68
import org.gvsig.vcsgis.lib.repository.VCSGisRepository;
69
import org.gvsig.vcsgis.lib.repository.localdb.requests.AbstractRequestLocaldb;
70
import org.gvsig.vcsgis.lib.repository.localdb.requests.AuthenticateRequestLocaldb;
71
import org.gvsig.vcsgis.lib.repository.localdb.requests.CheckoutRequestLocaldb;
72
import org.gvsig.vcsgis.lib.repository.localdb.requests.CommitRequestLocaldb;
73
import org.gvsig.vcsgis.lib.repository.localdb.requests.EntitiesRequestLocaldb;
74
import org.gvsig.vcsgis.lib.repository.localdb.requests.HistoryRequestLocaldb;
75
import org.gvsig.vcsgis.lib.repository.localdb.requests.RowCreateRequestLocaldb;
76
import org.gvsig.vcsgis.lib.repository.localdb.requests.RowDeleteRequestLocaldb;
77
import org.gvsig.vcsgis.lib.repository.localdb.requests.RowUpdateRequestLocaldb;
78
import org.gvsig.vcsgis.lib.repository.localdb.requests.TopologyPlansRequestLocaldb;
79
import org.gvsig.vcsgis.lib.repository.localdb.requests.UpdateRequestLocaldb;
80
import org.gvsig.vcsgis.lib.repository.localdb.requests.UsersRequestLocaldb;
81
import org.gvsig.vcsgis.lib.repository.localdb.tables.ConfigRepoTable;
82
import org.gvsig.vcsgis.lib.repository.localdb.tables.DataRepoTable;
83
import org.gvsig.vcsgis.lib.repository.localdb.tables.EntitiesRepoTable;
84
import org.gvsig.vcsgis.lib.repository.localdb.tables.HooksRepoTable;
85
import org.gvsig.vcsgis.lib.repository.localdb.tables.RevisionsRepoTable;
86
import org.gvsig.vcsgis.lib.repository.localdb.tables.TopologyplanRepoTable;
87
import org.gvsig.vcsgis.lib.repository.localdb.tables.UsersRepoTable;
88
import org.gvsig.vcsgis.lib.repository.requests.VCSGisAuthenticateRequest;
89
import org.gvsig.vcsgis.lib.repository.requests.VCSGisCheckoutRequest;
90
import org.gvsig.vcsgis.lib.repository.requests.VCSGisCommitRequest;
91
import org.gvsig.vcsgis.lib.repository.requests.VCSGisEntitiesRequest;
92
import org.gvsig.vcsgis.lib.repository.requests.VCSGisHistoryRequest;
93
import org.gvsig.vcsgis.lib.repository.requests.VCSGisRequest;
94
import org.gvsig.vcsgis.lib.repository.requests.VCSGisRowCreateRequest;
95
import org.gvsig.vcsgis.lib.repository.requests.VCSGisRowDeleteRequest;
96
import org.gvsig.vcsgis.lib.repository.requests.VCSGisRowUpdateRequest;
97
import org.gvsig.vcsgis.lib.repository.requests.VCSGisTopologyPlansRequest;
98
import org.gvsig.vcsgis.lib.repository.requests.VCSGisUpdateRequest;
99
import org.gvsig.vcsgis.lib.repository.requests.VCSGisUsersRequest;
100
import org.gvsig.vcsgis.lib.requests.AbstractRequest;
101
import org.slf4j.Logger;
102
import org.slf4j.LoggerFactory;
103

    
104
/**
105
 *
106
 * @author gvSIG Team
107
 */
108
@SuppressWarnings("UseSpecificCatch")
109
public class VCSGisRepositoryLocaldb extends AbstractDisposable implements VCSGisRepository {
110
    private static final Logger LOGGER = LoggerFactory.getLogger(VCSGisRepositoryLocaldb.class);
111

    
112
    
113
    public static int create(JDBCServerExplorerParameters serverParameters, VCSGisCodeGenerator codeGenerator, SimpleTaskStatus status) {
114
        if( status == null ) {
115
            status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("vcsgis init");
116
            status.add();
117
        }
118
        LOGGER.info("Initializing repository "+Objects.toString(serverParameters.toJson()).replace('\n', ' ').replaceAll("\"password\":\"[^\"]*\"", "\"password\":\"****\""));
119
        int r = 3;
120
        status.push();
121
        DataManager dataManager = DALLocator.getDataManager();
122
        JDBCServerExplorer server = null;
123
        try {
124
            server = (JDBCServerExplorer) dataManager.openServerExplorer(
125
                    serverParameters.getProviderName(),
126
                    serverParameters
127
            );
128
        } catch (Exception ex) {
129
            throw new VCSGisRuntimeException(VCSGisManager.ERR_INVALID_REPOSITORY, "Can't open server explorer.");
130
        }
131

    
132
        try {
133
            status.setTitle("vcsgis init");
134
            
135
            DatabaseWorkspaceManager databaseWorkspaceManager = dataManager.createDatabaseWorkspaceManager(serverParameters);
136
            
137
            if(!databaseWorkspaceManager.existsTable(TABLE_CONFIGURATION)){
138
                databaseWorkspaceManager.createTable(TABLE_CONFIGURATION);
139
            }
140
            if(!databaseWorkspaceManager.existsTable(TABLE_RESOURCES)){
141
                databaseWorkspaceManager.createTable(TABLE_RESOURCES);
142
            }
143
            if(!databaseWorkspaceManager.existsTable(TABLE_REPOSITORY)){
144
                databaseWorkspaceManager.createTable(TABLE_REPOSITORY);
145
                databaseWorkspaceManager.set(CONFIG_NAME_STORESREPOSITORYID, "VCSGIS");
146
            }
147
            databaseWorkspaceManager.connect();
148
            
149
            FeatureType[] tables = new FeatureType[] {
150
                ConfigRepoTable.featureType(),
151
                UsersRepoTable.featureType(),
152
                TopologyplanRepoTable.featureType(),
153
                EntitiesRepoTable.featureType(),
154
                RevisionsRepoTable.featureType(),
155
                DataRepoTable.featureType(),
156
                HooksRepoTable.featureType(),
157
            };
158
            r = 4;
159
            status.setRangeOfValues(0, tables.length);
160
            int step = 1;
161
            for (FeatureType table : tables) {
162
                status.message(table.getLabel());
163
                status.setCurValue(step++);
164
                r = 4+step;
165
                JDBCNewStoreParameters table_params = server.getAddParameters();
166
                table_params.setDefaultFeatureType(table.getEditable());
167
                String tableName = table.getTags().getString("ID");
168
                table_params.setTable(tableName);
169
                server.add(server.getProviderName(), table_params, false);
170
                
171
                JDBCStoreParameters openParams = server.get(tableName);
172
                databaseWorkspaceManager.writeStoresRepositoryEntry(tableName, openParams);
173
            }
174
            
175
            try {
176
                server.execute(VCSGisUtils.getSqlTemplate(serverParameters.getProviderName(), "createRepositoryIndex1"));
177
                server.execute(VCSGisUtils.getSqlTemplate(serverParameters.getProviderName(), "createRepositoryIndex2"));
178
            } catch (Exception ex) {
179
                LOGGER.warn("Can't create index in repository", ex);
180
            }
181

    
182
            VCSGisRepositoryLocaldb repo = new VCSGisRepositoryLocaldb();
183
            repo.initialize(serverParameters, codeGenerator);
184
            DisposeUtils.disposeQuietly(repo);
185
            status.terminate();
186
        } catch(Exception ex) {
187
            status.abort();
188
            LOGGER.warn("Can't init repository.",ex);
189
            status.message(ex.getMessage());
190
            return r;
191
        } finally {
192
            status.pop();
193
        }
194
        return 0;
195
    }
196
        
197
    private JDBCServerExplorer server;
198
    private JDBCServerExplorerParameters serverParameters;
199
    private Map<String,FeatureStore> stores;
200
    private VCSGisCodeGenerator codeGenerator;
201
    private String code;
202
//    private HooksRepoTable hooksTable;
203
    private boolean allowAssignTheRevisionDate;
204
//    private boolean authenticationRequired;
205
//    private boolean authorizationRequired;
206
    private String token;
207
    private String userCode;
208
    private int dataTableBatchSize=-1;
209
    private HooksRepoTable.RepositoryWatchersNotifier watchersNotifier;
210
    
211
    public VCSGisRepositoryLocaldb() {
212
        // For persistence
213
        this.codeGenerator = null;
214
        this.stores = null;
215
        this.server = null;
216
        this.serverParameters = null;
217
        this.code = null;
218
        this.allowAssignTheRevisionDate = false;
219
//        this.authenticationRequired = false;
220
//        this.authorizationRequired = false;
221
     }
222
    
223
    @SuppressWarnings({"LeakingThisInConstructor", "CallToThreadStartDuringObjectConstruction"})
224
    public VCSGisRepositoryLocaldb(JDBCServerExplorerParameters serverParameters, VCSGisCodeGenerator codeGenerator) {
225
        this.stores = null;
226
        this.codeGenerator = codeGenerator;
227
        this.serverParameters = serverParameters;
228
        DataManager dataManager = DALLocator.getDataManager();
229
        try {
230
            this.server = (JDBCServerExplorer) dataManager.openServerExplorer(
231
                    serverParameters.getProviderName(),
232
                    serverParameters
233
            );
234
        } catch (Exception ex) {
235
            throw new VCSGisRuntimeException(VCSGisManager.ERR_INVALID_REPOSITORY, "Can't open server explorer.");
236
        }
237

    
238
        ConfigRepoTable varsTable = new ConfigRepoTable();
239
        this.code = varsTable.get(this, "REPOSITORY_CODE");
240
        if (this.code == null){
241
            throw new VCSGisRuntimeException(VCSGisManager.ERR_INVALID_REPOSITORY, "The database can't have REPOSITORY_CODE variable.");
242
        }
243
//        this.authenticationRequired = BooleanUtils.toBoolean(varsTable.get(this, "AUTHENTICATION"));
244
//        this.authorizationRequired = BooleanUtils.toBoolean(varsTable.get(this, "AUTHORIZATION"));
245
        HooksRepoTable hooksTable = new HooksRepoTable();
246
        this.watchersNotifier = hooksTable.createRepositoryWatchersNotifier(this);
247
        this.watchersNotifier.start();
248
    }
249
    
250
    private void initialize(JDBCServerExplorerParameters serverParameters, VCSGisCodeGenerator codeGenerator) {
251
        this.stores = null;
252
        this.codeGenerator = codeGenerator;
253
        this.serverParameters = serverParameters;
254
        DataManager dataManager = DALLocator.getDataManager();
255
        try {
256
            this.server = (JDBCServerExplorer) dataManager.openServerExplorer(
257
                    serverParameters.getProviderName(),
258
                    serverParameters
259
            );
260
        } catch (Exception ex) {
261
            throw new VCSGisRuntimeException(VCSGisManager.ERR_INVALID_REPOSITORY, "Can't open server explorer.");
262
        }
263
        this.code = this.createUniqueCode();
264
        ConfigRepoTable varsTable = new ConfigRepoTable();
265
        varsTable.set(this, "REPOSITORY_CODE", this.code);
266
        varsTable.set(this, "AUTHENTICATION", "false");
267
        varsTable.set(this, "AUTHORIZATION", "false");
268
    }
269

    
270
    @Override
271
    protected void doDispose() {
272
        if(this.watchersNotifier != null){
273
            this.watchersNotifier.cancelRequest();
274
            this.watchersNotifier = null;
275
        }
276
        if(this.stores != null){
277
            for (FeatureStore store : this.stores.values()) {
278
                DisposeUtils.disposeQuietly(store);
279
            }
280
            this.stores = null;
281
        }
282
        DisposeUtils.disposeQuietly(this.server);
283
        this.server = null;
284
    }
285

    
286
    @Override
287
    public String getUserCode() {
288
        return this.userCode;
289
    }
290
    
291
    @Override
292
    public String getLabel() {
293
        return this.server.getParameters().getUrl();
294
    }
295

    
296
    @Override
297
    public String createUniqueCode() {
298
        return this.codeGenerator.generateCode();
299
    }
300

    
301
    public JDBCServerExplorer getServerExplorer() {
302
        return this.server;
303
    }
304
    
305
    public static void selfRegister() {
306
        Json.registerSerializer(VCSGisRepositoryLocaldb.class);
307
    }
308
    
309
    @Override
310
    public VCSGisCommitRequest createCommitRequest() {
311
        return new CommitRequestLocaldb(this);
312
    }
313

    
314
    @Override
315
    public VCSGisUpdateRequest createUpdateRequest(String entityName) {
316
        return new UpdateRequestLocaldb(this, entityName);
317
    }
318

    
319

    
320
    @Override
321
    public VCSGisCheckoutRequest createCheckoutRequest(String entityName) {
322
        return new CheckoutRequestLocaldb(this, entityName);
323
    }
324
    
325
    @Override
326
    public void fromJson(JsonObject json) {
327
        try {
328
            DataManager dataManager = DALLocator.getDataManager();
329
            DataServerExplorerParameters explorerParams = (DataServerExplorerParameters) Json.toObject(json, "explorerParams");
330
            this.server = (JDBCServerExplorer) dataManager.openServerExplorer(
331
                    explorerParams.getProviderName(), 
332
                    explorerParams
333
            );
334
            this.codeGenerator = VCSGisLocator.getVCSGisManager().getCodeGenerator();
335
            this.stores = new HashMap<>();
336
            this.code = json.getString("code", null);
337
            this.allowAssignTheRevisionDate = json.getBoolean("allowAssignTheRevisionDate", false);
338
            HooksRepoTable hooksTable = new HooksRepoTable();
339
            this.watchersNotifier = hooksTable.createRepositoryWatchersNotifier(this);
340
            this.watchersNotifier.start();
341

    
342
//            this.authenticationRequired = json.getBoolean("authenticationRequired", false);
343
            
344
        } catch (Exception ex) {
345
            throw new RuntimeException("Can't restore repository from json object.", ex);
346
        }
347
    }
348

    
349
    @Override
350
    public JsonObject toJson() {
351
        return this.toJsonBuilder().build();
352
    }
353

    
354
    @Override
355
    public JsonObjectBuilder toJsonBuilder() {
356
        JsonObjectBuilder builder = Json.createObjectBuilder();
357
        builder.add_class(this);
358
        builder.add("explorerParams", this.server.getParameters());
359
        builder.add("code", this.code);
360
        builder.add("allowAssignTheRevisionDate", this.allowAssignTheRevisionDate);
361
//        builder.add("authenticationRequired", this.authenticationRequired);
362
        return builder;
363
    }
364
    
365
    public FeatureStore getFeatureStore(String tableName) {
366
        if( this.stores==null ) {
367
            this.stores = new HashMap<>();
368
        }
369
        FeatureStore store = this.stores.get(tableName);
370
        if( store==null ) {
371
            store = this.openFeatureStore(tableName, null);
372
            this.stores.put(tableName, store);
373
        }
374
        DisposeUtils.bind(store);
375
        return store;
376
    }
377

    
378
    public FeatureStore openFeatureStore(String tableName, String sql) {
379
        return this.openFeatureStore(tableName, sql, -1);
380
    }
381

    
382
    public FeatureStore openFeatureStore(String tableName, String sql, int batchSize) {
383
        FeatureStore store;
384
        try {
385
            JDBCStoreParameters params = this.server.get(tableName);
386
            params = params.getCopy();
387
            params.setSQL(sql);
388
            if( batchSize>=0 ) {
389
                params.setBatchSize(batchSize);
390
            }
391
            store = (FeatureStore) DALLocator.getDataManager().openStore(params.getProviderName(), params);
392
            return store;
393
        } catch (Exception ex) {
394
            throw new RuntimeException("Can't open store '"+tableName+"'.", ex);
395
        }
396
    }
397

    
398
    @Override
399
    public VCSGisEntitiesRequest createEntitiesRequest() {
400
        return new EntitiesRequestLocaldb(this);
401
    }
402

    
403
    @Override
404
    public VCSGisHistoryRequest createHistoryRequest(String entityName) {
405
        return new HistoryRequestLocaldb(this, entityName);
406
    }
407
    
408
    @Override
409
    public VCSGisEntity getEntityByName(String entityName) {
410
        VCSGisEntitiesRequest request = this.createEntitiesRequest();
411
        if(request.execute() != ERR_OK){
412
            return null;
413
        }
414
        for (VCSGisEntity repositoryEntity : request.getRepositoryEntities()) {
415
            if(StringUtils.equalsIgnoreCase(repositoryEntity.getEntityName(), entityName)){
416
                return repositoryEntity;
417
            }
418
        }
419
        return null;
420
    }
421

    
422
    @Override
423
    public VCSGisRowCreateRequest createRowCreateRequest(String entityName, String localRevisionCode) {
424
        VCSGisRowCreateRequest request = new RowCreateRequestLocaldb(this, entityName, localRevisionCode);
425
        return request;
426
    }
427

    
428
    @Override
429
    public VCSGisRowDeleteRequest createRowDeleteRequest(String entityName, String localRevisionCode) {
430
        VCSGisRowDeleteRequest request = new RowDeleteRequestLocaldb(this, entityName, localRevisionCode);
431
        return request;
432
    }
433

    
434
    @Override
435
    public VCSGisRowUpdateRequest createRowUpdateRequest(String entityName, String localRevisionCode) {
436
        VCSGisRowUpdateRequest request = new RowUpdateRequestLocaldb(this, entityName, localRevisionCode);
437
        return request;
438
    }
439

    
440
    @Override
441
    public VCSGisTopologyPlansRequest createTopologyPlansRequest() {
442
        VCSGisTopologyPlansRequest request = new TopologyPlansRequestLocaldb(this);
443
        return request;
444
    }
445

    
446
    @Override
447
    public VCSGisUsersRequest createUsersRequest() {
448
        VCSGisUsersRequest request = new UsersRequestLocaldb(this);
449
        return request;
450
    }
451

    
452
    @Override
453
    public void addObserver(String tableName, String type, String operation, String command) {
454
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
455
    }
456

    
457
    public void notifyWatchers(VCSGisRequest request) {
458
        this.watchersNotifier.notify(this.getUserCode(), request.getRequestName(), null, null);
459
    }
460

    
461
    public void notifyWatchers(VCSGisRequest request, String tableName, String revisionCode) {
462
        this.watchersNotifier.notify(this.getUserCode(), request.getRequestName(), tableName, revisionCode);
463
    }
464

    
465
    public boolean isAllowedToAssignTheRevisionDate() {
466
        return this.allowAssignTheRevisionDate;
467
    }
468
    
469
    public void setAllowAssignTheRevisionDate(boolean allowAssignTheRevisionDate) {
470
        this.allowAssignTheRevisionDate = allowAssignTheRevisionDate;
471
    }
472

    
473
    public String getAuthenticationToken(String userCode, int minutesToExpire) {
474
        CRC32 crc = new CRC32();
475
        crc.update(userCode.getBytes());
476
        
477
        long expireTime = 0;
478
        if( minutesToExpire>0 ) {
479
            expireTime = toTimestamp(LocalDateTime.now().plusMinutes(minutesToExpire)).getTime();
480
        }
481
        
482
        String theToken = String.format("%016x%016x", 
483
                crc.getValue(),
484
                expireTime
485
        );
486
        
487
        return theToken;
488
    }
489

    
490
    public boolean isAuthenticationRequired() {
491
        ConfigRepoTable varsTable = new ConfigRepoTable();
492
        return BooleanUtils.toBoolean(varsTable.get(this, "AUTHENTICATION"));
493
    }
494
    
495
    public boolean isAuthorizationRequired() {
496
        ConfigRepoTable varsTable = new ConfigRepoTable();
497
        return BooleanUtils.toBoolean(varsTable.get(this, "AUTHORIZATION"));
498
    }
499
    
500
    public boolean isAuthenticated(AbstractRequest request) {
501
        if( !this.isAuthenticationRequired() ) {
502
            LOGGER.info("Authentication not required for this repository.");
503
            return true;
504
        }
505
        if( StringUtils.isBlank(request.getUserCode()) ) {
506
            request.error(ERR_INVALID_USERCODE,"User is not authenticated.");
507
            return false;
508
        }
509
        String authenticationToken = request.getAuthenticationToken();
510
        if( StringUtils.isBlank(authenticationToken) || authenticationToken.length()!=32 ) {
511
            request.error(ERR_INVALID_AUTHENTICATION_TOKEN,"User '"+request.getUserCode()+"' is not authenticated.");
512
            return false;
513
        }
514
        
515
        // TODO: check expire time and CRC
516
        long expireTime_l = Long.parseLong(authenticationToken.substring(17), 16);
517
        if( expireTime_l>0 ) {
518
            long now_l = new java.util.Date().getTime();
519
            if( now_l > expireTime_l ) {
520
                request.error(ERR_AUTHENTICATION_EXPIRED,"User '"+request.getUserCode()+"' is not authorized to '"+request.getRequestName()+"'.");
521
                return false;
522
            }
523
        }
524
        
525
        Date d = new java.util.Date(expireTime_l);
526
        Date now = new java.util.Date();
527

    
528
        LOGGER.info("Repository authentication for user with userCode '"+request.getUserCode()+"' expire at '"+d.toString()+"' (now is '"+now.toString()+"'.");        
529
        return true;
530
    }
531
    
532
    public boolean isAuthorized(AbstractRequestLocaldb request) {
533
        return this.isAuthorized(request, null);
534
    }
535
    
536
    public boolean isAuthorized(AbstractRequestLocaldb request, String operation) {
537
        if( !this.isAuthenticated(request) ) {
538
            return false;
539
        }
540
        if( !this.isAuthorizationRequired() ) {
541
            LOGGER.info("Repository authorization not required.");
542
            return true;
543
        }
544
        if( operation == null ) {
545
            operation = request.getRequestName().toLowerCase();
546
        }
547

    
548
        VCSGisUser user = request.getUser();
549
        if( user == null ) {
550
            request.error(ERR_USER_NOT_AUTHORIZED,"User '"+request.getUserCode()+"' is not authorized to '"+request.getRequestName()+"'.");
551
            return false;
552
        }
553
        List<String> operations = user.getAllowedOperationsAsList();
554
        if( operations == null ) {
555
            LOGGER.info("All repository operations are allowed for user '"+user.getIdentifier()+"' ("+user.getUserCode()+").");
556
            return true;
557
        }
558
        if( !operations.contains(operation) ) {
559
            request.error(ERR_USER_NOT_AUTHORIZED,"User '"+request.getUserCode()+"' is not authorized to '"+request.getRequestName()+"'.");
560
            return false;
561
        }
562
        LOGGER.info("Repository authorization for '"+operation + "' operation is allowed for user '"+user.getIdentifier()+"' ("+user.getUserCode()+").");
563
        return true;
564
    }
565

    
566
    @Override
567
    public VCSGisAuthenticateRequest createAuthenticateRequest(String userId, String password) {
568
        VCSGisAuthenticateRequest request = new AuthenticateRequestLocaldb(this);
569
        request.setUserId(userId);
570
        request.setPassword(password);
571
        return request;
572
    }
573

    
574
    @Override
575
    public String getAuthenticationToken() {
576
        return this.token;
577
    }
578

    
579
    @Override
580
    public void setAuthenticationToken(String token) {
581
        this.token = token;
582
    }
583

    
584
    @Override
585
    public void setUserCode(String userCode) {
586
        this.userCode = userCode;
587
    }
588

    
589
    @Override
590
    public int getDataTableBtachSize() {
591
        if (this.dataTableBatchSize < 0) {
592
            ConfigRepoTable varsTable = new ConfigRepoTable();
593
            int n = -1;
594
            try {
595
                n = Integer.parseInt(varsTable.get(this, "DATA_TABLE_BATCH_SIZE"));
596
            } catch (Exception ex) {
597
                // Ignore
598
            }
599
            if (n < 0) {
600
                n = DATA_TABLE_BATCH_SIZE;
601
            }
602
            this.dataTableBatchSize = n;
603
        }
604
        return this.dataTableBatchSize;
605
    }
606

    
607

    
608
}