Statistics
| Revision:

gvsig-projects-pool / org.gvsig.online / trunk / org.gvsig.online / org.gvsig.online.lib / org.gvsig.online.lib.impl / src / main / java / org / gvsig / online / lib / impl / OnlineManagerImpl.java @ 9515

History | View | Annotate | Download (30.3 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 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.online.lib.impl;
25

    
26
import java.io.File;
27
import java.io.IOException;
28
import java.io.InputStream;
29
import java.net.URI;
30
import java.net.URL;
31
import java.nio.file.Files;
32
import java.nio.file.Path;
33
import java.util.ArrayList;
34
import java.util.Collections;
35
import java.util.HashMap;
36
import java.util.Iterator;
37
import java.util.List;
38
import java.util.Map;
39
import java.util.Objects;
40
import javax.json.JsonObject;
41
import org.apache.commons.lang3.StringUtils;
42
import org.apache.commons.lang3.mutable.Mutable;
43
import org.apache.commons.lang3.mutable.MutableInt;
44
import org.apache.commons.lang3.mutable.MutableObject;
45
import org.apache.http.HttpResponse;
46
import org.apache.http.NameValuePair;
47
import org.apache.http.client.ClientProtocolException;
48
import org.apache.http.client.ResponseHandler;
49
import org.apache.http.client.entity.UrlEncodedFormEntity;
50
import org.apache.http.client.methods.HttpPost;
51
import org.apache.http.impl.client.CloseableHttpClient;
52
import org.apache.http.impl.client.HttpClientBuilder;
53
import org.apache.http.message.BasicNameValuePair;
54
import org.gvsig.fmap.dal.DALLocator;
55
import org.gvsig.fmap.dal.DataManager;
56
import org.gvsig.fmap.dal.DataServerExplorer;
57
import org.gvsig.fmap.dal.DataStore;
58
import org.gvsig.fmap.dal.DataStoreParameters;
59
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
60
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.CONFIG_NAME_STORESREPOSITORYID;
61
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_CONFIGURATION;
62
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_REPOSITORY;
63
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_RESOURCES;
64
import org.gvsig.fmap.dal.feature.FeatureStore;
65
import org.gvsig.fmap.dal.feature.FeatureType;
66
import org.gvsig.fmap.dal.store.h2.H2SpatialUtils;
67
import org.gvsig.fmap.dal.store.jdbc.JDBCNewStoreParameters;
68
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
69
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
70
import org.gvsig.fmap.dal.store.jdbc2.JDBCServerExplorer;
71
import org.gvsig.json.Json;
72
import org.gvsig.online.lib.api.OnlineCodeGenerator;
73
import org.gvsig.online.lib.api.OnlineManager;
74
import org.gvsig.online.lib.api.OnlineProject;
75
import org.gvsig.online.lib.api.OnlineSite;
76
import org.gvsig.online.lib.api.OnlineUserIdentificationRequester;
77
import static org.gvsig.online.lib.api.OnlineUserIdentificationRequester.CONFIG_FACTORYNAME_NAME;
78
import static org.gvsig.online.lib.api.OnlineUserIdentificationRequester.CONFIG_URLONLINE_NAME;
79
import org.gvsig.online.lib.api.workingcopy.OnlineWorkingcopy;
80
import org.gvsig.online.lib.api.workingcopy.OnlineWorkingcopyDescriptor;
81
import org.gvsig.online.lib.api.workingcopy.WorkingArea;
82
import org.gvsig.online.lib.api.OnlineUserIdentificationRequester.OnlineUserIdentificationRequesterConfig;
83
import org.gvsig.online.lib.api.OnlineUserIdentificationRequester.OnlineUserIdentificationRequesterFactory;
84
import org.gvsig.online.lib.impl.workspace.OnlineWorkingcopyDescriptorImpl;
85
import org.gvsig.online.lib.impl.workspace.OnlineWorkspaceImpl;
86
import org.gvsig.online.lib.impl.workspace.StoreProperties;
87
import org.gvsig.online.lib.impl.workspace.WorkingAreaImpl;
88
import org.gvsig.online.lib.impl.workspace.tables.EntitiesTable;
89
import org.gvsig.online.lib.impl.workspace.tables.RemoteChangesTable;
90
import org.gvsig.online.lib.impl.workspace.tables.VarsTable;
91
import org.gvsig.online.lib.impl.workspace.tables.WorkspaceChangesTable;
92
import org.gvsig.tools.ToolsLocator;
93
import org.gvsig.tools.dispose.DisposeUtils;
94
import org.gvsig.tools.task.SimpleTaskStatus;
95
import org.gvsig.tools.task.UserCancelTaskException;
96
import org.gvsig.tools.util.HasAFile;
97
import org.gvsig.tools.util.ListBuilder;
98
import org.slf4j.Logger;
99
import org.slf4j.LoggerFactory;
100
import org.gvsig.tools.util.Factory;
101

    
102
@SuppressWarnings("UseSpecificCatch")
103
public class OnlineManagerImpl implements OnlineManager {
104
    
105
    private static final Logger LOGGER = LoggerFactory.getLogger(OnlineManagerImpl.class);
106

    
107
    public static final List<String> INTERNAL_WORKSPACE_TABLES = ListBuilder.create(
108
            EntitiesTable.TABLE_NAME,
109
            VarsTable.TABLE_NAME,
110
            RemoteChangesTable.TABLE_NAME,
111
            WorkspaceChangesTable.TABLE_NAME,
112
            DatabaseWorkspaceManager.TABLE_RESOURCES_NAME,
113
            DatabaseWorkspaceManager.TABLE_CONFIGURATION_NAME,
114
            DatabaseWorkspaceManager.TABLE_REPOSITORY_NAME
115
    );
116
    
117
    private Map<String,OnlineUserIdentificationRequesterFactory> userIdentificationRequesters;
118
    private Map<String,OnlineWorkingcopyDescriptor> workspaces;
119

    
120
    public OnlineManagerImpl() {
121
        this.workspaces = new HashMap<>();
122
        this.userIdentificationRequesters = new HashMap<>();
123
    }
124
    
125
    @Override
126
    public String getErrorMessage(int errcode) {
127
        return OnlineUtils.getErrorMessage(errcode);
128
    }
129

    
130
    @Override
131
    public void addUserIdentificationRequester(OnlineUserIdentificationRequesterFactory factory) {        
132
        this.userIdentificationRequesters.put(factory.getName(), factory);
133
    }
134

    
135
    @Override
136
    public OnlineUserIdentificationRequesterFactory getUserIdentificationRequester(String mode) {
137
        return this.userIdentificationRequesters.get(mode);
138
    }
139
    
140
    @Override
141
    public OnlineUserIdentificationRequesterConfig getUserIdentificationRequester(JsonObject json) {
142
        String factoryName = json.getString(CONFIG_FACTORYNAME_NAME, null);
143
        String urlOnline = json.getString(CONFIG_URLONLINE_NAME, null);
144
        OnlineUserIdentificationRequesterFactory factory = this.getUserIdentificationRequester(factoryName);
145
        OnlineUserIdentificationRequesterConfig config = factory.create(urlOnline);
146
        config.fromJson(json);
147
        return config;
148
    }
149
    
150
    @Override
151
    public Iterable<OnlineUserIdentificationRequesterFactory> getUserIdentificationRequesters() {
152
        return this.userIdentificationRequesters.values();
153
    }
154

    
155
    @Override
156
    public OnlineWorkingcopyDescriptor getWorkingcopyDescriptor(String code) {
157
        OnlineWorkingcopyDescriptor descriptor = this.workspaces.get(code);
158
        if( descriptor!=null ) {
159
            DisposeUtils.bind(descriptor);
160
            return descriptor;
161
        }
162
        for (OnlineWorkingcopyDescriptor descriptor2 : this.workspaces.values()) {
163
            if( descriptor2==null ) {
164
                continue;
165
            }
166
            if( StringUtils.equalsIgnoreCase(descriptor2.getLabel(), code) ) {
167
                DisposeUtils.bind(descriptor2);
168
                return descriptor2;
169
            }
170
        }
171
        return null;
172
    }
173
    
174
    @Override
175
    public synchronized void clean() {
176
        for (OnlineWorkingcopyDescriptor workspace : workspaces.values()) {
177
            DisposeUtils.disposeQuietly(workspace);
178
        }
179
        this.workspaces = new HashMap<>();
180
        this.userIdentificationRequesters = null;
181
    }
182
    
183
    public OnlineWorkingcopy openWorkingcopy(JDBCServerExplorer wsexplorer, String label) {
184
        // Abre la copia de trabajo cambiando su label y asignando un code nuevo.
185
        if (wsexplorer == null) {
186
            return null;
187
        }
188
        JDBCServerExplorerParameters params = null;
189
        try {
190
            OnlineWorkingcopy workspace;
191
            params = wsexplorer.getParameters();
192
            
193
            workspace = new OnlineWorkspaceImpl(wsexplorer, this.getCodeGenerator(), label);
194
            this.registerWorkingcopy(workspace);
195
            dropExpiredCaches();
196
            return workspace;
197
        } catch (Exception ex) {
198
            LOGGER.debug("Can't get workspace from "+Objects.toString(params)+".", ex);
199
            return null;
200
        }
201
    }
202
    
203
    @Override
204
    public void registerWorkingcopy(OnlineWorkingcopy workspace) {
205
        OnlineWorkingcopyDescriptor descriptor = this.workspaces.get(workspace.getCode());
206
        if( descriptor == null ) {
207
            descriptor = new OnlineWorkingcopyDescriptorImpl(workspace);
208
            this.workspaces.put(workspace.getCode(), descriptor);
209
        } else {
210
            ((OnlineWorkingcopyDescriptorImpl)descriptor).setWorkspace(workspace);            
211
        }
212
    }
213

    
214
    @Override
215
    public void deregisterWorkingcopy(File dbfile) {
216
        Path dbpath = dbfile.toPath();
217
        List<String>wscodes = new ArrayList<>();
218
        for (Iterator<OnlineWorkingcopyDescriptor> iterator = this.workspaces.values().iterator(); iterator.hasNext();) {
219
            OnlineWorkingcopyDescriptorImpl descriptor = (OnlineWorkingcopyDescriptorImpl) iterator.next();
220
            JDBCServerExplorerParameters explorerParams = descriptor.getExplorerParameters();
221
            if( explorerParams instanceof HasAFile ) {
222
                Path p = ((HasAFile) explorerParams).getFile().toPath();
223
                try {
224
                    if( Files.isSameFile(dbpath, p) ) {
225
                        wscodes.add(descriptor.getCode());
226
                    }
227
                } catch (IOException ex) {
228
                    LOGGER.debug("Can't deregister workspace '"+dbfile.getAbsolutePath()+"'.",ex);
229
                }
230
            }
231
        }        
232
        for (String wscode : wscodes) {
233
            deregisterWorkingcopy(wscode);
234
        }
235
    }
236

    
237
    @Override
238
    public void deregisterWorkingcopy(OnlineWorkingcopy workspace) {
239
        this.deregisterWorkingcopy(workspace.getCode());
240
    }
241

    
242
    @Override
243
    public void deregisterWorkingcopy(String workspaceCode) {
244
        DisposeUtils.disposeQuietly(this.workspaces.get(workspaceCode));
245
        this.workspaces.remove(workspaceCode);
246
        dropExpiredCaches();
247
    }
248
    
249
    private void dropExpiredCaches() {
250
        for (Iterator<OnlineWorkingcopyDescriptor> iterator = this.workspaces.values().iterator(); iterator.hasNext();) {
251
            OnlineWorkingcopyDescriptorImpl value = (OnlineWorkingcopyDescriptorImpl) iterator.next();
252
            if(DisposeUtils.getReferences(value)<=0){
253
                iterator.remove();
254
            } else {
255
                value.dropExpiredCaches();
256
            }
257
        }
258
    }
259

    
260
    @Override
261
    public OnlineWorkingcopy getWorkingcopy(FeatureStore store) {
262
        try {
263
            OnlineWorkspaceImpl workspace;
264
            switch(StoreProperties.getOnlineMode(store)) {
265
                case StoreProperties.MODE_NOT_ONLINE:
266
                    return null;
267

    
268
                case StoreProperties.MODE_ONLINE:
269
                    String workspace_code = StoreProperties.getWorkspaceCode(store);
270
                    OnlineWorkingcopyDescriptor workspaceDescriptor = this.workspaces.get(workspace_code);
271
                    if( workspaceDescriptor!=null ) {
272
                        workspace = (OnlineWorkspaceImpl) workspaceDescriptor.getWorkspace();
273
                        if (workspace != null) {
274
                            if( workspace.isInStoreIgnoreChanges(store) ) {
275
                                return workspace;
276
                            }
277
                            String entity_name = StoreProperties.getEntityName(store);
278
                            EntitiesTable.EntityRow entity = (EntitiesTable.EntityRow) workspace.getWorkspaceEntityByName(entity_name);
279
                            if (entity == null) {
280
                                StoreProperties.setNotOnlineMode(store);
281
                                DisposeUtils.dispose(workspace);
282
                                return null;
283
                            }
284
                            if( workspace.isCorrupt(entity,store,0) ) {
285
//                                return null; 
286
                            }
287
//                            LOGGER.debug("===: GET WORKSPACE "+ hexId(workspace)+ " from property (code='"+workspace.getCode()+"', label='"+workspace.getLabel()+"') for store '"+store.getName()+"'");        
288
                            return workspace;
289
                        }
290
                    }                
291
                case StoreProperties.MODE_UNKNOWN:
292
                default:
293
                    DataStoreParameters params = store.getParameters();
294
                    if(!(params instanceof JDBCStoreParameters)) {
295
                        StoreProperties.setNotOnlineMode(store);
296
                        return null;
297
                    }
298
                    String entity_name = ((JDBCStoreParameters) params).getTable();
299

    
300
                    if (INTERNAL_WORKSPACE_TABLES.contains(entity_name)  ) {
301
                        StoreProperties.setNotOnlineMode(store);
302
                        return null;
303
                    }
304

    
305
                    String storeUrl = ((JDBCStoreParameters)params).getUrl();
306
                    List<OnlineWorkingcopyDescriptor> descriptors = new ArrayList<>(this.workspaces.values());
307
                    for (OnlineWorkingcopyDescriptor value : descriptors) {
308
                        if( value == null ) {
309
                            continue;
310
                        }
311
                        JDBCServerExplorerParameters explorerParams = value.getExplorerParameters();    
312
                        if( explorerParams == null ) {
313
                            continue;
314
                        }
315
                        if (!StringUtils.equals(storeUrl, explorerParams.getUrl())) {
316
                            continue;
317
                        }
318
                        workspace = (OnlineWorkspaceImpl) value.getWorkspace();
319
                        if( workspace == null ) {
320
                            continue;
321
                        }
322
                        EntitiesTable.EntityRow entity = (EntitiesTable.EntityRow) workspace.getWorkspaceEntityByName(entity_name);
323
                        if (entity == null) {
324
                            StoreProperties.setNotOnlineMode(store);
325
                            DisposeUtils.dispose(workspace);
326
                            return null;
327
                        }
328
                        StoreProperties.set(store, workspace, entity_name);
329
                        if( workspace.isCorrupt(entity,store,0) ) {
330
//                                return null;
331
                        }
332
//                            LOGGER.debug("===: GET WORKSPACE "+ hexId(workspace)+ " from registry (code='"+workspace.getCode()+"', label='"+workspace.getLabel()+"') for store '"+store.getName()+"'");        
333
                        return workspace;
334
                    }
335

    
336
                    JDBCServerExplorer explorer = null;
337
                    try {
338
                        explorer = (JDBCServerExplorer)store.getExplorer();
339
                        if( !this.isWorkingcopy(explorer.getParameters()) ) {
340
                            StoreProperties.setNotOnlineMode(store);
341
                            return null;
342
                        }
343
                        workspace = (OnlineWorkspaceImpl) openWorkingcopy(explorer);
344
                    } catch (Exception e) {
345
                        workspace = null;
346
                    } finally {
347
                        DisposeUtils.disposeQuietly(explorer);
348
                    }
349
                    if (workspace == null) {
350
                        StoreProperties.setNotOnlineMode(store);
351
                        return null;
352
                    }
353
                    this.registerWorkingcopy(workspace);
354

    
355
                    EntitiesTable.EntityRow entity = (EntitiesTable.EntityRow) workspace.getWorkspaceEntityByName(entity_name);
356
                    if (entity == null) {
357
                        StoreProperties.setNotOnlineMode(store);
358
                        return null;
359
                    }
360
                    StoreProperties.set(store, workspace, entity_name);
361
                    return workspace;
362
            }
363
        } catch (Exception ex) {
364
            LOGGER.warn("Can't get '" +store.getName()+ "'store's workspace ", ex);
365
            StoreProperties.setUnknownOnlineMode(store);
366
            throw new RuntimeException("Can't get '" +store.getName()+ "'store's workspace ", ex);
367
        }
368
    }
369
    
370
    @Override
371
    public Map<String, OnlineWorkingcopyDescriptor> getWorkingcopy() {
372
        return Collections.unmodifiableMap(this.workspaces);
373
    }
374

    
375
    @Override
376
    public synchronized void restoreWorkingcopy(Map<String, OnlineWorkingcopyDescriptor> descriptors) {
377
        this.workspaces = new HashMap<>();
378
        if( descriptors != null ) {
379
            this.workspaces.putAll(descriptors);
380
        }
381
    }
382
    
383
    @Override
384
    public boolean isWorkingcopy(JDBCServerExplorerParameters params) {
385
        DataServerExplorer explorer = null;
386
        try {
387
            DataManager dataManager = DALLocator.getDataManager();
388
            explorer = dataManager.openServerExplorer(params.getProviderName(), params);
389
            DataStoreParameters x = explorer.get(VarsTable.TABLE_NAME);
390
            if(x==null) {
391
                return false;
392
            }
393
            return explorer.exists(x);
394
        } catch (Exception ex) {
395
            return false;
396
        } finally {
397
            DisposeUtils.disposeQuietly(explorer);
398
        }
399
    }
400
    
401
    @Override
402
    public boolean isWorkingcopy(File dbfile) {
403
        try {
404
            DataManager dataManager = DALLocator.getDataManager();
405
            JDBCServerExplorerParameters params = (JDBCServerExplorerParameters) dataManager.createServerExplorerParameters(DataStore.H2SPATIAL_PROVIDER_NAME);
406
            ((HasAFile)params).setFile(dbfile);
407
            return isWorkingcopy(params);
408
        } catch (Exception ex) {
409
            return false;
410
        }
411
    }    
412
    
413
    
414
    @Override
415
    public int initWorkingcopy(File wsfile, OnlineProject project, String label, SimpleTaskStatus status) {
416
        int err = ERR_NO_ERROR;
417
        if (wsfile == null) {
418
            return ERR_DBFILE_IS_NULL;
419
        }
420
        if (status == null) {
421
            status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("Online init_workingcopy");
422
            status.setAutoremove(true);
423
            status.add();
424
        } else {
425
            status.push();
426
        }
427
        DataManager dataManager = DALLocator.getDataManager();
428
        JDBCServerExplorer explorer = null;
429
        try {
430
            wsfile = new File(H2SpatialUtils.removeH2FileNameExtension(wsfile.getAbsolutePath()));
431
            if (StringUtils.isBlank(label)) {
432
                label = wsfile.getName();
433
            }
434
            err = ERR_CANT_OPEN_WORKSPACE_SERVEREXPLORER;
435
            JDBCServerExplorerParameters explorerParams = (JDBCServerExplorerParameters) dataManager.createServerExplorerParameters(DataStore.H2SPATIAL_PROVIDER_NAME);
436
            ((HasAFile) explorerParams).setFile(wsfile);
437
            explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
438
                    explorerParams.getProviderName(),
439
                    explorerParams
440
            );
441
            return this.initWorkingcopy(explorer, project, label, status);
442
        } catch (Exception ex) {
443
            status.abort();
444
            LOGGER.warn("Can't init workspace in '" + wsfile.getAbsolutePath() + "'.", ex);
445
            status.message(ex.getMessage());
446
            return err;
447
        } finally {
448
            status.pop();
449
            DisposeUtils.disposeQuietly(explorer);
450
        }
451
    }
452

    
453
    @Override
454
    public int initWorkingcopy(JDBCServerExplorer wsexplorer, OnlineProject project, String label, SimpleTaskStatus status) {
455
        int err = ERR_NO_ERROR;
456
        if (wsexplorer == null) {
457
            return ERR_WSEXPLORER_IS_NULL;
458
        }
459
        if (StringUtils.isBlank(label)) {
460
            return ERR_LABEL_IS_NULL;
461
        }
462
        if (status == null) {
463
            status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("Online init_workingcopy");
464
            status.setAutoremove(true);
465
            status.add();
466
        } else {
467
            status.push();
468
        }
469
        LOGGER.info("Initializing workspace "+Objects.toString(wsexplorer.getParameters().toJson()).replace('\n', ' ').replaceAll("\"password\":\"[^\"]*\"", "\"password\":\"****\""));
470

    
471
        DataManager dataManager = DALLocator.getDataManager();
472
        OnlineWorkspaceImpl workspace = null;
473
        try {
474
            status.setTitle("Online init_workingcopy");
475
            
476
            DatabaseWorkspaceManager databaseWorkspaceManager = dataManager.createDatabaseWorkspaceManager(wsexplorer.getParameters());
477
            
478
            if(!databaseWorkspaceManager.existsTable(TABLE_CONFIGURATION)){
479
                databaseWorkspaceManager.createTable(TABLE_CONFIGURATION);
480
            }
481
            if(!databaseWorkspaceManager.existsTable(TABLE_RESOURCES)){
482
                databaseWorkspaceManager.createTable(TABLE_RESOURCES);
483
            }
484
            if(!databaseWorkspaceManager.existsTable(TABLE_REPOSITORY)){
485
                databaseWorkspaceManager.createTable(TABLE_REPOSITORY);
486
                databaseWorkspaceManager.set(CONFIG_NAME_STORESREPOSITORYID, "Online");
487
            }
488
            databaseWorkspaceManager.connect();
489

    
490
            
491
            FeatureType[] tables = new FeatureType[]{
492
                VarsTable.featureType(),
493
                EntitiesTable.featureType(),
494
                WorkspaceChangesTable.featureType(),
495
                RemoteChangesTable.featureType()
496
            };
497
            status.setRangeOfValues(0, tables.length);
498
            int step = 1;
499
            for (FeatureType table : tables) {
500
                status.message(table.getLabel());
501
                status.setCurValue(step++);
502
                err = ERR_CANT_CREATE_TABLE + step;
503
                JDBCNewStoreParameters table_params = wsexplorer.getAddParameters();
504
                table_params.setDefaultFeatureType(table.getEditable());
505
                String tableName = table.getTags().getString("ID");
506
                table_params.setTable(tableName);
507
                wsexplorer.add(wsexplorer.getProviderName(), table_params, false);
508
                
509
                JDBCStoreParameters openParams = wsexplorer.get(tableName);
510
                databaseWorkspaceManager.writeStoresRepositoryEntry(tableName, openParams);
511
                
512
            }
513
//            try {
514
//                wsexplorer.execute(OnlineUtils.getSqlTemplate(wsexplorer.getProviderName(), "createWorkspaceIndex1"));
515
//                wsexplorer.execute(OnlineUtils.getSqlTemplate(wsexplorer.getProviderName(), "createWorkspaceIndex2"));
516
//                wsexplorer.execute(OnlineUtils.getSqlTemplate(wsexplorer.getProviderName(), "createWorkspaceIndex3"));
517
//                
518
//            } catch (Exception ex) {
519
//                LOGGER.warn("Can't create index in workspace", ex);
520
//            }
521
//            
522
            status.setTitle("vcsgis retrieving entities");
523
            workspace = new OnlineWorkspaceImpl(wsexplorer, this.getCodeGenerator(), project, label);
524
            workspace.initialize();
525
            LOGGER.info("Workspace initialized "+workspace.getCode());
526

    
527
            this.registerWorkingcopy(workspace);
528
            status.terminate();
529
            return ERR_NO_ERROR;
530
        } catch (UserCancelTaskException ex) {
531
            status.cancel();
532
            LOGGER.warn("Cancelled by user (" + getMessageLabel(wsexplorer) + ").", ex);
533
            status.message("Cancelled by user.");
534
            throw ex;
535
        } catch (Exception ex) {
536
            status.abort();
537
            LOGGER.warn("Can't init workspace in '" + getMessageLabel(wsexplorer) + "'.", ex);
538
            status.message(ex.getMessage());
539
            return err;
540
        } finally {
541
            status.pop();
542
            DisposeUtils.disposeQuietly(workspace);
543
        }
544
    }
545
    
546
    private String getMessageLabel(JDBCServerExplorer explorer) {
547
        return explorer.getParameters().getUrl();
548
    }
549

    
550
    @Override
551
    public OnlineWorkingcopy openWorkingcopy(File wsfile) {
552
        if (wsfile == null) {
553
            return null;
554
        }
555
        JDBCServerExplorer explorer = null;
556
        try {
557
            DataManager dataManager = DALLocator.getDataManager();
558
            JDBCServerExplorerParameters explorerParams = (JDBCServerExplorerParameters) dataManager.createServerExplorerParameters(DataStore.H2SPATIAL_PROVIDER_NAME);
559
            ((HasAFile) explorerParams).setFile(wsfile);
560
            explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
561
                    explorerParams.getProviderName(),
562
                    explorerParams
563
            );
564
            OnlineWorkingcopy workspace = openWorkingcopy(explorer);
565
            return workspace;
566
        } catch (Exception ex) {
567
            return null;
568
        } finally {
569
            DisposeUtils.disposeQuietly(explorer);
570
        }
571
    }
