Project

General

Profile

Download (18 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2015 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.taxeditor.remoting.source;
10

    
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileNotFoundException;
14
import java.io.FileOutputStream;
15
import java.io.IOException;
16
import java.net.InetSocketAddress;
17
import java.net.Socket;
18
import java.util.ArrayList;
19
import java.util.Collections;
20
import java.util.Comparator;
21
import java.util.List;
22

    
23
import org.apache.commons.lang.StringUtils;
24
import org.apache.http.HttpEntity;
25
import org.apache.http.HttpResponse;
26
import org.apache.http.client.ClientProtocolException;
27
import org.apache.http.client.ResponseHandler;
28
import org.apache.http.client.methods.HttpGet;
29
import org.apache.http.impl.client.DefaultHttpClient;
30
import org.apache.http.params.HttpConnectionParams;
31
import org.apache.http.params.HttpParams;
32
import org.apache.http.util.EntityUtils;
33
import org.apache.log4j.Logger;
34
import org.json.JSONArray;
35
import org.json.JSONException;
36
import org.json.JSONObject;
37

    
38
import com.fasterxml.jackson.core.type.TypeReference;
39
import com.fasterxml.jackson.databind.ObjectMapper;
40

    
41
import eu.etaxonomy.cdm.api.application.CdmApplicationState;
42
import eu.etaxonomy.cdm.config.CdmSourceException;
43
import eu.etaxonomy.cdm.config.ConfigFileUtil;
44
import eu.etaxonomy.cdm.database.CdmPersistentDataSource;
45
import eu.etaxonomy.cdm.database.ICdmDataSource;
46
import eu.etaxonomy.cdm.model.metadata.CdmMetaData;
47
import eu.etaxonomy.taxeditor.remoting.server.CDMServerException;
48
import eu.etaxonomy.taxeditor.remoting.server.CDMServerUtils;
49

    
50
/**
51
 * @author cmathew
52
 * @date 20 Jan 2015
53
 *
54
 */
55
public class CdmServerInfo {
56
    public static final Logger logger = Logger.getLogger(CdmServerInfo.class);
57

    
58
    private final static String CDMSERVER_PREFIX = "cdmserver/";
59
    private final static String NAME_PRODUCTION = "cybertaxonomy.org";
60
    private final static String SERVER_PRODUCTION = "api.cybertaxonomy.org";
61

    
62
    private final static String NAME_DEMO_1 = "demo I";
63
    private final static String SERVER_DEMO_1 = "160.45.63.230";
64

    
65
    public final static String SERVER_LOCALHOST = "localhost";
66
    private final static String NAME_LOCALHOST = "localhost";
67
    public final static String NAME_LOCALHOST_MGD = "localhost mgd.";
68

    
69
    private final static String NAME_LOCALHOST_DEV = "localhost-dev";
70
    private final static String NAME_INSTANCE_LOCALHOST_DEV = "local-dev";
71
    private final static String SERVER_LOCALHOST_DEV = "localhost";
72
    private final static String BASEPATH_LOCALHOST_DEV = "";
73

    
74
    public final static int NULL_PORT = -1;
75
    public final static String NULL_PORT_STRING = "N/A";
76

    
77
    public static final int TIME_OUT = 7000;
78

    
79
    private static final String CDM_REMOTE_SERVERS_CONFIG_FILE = "cdm_remote_servers.json";
80

    
81

    
82
    private final String name;
83
    private final String server;
84
    private int port;
85
    private final List<CdmInstanceInfo> instances;
86

    
87
    private String cdmlibServicesVersion = "";
88
    private String cdmlibServicesLastModified = "";
89

    
90
    private String prefix = "";
91

    
92
    private boolean ignoreCdmLibVersion = false;
93

    
94

    
95
    public CdmServerInfo(CdmServerInfoConfig parameterObject) {
96
        this.name = parameterObject.getName();
97
        this.server = parameterObject.getServer();
98
        this.port = parameterObject.getPort();
99
        this.prefix = parameterObject.getPrefix();
100
        this.ignoreCdmLibVersion = parameterObject.isIgnoreCdmLibVersion();
101
        instances = new ArrayList<>();
102
    }
103

    
104

    
105
    public CdmInstanceInfo addInstance(String name, String basePath) {
106
        String _basePath = basePath;
107
        if(isLocalhostMgd()) {
108
            _basePath = "";
109
        }
110
        CdmInstanceInfo cii = new CdmInstanceInfo(name, _basePath);
111
        instances.add(cii);
112
        return cii;
113

    
114
    }
115

    
116
    public boolean isLocalhost() {
117
        return name.startsWith(SERVER_LOCALHOST);
118
    }
119

    
120
    public boolean isLocalhostMgd() {
121
        return NAME_LOCALHOST_MGD.equals(name);
122
    }
123

    
124
    public String getCdmlibServicesVersion() {
125
        return cdmlibServicesVersion;
126
    }
127

    
128
    public String getCdmlibLastModified() {
129
        return cdmlibServicesLastModified;
130
    }
131

    
132
    public void refreshInstances() throws CDMServerException {
133
        instances.clear();
134
        if(isLocalhostMgd()) {
135
            addInstancesFromDataSourcesConfig();
136
        } else {
137
            addInstancesViaHttp();
138
        }
139
        Collections.sort(instances, new Comparator<CdmInstanceInfo>() {
140
            @Override
141
            public int compare(CdmInstanceInfo cii1, CdmInstanceInfo cii2)
142
            {
143
                return cii1.getName().toString().compareTo(cii2.getName().toString());
144
            }
145
        });
146
    }
147

    
148
    public void updateInfo() throws CDMServerException {
149
        String url = "http://" + server + ":" + String.valueOf(port) + "/" + prefix + "info.jsp";
150
        String responseBody = getResponse(url);
151
        if(responseBody != null) {
152
            try {
153
                JSONObject info = new JSONObject(responseBody);
154
                cdmlibServicesVersion =  info.getString("cdmlibServicesVersion");
155
                cdmlibServicesLastModified = info.getString("cdmlibServicesLastModified");
156
            } catch (JSONException e) {
157
                throw new CDMServerException(e);
158
            }
159
        }
160
    }
161

    
162
    public void addInstancesViaHttp() throws CDMServerException {
163
        updateInfo();
164
        String url = "http://" + server + ":" + String.valueOf(port) + "/" + prefix + "instances.jsp";
165
        String responseBody = getResponse(url);
166
        if(responseBody != null) {
167
            try {
168
                JSONArray array = new JSONArray(responseBody);
169
                for(int i=0;i<array.length();i++) {
170
                    JSONObject instance = (JSONObject)array.get(i);
171
                    if(instance != null) {
172
                        JSONObject conf = (JSONObject)instance.get("configuration");
173
                        if(conf != null) {
174
                            String instanceName = conf.getString("instanceName");
175
                            // we need to remove the first (char) forward slash from
176
                            // the base path
177
                            String basePath = conf.getString("basePath").substring(1);
178
                            addInstance(instanceName, basePath);
179
                            logger.info("Added instance with name : " + instanceName + ", basePath : " + basePath);
180
                        }
181
                    }
182
                }
183
            } catch (JSONException e) {
184
                throw new CDMServerException(e);
185
            }
186
        }
187
    }
188

    
189
    private String getResponse(String url) throws CDMServerException {
190
        DefaultHttpClient client = new DefaultHttpClient();
191
       // client = HttpClientBuilder.create().build();
192
       // client.getParams();
193
        HttpParams params = client.getParams();
194

    
195
        HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
196
        HttpConnectionParams.setSoTimeout(params, TIME_OUT);
197

    
198
        HttpGet httpGet = new HttpGet(url);
199

    
200
        logger.info("Executing request " + httpGet.getRequestLine());
201

    
202
        // Create a custom response handler
203
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
204

    
205
            @Override
206
            public String handleResponse(
207
                    final HttpResponse response) throws ClientProtocolException, IOException {
208
                int status = response.getStatusLine().getStatusCode();
209
                if (status >= 200 && status < 300) {
210
                    HttpEntity entity = response.getEntity();
211
                    return entity != null ? EntityUtils.toString(entity) : null;
212
                } else {
213
                    throw new ClientProtocolException("Unexpected response status: " + status);
214
                }
215
            }
216

    
217
        };
218
        String responseBody = null;
219
        try {
220
            responseBody = client.execute(httpGet, responseHandler);
221
        } catch (ClientProtocolException e) {
222
            throw new CDMServerException(e);
223
        } catch (IOException e) {
224
            throw new CDMServerException(e);
225
        } finally{
226
            client.close();
227
        }
228
        return responseBody;
229
    }
230

    
231
    public void addInstancesFromDataSourcesConfig() {
232
        for(ICdmDataSource dataSource : CdmPersistentDataSource.getAllDataSources()){
233
            String datasourceNCName = CDMServerUtils.xmlNCNamefrom(dataSource.getName());
234
            logger.info("Adding local instance " + dataSource.getName() + " as " + datasourceNCName);
235
            addInstance(datasourceNCName, datasourceNCName);
236
        }
237
    }
238

    
239
    public String toString(String instanceName, int port) {
240
        return server + ":" + String.valueOf(port) + "/" + instanceName;
241
    }
242

    
243
    public CdmInstanceInfo getInstanceFromName(String instanceName) {
244
        if(instanceName == null) {
245
            return null;
246
        }
247

    
248
        for(CdmInstanceInfo instance : instances) {
249
            if(instance.getName() != null && instance.getName().equals(instanceName)) {
250
                return instance;
251
            }
252
        }
253
        return null;
254
    }
255

    
256
    public CdmRemoteSource getCdmRemoteSource(CdmInstanceInfo instance, int port) {
257
        if(instance != null) {
258
            return CdmRemoteSource.NewInstance(name,
259
                    server,
260
                    port,
261
                    instance.getBasePath()
262
                    );
263
        }
264
        return null;
265
    }
266

    
267
    public boolean pingServer() throws CDMServerException, IOException {
268
        if(isLocalhostMgd()) {
269
            return true;
270
        }
271
        Socket s = new Socket();
272
        s.connect(new InetSocketAddress(server, port), TIME_OUT);
273
        s.close();
274
        logger.info("[CDM-Server] Available @ " + server + ":" + port );
275
        updateInfo();
276
        return true;
277
    }
278

    
279
    public boolean pingInstance(CdmInstanceInfo instance, int port) throws CDMServerException  {
280

    
281
        ICdmRemoteSource crs = getCdmRemoteSource(instance, port);
282
        try {
283
            if(crs != null && crs.checkConnection()) {
284
                logger.info("[CDM-Server] Running @ " + server + ":" + port + " for instance " + instance);
285
                return true;
286
            }
287
        } catch (CdmSourceException e) {
288
            throw new CDMServerException(e);
289
        }
290

    
291
        return false;
292
    }
293

    
294
    public int compareDbSchemaVersion(CdmInstanceInfo instance, int port) throws CDMServerException {
295

    
296
        ICdmRemoteSource crs = getCdmRemoteSource(instance, port);
297
        String dbSchemaVersion;
298
        try {
299
            dbSchemaVersion = crs.getDbSchemaVersion();
300
        } catch (CdmSourceException e) {
301
            throw new CDMServerException(e);
302
        }
303

    
304

    
305
        if(dbSchemaVersion != null) {
306
            return CdmMetaData.compareVersion(dbSchemaVersion, CdmMetaData.getDbSchemaVersion(), 3, null);
307
        } else {
308
            throw new CDMServerException("Cannot determine editor db. schema version");
309
        }
310
    }
311

    
312
    public int compareCdmlibServicesVersion() throws CdmSourceException {
313

    
314
        String serverVersion = cdmlibServicesVersion;
315
        String serverCdmlibLastModified = cdmlibServicesLastModified;
316
        if(ignoreCdmLibVersion) {
317
            return 0;
318
        } else {
319
            return compareCdmlibServicesVersion(serverVersion, serverCdmlibLastModified);
320
        }
321
    }
322

    
323

    
324
    /**
325
     * @param serverVersion
326
     * @param editorVersion
327
     * @throws CdmSourceException
328
     */
329
    public static int compareCdmlibServicesVersion(String serverVersion, String serverCdmlibLastModified) throws CdmSourceException {
330

    
331
        String editorVersion = CdmApplicationState.getCdmlibVersion();
332
        String editorCdmlibLastModified = CdmApplicationState.getCdmlibLastModified();
333

    
334
        int result = 0;
335
        if(StringUtils.isBlank(serverVersion) || StringUtils.isBlank(editorVersion)) {
336
            throw new CdmSourceException("cdmlib-services server or editor version is empty");
337
        }
338

    
339
        String[] serverVersionSplit = serverVersion.split("\\.");
340
        String[] editorVersionSplit = editorVersion.split("\\.");
341

    
342
        if(serverVersionSplit.length < 3 || editorVersionSplit.length < 3 || serverVersionSplit.length > 4 || editorVersionSplit.length > 4) {
343
            throw new CdmSourceException("cdmlib-services server or editor version is invalid");
344
        }
345

    
346
        Integer serverVersionPart;
347
        Integer editorVersionPart;
348

    
349
        for(int i=0 ; i<3 ; i++) {
350
            serverVersionPart = Integer.valueOf(serverVersionSplit[i]);
351
            editorVersionPart = Integer.valueOf(editorVersionSplit[i]);
352

    
353
            int partCompare = serverVersionPart.compareTo(editorVersionPart);
354
            if (partCompare != 0){
355
                return partCompare;
356
            }
357
        }
358
        // at this point major, minor and patch versions are matching
359

    
360
        if(StringUtils.isBlank(serverCdmlibLastModified) || StringUtils.isBlank(editorCdmlibLastModified)) {
361
            throw new CdmSourceException("cdmlib-services server or editor version is empty");
362
        }
363

    
364
        String cdmServerIgnoreVersion = System.getProperty("cdm.server.version.lm.ignore");
365
        if(StringUtils.isBlank(cdmServerIgnoreVersion) || !cdmServerIgnoreVersion.equals("true")) {
366
            Long serverLastModified = Long.valueOf(serverCdmlibLastModified);
367
            Long editorLastModified = Long.valueOf(editorCdmlibLastModified);
368
            return serverLastModified.compareTo(editorLastModified);
369
        }
370

    
371
        return result;
372
    }
373

    
374

    
375

    
376
    public static List<CdmServerInfo> getCdmServers() {
377
        List<CdmServerInfoConfig> configList;
378
        File file = new File(ConfigFileUtil.perUserCdmFolder(), CDM_REMOTE_SERVERS_CONFIG_FILE);
379
        if (file.exists()){
380
            configList = loadFromConfigFile(file);
381
        }else{
382
            configList = loadFromConfigFile(new File(ConfigFileUtil.perUserCdmFolderFallback(), CDM_REMOTE_SERVERS_CONFIG_FILE));
383
        }
384
        List<CdmServerInfo> serverInfoList = new ArrayList<CdmServerInfo>(configList.size());
385
        for(CdmServerInfoConfig config : configList) {
386
            serverInfoList.add(new CdmServerInfo(config));
387
        }
388
        // The local host managed server must not be in the config file
389
        CdmServerInfoConfig localHostManagedConfig = new CdmServerInfoConfig(NAME_LOCALHOST_MGD, SERVER_LOCALHOST, NULL_PORT, CDMSERVER_PREFIX, false);
390
        serverInfoList.add(new CdmServerInfo(localHostManagedConfig));
391
        return serverInfoList;
392
    }
393

    
394

    
395
    /**
396
     * @param file
397
     * @throws IOException
398
     * @throws FileNotFoundException
399
     * @throws JsonMappingException
400
     * @throws JsonParseException
401
     */
402
    private static List<CdmServerInfoConfig>  loadFromConfigFile(File file) {
403

    
404
        List<CdmServerInfoConfig> serverList = null;
405

    
406
        ObjectMapper mapper = new ObjectMapper();
407

    
408
        if(!file.exists()) {
409
            logger.info("The remote server config file '" + file.getAbsolutePath() +
410
                    "' does not yet exist, it will be created based on the defaults.");
411
             try {
412
                serverList = createDefaultServerConfigList();
413
                mapper.writerWithDefaultPrettyPrinter().writeValue(new FileOutputStream(file), serverList);
414

    
415
            } catch (IOException e) {
416
                throw new RuntimeException(e);
417
            }
418
        } else {
419
            try {
420
                serverList = mapper.readValue(new FileInputStream(file), new TypeReference<List<CdmServerInfoConfig>>(){});
421
            } catch (IOException e) {
422
               throw new RuntimeException(e);
423
            }
424
        }
425

    
426
        return serverList;
427

    
428

    
429
    }
430

    
431

    
432
    /**
433
     *
434
     */
435
    private static List<CdmServerInfoConfig> createDefaultServerConfigList() {
436

    
437
        List<CdmServerInfoConfig> serverInfoList = new ArrayList<CdmServerInfoConfig>();
438
        serverInfoList.add(new CdmServerInfoConfig(NAME_PRODUCTION, SERVER_PRODUCTION, 80, "", false));
439
        serverInfoList.add(new CdmServerInfoConfig(NAME_DEMO_1, SERVER_DEMO_1, 80, CDMSERVER_PREFIX, false));
440
        serverInfoList.add(new CdmServerInfoConfig(NAME_LOCALHOST, SERVER_LOCALHOST, 8080, CDMSERVER_PREFIX, true));
441
        return serverInfoList;
442
    }
443

    
444
    public String getName() {
445
        return name;
446
    }
447

    
448
    public String getServer() {
449
        return server;
450
    }
451

    
452

    
453
    public int getPort() {
454
        return port;
455
    }
456

    
457
    public void setPort(int port) {
458
        this.port = port;
459
    }
460

    
461
    public List<CdmInstanceInfo> getInstances() throws CDMServerException {
462
        if(instances.isEmpty()) {
463
            refreshInstances();
464
        }
465
        return instances;
466
    }
467

    
468
    public static CdmRemoteSource getDevServerRemoteSource() {
469
        String value = System.getProperty("cdm.server.dev.port");
470
        boolean available = false;
471
        CdmInstanceInfo devInstance = null;
472
        if(value != null && !value.isEmpty()) {
473
            int devPort = Integer.valueOf(value);
474
            CdmServerInfo devCii = new CdmServerInfo(new CdmServerInfoConfig(NAME_LOCALHOST_DEV, SERVER_LOCALHOST_DEV, devPort, "", false));
475
            try {
476
                devInstance = devCii.addInstance(NAME_INSTANCE_LOCALHOST_DEV, BASEPATH_LOCALHOST_DEV);
477
                available = devCii.pingInstance(devInstance, devPort);
478
                if(available) {
479
                    return devCii.getCdmRemoteSource(devInstance, devPort);
480
                }
481
            } catch (Exception e) {
482

    
483
            }
484
        }
485
        return null;
486
    }
487

    
488
    public class CdmInstanceInfo {
489
        private final String name;
490

    
491
        /**
492
         * The full path of the instance including the the prefix (if any).
493
         * E.g. for an EDIT instance this would be something like "cdmserver/remoting"
494
         * For a managed local server this would simply be ""
495
         */
496
        private final String basePath;
497

    
498

    
499
        public CdmInstanceInfo(String name, String basePath) {
500
            this.name = name;
501
            this.basePath = basePath;
502
        }
503

    
504

    
505
        public String getName() {
506
            return name;
507
        }
508

    
509
        public String getBasePath() {
510
            return basePath;
511
        }
512
    }
513
}
(5-5/7)