View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  package org.waarp.openr66.configuration;
21  
22  import io.netty.handler.traffic.AbstractTrafficShapingHandler;
23  import org.dom4j.Document;
24  import org.dom4j.DocumentException;
25  import org.waarp.common.cpu.WaarpConstraintLimitHandler;
26  import org.waarp.common.crypto.Des;
27  import org.waarp.common.crypto.ssl.WaarpSecureKeyStore;
28  import org.waarp.common.crypto.ssl.WaarpSslContextFactory;
29  import org.waarp.common.database.ConnectionFactory;
30  import org.waarp.common.database.DbAdmin;
31  import org.waarp.common.database.DbRequest;
32  import org.waarp.common.database.data.AbstractDbData.UpdatedInfo;
33  import org.waarp.common.database.exception.WaarpDatabaseException;
34  import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException;
35  import org.waarp.common.database.exception.WaarpDatabaseSqlException;
36  import org.waarp.common.digest.FilesystemBasedDigest.DigestAlgo;
37  import org.waarp.common.exception.CryptoException;
38  import org.waarp.common.exception.InvalidArgumentException;
39  import org.waarp.common.file.AbstractDir;
40  import org.waarp.common.file.DirInterface;
41  import org.waarp.common.file.FileUtils;
42  import org.waarp.common.file.filesystembased.FilesystemBasedFileParameterImpl;
43  import org.waarp.common.logging.SysErrLogger;
44  import org.waarp.common.logging.WaarpLogger;
45  import org.waarp.common.logging.WaarpLoggerFactory;
46  import org.waarp.common.role.RoleDefault;
47  import org.waarp.common.role.RoleDefault.ROLE;
48  import org.waarp.common.utility.ParametersChecker;
49  import org.waarp.common.utility.SystemPropertyUtil;
50  import org.waarp.common.utility.WaarpSystemUtil;
51  import org.waarp.common.xml.XmlHash;
52  import org.waarp.common.xml.XmlRootHash;
53  import org.waarp.common.xml.XmlUtil;
54  import org.waarp.common.xml.XmlValue;
55  import org.waarp.gateway.kernel.rest.RestConfiguration;
56  import org.waarp.openr66.context.R66BusinessFactoryInterface;
57  import org.waarp.openr66.context.authentication.R66Auth;
58  import org.waarp.openr66.context.task.localexec.LocalExecClient;
59  import org.waarp.openr66.dao.DAOFactory;
60  import org.waarp.openr66.database.data.DbConfiguration;
61  import org.waarp.openr66.database.data.DbHostAuth;
62  import org.waarp.openr66.database.data.DbHostConfiguration;
63  import org.waarp.openr66.database.model.DbModelFactoryR66;
64  import org.waarp.openr66.pojo.Business;
65  import org.waarp.openr66.protocol.configuration.Configuration;
66  import org.waarp.openr66.protocol.configuration.Messages;
67  import org.waarp.openr66.protocol.configuration.PartnerConfiguration;
68  import org.waarp.openr66.protocol.configuration.R66SystemProperties;
69  import org.waarp.openr66.protocol.exception.OpenR66ProtocolSystemException;
70  import org.waarp.openr66.protocol.http.adminssl.HttpResponsiveSslHandler;
71  import org.waarp.openr66.protocol.http.rest.HttpRestR66Handler.RESTHANDLERS;
72  import org.waarp.openr66.protocol.monitoring.MonitorExporterTransfers;
73  import org.waarp.openr66.protocol.networkhandler.R66ConstraintLimitHandler;
74  import org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerInitializer;
75  import org.waarp.openr66.server.ServerInitDatabase;
76  import org.waarp.snmp.SnmpConfiguration;
77  
78  import java.io.File;
79  import java.io.IOException;
80  import java.net.InetAddress;
81  import java.net.InetSocketAddress;
82  import java.net.UnknownHostException;
83  import java.sql.SQLException;
84  import java.util.Arrays;
85  import java.util.List;
86  import java.util.Locale;
87  
88  import static org.waarp.common.database.DbConstant.*;
89  import static org.waarp.openr66.configuration.FileBasedElements.*;
90  
91  /**
92   * File Based Configuration
93   */
94  public class FileBasedConfiguration {
95    private static final String CANNOT_FIND_SSL_AUTHENTICATION_FOR_CURRENT_HOST =
96        "Cannot find SSL Authentication for current host";
97  
98    private static final String CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST =
99        "Cannot find Authentication for current host";
100 
101   private static final String IS_DEPRECATED_IN_SYSTEM_PROPERTIES_USE_INSTEAD =
102       "{} is deprecated in system properties use {} instead";
103 
104   private static final String CANNOT_LOAD_AUTHENTICATION_CONFIGURATION =
105       "Cannot load Authentication configuration";
106 
107   private static final String CANNOT_LOAD_LIMIT_CONFIGURATION =
108       "Cannot load Limit configuration";
109 
110   private static final String CANNOT_LOAD_DIRECTORY_CONFIGURATION =
111       "Cannot load Directory configuration";
112 
113   private static final String CANNOT_LOAD_DATABASE_CONFIGURATION =
114       "Cannot load Database configuration";
115 
116   private static final String CANNOT_LOAD_IDENTITY = "Cannot load Identity";
117 
118   private static final String FILE_BASED_CONFIGURATION_CANNOT_READ_XML =
119       "FileBasedConfiguration.CannotReadXml";
120 
121   private static final String FILE_BASED_CONFIGURATION_NO_SET_CONFIG =
122       "FileBasedConfiguration.NoSetConfig";
123   private static final String FILE_BASED_CONFIGURATION_INVALID_CONFIG =
124       "FileBasedConfiguration.NotValidConfig";
125   private static final String FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG =
126       "FileBasedConfiguration.NotFoundConfig";
127 
128   /**
129    * Internal Logger
130    */
131   private static final WaarpLogger logger =
132       WaarpLoggerFactory.getLogger(FileBasedConfiguration.class);
133   protected static final String REGEX_SEPARATOR = "\\s|\\|";
134 
135   private static XmlValue[] configuration;
136 
137   private static XmlRootHash hashRootConfig;
138 
139   protected FileBasedConfiguration() {
140   }
141 
142   public static void setXmlRootHash(final XmlRootHash xmlRootHash) {
143     hashRootConfig = xmlRootHash;
144   }
145 
146   /**
147    * Load the locale from configuration file
148    *
149    * @param hashConfig
150    */
151   private static void loadLocale(final XmlHash hashConfig) {
152     final XmlValue value = hashConfig.get(XML_LOCALE);
153     if (value != null && !value.isEmpty()) {
154       final String locale = value.getString();
155       if (ParametersChecker.isEmpty(locale)) {
156         return;
157       }
158       Messages.init(new Locale(locale));
159     }
160   }
161 
162   /**
163    * @param config
164    * @param hashRootConfig
165    *
166    * @return True if the identity of the server is correctly loaded
167    */
168   public static boolean loadIdentity(final Configuration config,
169                                      final XmlRootHash hashRootConfig) {
170     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_IDENTITY));
171     try {
172       loadLocale(hashConfig);
173       XmlValue value = hashConfig.get(XML_SERVER_HOSTID);
174       if (value != null && !value.isEmpty()) {
175         config.setHostId(value.getString());
176       } else {
177         logger.error(
178             Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
179             "Host ID"); //$NON-NLS-1$
180         return false;
181       }
182       value = hashConfig.get(XML_SERVER_SSLHOSTID);
183       if (value != null && !value.isEmpty()) {
184         config.setHostSslId(value.getString());
185       } else {
186         logger.warn(Messages.getString(
187             "FileBasedConfiguration.SSLIDNotFound")); //$NON-NLS-1$
188         config.setUseSSL(false);
189         config.setHostSslId(null);
190       }
191       value = hashConfig.get(XML_AUTHENTIFICATION_FILE);
192       if (value != null && !value.isEmpty()) {
193         config.setAuthFile(value.getString());
194       }
195       return setCryptoKey(config, hashConfig);
196     } finally {
197       hashConfig.clear();
198       hashConfig = null;
199     }
200   }
201 
202   private static boolean isDbInactive(final Configuration configuration) {
203     return !isDbUsed() || configuration.isSaveTaskRunnerWithNoDb();
204   }
205 
206   /**
207    * @param config
208    *
209    * @return True if the authentication of partners is correctly loaded
210    */
211   private static boolean loadAuthentication(final Configuration config) {
212     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_IDENTITY));
213     try {
214       if (isDbInactive(config)) {
215         // if no database, must load authentication from file
216         final XmlValue value = hashConfig.get(XML_AUTHENTIFICATION_FILE);
217         if (value != null && !value.isEmpty()) {
218           final String fileauthent = value.getString();
219           return AuthenticationFileBasedConfiguration.loadAuthentication(config,
220                                                                          fileauthent);
221         } else {
222           logger.warn(
223               Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
224               "Authentication file"); //$NON-NLS-1$
225           return false;
226         }
227       }
228       return true;
229     } finally {
230       hashConfig.clear();
231       hashConfig = null;
232     }
233   }
234 
235   private static boolean loadPushMonitorParam(final Configuration config) {
236     final XmlHash hashConfig =
237         new XmlHash(hashRootConfig.get(XML_PUSH_MONITOR));
238     try {
239       XmlValue value;
240       // Common part API REST and Elasticsearch
241       value = hashConfig.get(XML_PUSH_MONITOR_URL);
242       if (value != null && !value.isEmpty()) {
243         try {
244           ParametersChecker.checkSanityString(value.getString());
245         } catch (final InvalidArgumentException e) {
246           logger.error("Bad Push Monitor URL: {}", e.getMessage());
247           return false;
248         }
249         final String url = value.getString();
250         // Default value
251         int delay = 1000;
252         value = hashConfig.get(XML_PUSH_MONITOR_DELAY);
253         if (value != null && !value.isEmpty()) {
254           delay = value.getInteger();
255           if (delay < 0) {
256             delay = 1000;
257           }
258           if (delay < 500) {
259             delay = 500;
260           }
261         }
262         // Default value
263         boolean intervalIncluded =
264             MonitorExporterTransfers.MONITOR_INTERVAL_INCLUDED_DEFAULT;
265         value = hashConfig.get(XML_PUSH_MONITOR_INTERVAL_INCLUDED);
266         if (value != null && !value.isEmpty()) {
267           intervalIncluded = value.getBoolean();
268         }
269         // Default value
270         boolean longAsString =
271             MonitorExporterTransfers.MONITOR_LONG_AS_STRING_DEFAULT;
272         value = hashConfig.get(XML_PUSH_MONITOR_TRANSFORM_LONG_AS_STRING);
273         if (value != null && !value.isEmpty()) {
274           longAsString = value.getBoolean();
275         }
276         // Determine API REST or Elasticsearch through INDEX presence
277         // Elasticsearch Specific
278         String index = null;
279         value = hashConfig.get(XML_PUSH_MONITOR_ES_INDEX);
280         if (value != null && !value.isEmpty()) {
281           try {
282             ParametersChecker.checkSanityString(value.getString());
283           } catch (final InvalidArgumentException e) {
284             logger.error("Bad Push Monitor Index: {}", e.getMessage());
285             return false;
286           }
287           index = value.getString();
288         }
289         // API REST Specific
290         // Default value
291         String endpoint = "/";
292         value = hashConfig.get(XML_PUSH_MONITOR_ENDPOINT);
293         if (value != null && !value.isEmpty()) {
294           if (index != null) {
295             logger.error("Bad Push Monitor: both Index for Elasticsearch and " +
296                          "EndPoint for REST API are specified, while only one" +
297                          " can be specified");
298             return false;
299           }
300           try {
301             ParametersChecker.checkSanityString(value.getString());
302           } catch (final InvalidArgumentException e) {
303             logger.error("Bad Push Monitor EndPoint: {}", e.getMessage());
304             return false;
305           }
306           endpoint = value.getString();
307         }
308         String token = null;
309         value = hashConfig.get(XML_PUSH_MONITOR_TOKEN);
310         if (value != null && !value.isEmpty()) {
311           try {
312             ParametersChecker.checkSanityString(value.getString());
313           } catch (final InvalidArgumentException e) {
314             logger.error("Bad Push Monitor Token: {}", e.getMessage());
315             return false;
316           }
317           token = value.getString();
318         }
319         String apikey = null;
320         value = hashConfig.get(XML_PUSH_MONITOR_APIKEY);
321         if (value != null && !value.isEmpty()) {
322           try {
323             ParametersChecker.checkSanityString(value.getString());
324           } catch (final InvalidArgumentException e) {
325             logger.error("Bad Push Monitor ApiKey: {}", e.getMessage());
326             return false;
327           }
328           apikey = value.getString();
329         }
330         if (index == null) {
331           // API REST Specific continue
332           String basicAuthent = null;
333           value = hashConfig.get(XML_PUSH_MONITOR_BASIC_AUTHENT);
334           if (value != null && !value.isEmpty()) {
335             try {
336               ParametersChecker.checkSanityString(value.getString());
337             } catch (final InvalidArgumentException e) {
338               logger.error("Bad Push Monitor Basic Authent: {}",
339                            e.getMessage());
340               return false;
341             }
342             basicAuthent = value.getString();
343           }
344           // Default value
345           boolean keep =
346               MonitorExporterTransfers.MONITOR_KEEP_CONNECTION_DEFAULT;
347           value = hashConfig.get(XML_PUSH_MONITOR_KEEP_CONNECTION);
348           if (value != null && !value.isEmpty()) {
349             keep = value.getBoolean();
350           }
351           config.setMonitorExporterTransfers(url, basicAuthent, token, apikey,
352                                              endpoint, delay, keep,
353                                              intervalIncluded, longAsString);
354         } else {
355           // Elasticsearch Specific continue
356           String prefix = null;
357           value = hashConfig.get(XML_PUSH_MONITOR_ES_PREFIX);
358           if (value != null && !value.isEmpty()) {
359             try {
360               ParametersChecker.checkSanityString(value.getString());
361             } catch (final InvalidArgumentException e) {
362               logger.error("Bad Push Monitor Prefix: {}", e.getMessage());
363               return false;
364             }
365             prefix = value.getString();
366           }
367           String username = null;
368           value = hashConfig.get(XML_PUSH_MONITOR_ES_USERNAME);
369           if (value != null && !value.isEmpty()) {
370             try {
371               ParametersChecker.checkSanityString(value.getString());
372             } catch (final InvalidArgumentException e) {
373               logger.error("Bad Push Monitor Username: {}", e.getMessage());
374               return false;
375             }
376             username = value.getString();
377           }
378           String pwd = null;
379           value = hashConfig.get(XML_PUSH_MONITOR_ES_PWD);
380           if (value != null && !value.isEmpty()) {
381             try {
382               ParametersChecker.checkSanityString(value.getString());
383             } catch (final InvalidArgumentException e) {
384               logger.error("Bad Push Monitor Password: {}", e.getMessage());
385               return false;
386             }
387             pwd = value.getString();
388           }
389           if ((username != null && pwd == null) ||
390               (pwd != null && username == null)) {
391             logger.error("Username and Password must be both specified");
392             return false;
393           }
394           boolean compression = true;
395           value = hashConfig.get(XML_PUSH_MONITOR_ES_COMPRESSION);
396           if (value != null && !value.isEmpty()) {
397             try {
398               ParametersChecker.checkSanityString(value.getString());
399             } catch (final InvalidArgumentException e) {
400               logger.error("Bad Push Monitor Compression: {}", e.getMessage());
401               return false;
402             }
403             compression = value.getBoolean();
404           }
405           if (config.setMonitorExporterTransfers(url, username, pwd, token,
406                                                  apikey, prefix, index,
407                                                  intervalIncluded, longAsString,
408                                                  compression, delay)) {
409             logger.error("Elasticsearch Factory not available");
410             return false;
411           }
412         }
413       }
414       return true;
415     } finally {
416       hashConfig.clear();
417     }
418   }
419 
420   /**
421    * @param config
422    *
423    * @return True if the server parameters are correctly loaded
424    */
425   private static boolean loadServerParam(final Configuration config) {
426     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_SERVER));
427     try {
428       if (!loadServerConfig(config, hashConfig)) {
429         return false;
430       }
431       XmlValue value;
432       value = hashConfig.get(XML_USELOCALEXEC);
433       if (value != null && !value.isEmpty()) {
434         config.setUseLocalExec(value.getBoolean());
435         if (config.isUseLocalExec()) {
436           value = hashConfig.get(XML_LEXECADDR);
437           final String saddr;
438           final InetAddress addr;
439           if (value != null && !value.isEmpty()) {
440             saddr = value.getString();
441             try {
442               addr = InetAddress.getByName(saddr);
443             } catch (final UnknownHostException e) {
444               logger.error(Messages.getString(
445                   FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
446                            "LocalExec Address"); //$NON-NLS-1$
447               return false;
448             }
449           } else {
450             logger.warn(
451                 Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
452                 "LocalExec Address"); //$NON-NLS-1$
453             try {
454               addr = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
455             } catch (final UnknownHostException e) {
456               logger.error(Messages.getString(
457                   FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
458                            "LocalExec Address"); //$NON-NLS-1$
459               return false;
460             }
461           }
462           value = hashConfig.get(XML_LEXECPORT);
463           final int port;
464           if (value != null && !value.isEmpty()) {
465             port = value.getInteger();
466           } else {
467             port = 9999;
468           }
469           LocalExecClient.address = new InetSocketAddress(addr, port);
470         }
471       }
472       value = hashConfig.get(XML_CHECK_ADDRESS);
473       if (value != null && !value.isEmpty()) {
474         config.setCheckRemoteAddress(value.getBoolean());
475       }
476       value = hashConfig.get(XML_CHECK_CLIENTADDRESS);
477       if (value != null && !value.isEmpty()) {
478         config.setCheckClientAddress(value.getBoolean());
479       }
480       value = hashConfig.get(XML_MULTIPLE_MONITORS);
481       if (value != null && !value.isEmpty()) {
482         config.setMultipleMonitors(value.getInteger());
483         if (config.getMultipleMonitors() > 1) {
484           logger.warn(Messages.getString("FileBasedConfiguration.MMOn")
485                       //$NON-NLS-1$
486                       + config.getMultipleMonitors() + Messages.getString(
487               "FileBasedConfiguration.MMOn2")); //$NON-NLS-1$
488         } else {
489           config.setMultipleMonitors(1);
490           if (config.isWarnOnStartup()) {
491             logger.warn(Messages.getString(
492                 "FileBasedConfiguration.MMOff")); //$NON-NLS-1$
493           } else {
494             logger.info(Messages.getString(
495                 "FileBasedConfiguration.MMOff")); //$NON-NLS-1$
496           }
497         }
498       } else {
499         config.setMultipleMonitors(1);
500         if (config.isWarnOnStartup()) {
501           logger.warn(
502               Messages.getString("FileBasedConfiguration.MMOff")); //$NON-NLS-1$
503         } else {
504           logger.info(
505               Messages.getString("FileBasedConfiguration.MMOff")); //$NON-NLS-1$
506         }
507       }
508       value = hashConfig.get(XML_BUSINESS_FACTORY);
509       if (value != null && !value.isEmpty()) {
510         try {
511           ParametersChecker.checkSanityString(value.getString());
512         } catch (final InvalidArgumentException e) {
513           logger.error("Bad Business Factory class: {}", e.getMessage());
514           return false;
515         }
516         try {
517           config.setR66BusinessFactory(
518               (R66BusinessFactoryInterface) WaarpSystemUtil.newInstance(
519                   value.getString()));//NOSONAR
520         } catch (final Exception e) {
521           logger.error("Bad Business Factory class: {}", e.getMessage());
522           return false;
523         }
524       }
525       return true;
526     } finally {
527       hashConfig.clear();
528       hashConfig = null;
529     }
530   }
531 
532   public static boolean loadServerConfig(final Configuration config,
533                                          final XmlHash hashConfig) {
534     XmlValue value = hashConfig.get(XML_USESSL);
535     if (value != null && !value.isEmpty()) {
536       config.setUseSSL(value.getBoolean());
537     }
538     value = hashConfig.get(XML_USENOSSL);
539     if (value != null && !value.isEmpty()) {
540       config.setUseNOSSL(value.getBoolean());
541     }
542     value = hashConfig.get(XML_USEHTTPCOMP);
543     if (value != null && !value.isEmpty()) {
544       config.setUseHttpCompression(value.getBoolean());
545     }
546     value = hashConfig.get(XML_SERVER_ADMIN);
547     if (value != null && !value.isEmpty()) {
548       config.setAdminName(value.getString());
549     } else {
550       logger.error(
551           Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
552           "Administrator name"); //$NON-NLS-1$
553       return false;
554     }
555     if (config.getCryptoKey() == null) {
556       XmlHash hashConfig2 = new XmlHash(hashRootConfig.get(XML_IDENTITY));
557       try {
558         if (!setCryptoKey(config, hashConfig2)) {
559           logger.error(
560               Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
561               "Crypto Key"); //$NON-NLS-1$
562           return false;
563         }
564       } finally {
565         hashConfig2.clear();
566         hashConfig2 = null;
567       }
568     }
569     final byte[] decodedByteKeys;
570     value = hashConfig.get(XML_SERVER_PASSWD_FILE);
571     if (value == null || value.isEmpty()) {
572       final String passwd;
573       value = hashConfig.get(XML_SERVER_PASSWD);
574       if (value != null && !value.isEmpty()) {
575         passwd = value.getString();
576       } else {
577         logger.error(
578             Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
579             "Password"); //$NON-NLS-1$
580         return false;
581       }
582       try {
583         decodedByteKeys = config.getCryptoKey().decryptHexInBytes(passwd);
584       } catch (final Exception e) {
585         logger.error(
586             "Unable to Decrypt Server Password in Config file from: " + passwd +
587             ": {}", e.getMessage());
588         return false;
589       }
590     } else {
591       final String skey = value.getString();
592       // load key from file
593       config.setServerKeyFile(skey);
594       final File key = new File(skey);
595       if (!key.canRead()) {
596         logger.error("Unable to read Password in Config file from " + skey);
597         return false;
598       }
599       try {
600         decodedByteKeys = config.getCryptoKey().decryptHexFile(key);
601       } catch (final Exception e2) {
602         logger.error(
603             "Unable to Decrypt Server Password in Config file from: " + skey +
604             ": {}", e2.getMessage());
605         return false;
606       }
607     }
608     config.setSERVERKEY(decodedByteKeys);
609     value = hashConfig.get(XML_HTTPADMINPATH);
610     if (value == null || value.isEmpty()) {
611       logger.error(
612           Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
613           "Http Admin Base"); //$NON-NLS-1$
614       return false;
615     }
616     final String path = value.getString();
617     if (ParametersChecker.isEmpty(path)) {
618       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
619                    "Http Admin Base"); //$NON-NLS-1$
620       return false;
621     }
622     final File file = new File(path);
623     if (!file.isDirectory()) {
624       logger.error(Messages.getString("FileBasedConfiguration.NotDirectory") +
625                    "Http Admin Base {}", file.getAbsolutePath()); //$NON-NLS-1$
626       return false;
627     }
628     try {
629       config.setHttpBasePath(
630           AbstractDir.normalizePath(file.getCanonicalPath()) +
631           DirInterface.SEPARATOR);
632     } catch (final IOException e1) {
633       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
634                    "Http Admin Path"); //$NON-NLS-1$
635       return false;
636     }
637     value = hashConfig.get(XML_HTTPADMINMODEL);
638     // 0 = standard, 1 = responsive (preferred default)
639     int model =
640         !new File(file, HttpResponsiveSslHandler.LISTING_PAGE).isFile()? 0 : 1;
641     if (value != null && !value.isEmpty()) {
642       model = value.getInteger();
643     }
644     config.setHttpModel(model);
645 
646     // Key for HTTPS
647     value = hashConfig.get(XML_PATH_ADMIN_KEYPATH);
648     if (value != null && !value.isEmpty()) {
649       final String keypath = value.getString();
650       if (ParametersChecker.isEmpty(keypath)) {
651         logger.error("Bad Key Path");
652         return false;
653       }
654       value = hashConfig.get(XML_PATH_ADMIN_KEYSTOREPASS);
655       if (value == null || value.isEmpty()) {
656         logger.error("Unable to find: " + "KeyStore Passwd");
657         return false;
658       }
659       final String keystorepass = value.getString();
660       if (ParametersChecker.isEmpty(keystorepass)) {
661         logger.error("Bad KeyStore Passwd");
662         return false;
663       }
664       value = hashConfig.get(XML_PATH_ADMIN_KEYPASS);
665       if (value == null || value.isEmpty()) {
666         logger.error("Unable to find :" + "Key Passwd");
667         return false;
668       }
669       final String keypass = value.getString();
670       if (ParametersChecker.isEmpty(keypass)) {
671         logger.error("Bad Key Passwd");
672         return false;
673       }
674       try {
675         Configuration.setWaarpSecureKeyStore(
676             new WaarpSecureKeyStore(keypath, keystorepass, keypass));
677       } catch (final CryptoException e) {
678         logger.error("Bad SecureKeyStore construction for AdminSsl");
679         return false;
680       }
681       // No client authentication
682       Configuration.getWaarpSecureKeyStore().initEmptyTrustStore();
683       Configuration.setWaarpSslContextFactory(
684           new WaarpSslContextFactory(Configuration.getWaarpSecureKeyStore(),
685                                      true));
686     }
687     value = hashConfig.get(XML_MONITOR_PASTLIMIT);
688     if (value != null && !value.isEmpty()) {
689       config.setPastLimit((value.getLong() / 10) * 10);
690     }
691     value = hashConfig.get(XML_MONITOR_MINIMALDELAY);
692     if (value != null && !value.isEmpty()) {
693       config.setMinimalDelay((value.getLong() / 10) * 10);
694     }
695     value = hashConfig.get(XML_MONITOR_SNMP_CONFIG);
696     if (value != null && !value.isEmpty()) {
697       config.setSnmpConfig(value.getString());
698       final File snmpfile = new File(config.getSnmpConfig());
699       if (snmpfile.canRead()) {
700         if (!SnmpConfiguration.setConfigurationFromXml(snmpfile)) {
701           config.setSnmpConfig(null);
702         }
703       } else {
704         config.setSnmpConfig(null);
705       }
706     }
707     return true;
708   }
709 
710   /**
711    * @param config
712    *
713    * @return True if the client parameters are correctly loaded
714    */
715   private static boolean loadClientParam(final Configuration config) {
716     final XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_CLIENT));
717     try {
718       XmlValue value = hashConfig.get(XML_SAVE_TASKRUNNERNODB);
719       if (!isDbUsed()) {
720         if (value != null && !value.isEmpty() && value.getBoolean()) {
721           initNoDb(config);
722         }
723       }
724       value = hashConfig.get(XML_BUSINESS_FACTORY);
725       if (value != null && !value.isEmpty()) {
726         try {
727           ParametersChecker.checkSanityString(value.getString());
728         } catch (final InvalidArgumentException e) {
729           logger.error("Bad Business Factory class: {}", e.getMessage());
730           return false;
731         }
732         try {
733           config.setR66BusinessFactory(
734               (R66BusinessFactoryInterface) WaarpSystemUtil.newInstance(
735                   value.getString()));//NOSONAR
736         } catch (final Exception e) {
737           logger.error("Bad Business Factory class: {}", e.getMessage());
738           return false;
739         }
740       }
741       return true;
742     } finally {
743       hashConfig.clear();
744     }
745   }
746 
747   /**
748    * @param config
749    *
750    * @return True if the directory parameters are correctly loaded
751    */
752   private static boolean loadDirectory(final Configuration config) {
753     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_DIRECTORY));
754     try {
755       if (loadMinimalDirectory(config, hashConfig)) {
756         return false;
757       }
758       try {
759         config.setInPath(
760             AbstractDir.normalizePath(getSubPath(config, XML_INPATH)));
761       } catch (final OpenR66ProtocolSystemException e2) {
762         logger.error(
763             Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
764             "In"); //$NON-NLS-1$
765         return false;
766       } catch (final BadConfigurationException e2) {
767         logger.error(
768             Messages.getString(FILE_BASED_CONFIGURATION_INVALID_CONFIG) +
769             "In ({})", e2.getMessage()); //$NON-NLS-1$
770         return false;
771       }
772       try {
773         config.setOutPath(
774             AbstractDir.normalizePath(getSubPath(config, XML_OUTPATH)));
775       } catch (final OpenR66ProtocolSystemException e2) {
776         logger.error(
777             Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
778             "Out"); //$NON-NLS-1$
779         return false;
780       } catch (final BadConfigurationException e2) {
781         logger.error(
782             Messages.getString(FILE_BASED_CONFIGURATION_INVALID_CONFIG) +
783             "Out ({})", e2.getMessage()); //$NON-NLS-1$
784         return false;
785       }
786       try {
787         config.setWorkingPath(
788             AbstractDir.normalizePath(getSubPath(config, XML_WORKINGPATH)));
789       } catch (final OpenR66ProtocolSystemException e2) {
790         logger.error(
791             Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
792             "Working"); //$NON-NLS-1$
793         return false;
794       } catch (final BadConfigurationException e2) {
795         logger.error(
796             Messages.getString(FILE_BASED_CONFIGURATION_INVALID_CONFIG) +
797             "Working ({})", e2.getMessage()); //$NON-NLS-1$
798         return false;
799       }
800       loadExtendTaskFactory(config);
801       return true;
802     } finally {
803       hashConfig.clear();
804       hashConfig = null;
805     }
806   }
807 
808   private static boolean loadExtendTaskFactory(final Configuration config) {
809     final XmlHash hashConfig =
810         new XmlHash(hashRootConfig.get(XML_EXTEND_TASK_FACTORY));
811     try {
812       final XmlValue xfactories = hashConfig.get(XML_EXTENDED_TASK_FACTORIES);
813       if (xfactories != null && !xfactories.isEmpty()) {
814         final String sextendedFactoryClassList = xfactories.getString();
815         // Initiate Extended Task Factory
816         final String[] extendedFactories = sextendedFactoryClassList.split(",");
817         for (final String extendedFactory : extendedFactories) {
818           try {
819             WaarpSystemUtil.newInstance(extendedFactory);
820             logger.warn("Added ExtendedTaskFactory: {}", extendedFactory);
821           } catch (final Exception e) {
822             logger.error(Messages.getString(
823                 "ServerInitDatabase.ExtendedTaskFactory.error") +
824                          extendedFactory + " = " + e.getMessage());
825           }
826         }
827       }
828       return true;
829     } finally {
830       hashConfig.clear();
831     }
832   }
833 
834   public static boolean loadMinimalDirectory(final Configuration config,
835                                              final XmlHash hashConfig) {
836     final XmlValue value = hashConfig.get(XML_SERVER_HOME);
837     if (value == null || value.isEmpty()) {
838       logger.error(
839           Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
840           "Home"); //$NON-NLS-1$
841       return true;
842     }
843     final String path = value.getString();
844     final File file = new File(path);
845     if (!file.isDirectory()) {
846       logger.error(Messages.getString("FileBasedConfiguration.NotDirectory") +
847                    "Home"); //$NON-NLS-1$
848       return true;
849     }
850     try {
851       config.setBaseDirectory(
852           AbstractDir.normalizePath(file.getCanonicalPath()));
853     } catch (final IOException e1) {
854       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
855                    "Home"); //$NON-NLS-1$
856       return true;
857     }
858     try {
859       config.setConfigPath(
860           AbstractDir.normalizePath(getSubPath(config, XML_CONFIGPATH)));
861     } catch (final OpenR66ProtocolSystemException e2) {
862       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
863                    "Config"); //$NON-NLS-1$
864       return true;
865     } catch (final BadConfigurationException e2) {
866       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_INVALID_CONFIG) +
867                    "Config ({})", e2.getMessage()); //$NON-NLS-1$
868       return true;
869     }
870     try {
871       config.setArchivePath(
872           AbstractDir.normalizePath(getSubPath(config, XML_ARCHIVEPATH)));
873     } catch (final OpenR66ProtocolSystemException e2) {
874       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_NO_SET_CONFIG) +
875                    "Archive"); //$NON-NLS-1$
876       return true;
877     } catch (final BadConfigurationException e2) {
878       logger.error(Messages.getString(FILE_BASED_CONFIGURATION_INVALID_CONFIG) +
879                    "Archive ({})", e2.getMessage()); //$NON-NLS-1$
880       return true;
881     }
882     return false;
883   }
884 
885   private static boolean alreadySetLimit;
886 
887   /**
888    * Mainly for Junit
889    */
890   public static void resetAlreadySetLimit() {
891     alreadySetLimit = false;
892     // Clear Partner
893     Configuration.configuration.getVersions().clear();
894   }
895 
896   /**
897    * @param config
898    * @param updateLimit
899    *
900    * @return True if the limit configuration is correctly loaded
901    */
902   private static boolean loadLimit(final Configuration config,
903                                    final boolean updateLimit) {
904     if (alreadySetLimit) {
905       return true;
906     }
907     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_LIMIT));
908     try {
909       loadCommonLimit(config, hashConfig, updateLimit);
910       XmlValue value;
911       value = hashConfig.get(XML_LIMITRUNNING);
912       if (value != null && !value.isEmpty()) {
913         config.setRunnerThread(value.getInteger());
914       }
915       logger.info("Limit of Runner: {}", config.getRunnerThread());
916       value = hashConfig.get(XML_DELAYCOMMANDER);
917       if (value != null && !value.isEmpty()) {
918         config.setDelayCommander((value.getLong() / 10) * 10);
919         if (config.getDelayCommander() <= 100) {
920           config.setDelayCommander(100);
921         }
922         logger.info("Delay Commander: {}", config.getDelayCommander());
923       }
924       value = hashConfig.get(XML_DIGEST);
925       if (value != null && !value.isEmpty()) {
926         try {
927           int val = value.getInteger();
928           if (val < 0 || val >= DigestAlgo.values().length) {
929             val = 0;
930           }
931           config.setDigest(DigestAlgo.values()[val]);
932         } catch (final IllegalArgumentException e) {
933           // might be String
934           final String val = value.getString();
935           config.setDigest(PartnerConfiguration.getDigestAlgo(val));
936         }
937       }
938       logger.info("DigestAlgo used: {}", config.getDigest());
939       value = hashConfig.get(XML_GAPRESTART);
940       if (value != null && !value.isEmpty()) {
941         Configuration.setRankRestart(value.getInteger());
942         if (Configuration.getRankRestart() <= 0) {
943           Configuration.setRankRestart(1);
944         }
945       }
946       value = hashConfig.get(XML_BLOCKSIZE);
947       if (value != null && !value.isEmpty()) {
948         config.setBlockSize(value.getInteger());
949       }
950       value = hashConfig.get(XML_USETHRIFT);
951       if (value != null && !value.isEmpty()) {
952         config.setThriftport(value.getInteger());
953       }
954       value = hashConfig.get(XML_CHECKVERSION);
955       if (value != null && !value.isEmpty()) {
956         config.setExtendedProtocol(value.getBoolean());
957         logger.info("ExtendedProtocol= " + config.isExtendedProtocol());
958       }
959       value = hashConfig.get(XML_GLOBALDIGEST);
960       if (value != null && !value.isEmpty()) {
961         config.setGlobalDigest(value.getBoolean());
962       }
963       value = hashConfig.get(XML_LOCALDIGEST);
964       if (value != null && !value.isEmpty()) {
965         config.setLocalDigest(value.getBoolean());
966       }
967       value = hashConfig.get(XML_COMPRESSION);
968       logger.info("Compression {} {}", value != null && !value.isEmpty(),
969                   value != null && !value.isEmpty()? value.getBoolean() :
970                       false);
971       if (value != null && !value.isEmpty()) {
972         config.setCompressionAvailable(value.getBoolean());
973       }
974       alreadySetLimit = true;
975       return true;
976     } finally {
977       hashConfig.clear();
978       hashConfig = null;
979     }
980   }
981 
982   public static void loadCommonLimit(final Configuration config,
983                                      final XmlHash hashConfig,
984                                      final boolean updateLimit) {
985     XmlValue value = hashConfig.get(XML_LIMITGLOBAL);
986     if (value != null && !value.isEmpty()) {
987       config.setServerGlobalReadLimit(value.getLong());
988       if (config.getServerGlobalReadLimit() <= 0) {
989         config.setServerGlobalReadLimit(0);
990       }
991       config.setServerGlobalWriteLimit(config.getServerGlobalReadLimit());
992       logger.info("Global Limit: {}", config.getServerGlobalReadLimit());
993     }
994     value = hashConfig.get(XML_LIMITSESSION);
995     if (value != null && !value.isEmpty()) {
996       config.setServerChannelReadLimit(value.getLong());
997       if (config.getServerChannelReadLimit() <= 0) {
998         config.setServerChannelReadLimit(0);
999       }
1000       config.setServerChannelWriteLimit(config.getServerChannelReadLimit());
1001       logger.info("SessionInterface Limit: {}",
1002                   config.getServerChannelReadLimit());
1003     }
1004     config.setDelayLimit(AbstractTrafficShapingHandler.DEFAULT_CHECK_INTERVAL);
1005     value = hashConfig.get(XML_LIMITDELAY);
1006     if (value != null && !value.isEmpty()) {
1007       config.setDelayLimit((value.getLong() / 10) * 10);
1008       if (config.getDelayLimit() <= 0) {
1009         config.setDelayLimit(0);
1010       }
1011       logger.info("Delay Limit: {}", config.getDelayLimit());
1012     }
1013     value = hashConfig.get(XML_DELAYRETRY);
1014     if (value != null && !value.isEmpty()) {
1015       config.setDelayRetry((value.getLong() / 10) * 10);
1016       if (config.getDelayRetry() <= 1000) {
1017         config.setDelayRetry(1000);
1018       }
1019       logger.info("Delay Retry: {}", config.getDelayRetry());
1020     }
1021     if (updateLimit) {
1022       value = hashConfig.get(XML_SERVER_HOSTID);
1023       if (value != null && !value.isEmpty()) {
1024         config.setHostId(value.getString());
1025         try {
1026           final DbConfiguration configuration =
1027               new DbConfiguration(config.getHostId(),
1028                                   config.getServerGlobalReadLimit(),
1029                                   config.getServerGlobalWriteLimit(),
1030                                   config.getServerChannelReadLimit(),
1031                                   config.getServerChannelWriteLimit(),
1032                                   config.getDelayLimit());
1033           configuration.changeUpdatedInfo(UpdatedInfo.TOSUBMIT);
1034           if (configuration.exist()) {
1035             configuration.update();
1036           } else {
1037             configuration.insert();
1038           }
1039         } catch (final WaarpDatabaseException ignored) {
1040           // nothing
1041         }
1042       }
1043     }
1044     boolean useCpuLimit = false;
1045     boolean useCpuLimitJDK = false;
1046     double cpulimit = 1.0;
1047     value = hashConfig.get(XML_CSTRT_USECPULIMIT);
1048     if (value != null && !value.isEmpty()) {
1049       useCpuLimit = value.getBoolean();
1050       value = hashConfig.get(XML_CSTRT_USECPUJDKLIMIT);
1051       if (value != null && !value.isEmpty()) {
1052         useCpuLimitJDK = value.getBoolean();
1053       }
1054       value = hashConfig.get(XML_CSTRT_CPULIMIT);
1055       if (value != null && !value.isEmpty()) {
1056         cpulimit = value.getDouble();
1057         if (cpulimit > 0.99) {
1058           cpulimit = 1.0;
1059         }
1060       }
1061     }
1062     int connlimit = 0;
1063     value = hashConfig.get(XML_CSTRT_CONNLIMIT);
1064     if (value != null && !value.isEmpty()) {
1065       connlimit = value.getInteger();
1066       if (connlimit < 100) {
1067         connlimit = 0;
1068       }
1069     }
1070     double lowcpuLimit = 0.0;
1071     double highcpuLimit = 0.0;
1072     double percentageDecrease = 0;
1073     long delay = 1000000;
1074     long limitLowBandwidth = WaarpConstraintLimitHandler.LOWBANDWIDTH_DEFAULT;
1075     value = hashConfig.get(XML_CSTRT_LOWCPULIMIT);
1076     if (value != null && !value.isEmpty()) {
1077       lowcpuLimit = value.getDouble();
1078     }
1079     value = hashConfig.get(XML_CSTRT_HIGHCPULIMIT);
1080     if (value != null && !value.isEmpty()) {
1081       highcpuLimit = value.getDouble();
1082       if (highcpuLimit < 0.1) {
1083         highcpuLimit = 0.0;
1084       }
1085     }
1086     value = hashConfig.get(XML_CSTRT_PERCENTDECREASE);
1087     if (value != null && !value.isEmpty()) {
1088       percentageDecrease = value.getDouble();
1089     }
1090     value = hashConfig.get(XML_CSTRT_DELAYTHROTTLE);
1091     if (value != null && !value.isEmpty()) {
1092       delay = (value.getLong() / 10) * 10;
1093       if (delay < 100) {
1094         delay = 100;
1095       }
1096     }
1097     value = hashConfig.get(XML_CSTRT_LIMITLOWBANDWIDTH);
1098     if (value != null && !value.isEmpty()) {
1099       limitLowBandwidth = value.getLong();
1100     }
1101     if (config.getConstraintLimitHandler() != null) {
1102       config.getConstraintLimitHandler().release();
1103     }
1104     if (useCpuLimit || highcpuLimit > 0) {
1105       if (highcpuLimit > 0) {
1106         logger.debug("full setup of ContraintLimitHandler");
1107         config.setConstraintLimitHandler(
1108             new R66ConstraintLimitHandler(useCpuLimit, useCpuLimitJDK, cpulimit,
1109                                           connlimit, lowcpuLimit, highcpuLimit,
1110                                           percentageDecrease, null, delay,
1111                                           limitLowBandwidth));
1112       } else {
1113         logger.debug("partial setup of ContraintLimitHandler");
1114         config.setConstraintLimitHandler(
1115             new R66ConstraintLimitHandler(useCpuLimit, useCpuLimitJDK, cpulimit,
1116                                           connlimit));
1117       }
1118     } else {
1119       logger.debug("No setup of ContraintLimitHandler");
1120       config.setConstraintLimitHandler(
1121           new R66ConstraintLimitHandler(false, false, 1.0, connlimit));
1122     }
1123     value = hashConfig.get(XML_SERVER_THREAD);
1124     if (value != null && !value.isEmpty()) {
1125       config.setServerThread(value.getInteger());
1126     }
1127     value = hashConfig.get(XML_CLIENT_THREAD);
1128     if (value != null && !value.isEmpty()) {
1129       config.setClientThread(value.getInteger());
1130     }
1131     value = hashConfig.get(XML_MEMORY_LIMIT);
1132     if (value != null && !value.isEmpty()) {
1133       long lvalue = value.getLong();
1134       if (lvalue > Integer.MAX_VALUE) {
1135         lvalue = Integer.MAX_VALUE;
1136       }
1137       config.setMaxGlobalMemory((int) lvalue);
1138     }
1139     Configuration.getFileParameter().deleteOnAbort = false;
1140     value = hashConfig.get(XML_USENIO);
1141     if (value != null && !value.isEmpty()) {
1142       FilesystemBasedFileParameterImpl.useNio = value.getBoolean();
1143     }
1144     value = hashConfig.get(XML_TIMEOUTCON);
1145     if (value != null && !value.isEmpty()) {
1146       config.setTimeoutCon((value.getLong() / 10) * 10);
1147       config.getShutdownConfiguration().timeout = config.getTimeoutCon();
1148     }
1149   }
1150 
1151   /**
1152    * @param config
1153    * @param hashRootConfig
1154    *
1155    * @return True if the SSL configuration is correctly loaded
1156    */
1157   public static boolean loadSsl(final Configuration config,
1158                                 final XmlRootHash hashRootConfig) {
1159     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_SSL));
1160     try {
1161       // StoreKey for Server
1162       XmlValue value = hashConfig.get(XML_PATH_KEYPATH);
1163       if (value == null || value.isEmpty()) {
1164         logger.info("Unable to find Key Path");
1165         try {
1166           NetworkSslServerInitializer.setWaarpSecureKeyStore(
1167               new WaarpSecureKeyStore("secret", "secret"));//NOSONAR
1168         } catch (final CryptoException e) {
1169           logger.error("Bad SecureKeyStore construction");
1170           return false;
1171         }
1172       } else {
1173         final String keypath = value.getString();
1174         if (ParametersChecker.isEmpty(keypath)) {
1175           logger.error("Bad Key Path");
1176           return false;
1177         }
1178         value = hashConfig.get(XML_PATH_KEYSTOREPASS);
1179         if (value == null || value.isEmpty()) {
1180           logger.error("Unable to find KeyStore Passwd");
1181           return false;
1182         }
1183         final String keystorepass = value.getString();
1184         if (ParametersChecker.isEmpty(keystorepass)) {
1185           logger.error("Bad KeyStore Passwd");
1186           return false;
1187         }
1188         value = hashConfig.get(XML_PATH_KEYPASS);
1189         if (value == null || value.isEmpty()) {
1190           logger.error("Unable to find Key Passwd");
1191           return false;
1192         }
1193         final String keypass = value.getString();
1194         if (ParametersChecker.isEmpty(keypass)) {
1195           logger.error("Bad Key Passwd");
1196           return false;
1197         }
1198         try {
1199           NetworkSslServerInitializer.setWaarpSecureKeyStore(
1200               new WaarpSecureKeyStore(keypath, keystorepass, keypass));
1201         } catch (final CryptoException e) {
1202           logger.error("Bad SecureKeyStore construction");
1203           return false;
1204         }
1205       }
1206       // TrustedKey for OpenR66 server
1207       value = hashConfig.get(XML_PATH_TRUSTKEYPATH);
1208       if (value == null || value.isEmpty()) {
1209         logger.info("Unable to find TRUST Key Path");
1210         NetworkSslServerInitializer.getWaarpSecureKeyStore()
1211                                    .initEmptyTrustStore();
1212       } else {
1213         final String keypath = value.getString();
1214         if (ParametersChecker.isEmpty(keypath)) {
1215           logger.error("Bad TRUST Key Path");
1216           return false;
1217         }
1218         value = hashConfig.get(XML_PATH_TRUSTKEYSTOREPASS);
1219         if (value == null || value.isEmpty()) {
1220           logger.error("Unable to find TRUST KeyStore Passwd");
1221           return false;
1222         }
1223         final String keystorepass = value.getString();
1224         if (ParametersChecker.isEmpty(keystorepass)) {
1225           logger.error("Bad TRUST KeyStore Passwd");
1226           return false;
1227         }
1228         boolean useClientAuthent = false;
1229         value = hashConfig.get(XML_USECLIENT_AUTHENT);
1230         if (value != null && !value.isEmpty()) {
1231           useClientAuthent = value.getBoolean();
1232         }
1233         try {
1234           NetworkSslServerInitializer.getWaarpSecureKeyStore()
1235                                      .initTrustStore(keypath, keystorepass,
1236                                                      useClientAuthent);
1237         } catch (final CryptoException e) {
1238           logger.error("Bad TrustKeyStore construction");
1239           return false;
1240         }
1241       }
1242       NetworkSslServerInitializer.setWaarpSslContextFactory(
1243           new WaarpSslContextFactory(
1244               NetworkSslServerInitializer.getWaarpSecureKeyStore()));
1245       return true;
1246     } finally {
1247       hashConfig.clear();
1248       hashConfig = null;
1249     }
1250   }
1251 
1252   /**
1253    * @param config
1254    *
1255    * @return True if the network configuration is correctly loaded
1256    */
1257   private static boolean loadNetworkServer(final Configuration config) {
1258     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_NETWORK));
1259     try {
1260       XmlValue value = hashConfig.get(XML_SERVER_PORT);
1261       int port = 6666;
1262       if (value != null && !value.isEmpty()) {
1263         port = value.getInteger();
1264       }
1265       config.setServerPort(port);
1266       value = hashConfig.get(XML_SERVER_ADDRESSES);
1267       String[] ips = null;
1268       if (value != null && !value.isEmpty()) {
1269         final String temp = value.getString();
1270         ips = temp.split(",");
1271       }
1272       config.setServerAddresses(ips);
1273       value = hashConfig.get(XML_SERVER_SSLPORT);
1274       int sslport = 6667;
1275       if (value != null && !value.isEmpty()) {
1276         sslport = value.getInteger();
1277       }
1278       config.setServerSslPort(sslport);
1279       value = hashConfig.get(XML_SERVER_SSL_ADDRESSES);
1280       String[] ipsTls = null;
1281       if (value != null && !value.isEmpty()) {
1282         final String temp = value.getString();
1283         ipsTls = temp.split(",");
1284       }
1285       config.setServerSslAddresses(ipsTls);
1286       value = hashConfig.get(XML_SERVER_HTTPPORT);
1287       int httpport = 8066;
1288       if (value != null && !value.isEmpty()) {
1289         httpport = value.getInteger();
1290       }
1291       config.setServerHttpport(httpport);
1292       value = hashConfig.get(XML_SERVER_HTTP_ADDRESSES);
1293       String[] ipsHttp = null;
1294       if (value != null && !value.isEmpty()) {
1295         final String temp = value.getString();
1296         ipsHttp = temp.split(",");
1297       }
1298       config.setServerHttpAddresses(ipsHttp);
1299       value = hashConfig.get(XML_SERVER_HTTPSPORT);
1300       int httpsport = 8067;
1301       if (value != null && !value.isEmpty()) {
1302         httpsport = value.getInteger();
1303       }
1304       config.setServerHttpsPort(httpsport);
1305       value = hashConfig.get(XML_SERVER_HTTPS_ADDRESSES);
1306       String[] ipsHttpTls = null;
1307       if (value != null && !value.isEmpty()) {
1308         final String temp = value.getString();
1309         ipsHttpTls = temp.split(",");
1310       }
1311       config.setServerHttpsAddresses(ipsHttpTls);
1312       return true;
1313     } finally {
1314       hashConfig.clear();
1315       hashConfig = null;
1316     }
1317   }
1318 
1319   /**
1320    * @param configuration
1321    *
1322    * @return True if the REST configuration is correctly loaded
1323    */
1324   @SuppressWarnings("unchecked")
1325   private static boolean loadRest(final Configuration configuration) {
1326     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_REST));
1327     try {
1328       final XmlValue valueRest = hashConfig.get(XML_REST);
1329       if (valueRest != null && valueRest.getList() != null) {
1330         for (final XmlValue[] xml : (Iterable<XmlValue[]>) valueRest.getList()) {
1331           final RestConfiguration config = new RestConfiguration();
1332           final XmlHash subHash = new XmlHash(xml);
1333           XmlValue value = subHash.get(XML_SERVER_REST_PORT);
1334           int restPort = -1;
1335           if (value != null && !value.isEmpty()) {
1336             restPort = value.getInteger();
1337           }
1338           config.setRestPort(restPort);
1339           if (config.getRestPort() > 0) {
1340             value = subHash.get(XML_REST_ADDRESS);
1341             String restAddress = null;
1342             if (value != null && !value.isEmpty()) {
1343               restAddress = value.getString();
1344             }
1345             config.setRestAddress(restAddress);
1346             value = subHash.get(XML_REST_SSL);
1347             boolean restSsl = false;
1348             if (value != null && !value.isEmpty()) {
1349               restSsl = value.getBoolean();
1350             }
1351             config.setRestSsl(restSsl);
1352             value = subHash.get(XML_REST_AUTHENTICATED);
1353             boolean restAuthent = false;
1354             if (value != null && !value.isEmpty()) {
1355               restAuthent = value.getBoolean();
1356             }
1357             config.setRestAuthenticated(restAuthent);
1358             value = subHash.get(XML_REST_SIGNATURE);
1359             boolean restSignature = true;
1360             if (value != null && !value.isEmpty()) {
1361               restSignature = value.getBoolean();
1362             }
1363             config.setRestSignature(restSignature);
1364             if (config.isRestSignature() || config.isRestAuthenticated()) {
1365               final XmlValue valueKey = subHash.get(XML_REST_AUTH_KEY);
1366               if (valueKey != null && !valueKey.isEmpty()) {
1367                 String fileKey = valueKey.getString();
1368                 File file = new File(fileKey);
1369                 if (!file.canRead()) {
1370                   file = new File(
1371                       configuration.getConfigPath() + DirInterface.SEPARATOR +
1372                       fileKey);
1373                   if (!file.canRead()) {
1374                     logger.error("Unable to find REST Key in Config file");
1375                     return false;
1376                   }
1377                   fileKey =
1378                       configuration.getConfigPath() + DirInterface.SEPARATOR +
1379                       fileKey;
1380                 }
1381                 try {
1382                   config.initializeKey(file);
1383                 } catch (final CryptoException e) {
1384                   logger.error(
1385                       "Unable to load REST Key from Config file: " + fileKey +
1386                       ": {}", e.getMessage());
1387                   return false;
1388                 } catch (final IOException e) {
1389                   logger.error(
1390                       "Unable to load REST Key from Config file: " + fileKey +
1391                       ": {}", e.getMessage());
1392                   return false;
1393                 }
1394               }
1395             }
1396             value = subHash.get(XML_REST_TIME_LIMIT);
1397             long restTimeLimit = -1;
1398             if (value != null && !value.isEmpty()) {
1399               restTimeLimit = value.getLong();
1400             }
1401             config.setRestTimeLimit(restTimeLimit);
1402 
1403             final XmlValue valueMethod = subHash.get(XML_REST_METHOD);
1404             if (valueMethod != null && valueMethod.getList() != null) {
1405               boolean found = false;
1406               config.setResthandlersCrud(
1407                   new byte[RESTHANDLERS.values().length]);
1408               for (final XmlValue[] xmlmethod : (Iterable<XmlValue[]>) valueMethod.getList()) {
1409                 final XmlHash subHashMethod = new XmlHash(xmlmethod);
1410                 value = subHashMethod.get(XML_REST_METHOD_NAME);
1411                 final String name;
1412                 if (value != null && !value.isEmpty()) {
1413                   name = value.getString();
1414                 } else {
1415                   logger.warn("Restmethod entry ignore since name is empty");
1416                   continue;
1417                 }
1418                 value = subHashMethod.get(XML_REST_CRUD);
1419                 final String crud;
1420                 if (value != null && !value.isEmpty()) {
1421                   crud = value.getString().toUpperCase();
1422                 } else {
1423                   logger.warn(
1424                       "Restmethod entry ignore since crud field is empty");
1425                   continue;
1426                 }
1427                 found = true;
1428                 byte def = 0x0;
1429                 def |=
1430                     crud.contains("C")? RestConfiguration.CRUD.CREATE.mask : 0;
1431                 def |= crud.contains("R")? RestConfiguration.CRUD.READ.mask : 0;
1432                 def |=
1433                     crud.contains("U")? RestConfiguration.CRUD.UPDATE.mask : 0;
1434                 def |=
1435                     crud.contains("D")? RestConfiguration.CRUD.DELETE.mask : 0;
1436                 if ("all".equalsIgnoreCase(name)) {
1437                   Arrays.fill(config.getResthandlersCrud(), def);
1438                   // No more restmethod since ALL was selected
1439                   break;
1440                 } else {
1441                   final String[] handlers = name.split(REGEX_SEPARATOR);
1442                   for (final String string : handlers) {
1443                     final RESTHANDLERS handler = RESTHANDLERS.valueOf(string);
1444                     config.getResthandlersCrud()[handler.ordinal()] = def;
1445                   }
1446                 }
1447               }
1448               if (!found) {
1449                 // no METHOD !!!
1450                 logger.error(
1451                     "No active METHOD defined for REST in Config file: " +
1452                     config);
1453                 return false;
1454               }
1455             } else {
1456               // no METHOD !!!
1457               logger.error("No METHOD defined for REST in Config file");
1458               return false;
1459             }
1460             Configuration.configuration.getRestConfigurations().add(config);
1461             logger.info("{}", config);
1462           }
1463         }
1464       }
1465       return true;
1466     } finally {
1467       hashConfig.clear();
1468       hashConfig = null;
1469     }
1470   }
1471 
1472   /**
1473    * Set the Crypto Key from the Document
1474    *
1475    * @param config
1476    *
1477    * @return True if OK
1478    */
1479   private static boolean setCryptoKey(final Configuration config,
1480                                       final XmlHash hashConfig) {
1481     final XmlValue value = hashConfig.get(XML_PATH_CRYPTOKEY);
1482     if (value == null || value.isEmpty()) {
1483       logger.error("Unable to find CryptoKey in Config file");
1484       return false;
1485     }
1486     final String filename = value.getString();
1487     config.setCryptoFile(filename);
1488     final File key = new File(filename);
1489     final Des des = new Des();
1490     try {
1491       des.setSecretKey(key);
1492     } catch (final CryptoException e) {
1493       logger.error("Unable to load CryptoKey from Config file {}", filename);
1494       return false;
1495     } catch (final IOException e) {
1496       logger.error("Unable to load CryptoKey from Config file");
1497       return false;
1498     }
1499     config.setCryptoKey(des);
1500     return true;
1501   }
1502 
1503   /**
1504    * Load data from database or from files if not connected
1505    *
1506    * @param config
1507    *
1508    * @return True if OK
1509    */
1510   private static boolean loadFromDatabase(final Configuration config) {
1511     if (!isDbInactive(config)) {
1512       // load from database the limit to apply
1513       try {
1514         final DbConfiguration configuration =
1515             new DbConfiguration(config.getHostId());
1516         configuration.updateConfiguration();
1517       } catch (final WaarpDatabaseException e) {
1518         logger.info(Messages.getString("FileBasedConfiguration.NoBandwidth") +
1519                     e.getMessage()); //$NON-NLS-1$
1520       }
1521     } else {
1522       if (config.getBaseDirectory() != null && config.getConfigPath() != null) {
1523         // load Rules from files
1524         final File dirConfig =
1525             new File(config.getBaseDirectory() + config.getConfigPath());
1526         if (dirConfig.isDirectory()) {
1527           try {
1528             RuleFileBasedConfiguration.importRules(dirConfig);
1529           } catch (final OpenR66ProtocolSystemException e) {
1530             logger.error(Messages.getString("FileBasedConfiguration.NoRule"),
1531                          e); //$NON-NLS-1$
1532             return false;
1533           } catch (final WaarpDatabaseException e) {
1534             logger.error(
1535                 Messages.getString("FileBasedConfiguration.NoRule") + ": {}",
1536                 e.getMessage()); //$NON-NLS-1$
1537             return false;
1538           }
1539         } else {
1540           logger.error("Config Directory is not a directory: " +
1541                        config.getBaseDirectory() + config.getConfigPath());
1542           return false;
1543         }
1544       }
1545       // load if possible the limit to apply
1546       loadLimit(config, false);
1547     }
1548     return true;
1549   }
1550 
1551   public static boolean autoupgrade;
1552 
1553   /**
1554    * Load database parameter
1555    *
1556    * @param config
1557    * @param initdb
1558    *
1559    * @return True if OK
1560    */
1561   @SuppressWarnings("deprecation")
1562   private static boolean loadDatabase(final Configuration config,
1563                                       final boolean initdb) {
1564     if (hashRootConfig.get(XML_DB) == null) {
1565       return initNoDb(config);
1566     }
1567     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_DB));
1568     try {
1569       XmlValue value = hashConfig.get(XML_SAVE_TASKRUNNERNODB);
1570       if (value != null && !value.isEmpty() && value.getBoolean()) {
1571         return initNoDb(config);
1572       }
1573       value = hashConfig.get(XML_DBDRIVER);
1574       if (value == null || value.isEmpty()) {
1575         if (config.isWarnOnStartup()) {
1576           logger.warn(Messages.getString("FileBasedConfiguration.NoDB"));
1577           //$NON-NLS-1$
1578         }
1579         return initNoDb(config);
1580       } else {
1581         final String dbdriver = value.getString();
1582         value = hashConfig.get(XML_DBSERVER);
1583         if (value == null || value.isEmpty()) {
1584           logger.error(
1585               Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
1586               "DBServer"); //$NON-NLS-1$
1587           return false;
1588         }
1589         final String dbserver = value.getString();
1590         value = hashConfig.get(XML_DBUSER);
1591         if (value == null || value.isEmpty()) {
1592           logger.error(
1593               Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
1594               "DBUser"); //$NON-NLS-1$
1595           return false;
1596         }
1597         final String dbuser = value.getString();
1598         value = hashConfig.get(XML_DBPASSWD);
1599         if (value == null || value.isEmpty()) {
1600           logger.error(
1601               Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
1602               "DBPassword"); //$NON-NLS-1$
1603           return false;
1604         }
1605         final String dbpasswd = value.getString();
1606         if (ParametersChecker.isEmpty(dbdriver) ||
1607             ParametersChecker.isEmpty(dbserver) ||
1608             ParametersChecker.isEmpty(dbuser) ||
1609             ParametersChecker.isEmpty(dbpasswd)) {
1610           logger.error(
1611               Messages.getString(FILE_BASED_CONFIGURATION_NOT_FOUND_CONFIG) +
1612               "Correct DB data"); //$NON-NLS-1$
1613           return false;
1614         }
1615         try {
1616           admin =
1617               DbModelFactoryR66.initialize(dbdriver, dbserver, dbuser, dbpasswd,
1618                                            true);
1619           // New way of initializing database services
1620           try {
1621             ConnectionFactory.initialize(dbserver, dbuser, dbpasswd);
1622           } catch (final UnsupportedOperationException e) {
1623             logger.error(e.getMessage());
1624             return false;
1625           } catch (final SQLException e) {
1626             logger.error("Cannot create ConnectionFactory: {}", e.getMessage());
1627             return false;
1628           }
1629           DAOFactory.initialize(ConnectionFactory.getInstance());
1630 
1631           if (config.getMultipleMonitors() > 1) {
1632             noCommitAdmin =
1633                 DbModelFactoryR66.initialize(dbdriver, dbserver, dbuser,
1634                                              dbpasswd, true);
1635             Configuration.setNbDbSession(Configuration.getNbDbSession() + 1);
1636             noCommitAdmin.getSession().setAutoCommit(false);
1637           } else {
1638             noCommitAdmin = admin;
1639           }
1640           if (logger.isInfoEnabled()) {
1641             logger.info("Database connection: Admin: {}  NoCommitAdmin: {}",
1642                         (admin != null), (noCommitAdmin != null));
1643 
1644             try {
1645               logger.info("DefaultTransactionIsolation: " +
1646                           admin.getSession().getConn().getMetaData()
1647                                .getDefaultTransactionIsolation() +
1648                           " MaxConnections: " +
1649                           admin.getSession().getConn().getMetaData()
1650                                .getMaxConnections() + " MaxStatements: " +
1651                           admin.getSession().getConn().getMetaData()
1652                                .getMaxStatements());
1653             } catch (final SQLException e) {
1654               SysErrLogger.FAKE_LOGGER.syserr(e);
1655             }
1656           }
1657         } catch (final WaarpDatabaseNoConnectionException e2) {
1658           logger.error(Messages.getString("Database.CannotConnect"),
1659                        e2); //$NON-NLS-1$
1660           return false;
1661         }
1662         // Check if the database is ready (initdb already done before)
1663         final DbRequest request;
1664         if (!initdb) {
1665           try {
1666             request = new DbRequest(admin.getSession());
1667             try {
1668               request.select("SELECT * FROM " + DbConfiguration.table);
1669             } catch (final WaarpDatabaseSqlException e) {
1670               logger.warn(
1671                   Messages.getString("Database.DbNotInitiated") + " : {}",
1672                   e.getMessage()); //$NON-NLS-1$
1673               return true;
1674             } finally {
1675               request.close();
1676             }
1677           } catch (final WaarpDatabaseNoConnectionException e1) {
1678             // ignore
1679             /*
1680              * TODO: Why Ignore? throwing bad configuration seems better
1681              */
1682           }
1683         }
1684         // TODO to remove when <dbcheck> is drop from config file
1685         value = hashConfig.get(XML_DBCHECK);
1686         if (value != null && !value.isEmpty()) {
1687           logger.warn(
1688               "<{}> is deprecated in configuration file " + "use <{}> instead",
1689               XML_DBCHECK, XML_DBAUTOUPGRADE);
1690           autoupgrade = value.getBoolean();
1691         } else {
1692           // Keep this part
1693           value = hashConfig.get(XML_DBAUTOUPGRADE);
1694           if (value != null && !value.isEmpty()) {
1695             autoupgrade = value.getBoolean();
1696           }
1697         }
1698         if (autoupgrade && !initdb) {
1699           // Check if the database is up to date
1700           if (!ServerInitDatabase.upgradedb()) {
1701             return false;
1702           }
1703         }
1704       }
1705       return true;
1706     } finally {
1707       hashConfig.clear();
1708       hashConfig = null;
1709     }
1710   }
1711 
1712   private static boolean initNoDb(final Configuration config) {
1713     config.setSaveTaskRunnerWithNoDb(true);
1714     logger.info(
1715         Messages.getString("FileBasedConfiguration.NoDB")); //$NON-NLS-1$
1716     admin = new DbAdmin(); // no database support
1717     noCommitAdmin = admin;
1718     DAOFactory.initialize();
1719     return true;
1720   }
1721 
1722   /**
1723    * Load white list for Business if any
1724    *
1725    * @param config
1726    */
1727   private static void loadBusinessWhiteList(final Configuration config) {
1728     XmlHash hashConfig =
1729         new XmlHash(hashRootConfig.get(DbHostConfiguration.XML_BUSINESS));
1730     try {
1731       final XmlValue value = hashConfig.get(DbHostConfiguration.XML_BUSINESS);
1732       if (value != null && value.getList() != null) {
1733         @SuppressWarnings("unchecked")
1734         List<String> ids = (List<String>) value.getList();
1735         if (ids != null) {
1736           for (final String sval : ids) {
1737             if (sval.isEmpty()) {
1738               continue;
1739             }
1740             logger.info("Business Allow: {}", sval);
1741             config.getBusinessWhiteSet().add(sval.trim());
1742           }
1743           ids.clear();
1744           ids = null;
1745         }
1746       }
1747       loadAliases(config);
1748       setSelfVersion(config);
1749     } finally {
1750       hashConfig.clear();
1751       hashConfig = null;
1752     }
1753   }
1754 
1755   /**
1756    * Load the aliases configuration
1757    *
1758    * @param config
1759    */
1760   @SuppressWarnings("unchecked")
1761   private static void loadAliases(final Configuration config) {
1762     XmlHash hashConfig =
1763         new XmlHash(hashRootConfig.get(DbHostConfiguration.XML_ALIASES));
1764     try {
1765       XmlValue value = hashConfig.get(DbHostConfiguration.XML_ALIASES);
1766       if (value != null && value.getList() != null) {
1767         for (final XmlValue[] xml : (Iterable<XmlValue[]>) value.getList()) {
1768           final XmlHash subHash = new XmlHash(xml);
1769           value = subHash.get(DbHostConfiguration.XML_REALID);
1770           if (value == null || value.isEmpty()) {
1771             continue;
1772           }
1773           final String refHostId = value.getString();
1774           value = subHash.get(DbHostConfiguration.XML_ALIASID);
1775           if (value == null || value.isEmpty()) {
1776             continue;
1777           }
1778           final String aliasset = value.getString();
1779           final String[] alias = aliasset.split(REGEX_SEPARATOR);
1780           for (final String namealias : alias) {
1781             config.getAliases().put(namealias, refHostId);
1782           }
1783           config.getReverseAliases().put(refHostId, alias);
1784           logger.info("Aliases for: {} = {}", refHostId, aliasset);
1785         }
1786       }
1787     } finally {
1788       hashConfig.clear();
1789       hashConfig = null;
1790     }
1791   }
1792 
1793   /**
1794    * Add the local host in Versions
1795    *
1796    * @param config
1797    */
1798   private static void setSelfVersion(final Configuration config) {
1799     if (config.getHostId() != null) {
1800       config.getVersions().putIfAbsent(config.getHostId(),
1801                                        new PartnerConfiguration(
1802                                            config.getHostId()));
1803     }
1804     if (config.getHostSslId() != null) {
1805       config.getVersions().putIfAbsent(config.getHostSslId(),
1806                                        new PartnerConfiguration(
1807                                            config.getHostSslId()));
1808     }
1809     logger.debug("Partners: {}", config.getVersions());
1810   }
1811 
1812   /**
1813    * Load Role list if any
1814    *
1815    * @param config
1816    */
1817   @SuppressWarnings("unchecked")
1818   private static void loadRolesList(final Configuration config) {
1819     XmlHash hashConfig =
1820         new XmlHash(hashRootConfig.get(DbHostConfiguration.XML_ROLES));
1821     try {
1822       XmlValue value = hashConfig.get(DbHostConfiguration.XML_ROLES);
1823       if (value != null && value.getList() != null) {
1824         for (final XmlValue[] xml : (Iterable<XmlValue[]>) value.getList()) {
1825           final XmlHash subHash = new XmlHash(xml);
1826           value = subHash.get(DbHostConfiguration.XML_ROLEID);
1827           if (value == null || value.isEmpty()) {
1828             continue;
1829           }
1830           final String refHostId = value.getString();
1831           value = subHash.get(DbHostConfiguration.XML_ROLESET);
1832           if (value == null || value.isEmpty()) {
1833             continue;
1834           }
1835           final String roleset = value.getString();
1836           final String[] roles = roleset.split(REGEX_SEPARATOR);
1837           final RoleDefault newrole = new RoleDefault();
1838           for (final String role : roles) {
1839             try {
1840               final RoleDefault.ROLE roletype =
1841                   RoleDefault.ROLE.valueOf(role.toUpperCase());
1842               if (roletype == ROLE.NOACCESS) {
1843                 // reset
1844                 newrole.setRole(roletype);
1845               } else {
1846                 newrole.addRole(roletype);
1847               }
1848             } catch (final IllegalArgumentException e) {
1849               // ignore
1850             }
1851           }
1852           logger.info("New Role: {}:{}", refHostId, newrole);
1853           config.getRoles().put(refHostId, newrole);
1854         }
1855       }
1856     } finally {
1857       hashConfig.clear();
1858       hashConfig = null;
1859     }
1860   }
1861 
1862   /**
1863    * Finalize configuration for Server on DbHostConfiguration
1864    *
1865    * @param config
1866    */
1867   private static void finalizeDbHostConfiguration(final Configuration config) {
1868     // now check in DB
1869     if (admin != null) {
1870       DbHostConfiguration hostconfiguration = null;
1871       try {
1872         hostconfiguration = new DbHostConfiguration(config.getHostId());
1873       } catch (final WaarpDatabaseException e) {
1874         // ignore
1875         final Business business = new Business();
1876         business.setHostid(config.getHostId());
1877         hostconfiguration = new DbHostConfiguration(business);
1878       }
1879       if (hostconfiguration != null) {
1880         hostconfiguration.updateFromConfiguration(config);
1881       }
1882     }
1883 
1884   }
1885 
1886   /**
1887    * @param config
1888    * @param fromXML
1889    *
1890    * @return the new subpath
1891    *
1892    * @throws OpenR66ProtocolSystemException
1893    */
1894   private static String getSubPath(final Configuration config,
1895                                    final String fromXML)
1896       throws OpenR66ProtocolSystemException, BadConfigurationException {
1897     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_DIRECTORY));
1898     try {
1899       final XmlValue value = hashConfig.get(fromXML);
1900       if (value == null || value.isEmpty()) {
1901         logger.error(Messages.getString("FileBasedConfiguration.NoXmlPath") +
1902                      fromXML); //$NON-NLS-1$
1903         throw new OpenR66ProtocolSystemException(
1904             Messages.getString("FileBasedConfiguration.NoXmlPath") +
1905             fromXML); //$NON-NLS-1$
1906       }
1907 
1908       String path = value.getString();
1909       if (ParametersChecker.isEmpty(path)) {
1910         throw new OpenR66ProtocolSystemException(
1911             Messages.getString("FileBasedConfiguration.NotCorrectPath") +
1912             fromXML); //$NON-NLS-1$
1913       }
1914       path = checkNotAbsolutePathNotUnderBase(config, path);
1915       path = DirInterface.SEPARATOR + path;
1916       final String newpath = config.getBaseDirectory() + path;
1917       final File file = new File(newpath);
1918       if (!file.isDirectory()) {
1919         FileUtils.createDir(file);
1920       }
1921       return path;
1922     } finally {
1923       hashConfig.clear();
1924       hashConfig = null;
1925     }
1926   }
1927 
1928   /**
1929    * Check if path is really under Base directory (if defined)
1930    *
1931    * @param config
1932    * @param path
1933    *
1934    * @return new path (truncated if necessary)
1935    *
1936    * @throws BadConfigurationException
1937    */
1938   public static String checkNotAbsolutePathNotUnderBase(
1939       final Configuration config, final String path)
1940       throws BadConfigurationException {
1941     File tempPath = new File(path);
1942     if (config.getBaseDirectory() != null && tempPath.isAbsolute() &&
1943         tempPath.isDirectory()) {
1944       if (!FileUtils.isInSubdirectory(new File(config.getBaseDirectory()),
1945                                       tempPath)) {
1946         throw new BadConfigurationException(
1947             "Directory given is absolute and exists but must be below Base " +
1948             "directory");
1949       }
1950       // Check if path must be truncated
1951       return path.replace(config.getBaseDirectory(), "");
1952     }
1953     return path;
1954   }
1955 
1956   /**
1957    * Load minimalistic Limit configuration
1958    *
1959    * @param config
1960    * @param filename
1961    *
1962    * @return True if OK
1963    */
1964   public static boolean setConfigurationLoadLimitFromXml(
1965       final Configuration config, final String filename) {
1966     final Document document;
1967     alreadySetLimit = false;
1968     // Open config file
1969     try {
1970       document = XmlUtil.getNewSaxReader().read(filename);
1971     } catch (final DocumentException e) {
1972       logger.error(
1973           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
1974           filename + ": {}", e.getMessage()); //$NON-NLS-1$
1975       return false;
1976     }
1977     if (document == null) {
1978       logger.error(
1979           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
1980           filename); //$NON-NLS-1$
1981       return false;
1982     }
1983     configuration = XmlUtil.read(document, configServer);
1984     hashRootConfig = new XmlRootHash(configuration);
1985     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_IDENTITY));
1986     try {
1987       loadLocale(hashConfig);
1988     } finally {
1989       hashConfig.clear();
1990       hashConfig = null;
1991     }
1992     if (!loadLimit(config, true)) {
1993       logger.error(Messages.getString("FileBasedConfiguration.NoLimit") +
1994                    filename); //$NON-NLS-1$
1995       return false;
1996     }
1997     hashRootConfig.clear();
1998     hashRootConfig = null;
1999     configuration = null;
2000     return true;
2001   }
2002 
2003   /**
2004    * Load configuration for init database
2005    *
2006    * @param config
2007    * @param filename
2008    *
2009    * @return True if OK
2010    */
2011   public static boolean setConfigurationInitDatabase(final Configuration config,
2012                                                      final String filename,
2013                                                      final boolean initdb) {
2014     final Document document;
2015     // Open config file
2016     try {
2017       document = XmlUtil.getNewSaxReader().read(filename);
2018     } catch (final DocumentException e) {
2019       logger.error(
2020           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2021           filename + ": {}", e.getMessage()); //$NON-NLS-1$
2022       return false;
2023     }
2024     if (document == null) {
2025       logger.error(
2026           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2027           filename); //$NON-NLS-1$
2028       return false;
2029     }
2030     configuration = XmlUtil.read(document, configServer);
2031     hashRootConfig = new XmlRootHash(configuration);
2032     if (!loadIdentity(config, hashRootConfig)) {
2033       logger.error(CANNOT_LOAD_IDENTITY);
2034       return false;
2035     }
2036     if (!loadDatabase(config, initdb)) {
2037       logger.error(CANNOT_LOAD_DATABASE_CONFIGURATION);
2038       return false;
2039     }
2040     if (!loadDirectory(config)) {
2041       logger.error(CANNOT_LOAD_DIRECTORY_CONFIGURATION);
2042       return false;
2043     }
2044     if (!loadLimit(config, false)) {
2045       logger.error(CANNOT_LOAD_LIMIT_CONFIGURATION);
2046       return false;
2047     }
2048     if (config.isSaveTaskRunnerWithNoDb()) {
2049       // if no database, must load authentication from file
2050       if (!loadAuthentication(config)) {
2051         logger.error(CANNOT_LOAD_AUTHENTICATION_CONFIGURATION);
2052         return false;
2053       }
2054     }
2055     hashRootConfig.clear();
2056     hashRootConfig = null;
2057     configuration = null;
2058     return true;
2059   }
2060 
2061   /**
2062    * Load minimalistic configuration
2063    *
2064    * @param config
2065    * @param filename
2066    *
2067    * @return True if OK
2068    */
2069   @SuppressWarnings("deprecation")
2070   public static boolean setConfigurationServerMinimalFromXml(
2071       final Configuration config, final String filename) {
2072     if (!SystemPropertyUtil.get(
2073         R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, "").isEmpty()) {
2074       logger.warn(IS_DEPRECATED_IN_SYSTEM_PROPERTIES_USE_INSTEAD,
2075                   R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK,
2076                   R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE);
2077       autoupgrade = SystemPropertyUtil.getBoolean(
2078           R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, false);
2079     } else {
2080       autoupgrade = SystemPropertyUtil.getBoolean(
2081           R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE, false);
2082     }
2083 
2084     final Document document;
2085     // Open config file
2086     try {
2087       document = XmlUtil.getNewSaxReader().read(filename);
2088     } catch (final DocumentException e) {
2089       logger.error(
2090           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2091           filename + ": {}", e.getMessage()); //$NON-NLS-1$
2092       return false;
2093     }
2094     if (document == null) {
2095       logger.error(
2096           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2097           filename); //$NON-NLS-1$
2098       return false;
2099     }
2100     configuration = XmlUtil.read(document, configServer);
2101     hashRootConfig = new XmlRootHash(configuration);
2102     if (!loadIdentity(config, hashRootConfig)) {
2103       logger.error(CANNOT_LOAD_IDENTITY);
2104       return false;
2105     }
2106     if (!loadDatabase(config, false)) {
2107       logger.error(CANNOT_LOAD_DATABASE_CONFIGURATION);
2108       return false;
2109     }
2110     if (!loadDirectory(config)) {
2111       logger.error(CANNOT_LOAD_DIRECTORY_CONFIGURATION);
2112       return false;
2113     }
2114     if (!loadLimit(config, false)) {
2115       logger.error(CANNOT_LOAD_LIMIT_CONFIGURATION);
2116       return false;
2117     }
2118     if (config.isSaveTaskRunnerWithNoDb()) {
2119       // if no database, must load authentication from file
2120       if (!loadAuthentication(config)) {
2121         logger.error(CANNOT_LOAD_AUTHENTICATION_CONFIGURATION);
2122         return false;
2123       }
2124     }
2125     config.setHostAuth(R66Auth.getServerAuth(config.getHostId()));
2126     if (config.getHostAuth() == null && config.isUseNOSSL()) {
2127       logger.error(CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST);
2128       return false;
2129     }
2130     if (config.getHostSslId() != null) {
2131       config.setHostSslAuth(R66Auth.getServerAuth(config.getHostSslId()));
2132       if (config.getHostSslAuth() == null && config.isUseSSL()) {
2133         logger.error(CANNOT_FIND_SSL_AUTHENTICATION_FOR_CURRENT_HOST);
2134         return false;
2135       }
2136     }
2137     hashRootConfig.clear();
2138     hashRootConfig = null;
2139     configuration = null;
2140     return true;
2141   }
2142 
2143   /**
2144    * Initiate the configuration from the xml file for server shutdown
2145    *
2146    * @param config
2147    * @param filename
2148    *
2149    * @return True if OK
2150    */
2151   @SuppressWarnings("deprecation")
2152   public static boolean setConfigurationServerShutdownFromXml(
2153       final Configuration config, final String filename) {
2154     if (!SystemPropertyUtil.get(
2155         R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, "").isEmpty()) {
2156       logger.warn(IS_DEPRECATED_IN_SYSTEM_PROPERTIES_USE_INSTEAD,
2157                   R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK,
2158                   R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE);
2159       autoupgrade = SystemPropertyUtil.getBoolean(
2160           R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, false);
2161     } else {
2162       autoupgrade = SystemPropertyUtil.getBoolean(
2163           R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE, false);
2164     }
2165 
2166     final Document document;
2167     // Open config file
2168     try {
2169       document = XmlUtil.getNewSaxReader().read(filename);
2170     } catch (final DocumentException e) {
2171       logger.error(
2172           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2173           filename + ": {}", e.getMessage()); //$NON-NLS-1$
2174       return false;
2175     }
2176     if (document == null) {
2177       logger.error(
2178           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2179           filename); //$NON-NLS-1$
2180       return false;
2181     }
2182     configuration = XmlUtil.read(document, configServer);
2183     hashRootConfig = new XmlRootHash(configuration);
2184     // Now read the configuration
2185     if (!loadIdentity(config, hashRootConfig)) {
2186       logger.error(CANNOT_LOAD_IDENTITY);
2187       return false;
2188     }
2189     if (!loadDatabase(config, false)) {
2190       logger.error(CANNOT_LOAD_DATABASE_CONFIGURATION);
2191       return false;
2192     }
2193     if (!loadServerParam(config)) {
2194       logger.error("Cannot load Server Parameters");
2195       return false;
2196     }
2197     if (!loadDirectory(config)) {
2198       logger.error(CANNOT_LOAD_DIRECTORY_CONFIGURATION);
2199       return false;
2200     }
2201     if (!loadLimit(config, false)) {
2202       logger.error(CANNOT_LOAD_LIMIT_CONFIGURATION);
2203       return false;
2204     }
2205     if (config.isUseSSL() && !loadSsl(config, hashRootConfig)) {
2206       logger.error("Cannot load SSL configuration");
2207       return false;
2208     }
2209     if (!loadNetworkServer(config)) {
2210       logger.error("Cannot load Network configuration");
2211       return false;
2212     }
2213     if (config.isSaveTaskRunnerWithNoDb()) {
2214       // if no database, must load authentication from file
2215       if (!loadAuthentication(config)) {
2216         logger.error(CANNOT_LOAD_AUTHENTICATION_CONFIGURATION);
2217         return false;
2218       }
2219     }
2220     config.setHostAuth(R66Auth.getServerAuth(config.getHostId()));
2221     if (config.getHostAuth() == null && config.isUseNOSSL()) {
2222       logger.error(CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST);
2223       return false;
2224     }
2225     if (config.getHostSslId() != null) {
2226       config.setHostSslAuth(R66Auth.getServerAuth(config.getHostSslId()));
2227       if (config.getHostSslAuth() == null && config.isUseSSL()) {
2228         logger.error(CANNOT_FIND_SSL_AUTHENTICATION_FOR_CURRENT_HOST);
2229         return false;
2230       }
2231     }
2232     loadBusinessWhiteList(config);
2233     hashRootConfig.clear();
2234     hashRootConfig = null;
2235     configuration = null;
2236     return true;
2237   }
2238 
2239   /**
2240    * Initiate the configuration from the xml file for server
2241    *
2242    * @param config
2243    * @param filename
2244    * @param isStartupServer If True, will also load configuration for startup
2245    *     of server, else only what is necessary for instance for Initialize database
2246    *
2247    * @return True if OK
2248    */
2249   public static boolean setConfigurationServerFromXml(
2250       final Configuration config, final String filename,
2251       final boolean isStartupServer) {
2252     final Document document;
2253     // Open config file
2254     try {
2255       document = XmlUtil.getNewSaxReader().read(filename);
2256     } catch (final DocumentException e) {
2257       logger.error(
2258           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2259           filename + ": {}", e.getMessage()); //$NON-NLS-1$
2260       return false;
2261     }
2262     if (document == null) {
2263       logger.error(
2264           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2265           filename); //$NON-NLS-1$
2266       return false;
2267     }
2268     configuration = XmlUtil.read(document, configServer);
2269     hashRootConfig = new XmlRootHash(configuration);
2270     // Now read the configuration
2271     if (!loadIdentity(config, hashRootConfig)) {
2272       logger.error(CANNOT_LOAD_IDENTITY);
2273       return false;
2274     }
2275     if (!loadDatabase(config, false)) {
2276       logger.error(CANNOT_LOAD_DATABASE_CONFIGURATION);
2277       return false;
2278     }
2279     if (!loadServerParam(config)) {
2280       logger.error("Cannot load Server Parameters");
2281       return false;
2282     }
2283     if (isStartupServer) {
2284       if (!loadPushMonitorParam(config)) {
2285         logger.error("Cannot load Server Push Monitor Parameters");
2286         return false;
2287       }
2288     }
2289     if (!loadDirectory(config)) {
2290       logger.error(CANNOT_LOAD_DIRECTORY_CONFIGURATION);
2291       return false;
2292     }
2293     if (!loadLimit(config, false)) {
2294       logger.error(CANNOT_LOAD_LIMIT_CONFIGURATION);
2295       return false;
2296     }
2297     if (config.isUseSSL() && !loadSsl(config, hashRootConfig)) {
2298       logger.error("Cannot load SSL configuration");
2299       return false;
2300     }
2301     if (!loadNetworkServer(config)) {
2302       logger.error("Cannot load Network configuration");
2303       return false;
2304     }
2305     if (isStartupServer) {
2306       if (!loadRest(config)) {
2307         logger.error("Cannot load REST configuration");
2308         return false;
2309       }
2310     }
2311     if (!loadFromDatabase(config)) {
2312       logger.error("Cannot load configuration from Database");
2313       return false;
2314     }
2315     if (config.isSaveTaskRunnerWithNoDb()) {
2316       // if no database, must load authentication from file
2317       if (!loadAuthentication(config)) {
2318         logger.error(CANNOT_LOAD_AUTHENTICATION_CONFIGURATION);
2319         return false;
2320       }
2321     }
2322     config.setHostAuth(R66Auth.getServerAuth(config.getHostId()));
2323     if (config.getHostAuth() == null && config.isUseNOSSL()) {
2324       logger.error(CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST);
2325       return false;
2326     }
2327     if (config.getHostSslId() != null) {
2328       config.setHostSslAuth(R66Auth.getServerAuth(config.getHostSslId()));
2329       if (config.getHostSslAuth() == null && config.isUseSSL()) {
2330         logger.error(CANNOT_FIND_SSL_AUTHENTICATION_FOR_CURRENT_HOST);
2331         return false;
2332       }
2333     }
2334     loadBusinessWhiteList(config);
2335     loadRolesList(config);
2336     finalizeDbHostConfiguration(config);
2337     hashRootConfig.clear();
2338     hashRootConfig = null;
2339     configuration = null;
2340     return true;
2341   }
2342 
2343   /**
2344    * Initiate the configuration from the xml file for database client
2345    *
2346    * @param config
2347    * @param filename
2348    *
2349    * @return True if OK
2350    */
2351   @SuppressWarnings("deprecation")
2352   public static boolean setClientConfigurationFromXml(
2353       final Configuration config, final String filename) {
2354     if (!SystemPropertyUtil.get(
2355         R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, "").isEmpty()) {
2356       logger.warn(IS_DEPRECATED_IN_SYSTEM_PROPERTIES_USE_INSTEAD,
2357                   R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK,
2358                   R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE);
2359       autoupgrade = SystemPropertyUtil.getBoolean(
2360           R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, false);
2361     } else {
2362       autoupgrade = SystemPropertyUtil.getBoolean(
2363           R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE, false);
2364     }
2365 
2366     final Document document;
2367     // Open config file
2368     try {
2369       document = XmlUtil.getNewSaxReader().read(filename);
2370     } catch (final DocumentException e) {
2371       logger.error(
2372           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2373           filename + ": {}", e.getMessage()); //$NON-NLS-1$
2374       return false;
2375     }
2376     if (document == null) {
2377       logger.error(
2378           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2379           filename); //$NON-NLS-1$
2380       return false;
2381     }
2382     configuration = XmlUtil.read(document, configClient);
2383     hashRootConfig = new XmlRootHash(configuration);
2384     // Client enables SSL by default but could be reverted later on
2385     config.setUseSSL(true);
2386     if (!loadIdentity(config, hashRootConfig)) {
2387       logger.error(CANNOT_LOAD_IDENTITY);
2388       return false;
2389     }
2390     if (!loadDirectory(config)) {
2391       logger.error(CANNOT_LOAD_DIRECTORY_CONFIGURATION);
2392       return false;
2393     }
2394     if (!loadDatabase(config, false)) {
2395       logger.error(CANNOT_LOAD_DATABASE_CONFIGURATION);
2396       return false;
2397     }
2398     if (!loadClientParam(config)) {
2399       logger.error("Cannot load Client Parameters");
2400       return false;
2401     }
2402     if (!loadLimit(config, false)) {
2403       logger.error(CANNOT_LOAD_LIMIT_CONFIGURATION);
2404       return false;
2405     }
2406     if (config.isUseSSL() && !loadSsl(config, hashRootConfig)) {
2407       logger.error("Cannot load SSL configuration");
2408       return false;
2409     }
2410     if (!loadFromDatabase(config)) {
2411       logger.error("Cannot load configuration from Database");
2412       return false;
2413     }
2414     if (isDbInactive(config)) {
2415       // if no database, must load authentication from file
2416       if (!loadAuthentication(config)) {
2417         logger.error(CANNOT_LOAD_AUTHENTICATION_CONFIGURATION);
2418         return false;
2419       }
2420     }
2421     try {
2422       config.setHostAuth(new DbHostAuth(config.getHostId()));
2423     } catch (final WaarpDatabaseException e) {
2424       logger.error("Current Host is {}", config.getHostId());
2425       logger.error(CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST + ": {}",
2426                    e.getMessage());
2427       return false;
2428     }
2429     if (config.getHostAuth() == null) {
2430       logger.error(CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST);
2431       return false;
2432     }
2433     if (config.getHostSslId() != null) {
2434       config.setHostSslAuth(R66Auth.getServerAuth(config.getHostSslId()));
2435       if (config.getHostSslAuth() == null) {
2436         logger.error(CANNOT_FIND_SSL_AUTHENTICATION_FOR_CURRENT_HOST);
2437         return false;
2438       }
2439     }
2440     loadBusinessWhiteList(config);
2441     hashRootConfig.clear();
2442     hashRootConfig = null;
2443     configuration = null;
2444     return true;
2445   }
2446 
2447   /**
2448    * Initiate the configuration from the xml file for submit database client
2449    *
2450    * @param config
2451    * @param filename
2452    *
2453    * @return True if OK
2454    */
2455   @SuppressWarnings("deprecation")
2456   public static boolean setSubmitClientConfigurationFromXml(
2457       final Configuration config, final String filename) {
2458     if (!SystemPropertyUtil.get(
2459         R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, "").isEmpty()) {
2460       logger.warn(IS_DEPRECATED_IN_SYSTEM_PROPERTIES_USE_INSTEAD,
2461                   R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK,
2462                   R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE);
2463       autoupgrade = SystemPropertyUtil.getBoolean(
2464           R66SystemProperties.OPENR66_STARTUP_DATABASE_CHECK, false);
2465     } else {
2466       autoupgrade = SystemPropertyUtil.getBoolean(
2467           R66SystemProperties.OPENR66_STARTUP_DATABASE_AUTOUPGRADE, false);
2468     }
2469 
2470     final Document document;
2471     // Open config file
2472     try {
2473       document = XmlUtil.getNewSaxReader().read(filename);
2474     } catch (final DocumentException e) {
2475       logger.error(
2476           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2477           filename + ": {}", e.getMessage()); //$NON-NLS-1$
2478       return false;
2479     }
2480     if (document == null) {
2481       logger.error(
2482           Messages.getString(FILE_BASED_CONFIGURATION_CANNOT_READ_XML) +
2483           filename); //$NON-NLS-1$
2484       return false;
2485     }
2486     configuration = XmlUtil.read(document, configSubmitClient);
2487     hashRootConfig = new XmlRootHash(configuration);
2488     // Client enables SSL by default but could be reverted later on
2489     config.setUseSSL(true);
2490     if (!loadIdentity(config, hashRootConfig)) {
2491       logger.error(CANNOT_LOAD_IDENTITY);
2492       return false;
2493     }
2494     if (!loadDatabase(config, false)) {
2495       logger.error(CANNOT_LOAD_DATABASE_CONFIGURATION);
2496       return false;
2497     }
2498     if (!loadDirectory(config)) {
2499       logger.error(CANNOT_LOAD_DIRECTORY_CONFIGURATION);
2500       return false;
2501     }
2502     XmlHash hashConfig = new XmlHash(hashRootConfig.get(XML_LIMIT));
2503     try {
2504       final XmlValue value = hashConfig.get(XML_BLOCKSIZE);
2505       if (value != null && !value.isEmpty()) {
2506         config.setBlockSize(value.getInteger());
2507       }
2508     } finally {
2509       hashConfig.clear();
2510       hashConfig = null;
2511     }
2512     config.setHostAuth(R66Auth.getServerAuth(config.getHostId()));
2513     if (config.getHostAuth() == null) {
2514       logger.error(CANNOT_FIND_AUTHENTICATION_FOR_CURRENT_HOST);
2515       return false;
2516     }
2517     if (config.getHostSslId() != null) {
2518       config.setHostSslAuth(R66Auth.getServerAuth(config.getHostSslId()));
2519       if (config.getHostSslAuth() == null) {
2520         logger.error(CANNOT_FIND_SSL_AUTHENTICATION_FOR_CURRENT_HOST);
2521         return false;
2522       }
2523     }
2524     loadBusinessWhiteList(config);
2525     hashRootConfig.clear();
2526     hashRootConfig = null;
2527     configuration = null;
2528     return true;
2529   }
2530 }