572

    
573
    @Override
574
    public OnlineWorkingcopy openWorkingcopy(JDBCServerExplorer wsexplorer) {
575
        if (wsexplorer == null) {
576
            return null;
577
        }
578
        JDBCServerExplorerParameters params = null;
579
        try {
580
            OnlineWorkingcopy workspace;
581

    
582
            params = wsexplorer.getParameters();
583
            String url = params.getUrl();
584
            for (Iterator<OnlineWorkingcopyDescriptor> iterator = this.workspaces.values().iterator(); iterator.hasNext();) {
585
                OnlineWorkingcopyDescriptorImpl value = (OnlineWorkingcopyDescriptorImpl) iterator.next();
586
                if (DisposeUtils.getReferences(value)<=0) {
587
                    iterator.remove();
588
                    continue;
589
                }
590
                if (value.isWorkspaceInitialized() && StringUtils.equals(url, value.getExplorerParameters().getUrl())) {
591
                    workspace = value.getWorkspace();//FIXME: lo siguiente solo si es null
592
                    dropExpiredCaches();
593
//                    LOGGER.debug("===: OPEN WORKSPACE "+ hexId(workspace)+ " from registry (code='"+workspace.getCode()+"', label='"+workspace.getLabel()+"')");        
594
                    return workspace;
595
                }
596
            }
597

    
598
            workspace = new OnlineWorkspaceImpl(wsexplorer, this.getCodeGenerator(), null);
599
            this.registerWorkingcopy(workspace);
600
            dropExpiredCaches();
601
            return workspace;
602
        } catch (Exception ex) {
603
            LOGGER.debug("Can't get workspace from "+Objects.toString(params)+".", ex);
604
            return null;
605
        }
606
    }
607

    
608
    public OnlineWorkingcopy openWorkingcopy(File wsfile, String label) {
609
        if (wsfile == null) {
610
            return null;
611
        }
612
        JDBCServerExplorer explorer = null;
613
        try {
614
            DataManager dataManager = DALLocator.getDataManager();
615
            JDBCServerExplorerParameters explorerParams = (JDBCServerExplorerParameters) dataManager.createServerExplorerParameters(DataStore.H2SPATIAL_PROVIDER_NAME);
616
            ((HasAFile) explorerParams).setFile(wsfile);
617
            explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
618
                    explorerParams.getProviderName(),
619
                    explorerParams
620
            );
621
            OnlineWorkingcopy workspace = openWorkingcopy(explorer, label);
622
            return workspace;
623
        } catch (Exception ex) {
624
            return null;
625
        } finally {
626
            DisposeUtils.disposeQuietly(explorer);
627
        }
628
    }
629
    
630
    @Override
631
    public OnlineSite connectSite(OnlineUserIdentificationRequesterConfig userIdentificationRequesterConfig, URL siteurl) throws IOException {
632
        OnlineSiteImpl site = new OnlineSiteImpl();
633
        if( siteurl!=null) {
634
            site.connect(userIdentificationRequesterConfig, siteurl);
635
        }
636
        return site;
637
    }
638

    
639
    @SuppressWarnings("Convert2Lambda")
640
    @Override
641
    public String authenticate(String urlbase, String userId, String password) {
642
        try {
643
            MutableInt statusCode = new MutableInt();
644
            Mutable<String> token = new MutableObject<>();
645
            
646
            if( !StringUtils.endsWith("/", urlbase) ) {
647
                urlbase += "/";
648
            }                
649
            URI uri = new URI(urlbase+"auth/api-token-auth/");
650
            int numretries = 3;
651
            for (int retries = 0; retries < numretries; retries++) {            
652
                HttpPost request = new HttpPost(uri);
653
                List<NameValuePair> params = new ArrayList<>();
654
                params.add(new BasicNameValuePair("username", userId));
655
                params.add(new BasicNameValuePair("password", password));
656
                UrlEncodedFormEntity formdata = new UrlEncodedFormEntity(params);
657
                request.setEntity(formdata);
658
                request.setHeader("Content-type","application/x-www-form-urlencoded");
659
                CloseableHttpClient httpClient = HttpClientBuilder.create().build();                
660
                ResponseHandler responseHandler = new ResponseHandler() {
661
                    @Override
662
                    public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
663
                        statusCode.setValue(response.getStatusLine().getStatusCode());
664
                        InputStream content = response.getEntity().getContent();
665
                        JsonObject resp = Json.createObject(content);
666
                        token.setValue(resp.getString("token", null));
667
                        return null;
668
                    }
669
                };
670
                httpClient.execute(request,responseHandler);  
671
                if( statusCode.getValue()==200 ) {
672
                    break;
673
                }
674
            }
675
            if( statusCode.getValue()!=200 ) {
676
                LOGGER.warn("Toomany retries for authenticate (HTTP status "+statusCode.toString()+")");
677
                return null;
678
            }
679
            String authorization = "JWT " + token.getValue();
680
            return authorization;
681
            
682
        } catch (Exception ex) {
683
            LOGGER.warn("", ex);
684
            throw new RuntimeException("Can't get authorization from '"+urlbase+"' for user '"+userId+"'.", ex);
685
        }
686
    }
687
    @Override
688
    public WorkingArea createWorkingArea() {
689
        return new WorkingAreaImpl();
690
    }
691
    
692
    private OnlineCodeGenerator getCodeGenerator() {
693
        return new RandomCodeGenerator();
694
    }
695

    
696

    
697
}