001    package railo.runtime.config;
002    
003    import java.io.ByteArrayInputStream;
004    import java.io.ByteArrayOutputStream;
005    import java.io.IOException;
006    import java.io.InputStream;
007    import java.io.PrintWriter;
008    import java.lang.reflect.Constructor;
009    import java.lang.reflect.InvocationTargetException;
010    import java.lang.reflect.Method;
011    import java.util.ArrayList;
012    import java.util.HashMap;
013    import java.util.Iterator;
014    import java.util.LinkedHashMap;
015    import java.util.Locale;
016    import java.util.Map;
017    import java.util.Map.Entry;
018    import java.util.TimeZone;
019    
020    import javax.servlet.ServletConfig;
021    
022    import org.apache.xerces.parsers.DOMParser;
023    import org.jfree.chart.block.LabelBlockImpl;
024    import org.safehaus.uuid.UUIDGenerator;
025    import org.slf4j.impl.StaticLoggerBinder;
026    import org.w3c.dom.Document;
027    import org.w3c.dom.Element;
028    import org.w3c.dom.Node;
029    import org.w3c.dom.NodeList;
030    import org.xml.sax.InputSource;
031    import org.xml.sax.SAXException;
032    
033    import railo.aprint;
034    import railo.commons.collections.HashTable;
035    import railo.commons.date.TimeZoneUtil;
036    import railo.commons.digest.MD5;
037    import railo.commons.io.DevNullOutputStream;
038    import railo.commons.io.FileUtil;
039    import railo.commons.io.IOUtil;
040    import railo.commons.io.SystemUtil;
041    import railo.commons.io.log.Log;
042    import railo.commons.io.log.LogAndSource;
043    import railo.commons.io.log.LogUtil;
044    import railo.commons.io.res.Resource;
045    import railo.commons.io.res.ResourcesImpl;
046    import railo.commons.io.res.type.s3.S3ResourceProvider;
047    import railo.commons.io.res.util.ResourceClassLoader;
048    import railo.commons.io.res.util.ResourceClassLoaderFactory;
049    import railo.commons.io.res.util.ResourceUtil;
050    import railo.commons.lang.ByteSizeParser;
051    import railo.commons.lang.ClassException;
052    import railo.commons.lang.ClassLoaderHelper;
053    import railo.commons.lang.ClassUtil;
054    import railo.commons.lang.Md5;
055    import railo.commons.lang.StringUtil;
056    import railo.commons.lang.SystemOut;
057    import railo.commons.net.URLDecoder;
058    import railo.loader.TP;
059    import railo.loader.engine.CFMLEngineFactory;
060    import railo.runtime.CFMLFactoryImpl;
061    import railo.runtime.Component;
062    import railo.runtime.Info;
063    import railo.runtime.Mapping;
064    import railo.runtime.MappingImpl;
065    import railo.runtime.cache.CacheConnection;
066    import railo.runtime.cache.CacheConnectionImpl;
067    import railo.runtime.cache.ServerCacheConnection;
068    import railo.runtime.cache.eh.EHCacheLite;
069    import railo.runtime.cfx.customtag.CFXTagClass;
070    import railo.runtime.cfx.customtag.CPPCFXTagClass;
071    import railo.runtime.cfx.customtag.JavaCFXTagClass;
072    import railo.runtime.component.ImportDefintion;
073    import railo.runtime.config.ajax.AjaxFactory;
074    import railo.runtime.config.component.ComponentFactory;
075    import railo.runtime.crypt.BlowfishEasy;
076    import railo.runtime.db.DataSource;
077    import railo.runtime.db.DataSourceImpl;
078    import railo.runtime.dump.ClassicHTMLDumpWriter;
079    import railo.runtime.dump.DumpWriter;
080    import railo.runtime.dump.DumpWriterEntry;
081    import railo.runtime.dump.HTMLDumpWriter;
082    import railo.runtime.dump.SimpleHTMLDumpWriter;
083    import railo.runtime.dump.TextDumpWriter;
084    import railo.runtime.engine.ConsoleExecutionLog;
085    import railo.runtime.engine.ExecutionLog;
086    import railo.runtime.engine.ExecutionLogFactory;
087    import railo.runtime.engine.ThreadLocalConfig;
088    import railo.runtime.exp.ApplicationException;
089    import railo.runtime.exp.ExpressionException;
090    import railo.runtime.exp.PageException;
091    import railo.runtime.exp.SecurityException;
092    import railo.runtime.extension.Extension;
093    import railo.runtime.extension.ExtensionImpl;
094    import railo.runtime.extension.ExtensionProvider;
095    import railo.runtime.extension.ExtensionProviderImpl;
096    import railo.runtime.gateway.GatewayEngineImpl;
097    import railo.runtime.gateway.GatewayEntry;
098    import railo.runtime.gateway.GatewayEntryImpl;
099    import railo.runtime.listener.AppListenerUtil;
100    import railo.runtime.listener.ApplicationListener;
101    import railo.runtime.listener.ClassicAppListener;
102    import railo.runtime.listener.MixedAppListener;
103    import railo.runtime.listener.ModernAppListener;
104    import railo.runtime.listener.NoneAppListener;
105    import railo.runtime.monitor.IntervallMonitor;
106    import railo.runtime.monitor.IntervallMonitorWrap;
107    import railo.runtime.monitor.RequestMonitor;
108    import railo.runtime.monitor.RequestMonitorWrap;
109    import railo.runtime.net.mail.Server;
110    import railo.runtime.net.mail.ServerImpl;
111    import railo.runtime.net.proxy.ProxyData;
112    import railo.runtime.net.proxy.ProxyDataImpl;
113    import railo.runtime.op.Caster;
114    import railo.runtime.op.date.DateCaster;
115    import railo.runtime.orm.ORMConfiguration;
116    import railo.runtime.orm.ORMEngine;
117    import railo.runtime.orm.hibernate.HibernateORMEngine;
118    import railo.runtime.reflection.Reflector;
119    import railo.runtime.search.SearchEngine;
120    import railo.runtime.security.SecurityManager;
121    import railo.runtime.security.SecurityManagerImpl;
122    import railo.runtime.spooler.SpoolerEngineImpl;
123    import railo.runtime.text.xml.XMLCaster;
124    import railo.runtime.type.Collection.Key;
125    import railo.runtime.type.KeyImpl;
126    import railo.runtime.type.List;
127    import railo.runtime.type.Struct;
128    import railo.runtime.type.StructImpl;
129    import railo.runtime.type.scope.Cluster;
130    import railo.runtime.type.scope.ClusterRemote;
131    import railo.runtime.type.util.ArrayUtil;
132    import railo.runtime.video.VideoExecuter;
133    import railo.transformer.library.function.FunctionLib;
134    import railo.transformer.library.function.FunctionLibException;
135    import railo.transformer.library.tag.TagLib;
136    import railo.transformer.library.tag.TagLibException;
137    
138    /**
139     * 
140     */
141    public final class ConfigWebFactory {
142            /**
143         * creates a new ServletConfig Impl Object
144         * @param configServer
145         * @param configDir
146         * @param servletConfig
147         * @return new Instance
148         * @throws SAXException
149         * @throws ClassNotFoundException
150         * @throws PageException
151         * @throws IOException
152         * @throws TagLibException
153         * @throws FunctionLibException
154         */
155    
156        public static ConfigWebImpl newInstance(CFMLFactoryImpl factory,ConfigServerImpl configServer, Resource configDir, ServletConfig servletConfig) throws SAXException, 
157        ClassException, PageException, IOException, TagLibException, FunctionLibException {
158            try{
159            new LabelBlockImpl("aa");
160            }
161            catch(Throwable t){
162                    
163            }
164            
165            
166                    String hash=SystemUtil.hash(servletConfig.getServletContext());
167                    Map<String, String> labels = configServer.getLabels();
168                    String label=null;
169                    if(labels!=null) {
170                            label = labels.get(hash);
171                    }
172                    if(label==null) label=hash;
173                    
174            SystemOut.print(SystemUtil.PRINTWRITER_OUT,
175                            "===================================================================\n"+
176                            "WEB CONTEXT ("+label+")\n"+
177                            "-------------------------------------------------------------------\n"+
178                            "- config:"+configDir+"\n"+
179                            "- webroot:"+servletConfig.getServletContext().getRealPath("/")+"\n"+
180                            "- hash:"+hash+"\n"+
181                            "- label:"+label+"\n"+
182                            "===================================================================\n"
183                            
184                            );
185            
186            boolean doNew=doNew(configDir);
187            
188            
189            Resource configFile=configDir.getRealResource("railo-web.xml.cfm");
190            Resource configFileOld=configDir.getRealResource("railo-web.xml");
191            
192            
193            String strPath=servletConfig.getServletContext().getRealPath("/WEB-INF");
194            Resource path = ResourcesImpl.getFileResourceProvider().getResource(strPath);
195            
196            
197            // get config file
198            if(!configFile.exists()) {
199                    if(configFileOld.exists()){
200                            //if(!configFileOld.renameTo(configFile))
201                                    configFile=configFileOld;
202                    }
203                    else
204                            createConfigFile("web",configFile);
205            }
206            Document doc=null; 
207            
208            Resource bugFile;
209            int count=1;
210            // rename old bugfiles
211            while((bugFile=configDir.getRealResource("railo-web."+(count++)+".buggy.cfm")).exists()) {
212                            bugFile.renameTo(configDir.getRealResource("railo-web."+(count)+".buggy"));
213                    }
214                    
215                    
216                    
217                    try {
218                        doc=loadDocument(configFile);
219                    }
220                    catch(Exception e) {
221                        // rename buggy config files
222                            if(configFile.exists()) {
223                                    SystemOut.printDate(SystemUtil.PRINTWRITER_OUT, "config file "+configFile+" was not valid and has been replaced");
224                            count=1;
225                            while((bugFile=configDir.getRealResource("railo-web."+(count++)+".buggy")).exists()) {}
226                            IOUtil.copy(configFile,bugFile);
227                    configFile.delete();
228                }
229                createConfigFile("web",configFile);
230                doc=loadDocument(configFile);
231            }
232            
233    //      htaccess
234            if(path.exists())createHtAccess(path.getRealResource(".htaccess"));
235            if(configDir.exists())createHtAccess(configDir.getRealResource(".htaccess"));
236                    
237            
238            createContextFiles(configDir,servletConfig,doNew);
239                    ConfigWebImpl configWeb=new ConfigWebImpl(factory,configServer, servletConfig,configDir,configFile);
240                    
241                    load(configServer,configWeb,doc,false,doNew);
242                    createContextFilesPost(configDir,configWeb,servletConfig,false,doNew);
243                return configWeb;
244        }
245        
246    
247        public static void createHtAccess(Resource htAccess) {
248            if(!htAccess.exists()) {
249                            htAccess.createNewFile();
250                            
251                            String content="AuthName \"WebInf Folder\"\n" +
252                            "AuthType Basic\n"+
253                            "<Limit GET POST>\n"+
254                            "order deny,allow\n"+
255                            "deny from all\n"+
256                            "</Limit>";
257                            try {
258                                    IOUtil.copy(new ByteArrayInputStream(content.getBytes()), htAccess,true);
259                            }
260                            catch(Throwable t) {}
261                    }
262            }
263    
264    
265            /**
266         * reloads the Config Object
267         * @param config
268         * @param force
269         * @throws SAXException
270         * @throws ClassNotFoundException
271         * @throws PageException
272         * @throws IOException
273         * @throws TagLibException
274         * @throws FunctionLibException
275         */
276        public static void reloadInstance(ConfigImpl config, boolean force) throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException {
277            // first sleep a little bit
278            
279            Resource configFile=config.getConfigFile();
280            Resource configDir=config.getConfigDir();
281            
282            boolean doNew=doNew(configDir);
283            
284            if(configFile==null) return ;
285            
286            if(second(config.getLoadTime())>second(configFile.lastModified()) && !force) return ;
287            
288            Document doc=loadDocument(configFile);
289            createContextFiles(configDir,null,doNew);
290            config.reset();
291            
292                    load(config.getConfigServerImpl(),config,doc,true,doNew);
293                    createContextFilesPost(configDir,config,null,false,doNew);
294        }
295        
296        
297        
298        
299        
300        
301        private static long second(long ms) {
302                    return ms/1000;
303            }
304    
305    
306            /**
307         * @param configServer
308         * @param config 
309         * @param doc
310         * @throws ClassNotFoundException
311         * @throws IOException
312         * @throws FunctionLibException
313         * @throws TagLibException
314         * @throws PageException
315         */
316        public static void load(ConfigServerImpl configServer, ConfigImpl config, Document doc, boolean isReload, boolean doNew) 
317            throws ClassException, PageException, IOException, TagLibException, FunctionLibException {
318            ThreadLocalConfig.register(config);
319            
320            // fix
321            if(ConfigWebAdmin.fixS3(doc) | ConfigWebAdmin.fixPSQ(doc)) {
322                    XMLCaster.writeTo(doc,config.getConfigFile());
323                    try {
324                                    doc=ConfigWebFactory.loadDocument(config.getConfigFile());
325                            } catch (SAXException e) {}
326            }
327            
328            loadConstants(configServer,config,doc);
329            loadTempDirectory(configServer, config, doc,isReload);
330            loadId(config);
331            loadVersion(config,doc);
332            loadSecurity(configServer,config,doc);
333            ConfigServerImpl cs = configServer;
334            /* SNSN
335            if(configServer!=null) {
336                int version = configServer.getSerialNumber().getVersion();
337                boolean hasServerContext = version==SerialNumber.VERSION_ENTERPRISE || version==SerialNumber.VERSION_DEVELOP;
338                if(!hasServerContext)configServer=null;
339            }*/
340            loadLib(cs,config);
341            loadSystem(cs, config, doc);
342            loadORM(configServer, config, doc);
343            loadResourceProvider(cs,config,doc);
344            loadCharset(configServer,config,doc);
345            loadMappings(configServer,config,doc);
346            loadExtensions(configServer,config,doc);
347            loadPagePool(configServer,config,doc);
348            loadDataSources(configServer,config,doc);
349            loadCache(configServer,config,doc);
350            loadCustomTagsMappings(configServer,config,doc);
351            loadPassword(cs,config,doc);
352            //loadLabel(cs,config,doc);
353            loadFilesystem(cs,config,doc, doNew); // load tlds
354            loadTag(cs,config,doc); // load tlds
355            loadRegional(configServer,config,doc);
356            loadScope(configServer,config,doc);
357            loadMail(configServer,config,doc);
358            loadSearch(configServer,config,doc);
359            loadScheduler(configServer,config,doc);
360            loadDebug(configServer,config,doc);
361            loadError(configServer,config,doc);
362            loadCFX(configServer,config,doc);
363            loadComponent(configServer,config,doc);
364            loadApplication(configServer,config,doc);
365            loadUpdate(cs,config,doc);
366            loadJava(cs,config,doc); // define compile type
367            loadSetting(cs,config,doc);
368            loadProxy(cs,config,doc);
369            loadRemoteClient(cs, config, doc);
370            loadVideo(cs, config, doc);
371            loadFlex(configServer,config,doc);
372            settings(config);
373            loadListener(cs,config,doc);
374            loadDumpWriter(cs, config, doc);
375            loadGatewayEL(configServer,config,doc);
376            loadExeLog(configServer,config,doc);
377            loadMonitors(configServer,config,doc);
378            loadLogin(configServer, config, doc);
379            config.setLoadTime(System.currentTimeMillis());
380            
381            // this call is needed to make sure the railo StaticLoggerBinder is loaded
382            try{
383            StaticLoggerBinder.getSingleton();
384            }
385            catch(Throwable t){}
386    
387            //doNew(config.getConfigDir(), false);
388            
389            ThreadLocalConfig.release();
390        }
391    
392        private static void loadResourceProvider(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws ClassException {
393            boolean hasCS=configServer!=null;
394            config.clearResourceProviders();
395            Element resources=getChildByName(doc.getDocumentElement(),"resources");
396            Element[] providers=getChildren(resources,"resource-provider");
397            Element[] defaultProviders=getChildren(resources,"default-resource-provider");
398            
399            // Default Resource Provider
400            if(hasCS)config.setDefaultResourceProvider(configServer.getDefaultResourceProvider());
401            if(defaultProviders!=null && defaultProviders.length>0) {
402                    Element defaultProvider=defaultProviders[defaultProviders.length-1];
403                    String strDefaultProviderClass=defaultProvider.getAttribute("class");
404                    if(!StringUtil.isEmpty(strDefaultProviderClass)) {
405                            strDefaultProviderClass=strDefaultProviderClass.trim();
406                            config.setDefaultResourceProvider(strDefaultProviderClass,toArguments(defaultProvider.getAttribute("arguments")));
407                    }
408            }
409            
410                    // Resource Provider
411            if(hasCS)config.setResourceProviders(configServer.getResourceProviders());
412            if(providers!=null && providers.length>0) {
413                    
414                    String strProviderClass;
415                    String strProviderScheme;
416                    String httpClass=null;
417                    Map httpArgs=null;
418                    boolean hasHTTPs = false, hasS3=false;
419                    String s3Class="railo.commons.io.res.type.s3.S3ResourceProvider";
420                    for(int i=0;i<providers.length;i++) {                
421                            strProviderClass=providers[i].getAttribute("class");
422                            
423                            // ignore S3 extension
424                            if("railo.extension.io.resource.type.s3.S3ResourceProvider".equals(strProviderClass))
425                                    strProviderClass=S3ResourceProvider.class.getName();
426                            
427                            strProviderScheme=providers[i].getAttribute("scheme");
428                            if(!StringUtil.isEmpty(strProviderClass) && !StringUtil.isEmpty(strProviderScheme)) {
429                                    strProviderClass=strProviderClass.trim();
430                            strProviderScheme=strProviderScheme.trim().toLowerCase();
431                            config.addResourceProvider(strProviderScheme,strProviderClass,toArguments(providers[i].getAttribute("arguments")));
432                            
433                            // patch for user not having 
434                            if(strProviderScheme.equalsIgnoreCase("http"))  {
435                                    httpClass=strProviderClass;
436                                    httpArgs = toArguments(providers[i].getAttribute("arguments"));
437                            }
438                            else if(strProviderScheme.equalsIgnoreCase("https"))
439                                    hasHTTPs=true;
440                            else if(strProviderScheme.equalsIgnoreCase("s3"))
441                                    hasS3=true;
442                            }
443                }
444                    
445                    // adding https when not exists
446                    if(!hasHTTPs && httpClass!=null){
447                            config.addResourceProvider("https",httpClass,httpArgs);
448                    }
449                    // adding s3 when not exist
450                    if(!hasS3 && config instanceof ConfigServer) {
451                            config.addResourceProvider("s3",s3Class,toArguments("lock-timeout:10000;"));
452                    }
453            }
454            }
455        
456        
457        
458        private static void loadDumpWriter(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws ClassException {
459            boolean hasCS=configServer!=null;
460            
461            Element coll=getChildByName(doc.getDocumentElement(),"dump-writers");
462            Element[] writers=getChildren(coll,"dump-writer");
463            
464            Struct sct=new StructImpl();
465            
466            boolean hasPlain=false;
467            boolean hasRich=false;
468                    if(hasCS){
469                    DumpWriterEntry[] entries = configServer.getDumpWritersEntries();
470                    if(entries!=null)for(int i=0;i<entries.length;i++){
471                            if(entries[i].getDefaultType()==HTMLDumpWriter.DEFAULT_PLAIN)hasPlain=true;
472                            if(entries[i].getDefaultType()==HTMLDumpWriter.DEFAULT_RICH)hasRich=true;
473                            sct.put(entries[i].getName(),entries[i]);
474                    }
475            }
476            
477            if(writers!=null && writers.length>0) {
478                    String strClass;
479                    String strName;
480                    String strDefault;
481                    Class clazz;
482                    int def=HTMLDumpWriter.DEFAULT_NONE;
483                    for(int i=0;i<writers.length;i++) {          
484                            strClass=writers[i].getAttribute("class");
485                            strName=writers[i].getAttribute("name");
486                            strDefault=writers[i].getAttribute("default");
487                            clazz=ClassUtil.loadClass(strClass,null);
488                            if(clazz!=null && !StringUtil.isEmpty(strName)) {
489                                            if(StringUtil.isEmpty(strDefault))                                      def=HTMLDumpWriter.DEFAULT_NONE;                        
490                                            else if("browser".equalsIgnoreCase(strDefault))         def=HTMLDumpWriter.DEFAULT_RICH;
491                                            else if("console".equalsIgnoreCase(strDefault))         def=HTMLDumpWriter.DEFAULT_PLAIN;
492                                            sct.put(strName,new DumpWriterEntry(def,strName,(DumpWriter) ClassUtil.loadInstance(clazz)));
493                    }
494                }
495            }
496            else {
497                    //print.err("yep");
498                    if(!hasRich)sct.put("html",new DumpWriterEntry(HTMLDumpWriter.DEFAULT_RICH,"html", new HTMLDumpWriter()));
499                    if(!hasPlain)sct.put("text",new DumpWriterEntry(HTMLDumpWriter.DEFAULT_PLAIN,"text", new TextDumpWriter()));  
500                    
501                    sct.put("classic",new DumpWriterEntry(HTMLDumpWriter.DEFAULT_NONE,"classic", new ClassicHTMLDumpWriter()));  
502                    sct.put("simple",new DumpWriterEntry(HTMLDumpWriter.DEFAULT_NONE,"simple", new SimpleHTMLDumpWriter()));  
503    
504                    
505            }
506            DumpWriterEntry[] entries = new DumpWriterEntry[sct.size()];
507            Key[] keys = sct.keys();
508            for(int i=0;i<keys.length;i++){
509                    entries[i]=(DumpWriterEntry) sct.get(keys[i],null);
510            }
511            config.setDumpWritersEntries(entries);
512            }
513        
514        
515    
516    
517            private static Map<String,String> toArguments(String attributes) {
518                    Map<String,String> map=new HashTable();
519                    if(attributes==null) return map;
520                    String[] arr=List.toStringArray(List.listToArray(attributes, ';'),null);
521                    String[] item;
522                    int index;
523                    for(int i=0;i<arr.length;i++) {
524                            index=arr[i].indexOf(':');
525                            if(index==-1)map.put(arr[i].trim(), "");
526                            else map.put(arr[i].substring(0,index).trim(), arr[i].substring(index+1).trim());
527                    }
528                    return map;
529            }
530    
531    
532            private static void loadListener(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
533            if(config instanceof ConfigServer) {
534                    ConfigServer cs=(ConfigServer) config;
535                Element listener=getChildByName(doc.getDocumentElement(),"listener");
536                String strClass = listener.getAttribute("class");
537                String strArguments = listener.getAttribute("arguments");
538                if(strArguments==null)strArguments="";
539                
540                if(!StringUtil.isEmpty(strClass)) {
541                    try {
542                            
543                            Object obj=ClassUtil.loadInstance(strClass,new Object[]{strArguments},null);
544                            if(obj instanceof ConfigListener) {
545                                                    ConfigListener cl=(ConfigListener) obj;
546                                                    cs.setConfigListener(cl);
547                                            }
548                                    } 
549                    catch (Throwable t) {
550                                            t.printStackTrace(config.getErrWriter());
551                                            
552                                    }
553                    
554                }
555            }
556            else if(configServer!=null) {
557                    ConfigListener listener = configServer.getConfigListener();
558                    if(listener!=null)listener.onLoadWebContext(configServer, (ConfigWeb) config);
559            }
560            }
561    
562    
563    
564    
565        private static void settings(ConfigImpl config) {
566            if(!(config instanceof ConfigServer))doCheckChangesInLibraries(config);
567                    
568            }
569    
570    
571    
572    
573        private static void loadVersion(ConfigImpl config, Document doc) {
574            //boolean hasCS=configServer!=null;
575            
576            Element railoConfiguration = doc.getDocumentElement();
577            String strVersion=railoConfiguration.getAttribute("version");    
578            config.setVersion(Caster.toDoubleValue(strVersion,1.0d));
579        }
580        
581        private static void loadId(ConfigImpl config) {
582            Resource res=config.getConfigDir().getRealResource("id");
583                    String securityKey=null;        
584                    try {
585                    if(!res.exists()) {
586                        res.createNewFile();
587                        IOUtil.write(res,securityKey=UUIDGenerator.getInstance().generateRandomBasedUUID().toString(),SystemUtil.getCharset(),false);
588                    }
589                    else  {
590                        securityKey=IOUtil.toString(res, SystemUtil.getCharset());
591                    }
592                    }
593                    catch(IOException ioe) {}
594            
595            if(StringUtil.isEmpty(securityKey))securityKey=UUIDGenerator.getInstance().generateRandomBasedUUID().toString();
596            
597            config.setSecurityKey(securityKey);
598        }
599    
600    
601        public static void reloadLib(ConfigImpl config) throws IOException {
602            if(config instanceof ConfigWebImpl)
603                    loadLib(((ConfigWebImpl)config).getConfigServerImpl(), config);
604            else 
605                    loadLib(null, config);
606        }
607        
608        private static void loadLib(ConfigServerImpl configServer, ConfigImpl config) throws IOException {
609            Resource lib = config.getConfigDir().getRealResource("lib");
610            lib.mkdir();
611            Resource classes = config.getConfigDir().getRealResource("classes");
612            classes.mkdir();
613            Resource[] libs = lib.listResources();
614    
615            ResourceClassLoaderFactory classLoaderFactory;
616                    if(configServer==null){
617                    classLoaderFactory=new ResourceClassLoaderFactory(new ClassLoaderHelper().getClass().getClassLoader());
618            }
619            else {
620                    classLoaderFactory=new ResourceClassLoaderFactory(configServer.getClassLoader());
621            }
622            config.setClassLoaderFactory(classLoaderFactory);
623            
624            
625            //ClassLoader pcl = null;
626            if(libs.length>0 || !ResourceUtil.isEmptyDirectory(classes)){
627                    Resource[] trgs =new Resource[libs.length+1];
628                    for(int i=0;i<libs.length;i++){
629                            trgs[i]=libs[i];
630                    }
631                    trgs[libs.length]=classes;
632                    
633                    ResourceClassLoader cl = (ResourceClassLoader) config.getClassLoader();
634                    
635                    // are files removed
636                    if(cl==null){
637                            classLoaderFactory.addResources(trgs);
638                    }
639                    else {
640                            Resource[] srcs = cl.getResources();
641                            if(equal(srcs,trgs))return;     
642    
643                            Resource[] removed = getNewResources(trgs,srcs);
644                            if(removed.length>0){
645                                    classLoaderFactory.addResources(trgs);
646                            }
647                            else{
648                                    cl.addResources(getNewResources(srcs,trgs));
649                            }
650                    }
651                    
652            }
653            else{
654                    classLoaderFactory.addResources(new Resource[0]);
655            }
656        }
657        
658    
659    
660            private static boolean equal(Resource[] srcs, Resource[] trgs) {
661                    if(srcs.length!=trgs.length) return false;
662                    Resource src;
663                    outer:for(int i=0;i<srcs.length;i++){
664                            src=srcs[i];
665                            for(int y=0;y<trgs.length;y++){
666                                    if(src.equals(trgs[y]))continue outer;
667                            }
668                            return false;
669                    }
670                    return true;
671            }
672        
673        private static Resource[] getNewResources(Resource[] srcs, Resource[] trgs) {
674            Resource trg;
675                    java.util.List<Resource> list=new ArrayList<Resource>();
676                    outer:for(int i=0;i<trgs.length;i++){
677                            trg=trgs[i];
678                            for(int y=0;y<srcs.length;y++){
679                                    if(trg.equals(srcs[y]))continue outer;
680                            }
681                            list.add(trg);
682                    }
683                    return list.toArray(new Resource[list.size()]);
684            }
685    
686    
687            /**
688         * @param configServer
689         * @param config
690         * @param doc
691         */
692        private static void loadSecurity(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
693            
694    
695        // Serial Number
696            if(config instanceof ConfigServer) {
697                Element railoConfiguration = doc.getDocumentElement();
698                    String serial=railoConfiguration.getAttribute("serial-number");    
699                if(!StringUtil.isEmpty(serial))
700                    config.setSerialNumber(serial);
701            }
702            else if(configServer!=null) {
703                config.setSerialNumber(configServer.getSerialNumber());
704            }
705            
706        // Security Manger    
707           SecurityManager securityManager=null;
708           if(config instanceof ConfigServerImpl) {
709               ConfigServerImpl cs=(ConfigServerImpl)config;
710               Element security = getChildByName(doc.getDocumentElement(),"security");
711               
712               //Default SecurityManager
713                    SecurityManagerImpl sm = _toSecurityManager(security);
714                    
715                    // addional file accesss directories
716                    Element[] elFileAccesses=getChildren(security,"file-access");
717                    sm.setCustomFileAccess(_loadFileAccess(config,elFileAccesses));
718    
719                    cs.setDefaultSecurityManager(sm);
720                    
721               // Web SecurityManager
722                    Element[] accessors=getChildren(security,"accessor");
723                    for(int i=0;i<accessors.length;i++) {
724                        String id=accessors[i].getAttribute("id");
725                        if(id!=null){
726                            sm=_toSecurityManager(accessors[i]);
727                            elFileAccesses=getChildren(accessors[i],"file-access");
728                            sm.setCustomFileAccess(_loadFileAccess(config,elFileAccesses));
729                            cs.setSecurityManager(id,sm);
730                        }
731                    }
732                
733           }
734           
735           else if(configServer!=null) {
736               securityManager=configServer.getSecurityManager(config.getId());
737           }
738           if(config instanceof ConfigWebImpl) {
739               if(securityManager==null)securityManager=SecurityManagerImpl.getOpenSecurityManager();
740               ((ConfigWebImpl)config).setSecurityManager(securityManager);
741           }
742        }
743    
744        private static Resource[] _loadFileAccess(Config config,Element[] fileAccesses) {
745            if(ArrayUtil.isEmpty(fileAccesses))return new Resource[0];
746            
747            java.util.List reses=new ArrayList();
748            String path;
749            Resource res;
750            for(int i=0;i<fileAccesses.length;i++) {
751                path=fileAccesses[i].getAttribute("path");
752                if(!StringUtil.isEmpty(path)){
753                    res=config.getResource(path);
754                    if(res.isDirectory())
755                            reses.add(res); 
756                }
757            }
758                    return (Resource[]) reses.toArray(new Resource[reses.size()]);
759            }
760    
761    
762            private static SecurityManagerImpl _toSecurityManager(Element el) {
763            SecurityManagerImpl sm = new SecurityManagerImpl(
764                    _attr(el,"setting",SecurityManager.VALUE_YES),
765                    _attr(el,"file",SecurityManager.VALUE_ALL),
766                    _attr(el,"direct_java_access",SecurityManager.VALUE_YES),
767                    _attr(el,"mail",SecurityManager.VALUE_YES),
768                    _attr(el,"datasource",SecurityManager.VALUE_YES),
769                    _attr(el,"mapping",SecurityManager.VALUE_YES),
770                    _attr(el,"remote",SecurityManager.VALUE_YES),
771                    _attr(el,"custom_tag",SecurityManager.VALUE_YES),
772                    _attr(el,"cfx_setting",SecurityManager.VALUE_YES),
773                    _attr(el,"cfx_usage",SecurityManager.VALUE_YES),
774                    _attr(el,"debugging",SecurityManager.VALUE_YES),
775                    _attr(el,"search",SecurityManager.VALUE_YES),
776                    _attr(el,"scheduled_task",SecurityManager.VALUE_YES),
777                    _attr(el,"tag_execute",SecurityManager.VALUE_YES),
778                    _attr(el,"tag_import",SecurityManager.VALUE_YES),
779                    _attr(el,"tag_object",SecurityManager.VALUE_YES),
780                    _attr(el,"tag_registry",SecurityManager.VALUE_YES),
781                    _attr(el,"cache",SecurityManager.VALUE_YES),
782                    _attr(el,"gateway",SecurityManager.VALUE_YES),
783                    _attr(el,"orm",SecurityManager.VALUE_YES),
784                    _attr2(el,"access_read",SecurityManager.ACCESS_PROTECTED),
785                    _attr2(el,"access_write",SecurityManager.ACCESS_PROTECTED)
786            );
787            return sm;
788        }
789    
790        private static short _attr(Element el, String attr, short _default) {
791            return SecurityManagerImpl.toShortAccessValue(el.getAttribute(attr),_default);
792        }
793    
794        private static short _attr2(Element el, String attr, short _default) {
795            String strAccess = el.getAttribute(attr);
796            if(StringUtil.isEmpty(strAccess)) return _default;
797            strAccess=strAccess.trim().toLowerCase();
798            if("open".equals(strAccess))            return SecurityManager.ACCESS_OPEN;
799                    if("protected".equals(strAccess))       return SecurityManager.ACCESS_PROTECTED;
800                    if("close".equals(strAccess))           return SecurityManager.ACCESS_CLOSE;
801            return _default;
802        }
803    
804    
805        /**
806         * load XML Document from XML File
807         * @param xmlFile XML File to read
808         * @return returns the Document
809         * @throws SAXException
810         * @throws IOException
811         */
812        static Document loadDocument(Resource xmlFile) throws SAXException, IOException {
813            
814            InputStream is=null;
815            try {
816                    return _loadDocument(is=IOUtil.toBufferedInputStream(xmlFile.getInputStream()));
817            }
818            finally {
819                    IOUtil.closeEL(is);
820            }
821        }
822        
823        /**
824         * load XML Document from XML File
825         * @param is InoutStream to read
826         * @return returns the Document
827         * @throws SAXException
828         * @throws IOException
829         */
830        private static Document _loadDocument(InputStream is) throws SAXException, IOException {
831            DOMParser parser = new DOMParser();
832                InputSource source = new InputSource(is);
833                parser.parse(source);
834                is.close();
835                return parser.getDocument();
836        }
837            
838            /**
839             * creates the Config File, if File not exists
840             * @param xmlName
841             * @param configFile 
842             * @throws IOException
843             */
844            static void createConfigFile(String xmlName,Resource configFile) throws IOException {
845                configFile.createFile(true);
846                    createFileFromResource("/resource/config/"+xmlName+".xml",configFile.getAbsoluteResource());
847            }
848    
849        /**
850         * creates a File and his content froma a resurce
851         * @param resource
852         * @param file
853         * @throws IOException
854         */
855            static void createFileFromResource(String resource,Resource file) throws IOException {
856            createFileFromResource(resource,file,null);
857        }
858            
859            public static void createFileFromResourceEL(String resource,Resource file) {
860            try {
861                            createFileFromResource(resource,file,null);
862                    } 
863            catch (Throwable e) {
864            }
865        }
866        /**
867         * creates a File and his content froma a resurce
868         * @param resource
869         * @param file
870         * @param password
871         * @throws IOException
872         */
873        static void createFileFromResource(String resource,Resource file, String password) throws IOException {
874            SystemOut.printDate(SystemUtil.PRINTWRITER_OUT,"write file:"+file);
875            file.createNewFile(); 
876                IOUtil.copy(
877                        new Info().getClass().getResourceAsStream(resource),
878                        file,
879                    true
880            );  
881        }
882        
883        static String createMD5FromResource(String resource) throws IOException {
884            InputStream is=null;
885            try{
886                    is=new Info().getClass().getResourceAsStream(resource); 
887                    byte[] barr = IOUtil.toBytes(is);
888                    return MD5.getDigestAsString(barr);
889            }
890            finally{
891                    IOUtil.closeEL(is);
892            }
893        }
894        
895       
896        
897        static String createContentFromResource(Resource resource) throws IOException {
898            return IOUtil.toString(resource,null);
899        }
900        
901    
902        static void createFileFromResourceCheckSizeDiffEL(String resource,Resource file) {
903            try {
904                            createFileFromResourceCheckSizeDiff(resource, file);
905                    } 
906            catch (Throwable e) {
907                    aprint.err(resource);
908                    aprint.err(file);
909                    e.printStackTrace();
910            }
911        }
912        
913        /**
914         * creates a File and his content froma a resurce
915         * @param resource
916         * @param file
917         * @throws IOException
918         */
919        static void createFileFromResourceCheckSizeDiff(String resource,Resource file) throws IOException {
920            ByteArrayOutputStream baos = new ByteArrayOutputStream();
921                IOUtil.copy(
922                        new Info().getClass().getResourceAsStream(resource),
923                    baos,
924                    true,false
925            ); 
926                byte[] barr = baos.toByteArray();
927            
928            if(file.exists()) {
929                    long trgSize=file.length();
930                    long srcSize=barr.length;
931                    if(srcSize==trgSize)return;
932                    
933                    SystemOut.printDate(SystemUtil.PRINTWRITER_OUT,"update file:"+file);
934                    SystemOut.printDate(SystemUtil.PRINTWRITER_OUT," - source:"+srcSize);
935                    SystemOut.printDate(SystemUtil.PRINTWRITER_OUT," - target:"+trgSize);
936                    
937            }
938            else file.createNewFile(); 
939            
940            
941            //SystemOut.printDate("write file:"+file);
942            IOUtil.copy(
943                        new ByteArrayInputStream(barr),
944                        file,
945                    true
946            );  
947        }
948        
949        
950            
951            /**
952             * Creates all files for Railo Context
953             * @param configDir
954             * @throws IOException 
955             * @throws IOException
956             */
957            public static void createContextFiles(Resource configDir, ServletConfig servletConfig, boolean doNew) throws IOException {
958                // NICE dies muss dynamisch ersstelt werden, da hier der admin hinkommt und dieser sehr viele files haben wird
959                    Resource contextDir = configDir.getRealResource("context");
960                if(!contextDir.exists())contextDir.mkdirs();
961                
962                if(SystemUtil.isWindows()) {
963                    Resource systemDir=SystemUtil.getSystemDirectory();
964                    if(systemDir!=null) {
965                            Resource jacob=systemDir.getRealResource("jacob.dll");
966                        if(!jacob.exists()) {
967                            createFileFromResourceEL("/resource/bin/jacob.dll",jacob);
968                        
969                        }
970                    }
971                }
972            
973            // video
974            Resource videoDir = configDir.getRealResource("video");
975            if(!videoDir.exists())videoDir.mkdirs();
976            
977            Resource video=videoDir.getRealResource("video.xml");
978            if(!video.exists())createFileFromResourceEL("/resource/video/video.xml",video);
979            
980            // bin
981            Resource binDir = configDir.getRealResource("bin");
982            if(!binDir.exists())binDir.mkdirs();
983            
984            Resource ctDir = configDir.getRealResource("customtags");
985            if(!ctDir.exists())ctDir.mkdirs();
986    
987            Resource f=binDir.getRealResource("jacob.dll");
988            if(!f.exists())createFileFromResourceEL("/resource/bin/jacob.dll",f);
989    
990    
991            
992            Resource storDir = configDir.getRealResource("storage");
993            if(!storDir.exists())storDir.mkdirs();
994            
995            Resource cfcDir = configDir.getRealResource("components");
996            if(!cfcDir.exists())cfcDir.mkdirs();
997            
998           
999            // remove old cacerts files, they are now only in the server context
1000            Resource secDir = configDir.getRealResource("security");
1001            if(secDir.exists()){
1002                    f=secDir.getRealResource("cacerts");
1003                    if(f.exists())f.delete();
1004                    if(ResourceUtil.isEmpty(secDir))secDir.delete();
1005            }
1006            
1007            
1008            
1009            
1010            
1011                f=contextDir.getRealResource("railo-context.ra");
1012            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/railo-context.ra",f);
1013            else createFileFromResourceCheckSizeDiffEL("/resource/context/railo-context.ra",f);
1014    
1015            f=contextDir.getRealResource("component-dump.cfm");
1016                if(!f.exists())createFileFromResourceEL("/resource/context/component-dump.cfm",f);
1017                
1018                
1019                // Component.cfc
1020                String badContent="<cfcomponent displayname=\"Component\" hint=\"This is the Base Component\">\n</cfcomponent>";
1021                String badVersion="704b5bd8597be0743b0c99a644b65896";
1022                f=contextDir.getRealResource("Component.cfc");
1023    
1024                
1025                if(!f.exists())
1026                    createFileFromResourceEL("/resource/context/Component.cfc",f);
1027                else if(doNew && badVersion.equals(ConfigWebUtil.createMD5FromResource(f))){
1028                    createFileFromResourceEL("/resource/context/Component.cfc",f);
1029                }
1030                else if(doNew && badContent.equals(createContentFromResource(f).trim())){
1031                    createFileFromResourceEL("/resource/context/Component.cfc",f);
1032                }
1033                
1034                
1035                f=contextDir.getRealResource("application.cfm");
1036                if(!f.exists())createFileFromResourceEL("/resource/context/application.cfm",f);
1037                
1038                f=contextDir.getRealResource("form.cfm");
1039                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/form.cfm",f);
1040                
1041                f=contextDir.getRealResource("graph.cfm");
1042                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/graph.cfm",f);
1043                
1044                f=contextDir.getRealResource("wddx.cfm");
1045                if(!f.exists())createFileFromResourceEL("/resource/context/wddx.cfm",f);
1046            
1047            f=contextDir.getRealResource("railo-applet.cfm");
1048            if(!f.exists())createFileFromResourceEL("/resource/context/railo-applet.cfm",f);
1049            
1050            f=contextDir.getRealResource("railo-applet.jar");
1051            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/railo-applet.jar",f);
1052    
1053            //f=new BinaryFile(contextDir,"railo_context.ra");
1054            //if(!f.exists())createFileFromResource("/resource/context/railo_context.ra",f);
1055    
1056            
1057            f=contextDir.getRealResource("admin.cfm");
1058            if(!f.exists())createFileFromResourceEL("/resource/context/admin.cfm",f);
1059            
1060    
1061            // Video
1062            f=contextDir.getRealResource("swfobject.js");
1063            if(!f.exists() || doNew)createFileFromResourceEL("/resource/video/swfobject.js",f);
1064            f=contextDir.getRealResource("swfobject.js.cfm");
1065            if(!f.exists() || doNew)createFileFromResourceEL("/resource/video/swfobject.js.cfm",f);
1066            
1067            f=contextDir.getRealResource("mediaplayer.swf");
1068            if(!f.exists() || doNew)createFileFromResourceEL("/resource/video/mediaplayer.swf",f);
1069            f=contextDir.getRealResource("mediaplayer.swf.cfm");
1070            if(!f.exists() || doNew)createFileFromResourceEL("/resource/video/mediaplayer.swf.cfm",f);
1071            
1072            Resource adminDir = contextDir.getRealResource("admin");
1073            if(!adminDir.exists())adminDir.mkdirs();
1074            
1075            
1076        // Plugin
1077            Resource pluginDir = adminDir.getRealResource("plugin");
1078            if(!pluginDir.exists())pluginDir.mkdirs();
1079    
1080            f=pluginDir.getRealResource("Plugin.cfc");
1081            if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Plugin.cfc",f);
1082            
1083            // Plugin DDNS
1084                    /*File ddns = new File(pluginDir,"DDNS");
1085                    if(!ddns.exists())ddns.mkdirs();
1086            
1087                    f=new File(ddns,"language.xml");
1088                    if(!f.exists())createFileFromResource("/resource/context/admin/plugin/DDNS/language.xml",f);
1089            
1090                    f=new File(ddns,"overview.cfm");
1091                    if(!f.exists())createFileFromResource("/resource/context/admin/plugin/DDNS/overview.cfm",f);
1092            
1093                    f=new File(ddns,"Action.cfc");
1094                    if(!f.exists())createFileFromResource("/resource/context/admin/plugin/DDNS/Action.cfc",f);*/
1095    
1096            // Plugin Simon
1097                    Resource simon = pluginDir.getRealResource("Simon");
1098                    if(!simon.exists())simon.mkdirs();
1099            
1100                    f=simon.getRealResource("language.xml");
1101                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Simon/language.xml",f);
1102    
1103                    f=simon.getRealResource("overview.cfm");
1104                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Simon/overview.cfm",f);
1105    
1106                    f=simon.getRealResource("simon.swf.cfm");
1107                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Simon/simon.swf.cfm",f);
1108            
1109                    f=simon.getRealResource("Action.cfc");
1110                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Simon/Action.cfc",f);
1111    
1112            // Plugin Note
1113                    Resource note = pluginDir.getRealResource("Note");
1114                    if(!note.exists())note.mkdirs();
1115            
1116                    f=note.getRealResource("language.xml");
1117                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Note/language.xml",f);
1118            
1119                    f=note.getRealResource("overview.cfm");
1120                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Note/overview.cfm",f);
1121            
1122                    f=note.getRealResource("Action.cfc");
1123                    if(!f.exists())createFileFromResourceEL("/resource/context/admin/plugin/Note/Action.cfc",f);
1124                    
1125                    // gateway
1126                    Resource gatewayDir = configDir.getRealResource("components");
1127                    if(!gatewayDir.exists())gatewayDir.mkdirs();
1128                    
1129                    Resource dir = gatewayDir.getRealResource("railo/extension/gateway/");
1130                    if(!dir.exists())dir.mkdirs();
1131    
1132                    f=dir.getRealResource("DummyGateway.cfc");
1133                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/gateway/DummyGateway.cfc",f);
1134    
1135                f=dir.getRealResource("DirectoryWatcher.cfc");
1136                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/gateway/DirectoryWatcher.cfc",f);
1137                    
1138                f=dir.getRealResource("DirectoryWatcherListener.cfc");
1139                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/gateway/DirectoryWatcherListener.cfc",f);
1140    
1141                f=dir.getRealResource("MailWatcher.cfc");
1142                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/gateway/MailWatcher.cfc",f);
1143                    
1144                f=dir.getRealResource("MailWatcherListener.cfc");
1145                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/gateway/MailWatcherListener.cfc",f);
1146                    
1147            // resources/language
1148                Resource langDir = adminDir.getRealResource("resources/language");
1149                langDir.mkdirs();
1150                f=langDir.getRealResource("en.xml");
1151                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/resources/language/en.xml",f);
1152                
1153                f=langDir.getRealResource("de.xml");
1154                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/resources/language/de.xml",f);
1155    
1156            // G DRIVER
1157                Resource gDir = adminDir.getRealResource("gdriver");
1158                if(!gDir.exists())gDir.mkdirs();
1159    
1160                f=gDir.getRealResource("Gateway.cfc");
1161                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/gdriver/Gateway.cfc",f);
1162    
1163                f=gDir.getRealResource("DirectoryWatcher.cfc");
1164                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/gdriver/DirectoryWatcher.cfc",f);
1165                
1166                f=gDir.getRealResource("MailWatcher.cfc");
1167                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/gdriver/MailWatcher.cfc",f);
1168                
1169                f=gDir.getRealResource("Field.cfc");
1170                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/gdriver/Field.cfc",f);
1171    
1172                f=gDir.getRealResource("Group.cfc");
1173                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/gdriver/Group.cfc",f);
1174                            
1175            // C DRIVER
1176                Resource cDir = adminDir.getRealResource("cdriver");
1177                if(!cDir.exists())cDir.mkdirs();
1178    
1179                f=cDir.getRealResource("Cache.cfc");
1180                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/cdriver/Cache.cfc",f);
1181                
1182                f=cDir.getRealResource("RamCache.cfc");
1183                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/cdriver/RamCache.cfc",f);
1184                
1185                f=cDir.getRealResource("EHCacheLite.cfc");
1186                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/cdriver/EHCacheLite.cfc",f);
1187    
1188                f=cDir.getRealResource("Field.cfc");
1189                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/cdriver/Field.cfc",f);
1190    
1191                f=cDir.getRealResource("Group.cfc");
1192                if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/cdriver/Group.cfc",f);
1193                           
1194                                    
1195            
1196        // DB DRIVER
1197            Resource dbDir = adminDir.getRealResource("dbdriver");
1198            if(!dbDir.exists())dbDir.mkdirs();
1199            
1200            f=dbDir.getRealResource("Driver.cfc");
1201            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/Driver.cfc",f);
1202            
1203            f=dbDir.getRealResource("HSQLDB.cfc");
1204            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/HSQLDB.cfc",f);
1205    
1206            f=dbDir.getRealResource("H2.cfc");
1207            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/H2.cfc",f);
1208    
1209            f=dbDir.getRealResource("MSSQL.cfc");
1210            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/MSSQL.cfc",f);
1211    
1212            f=dbDir.getRealResource("MSSQL2.cfc");
1213            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/MSSQL2.cfc",f);
1214            
1215            f=dbDir.getRealResource("DB2.cfc");
1216            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/DB2.cfc",f);
1217            
1218            f=dbDir.getRealResource("Oracle.cfc");
1219            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/Oracle.cfc",f);
1220            
1221            f=dbDir.getRealResource("MySQL.cfc");
1222            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/MySQL.cfc",f);
1223    
1224            f=dbDir.getRealResource("ODBC.cfc");
1225            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/ODBC.cfc",f);
1226    
1227            f=dbDir.getRealResource("Sybase.cfc");
1228            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/Sybase.cfc",f);
1229    
1230            f=dbDir.getRealResource("PostgreSql.cfc");
1231            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/PostgreSql.cfc",f);
1232            
1233            f=dbDir.getRealResource("Other.cfc");
1234            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/Other.cfc",f);
1235            
1236            f=dbDir.getRealResource("Firebird.cfc");
1237            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/Firebird.cfc",f);
1238            
1239            Resource typesDir = dbDir.getRealResource("types");
1240            if(!typesDir.exists())typesDir.mkdirs();
1241            
1242            f=typesDir.getRealResource("Field.cfc");
1243            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/admin/dbdriver/types/Field.cfc",f);
1244    
1245            Resource templatesDir = contextDir.getRealResource("templates");
1246            if(!templatesDir.exists())templatesDir.mkdirs();
1247            
1248            Resource errorDir = templatesDir.getRealResource("error");
1249            if(!errorDir.exists())errorDir.mkdirs();
1250    
1251            f=errorDir.getRealResource("error.cfm");
1252            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/error/error.cfm",f);
1253    
1254            f=errorDir.getRealResource("error-neo.cfm");
1255            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/error/error-neo.cfm",f);
1256    
1257            f=errorDir.getRealResource("error-public.cfm");
1258            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/error/error-public.cfm",f);
1259            
1260            Resource debuggingDir = templatesDir.getRealResource("debugging");
1261            if(!debuggingDir.exists())debuggingDir.mkdirs();
1262            
1263            f=debuggingDir.getRealResource("debugging.cfm");
1264            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/debugging/debugging.cfm",f);
1265            
1266            f=debuggingDir.getRealResource("debugging-cascade.cfm");
1267            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/debugging/debugging-cascade.cfm",f);
1268            
1269            f=debuggingDir.getRealResource("debugging-comment.cfm");
1270            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/debugging/debugging-comment.cfm",f);
1271    
1272            f=debuggingDir.getRealResource("debugging-neo.cfm");
1273            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/debugging/debugging-neo.cfm",f);
1274    
1275            f=debuggingDir.getRealResource("debugging-2-console.cfm");
1276            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/debugging/debugging-2-console.cfm",f);
1277            
1278            //f=debuggingDir.getRealResource("debugging-stats.cfm");
1279            //if(!f.exists() || doNew)createFileFromResource("/resource/context/templates/debugging/debugging-stats.cfm",f);
1280    
1281            Resource displayDir = templatesDir.getRealResource("display");
1282            if(!displayDir.exists())displayDir.mkdirs();
1283    
1284            f=displayDir.getRealResource("Application.cfm");
1285            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/display/Application.cfm",f);
1286            
1287            f=displayDir.getRealResource("Application.cfc");
1288            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/display/Application.cfc",f);
1289            
1290            f=displayDir.getRealResource("debugging-console-output-pages.cfm");
1291            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/display/debugging-console-output-pages.cfm",f);
1292            
1293            f=displayDir.getRealResource("debugging-console-output-queries.cfm");
1294            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/display/debugging-console-output-queries.cfm",f);
1295    
1296            f=displayDir.getRealResource("debugging-console-output.cfm");
1297            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/display/debugging-console-output.cfm",f);
1298    
1299            f=displayDir.getRealResource("debugging-console.cfm");
1300            if(!f.exists() || doNew)createFileFromResourceEL("/resource/context/templates/display/debugging-console.cfm",f);
1301            
1302            //f=displayDir.getRealResource("debugging-stats.cfm");
1303            //if(!f.exists() || doNew)createFileFromResource("/resource/context/templates/display/debugging-stats.cfm",f);
1304    
1305            
1306            
1307            
1308            
1309            Resource lib = ResourceUtil.toResource(CFMLEngineFactory.getClassLoaderRoot(TP.class.getClassLoader()));
1310            f=lib.getRealResource("jfreechart-patch.jar");
1311            if(!f.exists())createFileFromResourceEL("/resource/lib/jfreechart-patch.jar",f);
1312            
1313            
1314            
1315    
1316            }
1317            
1318    
1319            public static void createContextFilesPost(Resource configDir, ConfigImpl config, ServletConfig servletConfig,boolean isEventGatewayContext,boolean doNew) throws IOException {
1320                    Resource contextDir = configDir.getRealResource("context");
1321                if(!contextDir.exists())contextDir.mkdirs();
1322    
1323                Resource adminDir = contextDir.getRealResource("admin");
1324            if(!adminDir.exists())adminDir.mkdirs();
1325            
1326            
1327        // Plugin
1328            Resource pluginDir = adminDir.getRealResource("plugin");
1329            if(!pluginDir.exists())pluginDir.mkdirs();
1330            
1331            
1332         // deploy org.railo.cfml components
1333            if(config instanceof ConfigWeb){
1334                    ImportDefintion _import = config.getComponentDefaultImport();
1335                    String path = _import.getPackageAsPath();
1336                    Resource components = config.getConfigDir().getRealResource("components");
1337                    Resource dir = components.getRealResource(path);
1338                    dir.mkdirs();
1339                    //print.o(dir);
1340                    ComponentFactory.deploy(dir, doNew);
1341            }
1342            
1343            
1344         // flex
1345            if(!isEventGatewayContext && servletConfig!=null && config.getAMFConfigType()==ConfigImpl.AMF_CONFIG_TYPE_XML){
1346                    String strPath=servletConfig.getServletContext().getRealPath("/WEB-INF");
1347                    Resource webInf = ResourcesImpl.getFileResourceProvider().getResource(strPath);
1348                    
1349                    Resource flex = webInf.getRealResource("flex");
1350                if(!flex.exists())flex.mkdirs();
1351    
1352                Resource f = flex.getRealResource("messaging-config.xml");
1353                if(!f.exists() || doNew)createFileFromResourceEL("/resource/flex/messaging-config.xml",f);
1354                f=flex.getRealResource("proxy-config.xml");
1355                if(!f.exists() || doNew)createFileFromResourceEL("/resource/flex/proxy-config.xml",f);
1356                f=flex.getRealResource("remoting-config.xml");
1357                if(!f.exists() || doNew)createFileFromResourceEL("/resource/flex/remoting-config.xml",f);
1358                f=flex.getRealResource("services-config.xml");
1359                if(!f.exists() || doNew)createFileFromResourceEL("/resource/flex/services-config.xml",f);
1360    
1361            }
1362    
1363            }
1364    
1365            static boolean doNew(Resource contextDir) {
1366                    
1367                    final boolean readonly=false;
1368                    try{
1369                            Resource version=contextDir.getRealResource("version");
1370                            String v=Info.getVersionAsString()+"-"+Info.getStateAsString()+"-"+Info.getRealeaseTime();
1371                            if(!version.exists()) {
1372                                    if(!readonly){
1373                            version.createNewFile();
1374                            IOUtil.write(version,v,SystemUtil.getCharset(),false);
1375                        }
1376                        return true;
1377                    }
1378                    else if(!IOUtil.toString(version,SystemUtil.getCharset()).equals(v)) {
1379                            if(!readonly)IOUtil.write(version,v,SystemUtil.getCharset(),false);
1380            
1381                        return true;
1382                    }
1383                    }
1384                    catch(Throwable t){}
1385            return false;
1386        }
1387            
1388            private static void doCheckChangesInLibraries(ConfigImpl config) {
1389                    // create current hash from libs
1390                    TagLib[] tlds = config.getTLDs();
1391                    FunctionLib[] flds = config.getFLDs();
1392                    StringBuffer sb=new StringBuffer(config.getTemplateCharset());
1393    
1394                    for(int i=0;i<tlds.length;i++){
1395                            sb.append(tlds[i].getHash());
1396                    }
1397    
1398                    for(int i=0;i<flds.length;i++){
1399                            sb.append(flds[i].getHash());
1400                    }
1401                    
1402                    boolean hasChanged=false;
1403                    try {
1404                            String hashValue=Md5.getDigestAsString(sb.toString());
1405                    
1406                            // check and compare lib version file
1407                            Resource contextDir = config.getConfigDir();
1408                            Resource libHash=contextDir.getRealResource("lib-hash");
1409                            
1410                    if(!libHash.exists()) {
1411                        libHash.createNewFile();
1412                        IOUtil.write(libHash,hashValue,SystemUtil.getCharset(),false);
1413                        
1414                        hasChanged= true;
1415                    }
1416                    else if(!IOUtil.toString(libHash,SystemUtil.getCharset()).equals(hashValue)) {
1417                        IOUtil.write(libHash,hashValue,SystemUtil.getCharset(),false);
1418                        hasChanged= true;
1419                    }
1420                    } 
1421                    catch (IOException e) {}
1422            // chnage Compile type
1423            if(hasChanged) {
1424                    try {
1425                                    config.getDeployDirectory().remove(true);
1426                            } 
1427                    catch (IOException e) {
1428                                    e.printStackTrace(config.getErrWriter());
1429                            }
1430            }
1431            
1432        }
1433    
1434    
1435        /**
1436             * load mapings from XML Document
1437             * @param configServer
1438             * @param config
1439         * @param doc
1440             * @throws IOException
1441         */
1442        private static void loadMappings(ConfigServerImpl configServer, ConfigImpl config,Document doc) throws IOException {
1443            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_MAPPING);
1444            Element el= getChildByName(doc.getDocumentElement(),"mappings");
1445            
1446            
1447            String strLogger=el.getAttribute("log");
1448            int logLevel=LogUtil.toIntType(el.getAttribute("log-level"),Log.LEVEL_ERROR);
1449            if(StringUtil.isEmpty(strLogger)){
1450                    if(configServer!=null){
1451                            LogAndSource log = configServer.getMailLogger();
1452                            strLogger=log.getSource();
1453                            logLevel=log.getLogLevel();
1454                    }
1455                    else strLogger="{railo-config}/logs/mapping.log";
1456            }
1457            
1458            config.setMappingLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel));
1459            
1460            
1461            
1462            Element[] _mappings=getChildren(el,"mapping");
1463            
1464            HashTable mappings=new HashTable();
1465            Mapping tmp;
1466            
1467            if(configServer!=null && config instanceof ConfigWeb) {
1468                Mapping[] sm=configServer.getMappings();
1469                for(int i=0;i<sm.length;i++) {
1470                
1471                    if(!sm[i].isHidden()) {
1472                        if(sm[i] instanceof MappingImpl) {
1473                            tmp = ((MappingImpl)sm[i]).cloneReadOnly(config);
1474                            mappings.put(tmp.getVirtualLowerCase(),tmp);
1475                            
1476                        }
1477                        else {
1478                            tmp = sm[i];
1479                            mappings.put(tmp.getVirtualLowerCase(),tmp);
1480                        }
1481                    }
1482                }
1483            }
1484            
1485            boolean finished = false;
1486            
1487            if(hasAccess) {
1488                    for(int i=0;i<_mappings.length;i++) {
1489                       el=_mappings[i];
1490                       
1491                       // File physical=getDir(sc,el.getAttribute("physical"),null,configDir);
1492                       // File archive=getFile(sc,el.getAttribute("archive"),null,configDir);
1493                       
1494                       String physical=el.getAttribute("physical");
1495                       String archive=el.getAttribute("archive");
1496                       String virtual=el.getAttribute("virtual");
1497                       boolean readonly=toBoolean(el.getAttribute("readonly"),false);
1498                       boolean hidden=toBoolean(el.getAttribute("hidden"),false);
1499                       boolean toplevel=toBoolean(el.getAttribute("toplevel"),true);
1500                       int clMaxEl=toInt(el.getAttribute("classloader-max-elements"),100);
1501                       
1502                       if(virtual.equalsIgnoreCase("/railo-context/"))toplevel=true;
1503                       
1504                       
1505                       
1506                       // physical!=null && 
1507                       if(virtual!=null && (physical!=null || archive!=null)) { 
1508                           boolean trusted=toBoolean(el.getAttribute("trusted"),false);
1509                           String primary=el.getAttribute("primary");
1510                           boolean physicalFirst=primary==null || !primary.equalsIgnoreCase("archive");
1511                           
1512                           tmp=new MappingImpl(config,virtual,physical,archive,trusted,physicalFirst,hidden,readonly,toplevel,false,false,clMaxEl);
1513                           mappings.put(tmp.getVirtualLowerCase(),tmp);
1514                           if(virtual.equals("/")) {
1515                               finished=true;
1516                               //break;
1517                           }
1518                               
1519                       }
1520                    }
1521            }
1522            
1523            if(!finished) {
1524                tmp=new MappingImpl(config,"/","/",null,false,true,true,true,true,false,false);
1525                mappings.put(tmp.getVirtualLowerCase(),tmp);
1526            }
1527            
1528            Mapping[] arrMapping=new Mapping[mappings.size()];
1529            int index=0;
1530            Iterator it = mappings.keySet().iterator();
1531            while(it.hasNext()) {
1532                arrMapping[index++]=(Mapping) mappings.get(it.next());
1533            }
1534            config.setMappings(arrMapping);
1535            //config.setMappings((Mapping[]) mappings.toArray(new Mapping[mappings.size()]));
1536        }
1537        
1538        
1539        private static void loadFlex(ConfigServerImpl configServer, ConfigImpl config,Document doc) {
1540            
1541            Element el= getChildByName(doc.getDocumentElement(),"flex");
1542            if(configServer!=null);
1543            
1544            // deploy
1545            String strConfig = el.getAttribute("configuration");
1546            if(!StringUtil.isEmpty(strConfig))
1547                    config.setAMFConfigType(strConfig);
1548            else if(configServer!=null)
1549                    config.setAMFConfigType(configServer.getAMFConfigType());
1550            
1551            // caster
1552            String strCaster = el.getAttribute("caster");
1553            if(StringUtil.isEmpty(strCaster))strCaster = el.getAttribute("caster-class");
1554            
1555            // arguments
1556            String strArgs = el.getAttribute("caster-arguments");
1557            if(StringUtil.isEmpty(strArgs))strArgs = el.getAttribute("caster-class-arguments");
1558            toArguments(strArgs);
1559            
1560            if(!StringUtil.isEmpty(strCaster))config.setAMFCaster(strCaster,toArguments(strArgs));
1561            else if(configServer!=null)config.setAMFCaster(config.getAMFCasterClass(), config.getAMFCasterArguments());
1562            
1563            
1564        }
1565        
1566        private static void loadExeLog(ConfigServerImpl configServer, ConfigImpl config,Document doc) {
1567            
1568            boolean hasServer=configServer!=null;
1569            
1570            Element el= getChildByName(doc.getDocumentElement(),"execution-log");
1571            
1572            // enabled
1573            Boolean bEnabled = Caster.toBoolean(el.getAttribute("enabled"),null);
1574            if(bEnabled==null){
1575                    if(hasServer)config.setExecutionLogEnabled(configServer.getExecutionLogEnabled());
1576            }
1577            else 
1578                    config.setExecutionLogEnabled(bEnabled.booleanValue());
1579           
1580            boolean hasChanged=false;
1581            String val=Caster.toString(config.getExecutionLogEnabled());
1582            try {
1583                            Resource contextDir = config.getConfigDir();
1584                            Resource exeLog=contextDir.getRealResource("exe-log");
1585                            
1586                    if(!exeLog.exists()) {
1587                            exeLog.createNewFile();
1588                        IOUtil.write(exeLog,val,SystemUtil.getCharset(),false);
1589                        hasChanged= true;
1590                    }
1591                    else if(!IOUtil.toString(exeLog,SystemUtil.getCharset()).equals(val)) {
1592                        IOUtil.write(exeLog,val,SystemUtil.getCharset(),false);
1593                        hasChanged= true;
1594                    }
1595                    } 
1596                    catch (IOException e) {}
1597            
1598            
1599                    if(hasChanged) {
1600                    try {
1601                                    if(config.getDeployDirectory().exists())config.getDeployDirectory().remove(true);
1602                            } 
1603                    catch (IOException e) {
1604                                    e.printStackTrace(config.getErrWriter());
1605                            }
1606            }
1607            
1608            
1609            
1610            
1611            // class
1612            String strClass = el.getAttribute("class");
1613            Class clazz;
1614            if(!StringUtil.isEmpty(strClass)){
1615                    try{
1616                                    if("console".equalsIgnoreCase(strClass)) 
1617                                            clazz=ConsoleExecutionLog.class;
1618                            else {
1619                                    Class c = ClassUtil.loadClass(strClass);
1620                                    if((c.newInstance() instanceof ExecutionLog)) {
1621                                            clazz=c;
1622                                    }
1623                                    else {
1624                                            clazz=ConsoleExecutionLog.class;
1625                                            SystemOut.printDate(config.getErrWriter(),"class ["+strClass+"] must implement the interface "+ExecutionLog.class.getName());
1626                                    }
1627                            }
1628                    }
1629                    catch(Exception e){
1630                            clazz=ConsoleExecutionLog.class;
1631                    }
1632                 // arguments
1633                    String strArgs = el.getAttribute("arguments");
1634                    if(StringUtil.isEmpty(strArgs))strArgs = el.getAttribute("class-arguments");
1635                    Map<String, String> args = toArguments(strArgs);
1636    
1637                    config.setExecutionLogFactory(new ExecutionLogFactory(clazz,args));
1638            }
1639            else {
1640                    if(hasServer)
1641                            config.setExecutionLogFactory(configServer.getExecutionLogFactory());
1642                    else
1643                            config.setExecutionLogFactory(new ExecutionLogFactory(ConsoleExecutionLog.class,new HashMap<String, String>()));
1644            }
1645        }
1646        
1647        
1648        /**
1649         * loads and sets the Page Pool
1650         * @param configServer
1651         * @param config
1652         * @param doc
1653         */
1654        private static void loadPagePool(ConfigServer configServer, Config config, Document doc) {
1655            // TODO xml configuration fr das erstellen
1656            // config.setPagePool( new PagePool(10000,1000));
1657        }
1658        
1659    
1660        /**
1661         * loads datasource settings from XMl DOM
1662         * @param configServer
1663         * @param config
1664         * @param doc
1665         * @throws ClassNotFoundException
1666         */
1667        private static void loadDataSources(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws ClassException {
1668            
1669            // When set to true, makes JDBC use a representation for DATE data that is compatible with the Oracle8i database.
1670            System.setProperty("oracle.jdbc.V8Compatible", "true");
1671            
1672            boolean hasCS=configServer!=null;
1673            HashTable datasources=new HashTable();
1674            
1675            // Copy Parent datasources as readOnly
1676            if(hasCS) {
1677                Map ds = configServer.getDataSourcesAsMap();
1678                Iterator it = ds.keySet().iterator();
1679                while(it.hasNext()) {
1680                            Object key=it.next();
1681                            if(!key.equals("_queryofquerydb"))
1682                                datasources.put(key,((DataSource)ds.get(key)).cloneReadOnly());
1683                        }
1684                    }
1685            
1686            // TODO support H2
1687            // Default query of query DB
1688                    /*setDatasource(datasources,
1689                            "_queryofquerydb"
1690                            ,"org.h2.Driver"
1691                ,""
1692                ,""
1693                ,-1
1694                            ,"jdbc:h2:.;MODE=HSQLDB"
1695                            ,"sa"
1696                            ,""
1697                ,-1
1698                ,-1
1699                ,true
1700                ,true
1701                ,DataSource.ALLOW_ALL,
1702                new StructImpl()
1703                    );*/
1704    //      Default query of query DB
1705                    setDatasource(config,datasources,
1706                            "_queryofquerydb"
1707                            ,"org.hsqldb.jdbcDriver"
1708                ,""
1709                ,""
1710                ,-1
1711                            ,"jdbc:hsqldb:."
1712                            ,"sa"
1713                            ,""
1714                ,-1
1715                ,-1
1716                ,60000
1717                ,true
1718                ,true
1719                ,DataSource.ALLOW_ALL
1720                ,false
1721                ,false
1722                ,null
1723                ,new StructImpl()
1724                    );
1725    
1726                    SecurityManager sm = config.getSecurityManager();
1727            short access = sm.getAccess(SecurityManager.TYPE_DATASOURCE);
1728            int accessCount=-1;
1729            if(access==SecurityManager.VALUE_YES) accessCount=-1;
1730            else if(access==SecurityManager.VALUE_NO) accessCount=0;
1731            else if(access>=SecurityManager.VALUE_1 && access<=SecurityManager.VALUE_10){
1732                    accessCount=access-SecurityManager.NUMBER_OFFSET;
1733            }
1734            
1735                    
1736                    
1737            // Databases
1738                    Element databases=getChildByName(doc.getDocumentElement(),"data-sources");
1739                    //if(databases==null)databases=doc.createElement("data-sources");
1740                    
1741                    
1742                    
1743                    // PSQ 
1744                    String strPSQ=databases.getAttribute("psq");
1745                    if(StringUtil.isEmpty(strPSQ)){
1746                            // prior version was buggy, was the opposite
1747                            strPSQ=databases.getAttribute("preserve-single-quote");
1748                            if(!StringUtil.isEmpty(strPSQ)){
1749                                    Boolean b=Caster.toBoolean(strPSQ,null);
1750                                    if(b!=null)strPSQ=b.booleanValue()?"false":"true";
1751                            }
1752                    }
1753                    if(access!=SecurityManager.VALUE_NO && !StringUtil.isEmpty(strPSQ)) {
1754                      config.setPSQL(toBoolean(strPSQ,true));
1755                    }
1756                    else if(hasCS)config.setPSQL(configServer.getPSQL());
1757                    
1758            
1759                    // Data Sources 
1760                    Element[] dataSources=getChildren(databases,"data-source");
1761                    if(accessCount==-1)accessCount=dataSources.length;
1762                    if(dataSources.length<accessCount)accessCount=dataSources.length;
1763                            
1764                            
1765                            
1766                      //if(hasAccess) {
1767                              for(int i=0;i<accessCount;i++) {
1768                    Element dataSource=dataSources[i];
1769                                    if(dataSource.hasAttribute("database")) {
1770                        setDatasourceEL(config,datasources,
1771                                             dataSource.getAttribute("name")
1772                                            ,dataSource.getAttribute("class")
1773                            ,dataSource.getAttribute("host")
1774                            ,dataSource.getAttribute("database")
1775                            ,toInt(dataSource.getAttribute("port"),-1)
1776                            ,dataSource.getAttribute("dsn")
1777                                            ,dataSource.getAttribute("username")
1778                            ,decrypt(dataSource.getAttribute("password"))
1779                            ,toInt(dataSource.getAttribute("connectionLimit"),-1)
1780                            ,toInt(dataSource.getAttribute("connectionTimeout"),-1)
1781                            ,toLong(dataSource.getAttribute("metaCacheTimeout"),60000)
1782                            ,toBoolean(dataSource.getAttribute("blob"),true)
1783                            ,toBoolean(dataSource.getAttribute("clob"),true)
1784                            ,toInt(dataSource.getAttribute("allow"),DataSource.ALLOW_ALL)
1785                            ,toBoolean(dataSource.getAttribute("validate"),false)
1786                            ,toBoolean(dataSource.getAttribute("storage"),false)
1787                            ,dataSource.getAttribute("timezone")
1788                            ,toStruct(dataSource.getAttribute("custom"))
1789                                    );
1790                                    }
1791                              }
1792                      //}
1793                      config.setDataSources(datasources);
1794            }
1795    
1796        /**
1797         * @param configServer
1798         * @param config
1799         * @param doc
1800         */
1801        /**
1802         * @param configServer
1803         * @param config
1804         * @param doc
1805         */
1806        private static void loadCache(ConfigServerImpl configServer, ConfigImpl config, Document doc)  {
1807            boolean hasCS=configServer!=null;
1808            HashTable caches=new HashTable();
1809            
1810    
1811            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManagerImpl.TYPE_CACHE);
1812                    //print.o("LOAD CACHE:"+hasAccess+":"+hasCS);
1813    
1814            
1815            Element eCache=getChildByName(doc.getDocumentElement(),"cache");
1816            
1817            // has changes
1818            
1819            String md5=getMD5(eCache,hasCS?configServer.getCacheMD5():"");
1820            if(md5.equals(config.getCacheMD5())) return;
1821            config.setCacheMD5(md5);
1822            
1823            // default query
1824            String defaultResource=eCache.getAttribute("default-resource");
1825            if(hasAccess && !StringUtil.isEmpty(defaultResource)){
1826                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE,defaultResource);
1827            }
1828            else if(hasCS){
1829                    if(eCache.hasAttribute("default-resource"))
1830                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE,"");
1831                    else
1832                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE,configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE));
1833            }
1834            else 
1835                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE,"");
1836        
1837            // default query
1838            String defaultQuery=eCache.getAttribute("default-query");
1839            if(hasAccess && !StringUtil.isEmpty(defaultQuery)){
1840                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY,defaultQuery);
1841            }
1842            else if(hasCS){
1843                    if(eCache.hasAttribute("default-query"))
1844                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY,"");
1845                    else
1846                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY,configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY));
1847            }
1848            else 
1849                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY,"");
1850            
1851            
1852                    // default template
1853            String defaultTemplate=eCache.getAttribute("default-template");
1854            if(hasAccess && !StringUtil.isEmpty(defaultTemplate)){
1855                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE,defaultTemplate);
1856            }
1857            else if(hasCS){
1858                    if(eCache.hasAttribute("default-template"))
1859                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE,"");
1860                    else
1861                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE,configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE));
1862            }
1863            else 
1864                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE,"");
1865                
1866            // default object
1867            String defaultObject=eCache.getAttribute("default-object");
1868            if(hasAccess && !StringUtil.isEmpty(defaultObject)){
1869                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT,defaultObject);
1870            }
1871            else if(hasCS){
1872                    if(eCache.hasAttribute("default-object"))
1873                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT,"");
1874                    else
1875                            config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT,configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT));
1876            }
1877            else    
1878                    config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT,"");
1879                 
1880                
1881            
1882                    // cache connections
1883            Element[] eConnections=getChildren(eCache,"connection");
1884                    
1885                    //if(hasAccess) {
1886                    String name,clazzName;
1887                    CacheConnection cc;
1888                    Class cacheClazz;
1889                    // caches
1890                    if(hasAccess)for(int i=0;i<eConnections.length;i++) {
1891                    Element eConnection=eConnections[i];
1892                    name=eConnection.getAttribute("name");
1893                    clazzName=eConnection.getAttribute("class");
1894                    if(clazzName!=null) clazzName=clazzName.trim();
1895                    
1896                    //
1897                                    try{
1898                                            
1899                            // Workaround for old EHCacheLite class defintion
1900                            if("railo.extension.io.cache.eh.EHCacheLite".equals(clazzName)) cacheClazz=EHCacheLite.class;
1901                            else cacheClazz=ClassUtil.loadClass(config.getClassLoader(),clazzName);
1902                    
1903                                            cc=new CacheConnectionImpl(config,
1904                                            name,
1905                                            cacheClazz,
1906                                    toStruct(eConnection.getAttribute("custom")),
1907                                    Caster.toBooleanValue(eConnection.getAttribute("read-only"),false),
1908                                    Caster.toBooleanValue(eConnection.getAttribute("storage"),false)
1909                                    );
1910                                            if(!StringUtil.isEmpty(name)){
1911                                                    caches.put(name.toLowerCase(),cc);
1912                                            }
1913                                            else
1914                                                    SystemOut.print(config.getErrWriter(), "missing cache name");
1915                            
1916                                    }
1917                                    catch(ClassException ce){
1918                                            SystemOut.print(config.getErrWriter(), ce.getMessage());
1919                                    }catch (IOException e) {
1920                                            SystemOut.print(config.getErrWriter(), e.getMessage());
1921                                    }
1922                              }
1923                      //}
1924                      
1925                    // call static init once per driver
1926                    {
1927                            // group by classes
1928                            Map _caches=new HashMap();
1929                            Iterator it = caches.entrySet().iterator();
1930                            Map.Entry entry;
1931                            ArrayList list;
1932                            while(it.hasNext()){
1933                                    entry=(Entry) it.next();
1934                                    cc=(CacheConnection) entry.getValue();
1935                                    list=(ArrayList) _caches.get(cc.getClazz());
1936                                    if(list==null){
1937                                            list=new ArrayList();
1938                                            _caches.put(cc.getClazz(), list);
1939                                    }
1940                                    list.add(cc);
1941                            }
1942                            
1943                            // call
1944                            it=_caches.entrySet().iterator();
1945                            Class clazz;
1946                            while(it.hasNext()){
1947                                    entry=(Entry) it.next();
1948                                    list= (ArrayList) entry.getValue();
1949                                    clazz= (Class) entry.getKey();
1950                                    try {
1951                                            Method m = clazz.getMethod("init", new Class[]{Config.class,String[].class,Struct[].class});
1952                                            
1953                                            m.invoke(null, new Object[]{config,_toCacheNames(list),_toArguments(list)});
1954                                    } catch (InvocationTargetException e) {
1955                                            e.getTargetException().printStackTrace();
1956                                    } catch (RuntimeException e) {
1957                                            e.printStackTrace();
1958                                    } catch (NoSuchMethodException e) {
1959                                            SystemOut.print(config.getErrWriter(),"missing method [public static init(Config,String[],Struct[]):void] for class ["+clazz.getName()+"] ");
1960                                    }  
1961                                    catch (Throwable e) {
1962                                            e.printStackTrace();
1963                                    }
1964                            }
1965                    }
1966                    
1967                    
1968                    // Copy Parent caches as readOnly
1969            if(hasCS) {
1970                Map ds = configServer.getCacheConnections();
1971                //print.o("PARENT");
1972                //print.o(ds);
1973                Iterator it = ds.entrySet().iterator();
1974                Map.Entry entry;
1975                while(it.hasNext()) {
1976                            entry=(Entry) it.next();
1977                            cc=((CacheConnection)entry.getValue());
1978                            if(!caches.containsKey(entry.getKey()))caches.put(entry.getKey(),new ServerCacheConnection(configServer,cc));
1979                    }
1980                }
1981            config.setCaches(caches);
1982            }
1983    
1984    
1985        private static String getMD5(Node node,String parentMD5) {
1986                    try {
1987                            return MD5.getDigestAsString(XMLCaster.toString(node,"")+":"+parentMD5);
1988                    } catch (IOException e) {
1989                            return "";
1990                    }
1991            }
1992    
1993    
1994            private static void loadGatewayEL(ConfigServerImpl configServer, ConfigImpl config, Document doc)  {
1995                    try {
1996                            loadGateway(configServer, config, doc);
1997                    } catch (Throwable t) {
1998                            t.printStackTrace();
1999                    }
2000            }
2001    
2002            private static void loadGateway(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws IOException  {
2003                    boolean hasCS=configServer!=null;
2004                    if(!hasCS) return;
2005                    ConfigWebImpl cw=(ConfigWebImpl) config;
2006                    
2007            Map<String, GatewayEntry> mapGateways=new HashMap<String, GatewayEntry>();
2008            
2009            Resource configDir=config.getConfigDir();
2010            Element eGateWay=getChildByName(doc.getDocumentElement(),"gateways");
2011            
2012            String strCFCDirectory = ConfigWebUtil.translateOldPath(eGateWay.getAttribute("cfc-directory"));
2013                    if(StringUtil.isEmpty(strCFCDirectory))strCFCDirectory="{railo-config}/gateway/";
2014                    
2015                    // Deploy Dir
2016                    //Resource cfcDirectory = ConfigWebUtil.getFile(configDir,strCFCDirectory, "gateway",configDir,FileUtil.TYPE_DIR,config);
2017                    
2018                    boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManagerImpl.TYPE_GATEWAY);
2019                    
2020            // Logger
2021            String strLogger=hasAccess?eGateWay.getAttribute("log"):"";
2022            //if(StringUtil.isEmpty(strLogger) && hasCS) strLogger=configServer.getGatewayLogger().getSource();
2023            if(StringUtil.isEmpty(strLogger))strLogger="{railo-config}/logs/gateway.log";
2024            
2025            int logLevel=LogUtil.toIntType(eGateWay.getAttribute("log-level"),-1);
2026            if(logLevel==-1 && hasCS)
2027                    logLevel=configServer.getMailLogger().getLogLevel();
2028            if(logLevel==-1)logLevel=Log.LEVEL_ERROR;
2029            cw.setGatewayLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,hasAccess,logLevel));
2030            
2031            GatewayEntry ge; 
2032        
2033            
2034                    // cache connections
2035            Element[] gateways=getChildren(eGateWay,"gateway");
2036                    
2037                    //if(hasAccess) {
2038                    String id;
2039                    GatewayEngineImpl engine = cw.getGatewayEngine();
2040                    //engine.reset();
2041                    
2042                    // caches
2043                    if(hasAccess){
2044                            for(int i=0;i<gateways.length;i++) {
2045                                    Element eConnection=gateways[i];
2046                                    id=eConnection.getAttribute("id").trim().toLowerCase();
2047                
2048                                    ge=new GatewayEntryImpl(engine,
2049                                                    id,
2050                                            eConnection.getAttribute("class"),
2051                                                    eConnection.getAttribute("cfc-path"),
2052                                            eConnection.getAttribute("listener-cfc-path"),
2053                                                    eConnection.getAttribute("startup-mode"),
2054                                            toStruct(eConnection.getAttribute("custom")),
2055                                            Caster.toBooleanValue(eConnection.getAttribute("read-only"),false));
2056                                    
2057                                    if(!StringUtil.isEmpty(id)){
2058                                            mapGateways.put(id.toLowerCase(),ge);
2059                                    }
2060                                    else
2061                                            SystemOut.print(config.getErrWriter(), "missing id");
2062                            }
2063                            cw.setGatewayEntries(mapGateways);
2064                    }
2065                    else {
2066                            try {
2067                                    cw.getGatewayEngine().clear();
2068                            } catch (PageException e) {e.printStackTrace();}
2069                    }
2070            }
2071        
2072        private static Struct[] _toArguments(ArrayList list) {
2073            Iterator it = list.iterator();
2074            Struct[] args=new Struct[list.size()];
2075            CacheConnection cc;
2076            int index=0;
2077            while(it.hasNext()){
2078                    cc=(CacheConnection) it.next();
2079                    args[index++]=cc.getCustom();
2080            }
2081            return args;
2082        }
2083    
2084    
2085            private static String[] _toCacheNames(ArrayList list) {
2086            Iterator it = list.iterator();
2087            String[] names=new String[list.size()];
2088            CacheConnection cc;
2089            int index=0;
2090            while(it.hasNext()){
2091                    cc=(CacheConnection) it.next();
2092                    names[index++]=cc.getName();
2093            }
2094            return names;
2095        }
2096    
2097    
2098            protected static String decrypt(String str) {
2099                    if(StringUtil.isEmpty(str) || !StringUtil.startsWithIgnoreCase(str, "encrypted:")) return str;
2100                    str=str.substring(10);
2101                    return new BlowfishEasy("sdfsdfs").decryptString(str);
2102            }
2103        protected static String encrypt(String str) {
2104            if(StringUtil.isEmpty(str)) return "";
2105            if(StringUtil.startsWithIgnoreCase(str, "encrypted:")) return str;
2106                    return "encrypted:"+new BlowfishEasy("sdfsdfs").encryptString(str);
2107            }
2108    
2109    
2110            private static Struct toStruct(String str) {
2111                    
2112            Struct sct=new StructImpl();
2113            try {
2114                String[] arr = List.toStringArray(List.listToArrayRemoveEmpty(str,'&'));
2115                
2116                String[] item;
2117                for(int i=0;i<arr.length;i++) {
2118                    item = List.toStringArray(List.listToArrayRemoveEmpty(arr[i],'='));
2119                    if(item.length==2) sct.setEL(KeyImpl.getInstance(URLDecoder.decode(item[0],true).trim()),URLDecoder.decode(item[1],true));
2120                    else if(item.length==1) sct.setEL(KeyImpl.getInstance(URLDecoder.decode(item[0],true).trim()),"");
2121                }   
2122            }
2123            catch(PageException ee) {}
2124            
2125            return sct;
2126        }
2127    
2128    
2129        private static void setDatasource(ConfigImpl config,Map<String,DataSource> datasources,String datasourceName, String className, String server, 
2130                String databasename, int port, String dsn, String user, String pass, 
2131                int connectionLimit, int connectionTimeout, long metaCacheTimeout, boolean blob, boolean clob, int allow,
2132                boolean validate,boolean storage,String timezone, Struct custom) throws ClassException {
2133                    
2134            
2135                    datasources.put(datasourceName.toLowerCase(),
2136              new DataSourceImpl(datasourceName,className, server, dsn, databasename, port, user, pass,connectionLimit,connectionTimeout,
2137                              metaCacheTimeout,blob,clob, allow,custom, false,validate,storage,StringUtil.isEmpty(timezone,true)?null:TimeZoneUtil.toTimeZone(timezone,null)));
2138    
2139        }
2140        private static void setDatasourceEL(ConfigImpl config,Map datasources,String datasourceName, String className, String server, 
2141                String databasename, int port, String dsn, String user, String pass, 
2142                int connectionLimit, int connectionTimeout, long metaCacheTimeout, boolean blob, boolean clob, int allow,boolean validate,
2143                boolean storage,String timezone, Struct custom) {
2144            try {
2145                            setDatasource(config,datasources,datasourceName,className, server, 
2146                                    databasename, port, dsn, user, pass, connectionLimit, connectionTimeout,metaCacheTimeout, blob, clob, allow, validate,storage,timezone,custom);
2147                    } catch (Throwable t) {}
2148        }
2149        
2150        /**
2151         * @param configServer
2152         * @param config
2153         * @param doc
2154         * @throws IOException
2155         */
2156        private static void loadCustomTagsMappings(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
2157                
2158            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_CUSTOM_TAG);
2159            boolean hasCS=configServer!=null;
2160            
2161            Element customTag=getChildByName(doc.getDocumentElement(),"custom-tag");
2162            Element[] ctMappings=getChildren(customTag,"mapping");
2163            //String virtualx="/custom-tag/";
2164            
2165    
2166            // do patch cache
2167            String strDoPathcache=customTag.getAttribute("use-cache-path");
2168            if(hasAccess && !StringUtil.isEmpty(strDoPathcache,true)) {
2169                    config.setUseCTPathCache(Caster.toBooleanValue(strDoPathcache.trim(),true));
2170            }
2171            else if(hasCS) {
2172                config.setUseCTPathCache(configServer.useCTPathCache());
2173            }
2174    
2175            // do custom tag local search
2176            String strDoCTLocalSearch=customTag.getAttribute("custom-tag-local-search");
2177            if(hasAccess && !StringUtil.isEmpty(strDoCTLocalSearch)) {
2178                    config.setDoLocalCustomTag(Caster.toBooleanValue(strDoCTLocalSearch.trim(),true));
2179            }
2180            else if(hasCS) {
2181                config.setDoLocalCustomTag(configServer.doLocalCustomTag());
2182            }
2183    
2184            // do custom tag deep search
2185            String strDoCTDeepSearch=customTag.getAttribute("custom-tag-deep-search");
2186            if(hasAccess && !StringUtil.isEmpty(strDoCTDeepSearch)) {
2187                    config.setDoCustomTagDeepSearch(Caster.toBooleanValue(strDoCTDeepSearch.trim(),false));
2188            }
2189            else if(hasCS) {
2190                config.setDoCustomTagDeepSearch(configServer.doCustomTagDeepSearch());
2191            }
2192    
2193            // extensions
2194            String strExtensions=customTag.getAttribute("extensions");
2195            if(hasAccess && !StringUtil.isEmpty(strExtensions)) {
2196                    try {
2197                                    String[] arr = List.toStringArray(List.listToArrayRemoveEmpty(strExtensions, ","));
2198                                    config.setCustomTagExtensions(List.trimItems(arr));
2199                            } 
2200                    catch (PageException e) {}
2201            }
2202            else if(hasCS) {
2203                config.setCustomTagExtensions(configServer.getCustomTagExtensions());
2204            }
2205    
2206            
2207            // Web Mapping
2208            boolean hasSet=false;
2209            Mapping[] mappings=null;
2210            if(hasAccess && ctMappings.length>0) {
2211                    mappings=new Mapping[ctMappings.length];
2212                    for(int i=0;i<ctMappings.length;i++) {
2213                       Element ctMapping=ctMappings[i];
2214                       String physical=ctMapping.getAttribute("physical");
2215                       String archive=ctMapping.getAttribute("archive");
2216                       boolean readonly=toBoolean(ctMapping.getAttribute("readonly"),false);
2217                       boolean hidden=toBoolean(ctMapping.getAttribute("hidden"),false);
2218                       boolean trusted=toBoolean(ctMapping.getAttribute("trusted"),false);
2219                       int clMaxEl=toInt(ctMapping.getAttribute("classloader-max-elements"),100);
2220                       
2221                       String primary=ctMapping.getAttribute("primary");
2222                       
2223                       boolean physicalFirst=archive==null || !primary.equalsIgnoreCase("archive");
2224                       //print.out("xxx:"+physicalFirst);
2225                       hasSet=true;
2226                       mappings[i]= new MappingImpl(config,"/"+i+"/",physical,archive,trusted,physicalFirst,hidden,readonly,true,false,true,clMaxEl);
2227                       //print.out(mappings[i].isPhysicalFirst());
2228                    }
2229                    
2230                    config.setCustomTagMappings(mappings);
2231                    
2232            }
2233            
2234            // Server Mapping
2235            if(hasCS) {
2236                    Mapping[] originals=configServer.getCustomTagMappings();
2237                    Mapping[] clones=new Mapping[originals.length];
2238                    LinkedHashMap map=new LinkedHashMap();
2239                    Mapping m;
2240                    for(int i=0;i<clones.length;i++){
2241                            m=((MappingImpl)originals[i]).cloneReadOnly(config);
2242                            map.put(toKey(m), m);
2243                            //clones[i]=((MappingImpl)m[i]).cloneReadOnly(config);
2244                    }
2245                    
2246                    if(mappings!=null) {
2247                            for(int i=0;i<mappings.length;i++){
2248                            m=mappings[i];
2249                            map.put(toKey(m), m);
2250                    }
2251                    }
2252                if(originals.length>0) {
2253                    clones=new Mapping[map.size()];
2254                    Iterator it = map.entrySet().iterator();
2255                    Map.Entry entry;
2256                    int index=0;
2257                    while(it.hasNext()){
2258                            entry=(Entry) it.next();
2259                            clones[index++]=(Mapping) entry.getValue();
2260                            //print.out("c:"+clones[index-1]);
2261                    }
2262                    hasSet=true;
2263                    //print.err("set:"+clones.length);
2264                    
2265                    config.setCustomTagMappings(clones);
2266                }
2267            }
2268            
2269                if(!hasSet) {
2270                    MappingImpl m=new MappingImpl(config,"/0/","{railo-web}/customtags/",null,false,true,false,false,true,false,true);
2271                    if(m!=null)config.setCustomTagMappings(new Mapping[]{m.cloneReadOnly(config)});
2272                }
2273            
2274        }
2275        
2276        private static Object toKey(Mapping m) {
2277                    if(!StringUtil.isEmpty(m.getStrPhysical(),true)) return m.getStrPhysical().toLowerCase().trim();
2278            return (m.getStrPhysical()+":"+m.getStrArchive()).toLowerCase();
2279            }
2280    
2281    
2282            /**
2283         * @param configServer 
2284         * @param config
2285         * @param doc
2286         */
2287        private static void loadPassword(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
2288                    Element railoConfiguration = doc.getDocumentElement();
2289                    String password=railoConfiguration.getAttribute("password");
2290                    if(!StringUtil.isEmpty(password)) {
2291                        config.setPassword(new BlowfishEasy("tpwisgh").decryptString(password));
2292                    }
2293                    else if (configServer!=null) {
2294                        config.setPassword(configServer.getDefaultPassword());
2295                    }
2296                    
2297                    if(config instanceof ConfigServerImpl) {
2298                        password=railoConfiguration.getAttribute("default-password");
2299                        if(!StringUtil.isEmpty(password))
2300                            ((ConfigServerImpl)config).setDefaultPassword(new BlowfishEasy("tpwisgh").decryptString(password));
2301                    }
2302        }
2303        
2304        
2305        /*private static void loadLabel(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
2306                    // do only for web config
2307            if(configServer!=null && config instanceof ConfigWebImpl) {
2308                            ConfigWebImpl cs=(ConfigWebImpl) config;
2309                            String hash=SystemUtil.hash(cs.getServletContext());
2310                            config.setLabel(hash);
2311                            
2312                            Map<String, String> labels = configServer.getLabels();
2313                            if(labels!=null) {
2314                                    String label = labels.get(hash);
2315                                    if(!StringUtil.isEmpty(label)) {
2316                                            print.o("label:"+label);
2317                                            config.setLabel(label);
2318                                            config.getFactory().setLabel(label);
2319                                    }
2320                            }
2321                    }
2322        }*/
2323    
2324    
2325        private static void loadTag(ConfigServerImpl configServer, ConfigImpl config, Document doc)  {
2326            Element parent=getChildByName(doc.getDocumentElement(),"tags");
2327            Element[] tags=getChildren(parent,"tag");
2328            Element tag;
2329            
2330            String nss,ns,n,c;
2331            if(tags!=null) {
2332                    for(int i=0;i<tags.length;i++) {
2333                            tag=tags[i];
2334                            ns = tag.getAttribute("namespace");
2335                            nss = tag.getAttribute("namespace-seperator");
2336                            n = tag.getAttribute("name");
2337                            c=tag.getAttribute("class");
2338                            config.addTag(ns,nss,n,c);
2339                    }
2340                    }
2341                    
2342        }
2343            
2344        
2345        
2346        private static void loadTempDirectory(ConfigServerImpl configServer, ConfigImpl config, Document doc, boolean isReload) throws ExpressionException, TagLibException, FunctionLibException {
2347            Resource configDir=config.getConfigDir();
2348            boolean hasCS=configServer!=null;
2349            
2350            
2351            Element fileSystem=                             getChildByName(doc.getDocumentElement(),"file-system");
2352                    if(fileSystem==null)fileSystem= getChildByName(doc.getDocumentElement(),"filesystem");
2353                    
2354                    String strTempDirectory=null;
2355                    if(fileSystem!=null) strTempDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("temp-directory"));
2356                    
2357            // Temp Dir
2358                    if(!StringUtil.isEmpty(strTempDirectory)) {
2359                            config.setTempDirectory(ConfigWebUtil.getFile(configDir,strTempDirectory, 
2360                                            null, // create no default
2361                                            configDir,FileUtil.TYPE_DIR,config),!isReload);
2362                    }
2363                    else if(hasCS) {
2364                            config.setTempDirectory(configServer.getTempDirectory(),!isReload);
2365                    }
2366                    if(config.getTempDirectory()==null) {
2367                            config.setTempDirectory(ConfigWebUtil.getFile(configDir,"temp", 
2368                                            null, // create no default
2369                                            configDir,FileUtil.TYPE_DIR,config),!isReload);
2370                    }
2371        }
2372    
2373        /**
2374         * @param configServer 
2375         * @param config
2376         * @param doc
2377         * @throws ExpressionException
2378         * @throws TagLibException
2379         * @throws FunctionLibException
2380         */    
2381        private static void loadFilesystem(ConfigServerImpl configServer, ConfigImpl config, Document doc, boolean doNew) throws ExpressionException, TagLibException, FunctionLibException {
2382            
2383            if(configServer!=null){
2384                    Resource src = configServer.getConfigDir().getRealResource("distribution");
2385                    Resource trg = config.getConfigDir().getRealResource("context/");
2386                    copyContextFiles(src,trg);
2387            }
2388            
2389            
2390            
2391            Resource configDir=config.getConfigDir();
2392            
2393            boolean hasCS=configServer!=null;
2394            
2395            
2396            Element fileSystem=                             getChildByName(doc.getDocumentElement(),"file-system");
2397                    if(fileSystem==null)fileSystem= getChildByName(doc.getDocumentElement(),"filesystem");
2398                    
2399                    String strAllowRealPath=null;
2400                    String strDeployDirectory=null;
2401                    //String strTempDirectory=null;
2402                    String strTLDDirectory=null;
2403                    String strFLDDirectory=null;
2404                    String strTagDirectory=null;
2405                    String strFunctionDirectory=null;
2406                    
2407                    if(fileSystem!=null) {
2408                            strAllowRealPath=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("allow-realpath"));
2409                            strDeployDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("deploy-directory"));
2410                            //strTempDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("temp-directory"));
2411                            strTLDDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("tld-directory"));
2412                            strFLDDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("fld-directory"));
2413                            strTagDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("tag-directory"));
2414                            strFunctionDirectory=ConfigWebUtil.translateOldPath(fileSystem.getAttribute("function-directory"));
2415                    }
2416                    if(StringUtil.isEmpty(strFLDDirectory))strFLDDirectory="{railo-config}/library/fld/";
2417                    if(StringUtil.isEmpty(strTLDDirectory))strTLDDirectory="{railo-config}/library/tld/";
2418                    if(StringUtil.isEmpty(strFunctionDirectory))strFunctionDirectory="{railo-config}/library/function/";
2419                    if(StringUtil.isEmpty(strTagDirectory))strTagDirectory="{railo-config}/library/tag/";
2420                     
2421                    // Deploy Dir
2422                    // gateway must run in server env
2423                    //if(!(config instanceof ConfigServer)) {
2424                            Resource dd = ConfigWebUtil.getFile(configDir,strDeployDirectory, "cfclasses",configDir,FileUtil.TYPE_DIR,config);
2425                            config.setDeployDirectory(dd);
2426                    //}
2427                    
2428            // Temp Dir
2429                    /*if(!StringUtil.isEmpty(strTempDirectory)) {
2430                            config.setTempDirectory(ConfigWebUtil.getFile(configDir,strTempDirectory, 
2431                                            null, // create no default
2432                                            configDir,FileUtil.TYPE_DIR,config));
2433                    }
2434                    else if(hasCS) {
2435                            config.setTempDirectory(configServer.getTempDirectory());
2436                    }
2437                    if(config.getTempDirectory()==null) {
2438                            config.setTempDirectory(ConfigWebUtil.getFile(configDir,"temp", 
2439                                            null, // create no default
2440                                            configDir,FileUtil.TYPE_DIR,config));
2441                    }*/
2442    
2443            // TLD Dir
2444                    //if(hasCS) {
2445                    //      config.setTldFile(configServer.getTldFile());
2446                    //}
2447                    if(strTLDDirectory!=null) {
2448                            Resource tld=ConfigWebUtil.getFile(config,configDir,strTLDDirectory,FileUtil.TYPE_DIR);
2449                            //print.err(tld);
2450                      if(tld!=null) config.setTldFile(tld);
2451                    }
2452                    
2453                    // Tag Directory
2454                    if(strTagDirectory!=null) {
2455                            Resource dir=ConfigWebUtil.getFile(config,configDir,strTagDirectory,FileUtil.TYPE_DIR);
2456                            createTagFiles(config,configDir,dir,doNew);
2457                            if(dir!=null) {
2458                                    config.setTagDirectory(dir);
2459                            }
2460                    }
2461                    
2462            // allow realpath
2463                    if(hasCS) {
2464                            config.setAllowRealPath(configServer.allowRealPath());
2465                    }
2466                    if(!StringUtil.isEmpty(strAllowRealPath,true)) {
2467                            config.setAllowRealPath(Caster.toBooleanValue(strAllowRealPath,true));
2468                    }
2469                    
2470                    
2471                    
2472                    
2473                    // FLD Dir
2474                    //if(hasCS) {
2475                    //      config.setFldFile(configServer.getFldFile());
2476                    //}
2477                    if(strFLDDirectory!=null) {
2478                    Resource fld=ConfigWebUtil.getFile(config,configDir,strFLDDirectory,FileUtil.TYPE_DIR);
2479                      if(fld!=null) config.setFldFile(fld);
2480                    }
2481                    
2482    
2483                    // Function Directory
2484                    if(strFunctionDirectory!=null) {
2485                            Resource dir=ConfigWebUtil.getFile(config,configDir,strFunctionDirectory,FileUtil.TYPE_DIR);
2486                            createFunctionFiles(config,configDir,dir,doNew);
2487                      if(dir!=null) config.setFunctionDirectory(dir);
2488                    }
2489                    
2490                    
2491                    /* / Function Dir
2492                    if(strFunctionDirectory!=null) {
2493                            Resource func=ConfigWebUtil.getFile(config,configDir,strFunctionDirectory,FileUtil.TYPE_DIR);
2494                            if(func!=null) config.setFldFile(fld);
2495                    }*/
2496                    
2497        }
2498    
2499    
2500        private static void createTagFiles(Config config,Resource configDir,Resource dir, boolean doNew) {
2501            if(config instanceof ConfigServer){
2502                    Resource f = dir.getRealResource("Dump.cfc");
2503                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/tag/Dump.cfc",f);
2504    
2505            // AJAX
2506                AjaxFactory.deployTags(dir, doNew);
2507               
2508            }
2509            }
2510    
2511        private static void createFunctionFiles(Config config,Resource configDir,Resource dir, boolean doNew) {
2512            
2513            if(config instanceof ConfigServer){
2514                    Resource f = dir.getRealResource("writeDump.cfm");
2515                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/writeDump.cfm",f);
2516                    
2517                f = dir.getRealResource("dump.cfm");
2518                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/dump.cfm",f);
2519                    
2520                f = dir.getRealResource("location.cfm");
2521                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/location.cfm",f);
2522                    
2523                f = dir.getRealResource("threadJoin.cfm");
2524                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/threadJoin.cfm",f);
2525                    
2526                f = dir.getRealResource("threadTerminate.cfm");
2527                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/threadTerminate.cfm",f);
2528                    
2529                f = dir.getRealResource("throw.cfm");
2530                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/throw.cfm",f);
2531                    
2532                f = dir.getRealResource("trace.cfm");
2533                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/trace.cfm",f);
2534                    
2535                f = dir.getRealResource("transactionCommit.cfm");
2536                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/transactionCommit.cfm",f);
2537                    
2538                f = dir.getRealResource("transactionRollback.cfm");
2539                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/transactionRollback.cfm",f);
2540                    
2541                f = dir.getRealResource("writeLog.cfm");
2542                if(!f.exists() || doNew)createFileFromResourceEL("/resource/library/function/writeLog.cfm",f);
2543                
2544                AjaxFactory.deployFunctions(dir, doNew);
2545                
2546            }
2547            }
2548    
2549    
2550            private static void copyContextFiles(Resource src, Resource trg) {
2551            // directory
2552                    if(src.isDirectory()){
2553                            if(trg.exists())trg.mkdirs();
2554                            Resource[] children = src.listResources();
2555                            for(int i=0;i<children.length;i++){
2556                                    copyContextFiles(children[i], trg.getRealResource(children[i].getName()));
2557                            }
2558                    }
2559                    // file
2560                    else if(src.isFile()){
2561                            if(src.lastModified()>trg.lastModified()){   
2562                                    try {   
2563                                            if(trg.exists())trg.remove(true);
2564                                            trg.createFile(true);
2565                                            src.copyTo(trg, false);
2566                                    } catch (IOException e) {
2567                                            e.printStackTrace();
2568                                    }
2569                            }
2570                            
2571                    }
2572            }
2573    
2574    
2575            /**
2576         * @param configServer
2577         * @param config
2578         * @param doc
2579         */
2580        private static void loadUpdate(ConfigServer configServer, Config config, Document doc) {
2581            
2582            // Server
2583            if(config instanceof ConfigServer) {
2584                ConfigServer cs = (ConfigServer) config;
2585                Element update=getChildByName(doc.getDocumentElement(),"update");
2586                
2587                if(update!=null) {
2588                    cs.setUpdateType(update.getAttribute("type"));
2589                    cs.setUpdateLocation(update.getAttribute("location"),null);   
2590                }
2591            }   
2592        }
2593        
2594        private static void loadVideo(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws ApplicationException {
2595            
2596            Element video=config instanceof ConfigServerImpl?getChildByName(doc.getDocumentElement(),"video"):null;
2597            boolean hasCS=configServer!=null;
2598            String str=null;
2599         
2600         // video-executer
2601            if(video!=null){
2602                    str=video.getAttribute("video-executer-class");
2603                    if(StringUtil.isEmpty(str))str=video.getAttribute("video-executer");
2604            }
2605            if(!StringUtil.isEmpty(str)) {
2606                    try{
2607                            Class clazz = ClassUtil.loadClass(config.getClassLoader(),str);
2608                                    if(!Reflector.isInstaneOf(clazz,VideoExecuter.class))
2609                                    throw new ApplicationException("class ["+clazz.getName()+"] does not implement interface ["+VideoExecuter.class.getName()+"]");
2610                                    config.setVideoExecuterClass(clazz);
2611                                    
2612                            } catch (ClassException e) {
2613                                    e.printStackTrace();
2614                            }
2615            }
2616            else if(hasCS)config.setVideoExecuterClass(configServer.getVideoExecuterClass());
2617            
2618        }
2619        
2620        /**
2621         * @param configServer
2622         * @param config
2623         * @param doc
2624         */
2625        private static void loadSetting(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
2626            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
2627            
2628            Element setting=hasAccess?getChildByName(doc.getDocumentElement(),"setting"):null;
2629            boolean hasCS=configServer!=null;
2630            
2631            
2632    
2633            // suppress whitespace
2634            String str=null;
2635            if(setting!=null){
2636                    str=setting.getAttribute("suppress-content");
2637            }
2638            if(!StringUtil.isEmpty(str) && hasAccess) {
2639              config.setSuppressContent(toBoolean(str,false));
2640            }
2641            else if(hasCS)config.setSuppressContent(configServer.isSuppressContent());
2642            
2643            // suppress whitespace
2644            str=null;
2645            if(setting!=null){
2646                    str=setting.getAttribute("suppress-whitespace");
2647                    if(StringUtil.isEmpty(str))str=setting.getAttribute("suppresswhitespace");
2648            }
2649            if(!StringUtil.isEmpty(str) && hasAccess) {
2650              config.setSuppressWhitespace(toBoolean(str,false));
2651            }
2652            else if(hasCS)config.setSuppressWhitespace(configServer.isSuppressWhitespace());
2653    
2654            // show version
2655                    str=null;
2656                    if(setting!=null){
2657                            str=setting.getAttribute("show-version");
2658                            if(StringUtil.isEmpty(str))str=setting.getAttribute("showversion");
2659                    }
2660                    if(!StringUtil.isEmpty(str) && hasAccess) {
2661                        config.setShowVersion(toBoolean(str,true));
2662                    }
2663                    else if(hasCS)config.setShowVersion(configServer.isShowVersion());
2664            
2665            // close connection
2666                   str=null;
2667                   if(setting!=null){
2668                       str=setting.getAttribute("close-connection");
2669                       if(StringUtil.isEmpty(str))str=setting.getAttribute("closeconnection");
2670                   }
2671                   if(!StringUtil.isEmpty(str) && hasAccess) {
2672                     config.setCloseConnection(toBoolean(str,false));
2673                   }
2674                   else if(hasCS)config.setCloseConnection(configServer.closeConnection());
2675    
2676           // content-length 
2677                str=null;
2678                if(setting!=null){
2679                    str=setting.getAttribute("content-length");
2680                    if(StringUtil.isEmpty(str))str=setting.getAttribute("contentlength");
2681                }  
2682                if(!StringUtil.isEmpty(str) && hasAccess) {
2683                    config.setContentLength(toBoolean(str,true));
2684                }
2685              else if(hasCS)config.setContentLength(configServer.contentLength());   
2686                
2687    
2688            // allow-compression
2689                 str=null;
2690                 if(setting!=null){
2691                    str=setting.getAttribute("allow-compression");
2692                    if(StringUtil.isEmpty(str))str=setting.getAttribute("allowcompression");
2693                 }  
2694                 if(!StringUtil.isEmpty(str) && hasAccess) {
2695                    config.setAllowCompression(toBoolean(str,true));
2696                 }
2697               else if(hasCS)config.setAllowCompression(configServer.allowCompression());   
2698                
2699                
2700            }
2701        
2702        private static void loadRemoteClient(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws IOException {
2703            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManagerImpl.TYPE_REMOTE);
2704            
2705            // SNSN
2706            // RemoteClientUsage
2707            
2708            //boolean hasCS=configServer!=null;
2709            Element _clients=getChildByName(doc.getDocumentElement(),"remote-clients");
2710            
2711                 // usage
2712                    String strUsage=_clients.getAttribute("usage");
2713                    Struct sct;
2714                    if(!StringUtil.isEmpty(strUsage))
2715                            sct=toStruct(strUsage);//config.setRemoteClientUsage(toStruct(strUsage));
2716                    else
2717                            sct=new StructImpl();
2718                    // TODO make this generic
2719                    if(configServer!=null){
2720                            String sync = Caster.toString(configServer.getRemoteClientUsage().get("synchronisation", ""),"");
2721                            if(!StringUtil.isEmpty(sync)){
2722                                    sct.setEL("synchronisation", sync);
2723                            }
2724                    }
2725                    config.setRemoteClientUsage(sct);
2726    
2727                 // max-threads
2728                    int maxThreads=Caster.toIntValue(_clients.getAttribute("max-threads"),20);
2729                    
2730                 // Logger
2731                    String strLogger=hasAccess?_clients.getAttribute("log"):null;
2732                    int logLevel=LogUtil.toIntType(_clients.getAttribute("log-level"),Log.LEVEL_ERROR);
2733                    LogAndSource log=ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel);
2734                    config.setRemoteClientLog(log);
2735        
2736            // directory
2737                    Resource file = ConfigWebUtil.getFile(config.getRootDirectory(),_clients.getAttribute("directory"), "client-task",config.getConfigDir(),FileUtil.TYPE_DIR,config);
2738                    config.setRemoteClientDirectory(file);
2739            
2740                    Element[] clients;
2741                    Element client;
2742                    
2743                    if(!hasAccess) clients=new Element[0];
2744                    else clients = getChildren(_clients,"remote-client");
2745                    java.util.List<RemoteClient> list=new ArrayList<RemoteClient>();
2746                    for(int i=0;i<clients.length;i++) {
2747                            client=clients[i];
2748                            // type
2749                            String type = client.getAttribute("type");
2750                            if(StringUtil.isEmpty(type))type="web";
2751                            // url
2752                            String url = client.getAttribute("url");
2753                            String label = client.getAttribute("label");
2754                            if(StringUtil.isEmpty(label)) label=url;
2755                            String sUser = client.getAttribute("server-username");
2756                            String sPass = ConfigWebFactory.decrypt(client.getAttribute("server-password"));
2757                            String aPass = ConfigWebFactory.decrypt(client.getAttribute("admin-password"));
2758                            String aCode = ConfigWebFactory.decrypt(client.getAttribute("security-key"));
2759                            //if(aCode!=null && aCode.indexOf('-')!=-1)continue;
2760                            String usage = client.getAttribute("usage");
2761                            if(usage==null)usage="";
2762                            
2763                            String pUrl = client.getAttribute("proxy-server");
2764                            int pPort = Caster.toIntValue(client.getAttribute("proxy-port"),-1);
2765                            String pUser = client.getAttribute("proxy-username");
2766                            String pPass = ConfigWebFactory.decrypt(client.getAttribute("proxy-password"));
2767                            
2768                            ProxyData pd=null;
2769                            if(!StringUtil.isEmpty(pUrl,true)) {
2770                                    pd=new ProxyDataImpl();
2771                                    pd.setServer(pUrl);
2772                                    if(!StringUtil.isEmpty(pUser)){
2773                                            pd.setUsername(pUser);
2774                                            pd.setPassword(pPass);
2775                                    }
2776                                    if(pPort>0)pd.setPort(pPort);
2777                            }
2778                            list.add(new RemoteClientImpl(label,type,url,sUser,sPass,aPass,pd,aCode,usage));
2779                    }
2780                    if(list.size()>0)config.setRemoteClients((RemoteClient[])list.toArray(new RemoteClient[list.size()]));
2781                    else config.setRemoteClients(new RemoteClient[0]);
2782            
2783            // init spooler engine
2784            Resource dir = config.getRemoteClientDirectory();
2785                    if(dir!=null && !dir.exists())dir.mkdirs();
2786                    if(config.getSpoolerEngine()==null)     {
2787                            config.setSpoolerEngine(new SpoolerEngineImpl(config,dir,"Remote Client Spooler",config.getRemoteClientLog(),maxThreads));
2788                    }
2789                    else    {
2790                            SpoolerEngineImpl engine = (SpoolerEngineImpl) config.getSpoolerEngine();
2791                            engine.setConfig(config);
2792                            engine.setLog(config.getRemoteClientLog());
2793                            engine.setPersisDirectory(dir);
2794                            
2795                    }
2796        }
2797        
2798    
2799        
2800        private static void loadSystem(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
2801            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
2802            
2803            Element sys=hasAccess?getChildByName(doc.getDocumentElement(),"system"):null;
2804            
2805            boolean hasCS=configServer!=null;
2806            
2807            String out=null,err=null;
2808            if(sys!=null){
2809                    out=sys.getAttribute("out");
2810                    err=sys.getAttribute("err");
2811            }
2812            if(!StringUtil.isEmpty(out) && hasAccess) {
2813              config.setOut(toPrintwriter(config,out,false));
2814            }
2815            else if(hasCS)config.setOut(configServer.getOutWriter());
2816            
2817            if(!StringUtil.isEmpty(err) && hasAccess) {
2818                    config.setErr(toPrintwriter(config,err,true));
2819            }
2820            else if(hasCS)config.setErr(configServer.getErrWriter());
2821           
2822        }
2823    
2824        private static PrintWriter toPrintwriter(ConfigImpl config, String streamtype, boolean iserror) {
2825            if(!StringUtil.isEmpty(streamtype)) {
2826                    streamtype=streamtype.trim();
2827                    
2828                    if(streamtype.equalsIgnoreCase("null")) return new PrintWriter(DevNullOutputStream.DEV_NULL_OUTPUT_STREAM);
2829                    else if(StringUtil.startsWithIgnoreCase(streamtype, "class:")) {
2830                            String classname=streamtype.substring(6);
2831                            try {
2832                                            return (PrintWriter) ClassUtil.loadInstance(classname);
2833                                    } catch (Throwable t) {
2834                                            t.printStackTrace();
2835                                    }
2836                    }
2837                    else if(StringUtil.startsWithIgnoreCase(streamtype, "file:")) {
2838                            String strRes=streamtype.substring(5);
2839                            try {
2840                                    strRes=ConfigWebUtil.translateOldPath(strRes);
2841                                    Resource res=ConfigWebUtil.getFile(config, config.getConfigDir(),strRes, ResourceUtil.TYPE_FILE);
2842                            if(res!=null)return new PrintWriter(res.getOutputStream(),true);
2843                                    } 
2844                            catch (Throwable t) {
2845                                            t.printStackTrace();
2846                                    }
2847                    }
2848                    
2849            }
2850            if(iserror)return SystemUtil.PRINTWRITER_ERR;
2851            return SystemUtil.PRINTWRITER_OUT;
2852            }
2853    
2854    
2855            /**
2856         * @param configServer 
2857         * @param config
2858         * @param doc
2859         */
2860        private static void loadCharset(ConfigServer configServer, ConfigImpl config, Document doc) {
2861            
2862            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
2863    
2864            Element charset=hasAccess?getChildByName(doc.getDocumentElement(),"charset"):null;
2865            Element regional=hasAccess?getChildByName(doc.getDocumentElement(),"regional"):null;
2866            Element fileSystem=hasAccess?getChildByName(doc.getDocumentElement(),"file-system"):null;
2867                    
2868            boolean hasCS=configServer!=null;
2869    
2870            // template
2871            String template=null,fsCharset=null,fsEncoding=null;
2872            if(charset!=null)template=charset.getAttribute("template-charset");
2873            if(fileSystem!=null)fsCharset=fileSystem.getAttribute("charset"); // deprecated but still supported
2874            if(fileSystem!=null)fsEncoding=fileSystem.getAttribute("encoding"); // deprecated but still supported
2875            
2876            if(!StringUtil.isEmpty(template))
2877                            config.setTemplateCharset(template);
2878            else if(!StringUtil.isEmpty(fsCharset))
2879                            config.setTemplateCharset(fsCharset);
2880            else if(!StringUtil.isEmpty(fsEncoding))
2881                            config.setTemplateCharset(fsEncoding);
2882                    else if(hasCS)
2883                            config.setTemplateCharset(configServer.getTemplateCharset());
2884            
2885            
2886            // web
2887            String web=null,defaultEncoding=null;
2888            if(charset!=null)web=charset.getAttribute("web-charset");
2889            if(regional!=null)defaultEncoding=regional.getAttribute("default-encoding"); // deprecated but still supported
2890                    if(!StringUtil.isEmpty(web))
2891                            config.setWebCharset(web);
2892                    else if(!StringUtil.isEmpty(defaultEncoding))
2893                            config.setWebCharset(defaultEncoding);
2894                    else if(hasCS)
2895                            config.setWebCharset(configServer.getWebCharset());
2896            
2897            
2898            // resource
2899            String resource=null;
2900            if(charset!=null)resource=charset.getAttribute("resource-charset");
2901            if(!StringUtil.isEmpty(resource))
2902                            config.setResourceCharset(resource);
2903                    else if(hasCS)
2904                            config.setResourceCharset(configServer.getResourceCharset());
2905                    
2906            
2907                    
2908        }
2909        
2910        /**
2911         * @param configServer 
2912         * @param config
2913         * @param doc
2914         */
2915        private static void loadRegional(ConfigServer configServer, ConfigImpl config, Document doc) {
2916            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
2917            
2918            Element regional=hasAccess?getChildByName(doc.getDocumentElement(),"regional"):null;
2919            boolean hasCS=configServer!=null;
2920            
2921            // timeZone
2922            String strTimeZone=null;
2923            if(regional!=null)strTimeZone=regional.getAttribute("timezone");
2924            
2925            if(!StringUtil.isEmpty(strTimeZone)) config.setTimeZone(TimeZone.getTimeZone(strTimeZone));
2926            else if(hasCS) config.setTimeZone(configServer.getTimeZone());
2927            else config.setTimeZone(TimeZone.getDefault());
2928            
2929            // timeserver
2930            String strTimeServer=null;
2931            Boolean useTimeServer=null;
2932            if(regional!=null){
2933                    strTimeServer=regional.getAttribute("timeserver");
2934                    useTimeServer=Caster.toBoolean(regional.getAttribute("use-timeserver"),null);//31       
2935            }
2936            
2937            if(!StringUtil.isEmpty(strTimeServer)) config.setTimeServer(strTimeServer);     
2938            else if(hasCS) config.setTimeServer(configServer.getTimeServer());   
2939            
2940            if(useTimeServer!=null)config.setUseTimeServer(useTimeServer.booleanValue());     
2941            else if(hasCS) config.setUseTimeServer(((ConfigImpl)configServer).getUseTimeServer());   
2942            
2943            // locale
2944            String strLocale=null;
2945            if(regional!=null)strLocale=regional.getAttribute("locale");
2946            
2947            if(!StringUtil.isEmpty(strLocale)) config.setLocale(strLocale);     
2948            else if(hasCS) config.setLocale(configServer.getLocale());   
2949            else config.setLocale(Locale.US);
2950            
2951        }
2952        
2953        
2954        private static void loadORM(ConfigServer configServer, ConfigImpl config, Document doc) throws IOException {
2955            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManagerImpl.TYPE_ORM);
2956                    
2957            Element orm=hasAccess?getChildByName(doc.getDocumentElement(),"orm"):null;
2958            boolean hasCS=configServer!=null;
2959            
2960            
2961            
2962          // log
2963            String strLogger=hasAccess?orm.getAttribute("log"):null;
2964            if(hasAccess && StringUtil.isEmpty(strLogger) && hasCS) 
2965                    strLogger=((ConfigServerImpl)configServer).getORMLogger().getSource();
2966            else
2967                    strLogger="{railo-config}/logs/orm.log";
2968            
2969                    
2970            int logLevel=hasAccess?LogUtil.toIntType(orm.getAttribute("log-level"),-1):-1;
2971            if(logLevel==-1 && hasCS)
2972                    logLevel=((ConfigServerImpl)configServer).getORMLogger().getLogLevel();
2973            if(logLevel==-1)logLevel=Log.LEVEL_ERROR;
2974            
2975            config.setORMLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,hasAccess,logLevel));
2976            
2977            
2978          // engine
2979            String defaulrEngineClass=HibernateORMEngine.class.getName();//"railo.runtime.orm.hibernate.HibernateORMEngine";
2980            
2981            //print.o("orm:"+defaulrEngineClass);
2982            String strEngine=null;
2983            if(orm!=null)strEngine=orm.getAttribute("engine-class");
2984            if(StringUtil.isEmpty(strEngine,true))
2985                    strEngine=defaulrEngineClass;
2986            
2987            // load class
2988            Class<ORMEngine> clazz;
2989            try{
2990                    clazz=ClassUtil.loadClass(strEngine);
2991                    // TODO check interface as well
2992            }
2993            catch(ClassException ce){
2994                    ce.printStackTrace();
2995                    clazz=ClassUtil.loadClass(defaulrEngineClass,null);
2996            }
2997            config.setORMEngineClass(clazz);
2998            
2999            
3000        // config
3001            if(orm==null) orm = doc.createElement("orm"); // this is just a dummy 
3002            ORMConfiguration def=hasCS?((ConfigServerImpl)configServer).getORMConfig():null;
3003            ORMConfiguration ormConfig=ORMConfiguration.load(config,null,orm,config.getRootDirectory(),def);
3004            config.setORMConfig(ormConfig);
3005            
3006        }
3007        
3008        
3009    
3010        /**
3011         * @param configServer 
3012         * @param config
3013         * @param doc
3014         * @throws PageException
3015         * @throws IOException
3016         */
3017        private static void loadScope(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws PageException {
3018            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
3019            
3020            Element scope=getChildByName(doc.getDocumentElement(),"scope");
3021            boolean hasCS=configServer!=null;
3022            
3023            // Cluster Scope
3024            if(!hasCS){
3025                    String strClass=scope.getAttribute("cluster-class");
3026                    if(hasAccess && !StringUtil.isEmpty(strClass)) {
3027                            try {
3028                                            Class clazz = ClassUtil.loadClass(config.getClassLoader(),strClass);
3029                                            if(!Reflector.isInstaneOf(clazz,Cluster.class) && !Reflector.isInstaneOf(clazz,ClusterRemote.class))
3030                                            throw new ApplicationException("class ["+clazz.getName()+"] does not implement interface ["+Cluster.class.getName()+"] or ["+ClusterRemote.class.getName()+"]");
3031                                    
3032                                            config.setClusterClass(clazz);
3033                                            
3034                                    } catch (ClassException e) {
3035                                            e.printStackTrace();
3036                                    }
3037                            
3038                            
3039                        }
3040            }
3041                //else if(hasCS) config.setClassClusterScope(configServer.getClassClusterScope());
3042            
3043            
3044            // Local Mode
3045            String strLocalMode=scope.getAttribute("local-mode");
3046            if(hasAccess && !StringUtil.isEmpty(strLocalMode)) {
3047                    config.setLocalMode(strLocalMode);
3048                }
3049                else if(hasCS) config.setLocalMode(configServer.getLocalMode());
3050            
3051            // Session-Type
3052                String strSessionType=scope.getAttribute("session-type");
3053                        if(hasAccess && !StringUtil.isEmpty(strSessionType)) {
3054                            config.setSessionType(strSessionType);
3055                        }
3056                        else if(hasCS) config.setSessionType(configServer.getSessionType());
3057            
3058                // Cascading
3059                String strScopeCascadingType=scope.getAttribute("cascading");
3060                if(hasAccess && !StringUtil.isEmpty(strScopeCascadingType)) {
3061                    config.setScopeCascadingType(strScopeCascadingType);
3062                }
3063                else if(hasCS) config.setScopeCascadingType(configServer.getScopeCascadingType());
3064            
3065                // cascade-to-resultset
3066                String strAllowImplicidQueryCall=scope.getAttribute("cascade-to-resultset");
3067                if(hasAccess && !StringUtil.isEmpty(strAllowImplicidQueryCall)) {
3068                    config.setAllowImplicidQueryCall(toBoolean(strAllowImplicidQueryCall,true));
3069                }
3070                else if(hasCS) config.setAllowImplicidQueryCall(configServer.allowImplicidQueryCall());
3071                
3072                // Merge url and Form
3073                String strMergeFormAndURL=scope.getAttribute("merge-url-form");
3074                if(hasAccess && !StringUtil.isEmpty(strMergeFormAndURL)) {
3075                    config.setMergeFormAndURL(toBoolean(strMergeFormAndURL,false));
3076                }
3077                else if(hasCS) config.setMergeFormAndURL(configServer.mergeFormAndURL());
3078    
3079                // Client Timeout
3080                String clientTimeout=scope.getAttribute("clienttimeout");
3081                if(StringUtil.isEmpty(clientTimeout,true)){
3082                    // deprecated
3083                    clientTimeout=scope.getAttribute("client-max-age");
3084                    int days=Caster.toIntValue(clientTimeout,-1);
3085                    if(days>0) clientTimeout=days+",0,0,0";
3086                    else clientTimeout="";
3087                }
3088                if(hasAccess && !StringUtil.isEmpty(clientTimeout)) {
3089                    config.setClientTimeout(clientTimeout);
3090                }
3091                else if(hasCS) config.setClientTimeout(configServer.getClientTimeout());
3092    
3093                
3094                
3095                
3096                
3097                // Session Timeout
3098                String sessionTimeout=scope.getAttribute("sessiontimeout");
3099                if(hasAccess && !StringUtil.isEmpty(sessionTimeout)) {
3100                    config.setSessionTimeout(sessionTimeout);
3101                }
3102                else if(hasCS) config.setSessionTimeout(configServer.getSessionTimeout());
3103    
3104                // App Timeout
3105                String appTimeout=scope.getAttribute("applicationtimeout");
3106                if(hasAccess && !StringUtil.isEmpty(appTimeout)) {
3107                    config.setApplicationTimeout(appTimeout);
3108                }
3109                else if(hasCS) config.setApplicationTimeout(configServer.getApplicationTimeout());
3110              
3111                    // Client Type
3112                    String strClientType=scope.getAttribute("clienttype");
3113                    if(hasAccess && !StringUtil.isEmpty(strClientType)) {
3114                  config.setClientType(strClientType);
3115                    }
3116                    else if(hasCS) config.setClientType(configServer.getClientType());
3117            
3118                
3119                // Client
3120                    Resource configDir=config.getConfigDir();
3121              String strClientDirectory=scope.getAttribute("client-directory");
3122                if(hasAccess && !StringUtil.isEmpty(strClientDirectory)) {
3123                    strClientDirectory=ConfigWebUtil.translateOldPath(strClientDirectory);
3124                    Resource res = ConfigWebUtil.getFile(configDir,strClientDirectory, "client-scope",configDir,FileUtil.TYPE_DIR,config);
3125                    config.setClientScopeDir(res);
3126                }
3127                    else {
3128                            config.setClientScopeDir(configDir.getRealResource("client-scope"));
3129                    }
3130                
3131                String strMax=scope.getAttribute("client-directory-max-size");
3132                if(hasAccess && !StringUtil.isEmpty(strMax)) {
3133                    config.setClientScopeDirSize(ByteSizeParser.parseByteSizeDefinition(strMax,config.getClientScopeDirSize()));
3134                }
3135                else if(hasCS) config.setClientScopeDirSize(configServer.getClientScopeDirSize());
3136    
3137                
3138                
3139                
3140            // Session Management
3141                    String strSessionManagement=scope.getAttribute("sessionmanagement");
3142                    if(hasAccess && !StringUtil.isEmpty(strSessionManagement)) {
3143                        config.setSessionManagement(toBoolean(strSessionManagement,true));
3144                    }
3145                    else if(hasCS) config.setSessionManagement(configServer.isSessionManagement());
3146    
3147                    // Client Management
3148                    String strClientManagement=scope.getAttribute("clientmanagement");
3149                    if(hasAccess && !StringUtil.isEmpty(strClientManagement)) {
3150                        config.setClientManagement(toBoolean(strClientManagement,false));
3151                    }
3152                    else if(hasCS) config.setClientManagement(configServer.isClientManagement());
3153    
3154            // Client Cookies
3155                    String strClientCookies=scope.getAttribute("setclientcookies");
3156                    if(hasAccess && !StringUtil.isEmpty(strClientCookies)) {
3157                        config.setClientCookies(toBoolean(strClientCookies,true));
3158                    }
3159                    else if(hasCS) config.setClientCookies(configServer.isClientCookies());
3160    
3161            // Domain Cookies
3162                    String strDomainCookies=scope.getAttribute("setdomaincookies");
3163                    if(hasAccess && !StringUtil.isEmpty(strDomainCookies)) {
3164                        config.setDomainCookies(toBoolean(strDomainCookies,false));
3165                    }
3166                    else if(hasCS) config.setDomainCookies(configServer.isDomainCookies());
3167        }
3168        
3169        
3170    
3171    
3172            private static void loadJava(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
3173            boolean hasCS=configServer!=null;
3174            Element java=getChildByName(doc.getDocumentElement(),"java");
3175            
3176            //
3177            String strInspectTemplate=java.getAttribute("inspect-template");
3178            if(!StringUtil.isEmpty(strInspectTemplate)) {
3179                    strInspectTemplate=strInspectTemplate.trim().toLowerCase();
3180                    if(strInspectTemplate.equals("always")) 
3181                    config.setInspectTemplate(ConfigImpl.INSPECT_ALWAYS);
3182                    else if(strInspectTemplate.equals("never")) 
3183                    config.setInspectTemplate(ConfigImpl.INSPECT_NEVER);
3184                    else
3185                    config.setInspectTemplate(ConfigImpl.INSPECT_ONCE);
3186            }
3187            else if(hasCS) {
3188                config.setInspectTemplate(configServer.getInspectTemplate());
3189            }
3190            
3191            // 
3192            String strCompileType=java.getAttribute("compile-type");
3193            if(!StringUtil.isEmpty(strCompileType)) {
3194                strCompileType=strCompileType.trim().toLowerCase();
3195                if(strCompileType.equals("after-startup")) {
3196                    config.setCompileType(Config.RECOMPILE_AFTER_STARTUP);
3197                }
3198                else if(strCompileType.equals("always")) {
3199                    config.setCompileType(Config.RECOMPILE_ALWAYS);
3200                }
3201            }
3202            else if(hasCS) {
3203                config.setCompileType(configServer.getCompileType());
3204            }
3205            
3206            
3207        }
3208    
3209        private static void loadConstants(ConfigServerImpl configServer, ConfigImpl config, Document doc)  {
3210            
3211            boolean hasCS=configServer!=null;
3212            Element constant=getChildByName(doc.getDocumentElement(),"constants");
3213            
3214            // Constants
3215            Element[] elConstants = getChildren(constant,"constant");
3216            Struct sct=null;
3217            if(hasCS) {
3218                    sct=configServer.getConstants();
3219                    if(sct!=null) sct=(Struct) sct.duplicate(false);
3220            }
3221            if(sct==null) sct=new StructImpl();
3222            String name;
3223            for(int i=0;i<elConstants.length;i++) {
3224                    name=elConstants[i].getAttribute("name");
3225                    if(StringUtil.isEmpty(name))continue;
3226                    sct.setEL(KeyImpl.getInstance(name.trim()), elConstants[i].getAttribute("value"));
3227            }
3228            config.setConstants(sct);
3229        }
3230        
3231        private static void loadLogin(ConfigServerImpl configServer, ConfigImpl config, Document doc)  {
3232            // server context
3233            if(config instanceof ConfigServer) {
3234                    Element login=getChildByName(doc.getDocumentElement(),"login");
3235                    boolean captcha=Caster.toBooleanValue(login.getAttribute("captcha"),false);
3236                    int delay=Caster.toIntValue(login.getAttribute("delay"),0);
3237                    ConfigServerImpl cs=(ConfigServerImpl) config;
3238                    cs.setLoginDelay(delay);
3239                    cs.setLoginCaptcha(captcha);
3240            }
3241        }
3242            
3243    
3244        /**
3245         * @param configServer
3246         * @param config
3247         * @param doc
3248         * @throws IOException
3249         */
3250        private static void loadMail(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws IOException {
3251            
3252            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_MAIL);
3253            
3254            boolean hasCS=configServer!=null;
3255            Element mail=getChildByName(doc.getDocumentElement(),"mail");
3256            
3257            // Spool Interval
3258            String strSpoolInterval=mail.getAttribute("spool-interval");
3259            if(!StringUtil.isEmpty(strSpoolInterval) && hasAccess) {
3260                config.setMailSpoolInterval(toInt(strSpoolInterval,30));
3261            }
3262            else if(hasCS) config.setMailSpoolInterval(configServer.getMailSpoolInterval());
3263    
3264                    String strEncoding = mail.getAttribute("default-encoding");
3265                    if(!StringUtil.isEmpty(strEncoding) && hasAccess)
3266                            config.setMailDefaultEncoding(strEncoding);
3267                    else if(hasCS)
3268                            config.setMailDefaultEncoding(configServer.getMailDefaultEncoding());
3269            
3270            // Mail Logger
3271            String strMailLogger=mail.getAttribute("log");
3272            if(StringUtil.isEmpty(strMailLogger) && hasCS)
3273                    strMailLogger=configServer.getMailLogger().getSource();
3274                    
3275            int logLevel=LogUtil.toIntType(mail.getAttribute("log-level"),-1);
3276            if(logLevel==-1 && hasCS)
3277                    logLevel=configServer.getMailLogger().getLogLevel();
3278            if(logLevel==-1)logLevel=Log.LEVEL_ERROR;
3279            
3280            config.setMailLogger(ConfigWebUtil.getLogAndSource(configServer,config,strMailLogger,hasAccess,logLevel));
3281            
3282            // Spool Enable
3283            String strSpoolEnable=mail.getAttribute("spool-enable");
3284            if(!StringUtil.isEmpty(strSpoolEnable) && hasAccess) {
3285                config.setMailSpoolEnable(toBoolean(strSpoolEnable,false));
3286            }
3287            else if(hasCS) config.setMailSpoolEnable(configServer.isMailSpoolEnable());
3288    
3289            // Timeout
3290            String strTimeout=mail.getAttribute("timeout");
3291            if(!StringUtil.isEmpty(strTimeout) && hasAccess) {
3292                config.setMailTimeout(toInt(strTimeout,60));
3293            }
3294            else if(hasCS) config.setMailTimeout(configServer.getMailTimeout());
3295    
3296            // Servers
3297            int index=0;
3298            Server[] servers=null;
3299            Element[] elServers = getChildren(mail,"server");
3300            if(hasCS) {
3301                Server[] readOnlyServers = configServer.getMailServers();
3302                servers=new Server[readOnlyServers.length+(hasAccess?elServers.length:0)];
3303                for(int i=0;i<readOnlyServers.length;i++) {
3304                    servers[i]=readOnlyServers[index++].cloneReadOnly();
3305                }
3306            }
3307            else {
3308                servers=new Server[elServers.length];
3309            }
3310            if(hasAccess) {
3311                    for(int i=0;i<elServers.length;i++) {
3312                                    Element el=elServers[i];
3313                                    if(el.getNodeName().equals("server"))
3314                                    servers[index++]=new ServerImpl(
3315                                                    el.getAttribute("smtp"),
3316                                                    toInt(el.getAttribute("port"),25),
3317                                                    el.getAttribute("username"),
3318                                                    decrypt(el.getAttribute("password")),
3319                                                    toBoolean(el.getAttribute("tls"),false),
3320                                                    toBoolean(el.getAttribute("ssl"),false)
3321                                    );
3322                            
3323                    }
3324            }
3325            config.setMailServers(servers);
3326        }
3327        
3328    
3329        private static void loadMonitors(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws IOException {
3330            if(configServer!=null) return;
3331            
3332            configServer=(ConfigServerImpl) config;
3333            
3334    
3335            Element parent=getChildByName(doc.getDocumentElement(),"monitoring");
3336            boolean enabled=Caster.toBooleanValue(parent.getAttribute("enabled"),false);
3337            configServer.setMonitoringEnabled(enabled);
3338            
3339            int index=0;
3340            Element[] children = getChildren(parent,"monitor");
3341            java.util.List<IntervallMonitor> intervalls=new ArrayList<IntervallMonitor>();
3342            java.util.List<RequestMonitor> requests=new ArrayList<RequestMonitor>();
3343            String className,strType,name;
3344            boolean log;
3345            short type;
3346            for(int i=0;i<children.length;i++) {
3347                    Element el=children[i];
3348                    className=el.getAttribute("class");
3349                    strType=el.getAttribute("type");
3350                    name=el.getAttribute("name");
3351                    log=Caster.toBooleanValue(el.getAttribute("log"),true);
3352                    if("request".equalsIgnoreCase(strType))
3353                            type=IntervallMonitor.TYPE_REQUEST;
3354                    else
3355                            type=IntervallMonitor.TYPE_INTERVALL;
3356                    
3357                    if(!StringUtil.isEmpty(className) && !StringUtil.isEmpty(name)) {
3358                            name=name.trim();
3359                            try{
3360                                    Class clazz = ClassUtil.loadClass(config.getClassLoader(),className);
3361                                    Constructor constr = clazz.getConstructor(new Class[]{ConfigServer.class});
3362                                    Object obj = constr.newInstance(new Object[]{configServer});
3363                                    if(type==IntervallMonitor.TYPE_INTERVALL) {
3364                                            IntervallMonitorWrap m = new IntervallMonitorWrap(obj);
3365                                            m.init(configServer,name,log);
3366                                            intervalls.add(m);
3367                                    }
3368                                    else {
3369                                            RequestMonitorWrap m = new RequestMonitorWrap(obj);
3370                                            m.init(configServer,name,log);
3371                                            requests.add(m);
3372                                    }
3373                            }
3374                            catch(Throwable t){
3375                                    t.printStackTrace();
3376                            }
3377                    }
3378                    
3379            }
3380            configServer.setRequestMonitors(requests.toArray(new RequestMonitor[requests.size()]));
3381            configServer.setIntervallMonitors(intervalls.toArray(new IntervallMonitor[intervalls.size()]));
3382            configServer.getCFMLEngineImpl().touchMonitor(configServer);
3383        }
3384    
3385        /**
3386         * @param configServer 
3387         * @param config
3388         * @param doc
3389         * @throws PageException
3390         */
3391        private static void loadSearch(ConfigServer configServer, ConfigImpl config, Document doc) throws PageException {
3392            if(config instanceof ConfigServer) return;
3393            
3394            //ServletContext sc=config.getServletContext();
3395            Resource configDir=config.getConfigDir();
3396            
3397            Element search=getChildByName(doc.getDocumentElement(),"search");
3398                
3399                String strEngineClass=search.getAttribute("engine-class");
3400                SearchEngine se=null;
3401                Object o=ClassUtil.loadInstance(strEngineClass,(Object)null);
3402                if(o instanceof SearchEngine) se=(SearchEngine) o;
3403                
3404                if(se==null)se=new railo.runtime.search.lucene2.LuceneSearchEngine();
3405                
3406                try {
3407                    // Logger
3408                String strLogger=search.getAttribute("log");
3409                int logLevel=LogUtil.toIntType(search.getAttribute("log-level"),Log.LEVEL_ERROR);
3410                LogAndSource log=ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel);
3411                
3412                // Init
3413                se.init(config,
3414                        ConfigWebUtil.getFile(configDir,(search==null)?
3415                        null:
3416                        ConfigWebUtil.translateOldPath(search.getAttribute("directory")), "search",configDir,FileUtil.TYPE_DIR,config),
3417                        log
3418                );
3419            } 
3420                catch (Exception e) {
3421                throw Caster.toPageException(e);
3422            }
3423                
3424                config.setSearchEngine(se);
3425        }
3426    
3427        /**
3428         * @param configServer 
3429         * @param config
3430         * @param doc
3431         * @param isEventGatewayContext 
3432         * @throws IOException
3433         * @throws PageException
3434         */
3435        private static void loadScheduler(ConfigServer configServer, ConfigImpl config, Document doc) throws PageException, IOException {
3436            if(config instanceof ConfigServer) return;
3437            
3438            Resource configDir=config.getConfigDir();
3439            Element scheduler=getChildByName(doc.getDocumentElement(),"scheduler");
3440            
3441            // Logger
3442            String strLogger=scheduler.getAttribute("log");
3443            int logLevel=LogUtil.toIntType(scheduler.getAttribute("log-level"),Log.LEVEL_INFO);
3444            LogAndSource log=ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel);
3445            
3446            // set scheduler
3447            Resource file = ConfigWebUtil.getFile(config.getRootDirectory(),(scheduler==null)?
3448                    null:
3449                    scheduler.getAttribute("directory"), "scheduler",configDir,FileUtil.TYPE_DIR,config);
3450            config.setScheduler(configServer.getCFMLEngine(),file,log);
3451        }
3452    
3453        /**
3454         * @param configServer 
3455         * @param config
3456         * @param doc
3457         */
3458        private static void loadDebug(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
3459            boolean hasCS=configServer!=null;
3460            
3461            Element debugging=getChildByName(doc.getDocumentElement(),"debugging");
3462            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_DEBUGGING);
3463            
3464            // debug
3465            String strDebug=debugging.getAttribute("debug");
3466            if(hasAccess && !StringUtil.isEmpty(strDebug)) {
3467                config.setDebug(toBoolean(strDebug,false)?ConfigImpl.CLIENT_BOOLEAN_TRUE:ConfigImpl.CLIENT_BOOLEAN_FALSE);
3468            }
3469            else if(hasCS)config.setDebug(configServer.debug()?ConfigImpl.SERVER_BOOLEAN_TRUE:ConfigImpl.SERVER_BOOLEAN_FALSE);
3470            
3471            // debug template
3472            String template=debugging.getAttribute("template");
3473            if(hasAccess && !StringUtil.isEmpty(template)) {
3474                config.setDebugTemplate(template);
3475            }
3476            else if(hasCS) {
3477                config.setDebugTemplate(configServer.getDebugTemplate());
3478            }
3479            else {
3480                config.setDebugTemplate("/railo-context/templates/debugging/debugging.cfm");
3481            }       
3482            
3483            // show-usage
3484            Boolean showUsage = Caster.toBoolean(debugging.getAttribute("show-query-usage"),null);
3485            if(showUsage!=null && hasAccess) {
3486                config.setDebugShowQueryUsage(showUsage.booleanValue());
3487            }
3488            else if(hasCS) {
3489                config.setDebugShowQueryUsage(configServer.getDebugShowQueryUsage());
3490            }
3491        }
3492    
3493        /**
3494         * @param configServer 
3495         * @param config
3496         * @param doc
3497         */
3498        private static void loadCFX(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
3499            
3500            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_CFX_SETTING);
3501            
3502            HashTable map=new HashTable();
3503            if(configServer!=null) {
3504                try {
3505                    Map classes = configServer.getCFXTagPool().getClasses();
3506                    Iterator it = classes.keySet().iterator();
3507                    while(it.hasNext()) {
3508                        Object key=it.next();
3509                        map.put(key,((CFXTagClass)classes.get(key)).cloneReadOnly());
3510                    }
3511                } 
3512                catch (SecurityException e) {}
3513            }
3514            
3515            if(hasAccess) {
3516                    if(configServer==null) {
3517                            System.setProperty("cfx.bin.path",config.getConfigDir().getRealResource("bin").getAbsolutePath());
3518                    }
3519                    
3520                    // Java CFX Tags
3521                    Element cfxTagsParent=getChildByName(doc.getDocumentElement(),"ext-tags",false,true);
3522                    if(cfxTagsParent==null) cfxTagsParent=getChildByName(doc.getDocumentElement(),"cfx-tags",false,true);
3523                    if(cfxTagsParent==null) cfxTagsParent=getChildByName(doc.getDocumentElement(),"ext-tags");
3524                    
3525                    boolean oldStyle=cfxTagsParent.getNodeName().equals("cfx-tags");
3526                    
3527                    
3528                    if(cfxTagsParent!=null) {
3529                        Element[] cfxTags = oldStyle?getChildren(cfxTagsParent,"cfx-tag"):getChildren(cfxTagsParent,"ext-tag");  
3530                        for(int i=0;i<cfxTags.length; i++) {
3531                            String type=cfxTags[i].getAttribute("type");
3532                            if(type!=null){
3533                                    // Java CFX Tags
3534                                    if(type.equalsIgnoreCase("java")) {
3535                                        String name=cfxTags[i].getAttribute("name");
3536                                        String clazz=cfxTags[i].getAttribute("class");
3537                                        if(!StringUtil.isEmpty(name) && !StringUtil.isEmpty(clazz)) {
3538                                            map.put(name.toLowerCase(),new JavaCFXTagClass(name,clazz));
3539                                        }
3540                                    }
3541                                    // C++ CFX Tags
3542                                    else if(type.equalsIgnoreCase("cpp")) {
3543                                            String name=cfxTags[i].getAttribute("name");
3544                                            String serverLibrary=cfxTags[i].getAttribute("server-library");
3545                                            String procedure=cfxTags[i].getAttribute("procedure");
3546                                            boolean keepAlive=Caster.toBooleanValue(cfxTags[i].getAttribute("keep-alive"),false);
3547                                      
3548                                            if(!StringUtil.isEmpty(name) && !StringUtil.isEmpty(serverLibrary) && !StringUtil.isEmpty(procedure)) {
3549                                                    map.put(name.toLowerCase(),new CPPCFXTagClass(name,serverLibrary,procedure,keepAlive));
3550                                            }
3551                                    }
3552                            }
3553                        }
3554                    }
3555            }
3556            config.setCFXTagPool(map);
3557        }
3558    
3559        private static void loadExtensions(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
3560            
3561            
3562            Element xmlExtParent=getChildByName(doc.getDocumentElement(),"extensions");
3563            
3564            String strEnabled = xmlExtParent.getAttribute("enabled");
3565            if(!StringUtil.isEmpty(strEnabled)){
3566                    config.setExtensionEnabled(Caster.toBooleanValue(strEnabled,false));
3567            }
3568            
3569            if(xmlExtParent!=null) {
3570       // providers
3571                    Element[] xmlProviders = getChildren(xmlExtParent,"provider");
3572                    String provider;
3573                    Map list=new HashMap();
3574                    
3575                    for(int i=0;i<ConfigImpl.RAILO_EXTENSION_PROVIDERS.length; i++) {
3576                            list.put(ConfigImpl.RAILO_EXTENSION_PROVIDERS[i],"");
3577                    }
3578                    
3579                    
3580                    for(int i=0;i<xmlProviders.length; i++) {
3581                            provider=xmlProviders[i].getAttribute("url");
3582                            if(!StringUtil.isEmpty(provider,true) 
3583                                            && !"http://www.railo-technologies.com/ExtensionProvider.cfc".equals(provider)
3584                                            && !"http://www.railo.ch/ExtensionProvider.cfc".equals(provider)
3585                                            ){
3586                                    list.put(new ExtensionProviderImpl(provider.trim(),false),"");
3587                    }
3588                }
3589                config.setExtensionProviders((ExtensionProvider[]) list.keySet().toArray(new ExtensionProvider[list.size()]));
3590                    
3591                    
3592                    
3593                    
3594                    // extensions 
3595                Element[] xmlExtensions = getChildren(xmlExtParent,"extension");
3596                Extension[] extensions=new Extension[xmlExtensions.length];
3597                Element xmlExtension;
3598                for(int i=0;i<xmlExtensions.length; i++) {
3599                    xmlExtension=xmlExtensions[i];
3600                    extensions[i]=new ExtensionImpl(
3601                                    xmlExtension.getAttribute("config"),
3602                                    xmlExtension.getAttribute("id"),
3603                                    xmlExtension.getAttribute("provider"),
3604                                    xmlExtension.getAttribute("version"),
3605                                    
3606                                    xmlExtension.getAttribute("name"),
3607                                    xmlExtension.getAttribute("label"),
3608                                    xmlExtension.getAttribute("description"),
3609                                    xmlExtension.getAttribute("category"),
3610                                    xmlExtension.getAttribute("image"),
3611                                    xmlExtension.getAttribute("author"),
3612                                    xmlExtension.getAttribute("codename"),
3613                                    xmlExtension.getAttribute("video"),
3614                                    xmlExtension.getAttribute("support"),
3615                                    xmlExtension.getAttribute("documentation"),
3616                                    xmlExtension.getAttribute("forum"),
3617                                    xmlExtension.getAttribute("mailinglist"),
3618                                    xmlExtension.getAttribute("network"),
3619                                    DateCaster.toDateAdvanced(xmlExtension.getAttribute("created"), null,null),
3620                                    xmlExtension.getAttribute("type")
3621                            );
3622                }
3623                config.setExtensions(extensions);
3624            }
3625            
3626        }
3627        
3628        /**
3629         * @param configServer 
3630         * @param config
3631         * @param doc
3632         * @throws IOException 
3633         */
3634        private static void loadComponent(ConfigServer configServer, ConfigImpl config, Document doc) {
3635            Element component=getChildByName(doc.getDocumentElement(),"component");
3636            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
3637            boolean hasSet=false;
3638            boolean hasCS=configServer!=null;
3639            
3640            //String virtual="/component/";
3641            
3642            if(component!=null && hasAccess) {
3643                    
3644                    // component-default-import
3645                String strCDI=component.getAttribute("component-default-import");
3646                if(StringUtil.isEmpty(strCDI,true) && configServer!=null) {
3647                    strCDI=((ConfigServerImpl)configServer).getComponentDefaultImport().toString();
3648                }
3649                if(!StringUtil.isEmpty(strCDI,true))
3650                    config.setComponentDefaultImport(strCDI);
3651                
3652                    
3653                    // Base
3654                String strBase=component.getAttribute("base");
3655                if(StringUtil.isEmpty(strBase,true) && configServer!=null) {
3656                    strBase=configServer.getBaseComponentTemplate();
3657                }
3658                config.setBaseComponentTemplate(strBase);
3659                
3660                // deep search
3661                String strDeepSearch=component.getAttribute("deep-search");
3662                if(!StringUtil.isEmpty(strDeepSearch)) {
3663                    config.setDoComponentDeepSearch(Caster.toBooleanValue(strDeepSearch.trim(),false));
3664                }
3665                else if(hasCS) {
3666                    config.setDoComponentDeepSearch(((ConfigServerImpl)configServer).doComponentDeepSearch());
3667                }
3668                
3669                
3670                // Dump-Template
3671                String strDumpRemplate=component.getAttribute("dump-template");
3672                if((strDumpRemplate==null || strDumpRemplate.trim().length()==0) && configServer!=null) {
3673                    strDumpRemplate=configServer.getComponentDumpTemplate();
3674                }
3675                config.setComponentDumpTemplate(strDumpRemplate);
3676                
3677                // data-member-default-access
3678                String strDmda=component.getAttribute("data-member-default-access");
3679                if(strDmda!=null && strDmda.trim().length()>0) {
3680                    strDmda=strDmda.toLowerCase().trim();
3681                    if(strDmda.equals("remote"))config.setComponentDataMemberDefaultAccess(Component.ACCESS_REMOTE);
3682                    else if(strDmda.equals("public"))config.setComponentDataMemberDefaultAccess(Component.ACCESS_PUBLIC);
3683                    else if(strDmda.equals("package"))config.setComponentDataMemberDefaultAccess(Component.ACCESS_PACKAGE);
3684                    else if(strDmda.equals("private"))config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE);               
3685                }
3686                else if(configServer!=null) {
3687                        config.setComponentDataMemberDefaultAccess(configServer.getComponentDataMemberDefaultAccess());  
3688                }
3689                
3690                // trigger-properties
3691                Boolean tp = Caster.toBoolean(component.getAttribute("trigger-data-member"),null);
3692                    if(tp!=null)config.setTriggerComponentDataMember(tp.booleanValue());
3693                    else if(configServer!=null) {
3694                        config.setTriggerComponentDataMember(configServer.getTriggerComponentDataMember());  
3695                }
3696                    
3697                    // local search
3698                    Boolean ls = Caster.toBoolean(component.getAttribute("local-search"),null);
3699                    if(ls!=null)config.setComponentLocalSearch(ls.booleanValue());
3700                    else if(configServer!=null) {
3701                            config.setComponentLocalSearch(((ConfigServerImpl)configServer).getComponentLocalSearch()); 
3702                }
3703    
3704                    // use component shadow
3705                    Boolean ucp = Caster.toBoolean(component.getAttribute("use-cache-path"),null);
3706                    if(ucp!=null)config.setUseComponentPathCache(ucp.booleanValue());
3707                    else if(configServer!=null) {
3708                            config.setUseComponentPathCache(((ConfigServerImpl)configServer).useComponentPathCache()); 
3709                }
3710    
3711                    // use component shadow
3712                    Boolean ucs = Caster.toBoolean(component.getAttribute("use-shadow"),null);
3713                    if(ucs!=null)config.setUseComponentShadow(ucs.booleanValue());
3714                    else if(configServer!=null) {
3715                            config.setUseComponentShadow(configServer.useComponentShadow()); 
3716                }
3717                    
3718                    
3719            }
3720            else if(configServer!=null) {
3721                config.setBaseComponentTemplate(configServer.getBaseComponentTemplate());
3722                config.setComponentDumpTemplate(configServer.getComponentDumpTemplate());
3723                config.setComponentDataMemberDefaultAccess(configServer.getComponentDataMemberDefaultAccess());  
3724                config.setTriggerComponentDataMember(configServer.getTriggerComponentDataMember());  
3725            }
3726            
3727         // Web Mapping
3728    
3729            Element[] cMappings=getChildren(component,"mapping");
3730            hasSet=false;
3731            Mapping[] mappings=null;
3732            if(hasAccess && cMappings.length>0) {
3733                    mappings=new Mapping[cMappings.length];
3734                    for(int i=0;i<cMappings.length;i++) {
3735                       Element cMapping=cMappings[i];
3736                       String physical=cMapping.getAttribute("physical");
3737                       String archive=cMapping.getAttribute("archive");
3738                       boolean readonly=toBoolean(cMapping.getAttribute("readonly"),false);
3739                       boolean hidden=toBoolean(cMapping.getAttribute("hidden"),false);
3740                       boolean trusted=toBoolean(cMapping.getAttribute("trusted"),false);
3741                       int clMaxEl=toInt(cMapping.getAttribute("classloader-max-elements"),100);
3742                       
3743                       String primary=cMapping.getAttribute("primary");
3744                       
3745                       boolean physicalFirst=archive==null || !primary.equalsIgnoreCase("archive");
3746                       //print.out("xxx:"+physicalFirst);
3747                       hasSet=true;
3748                       mappings[i]= new MappingImpl(config,"/"+i+"/",physical,archive,trusted,physicalFirst,hidden,readonly,true,false,true,clMaxEl);
3749                       //print.out(mappings[i].isPhysicalFirst());
3750                    }
3751                    
3752                    config.setComponentMappings(mappings);
3753                    
3754            }
3755            
3756            // Server Mapping
3757            if(hasCS) {
3758                    Mapping[] originals=((ConfigServerImpl)configServer).getComponentMappings();
3759                    Mapping[] clones=new Mapping[originals.length];
3760                    LinkedHashMap map=new LinkedHashMap();
3761                    Mapping m;
3762                    for(int i=0;i<clones.length;i++){
3763                            m=((MappingImpl)originals[i]).cloneReadOnly(config);
3764                            map.put(toKey(m), m);
3765                            //clones[i]=((MappingImpl)m[i]).cloneReadOnly(config);
3766                    }
3767                    
3768                    if(mappings!=null) {
3769                            for(int i=0;i<mappings.length;i++){
3770                            m=mappings[i];
3771                            map.put(toKey(m), m);
3772                    }
3773                    }
3774                if(originals.length>0) {
3775                    clones=new Mapping[map.size()];
3776                    Iterator it = map.entrySet().iterator();
3777                    Map.Entry entry;
3778                    int index=0;
3779                    while(it.hasNext()){
3780                            entry=(Entry) it.next();
3781                            clones[index++]=(Mapping) entry.getValue();
3782                            //print.out("c:"+clones[index-1]);
3783                    }
3784                    hasSet=true;
3785                    //print.err("set:"+clones.length);
3786                    
3787                    config.setComponentMappings(clones);
3788                }
3789            }
3790            
3791            
3792                if(!hasSet) {
3793                    MappingImpl m=new MappingImpl(config,"/0","{railo-web}/components/",null,false,true,false,false,true,false,true);
3794                    if(m!=null)config.setComponentMappings(new Mapping[]{m.cloneReadOnly(config)});
3795                }
3796            
3797        }
3798        
3799        private static void loadProxy(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
3800    
3801            boolean hasCS=configServer!=null;
3802            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
3803            Element proxy=getChildByName(doc.getDocumentElement(),"proxy");
3804    
3805            // server
3806            
3807            // proxy enabled
3808            //String enabled=proxy.getAttribute("enabled");
3809            //if(hasAccess && !StringUtil.isEmpty(enabled)) config.setProxyEnable(toBoolean(enabled, false));
3810            //else if(hasCS) config.setProxyEnable(configServer.isProxyEnable());
3811    
3812            
3813            // proxy server
3814            String server=proxy.getAttribute("server");
3815            if(hasAccess && !StringUtil.isEmpty(server)) config.setProxyServer(server);
3816            else if(hasCS) config.setProxyServer(configServer.getProxyServer());
3817    
3818            // proxy username
3819            String username=proxy.getAttribute("username");
3820            if(hasAccess && !StringUtil.isEmpty(username)) config.setProxyUsername(username);
3821            else if(hasCS) config.setProxyUsername(configServer.getProxyUsername());
3822    
3823            // proxy password
3824            String password=proxy.getAttribute("password");
3825            if(hasAccess && !StringUtil.isEmpty(password)) config.setProxyPassword(password);
3826            else if(hasCS) config.setProxyPassword(configServer.getProxyPassword());
3827    
3828            // proxy port
3829            int port=toInt(proxy.getAttribute("port"),-1);
3830            if(hasAccess && port!=-1) config.setProxyPort(port);
3831            else if(hasCS) config.setProxyPort(configServer.getProxyPort());
3832    
3833            
3834        }
3835        
3836        
3837        
3838        private static void loadError(ConfigServerImpl configServer, ConfigImpl config, Document doc) {
3839            Element error=getChildByName(doc.getDocumentElement(),"error");
3840            boolean hasCS=configServer!=null;
3841            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_DEBUGGING);
3842            
3843            // error template
3844            String template=error.getAttribute("template");
3845            
3846            // 500
3847            String template500=error.getAttribute("template-500");
3848            if(StringUtil.isEmpty(template500))template500=error.getAttribute("template500");
3849            if(StringUtil.isEmpty(template500))template500=error.getAttribute("500");
3850            if(StringUtil.isEmpty(template500))template500=template;
3851            if(hasAccess && !StringUtil.isEmpty(template500)) {
3852                config.setErrorTemplate(500,template500);
3853            }
3854            else if(hasCS)  config.setErrorTemplate(500,configServer.getErrorTemplate(500));
3855            else                    config.setErrorTemplate(500,"/railo-context/templates/error/error.cfm");
3856            
3857            // 404
3858            String template404=error.getAttribute("template-404");
3859            if(StringUtil.isEmpty(template404))template404=error.getAttribute("template404");
3860            if(StringUtil.isEmpty(template404))template404=error.getAttribute("404");
3861            if(StringUtil.isEmpty(template404))template404=template;
3862            if(hasAccess && !StringUtil.isEmpty(template404)) {
3863                config.setErrorTemplate(404,template404);
3864            }
3865            else if(hasCS)  config.setErrorTemplate(404,configServer.getErrorTemplate(404));
3866            else                    config.setErrorTemplate(404,"/railo-context/templates/error/error.cfm");
3867            
3868            // status code
3869            String strStausCode = error.getAttribute("status-code");
3870            if(StringUtil.isEmpty(strStausCode))strStausCode = error.getAttribute("statusCode");
3871            if(StringUtil.isEmpty(strStausCode))strStausCode = error.getAttribute("status");
3872    
3873            if(!StringUtil.isEmpty(strStausCode) && hasAccess) {
3874                config.setErrorStatusCode(toBoolean(strStausCode, true));
3875            }
3876            else if(hasCS) config.setErrorStatusCode(configServer.getErrorStatusCode());
3877    
3878            
3879            
3880        }
3881        
3882    
3883        /**
3884         * @param configServer 
3885         * @param config
3886         * @param doc
3887         * @throws IOException
3888         * @throws PageException 
3889         */
3890        private static void loadApplication(ConfigServerImpl configServer, ConfigImpl config, Document doc) throws IOException, PageException {
3891            boolean hasCS=configServer!=null;
3892            boolean hasAccess=ConfigWebUtil.hasAccess(config,SecurityManager.TYPE_SETTING);
3893            
3894            
3895            Element application=getChildByName(doc.getDocumentElement(),"application");
3896            Element scope=          getChildByName(doc.getDocumentElement(),"scope");
3897            
3898    
3899            // Scope Logger
3900            String strLogger=scope.getAttribute("log");
3901            if(StringUtil.isEmpty(strLogger))strLogger="{railo-web}/logs/scope.log";
3902            int logLevel=LogUtil.toIntType(scope.getAttribute("log-level"),Log.LEVEL_ERROR);
3903            config.setScopeLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel));
3904    
3905            
3906            
3907            // Apllication Logger
3908            strLogger=application.getAttribute("application-log");
3909            logLevel=LogUtil.toIntType(application.getAttribute("application-log-level"),Log.LEVEL_ERROR);
3910            config.setApplicationLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel));
3911    
3912            // Exception Logger
3913            strLogger=application.getAttribute("exception-log");
3914            logLevel=LogUtil.toIntType(application.getAttribute("exception-log-level"),Log.LEVEL_ERROR);
3915            config.setExceptionLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel));
3916    
3917            // Trace Logger
3918            strLogger=application.getAttribute("trace-log");
3919            logLevel=LogUtil.toIntType(application.getAttribute("trace-log-level"),Log.LEVEL_INFO);
3920            config.setTraceLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel));
3921    
3922            // Thread Logger
3923            strLogger=hasAccess?application.getAttribute("thread-log"):"";
3924            if(StringUtil.isEmpty(strLogger) && hasCS)
3925                    strLogger=configServer.getThreadLogger().getSource();
3926            if(StringUtil.isEmpty(strLogger))
3927                    strLogger="{railo-config}/logs/thread.log";
3928            
3929            logLevel=LogUtil.toIntType(application.getAttribute("thread-log-level"),Log.LEVEL_ERROR);
3930            config.setThreadLogger(ConfigWebUtil.getLogAndSource(configServer,config,strLogger,true,logLevel));
3931            
3932            //print.o(strLogger);
3933            
3934            // Listener
3935            //boolean hasCS=configServer!=null;
3936            
3937            String strListenerType=application.getAttribute("listener-type");
3938            ApplicationListener listener;
3939            if(StringUtil.isEmpty(strListenerType) && hasCS) strListenerType=configServer.getApplicationListener().getType();
3940    
3941            // none
3942            if("none".equalsIgnoreCase(strListenerType))    {
3943                    listener=new NoneAppListener();
3944                    listener.setType("none");
3945            }
3946            // classic
3947            else if("classic".equalsIgnoreCase(strListenerType)){
3948                    listener=new ClassicAppListener();
3949                    listener.setType("classic");
3950            }
3951            // modern
3952            else if("modern".equalsIgnoreCase(strListenerType))     {
3953                    listener=new ModernAppListener();
3954                    listener.setType("modern");
3955            }
3956            // mixed
3957            else {
3958                    listener=new MixedAppListener();
3959                    listener.setType("mixed");
3960            }
3961            
3962            
3963            String strListenerMode=application.getAttribute("listener-mode");
3964            int listenerMode=ApplicationListener.MODE_CURRENT2ROOT;
3965            if(StringUtil.isEmpty(strListenerMode) && hasCS) {
3966               listenerMode=configServer.getApplicationListener().getMode();
3967            }
3968            else if("current".equalsIgnoreCase(strListenerMode) || "curr".equalsIgnoreCase(strListenerMode))                
3969                    listenerMode=ApplicationListener.MODE_CURRENT;
3970            else if("current2root".equalsIgnoreCase(strListenerMode) || "curr2root".equalsIgnoreCase(strListenerMode))              
3971                    listenerMode=ApplicationListener.MODE_CURRENT2ROOT;
3972            else if("root".equalsIgnoreCase(strListenerMode))               
3973                    listenerMode=ApplicationListener.MODE_ROOT;
3974            
3975            listener.setMode(listenerMode);    
3976            config.setApplicationListener(listener);
3977            
3978         // Req Timeout URL
3979            String allowURLReqTimeout=application.getAttribute("allow-url-requesttimeout");
3980            if(hasAccess && !StringUtil.isEmpty(allowURLReqTimeout)) {
3981                    config.setAllowURLRequestTimeout(Caster.toBooleanValue(allowURLReqTimeout,false));
3982                }
3983                else if(hasCS) config.setAllowURLRequestTimeout(configServer.isAllowURLRequestTimeout());
3984    
3985            
3986            // Req Timeout
3987            String reqTimeoutApplication=application.getAttribute("requesttimeout");
3988            String reqTimeoutScope=scope.getAttribute("requesttimeout"); // deprecated
3989            if(hasAccess && !StringUtil.isEmpty(reqTimeoutApplication)) {
3990                    config.setRequestTimeout(reqTimeoutApplication);
3991                }
3992            else if(hasAccess && !StringUtil.isEmpty(reqTimeoutScope)) {
3993                    config.setRequestTimeout(reqTimeoutScope);
3994                }
3995                else if(hasCS) config.setRequestTimeout(configServer.getRequestTimeout());
3996    
3997            // Req Timeout Log
3998            String strReqTimeLog=application.getAttribute("requesttimeout-log");
3999            if(StringUtil.isEmpty(strReqTimeLog))strReqTimeLog=scope.getAttribute("requesttimeout-log"); // deprecated
4000            logLevel=LogUtil.toIntType(application.getAttribute("requesttimeout-log-level"),-1);
4001            if(logLevel==-1)logLevel=LogUtil.toIntType(scope.getAttribute("requesttimeout-log-level"),Log.LEVEL_ERROR); // deprecated
4002            config.setRequestTimeoutLogger(ConfigWebUtil.getLogAndSource(configServer,config,strReqTimeLog,hasAccess,logLevel));
4003    
4004            // script-protect
4005            String strScriptProtect=application.getAttribute("script-protect");
4006            
4007            if(hasAccess && !StringUtil.isEmpty(strScriptProtect)) {
4008                    //print.err("sp:"+strScriptProtect);
4009                    config.setScriptProtect(AppListenerUtil.translateScriptProtect(strScriptProtect));
4010                }
4011                else if(hasCS) config.setScriptProtect(configServer.getScriptProtect());
4012            
4013            // classic-date-parsing
4014            if(config instanceof ConfigServer){
4015                    String strClassicDateParsing=application.getAttribute("classic-date-parsing");
4016                    
4017                    if(!StringUtil.isEmpty(strClassicDateParsing)) {
4018                            DateCaster.classicStyle=Caster.toBooleanValue(strClassicDateParsing,false);
4019                        }
4020            }
4021            
4022            
4023    
4024                // Cache
4025                    Resource configDir=config.getConfigDir();
4026                    String strCacheDirectory=application.getAttribute("cache-directory");
4027                    if(hasAccess && !StringUtil.isEmpty(strCacheDirectory)) {
4028                    strCacheDirectory=ConfigWebUtil.translateOldPath(strCacheDirectory);
4029                    Resource res = ConfigWebUtil.getFile(configDir,strCacheDirectory, "cache",configDir,FileUtil.TYPE_DIR,config);
4030                        config.setCacheDir(res);
4031                }
4032                    else {
4033                            config.setCacheDir(configDir.getRealResource("cache"));
4034                    }
4035                    
4036                String strMax=application.getAttribute("cache-directory-max-size");
4037                if(hasAccess && !StringUtil.isEmpty(strMax)) {
4038                    config.setCacheDirSize(ByteSizeParser.parseByteSizeDefinition(strMax,config.getCacheDirSize()));
4039                }
4040                else if(hasCS) config.setCacheDirSize(configServer.getCacheDirSize());
4041    
4042                
4043                //admin sync
4044                String strClass=application.getAttribute("admin-sync-class");
4045                    if(StringUtil.isEmpty(strClass))strClass=scope.getAttribute("admin-sync");
4046                    if(StringUtil.isEmpty(strClass))strClass=scope.getAttribute("admin-synchronisation-class");
4047                    if(StringUtil.isEmpty(strClass))strClass=scope.getAttribute("admin-synchronisation");
4048            
4049                if(hasAccess && !StringUtil.isEmpty(strClass)){     
4050                    try {
4051                                    Class clazz = ClassUtil.loadClass(config.getClassLoader(),strClass);
4052                                    if(!Reflector.isInstaneOf(clazz,AdminSync.class))
4053                                    throw new ApplicationException("class ["+clazz.getName()+"] does not implement interface ["+AdminSync.class.getName()+"]");
4054                                    config.setAdminSyncClass(clazz);
4055                                    
4056                            } catch (ClassException e) {
4057                                    e.printStackTrace();
4058                            }
4059            }
4060                else if(hasCS) config.setAdminSyncClass(configServer.getAdminSyncClass());   
4061        }
4062        
4063        /**
4064             * cast a string value to a int
4065             * @param value String value represent a int value
4066             * @param defaultValue if can't cast to a int is value will be returned
4067             * @return int value
4068             */
4069            public static int toInt(String value, int defaultValue) {
4070                    
4071                    if(value==null || value.trim().length()==0) return defaultValue;
4072                    int intValue=Caster.toIntValue(value.trim(),Integer.MIN_VALUE);
4073                    if(intValue==Integer.MIN_VALUE) return defaultValue;
4074                    return intValue;
4075            }
4076            
4077            public static long toLong(String value, long defaultValue) {
4078                    
4079                    if(value==null || value.trim().length()==0) return defaultValue;
4080                    long longValue=Caster.toLongValue(value.trim(),Long.MIN_VALUE);
4081                    if(longValue==Long.MIN_VALUE) return defaultValue;
4082                    return longValue;
4083            }
4084    
4085            /**
4086             * cast a string value to a boolean
4087             * @param value String value represent a booolean ("yes", "no","true" aso.)
4088             * @param defaultValue if can't cast to a boolean is value will be returned
4089             * @return boolean value
4090             */
4091            private static boolean toBoolean(String value, boolean defaultValue) {
4092                    
4093                    if(value==null || value.trim().length()==0) return defaultValue;
4094                    
4095                    try {
4096                            return Caster.toBooleanValue(value.trim());
4097                    } catch (PageException e) {
4098                            return defaultValue;
4099                    }
4100            }
4101        
4102    
4103        /* *
4104             * return first direct child Elements of a Element with given Name and matching attribute
4105         * @param parent
4106         * @param nodeName
4107         * @param attributeName
4108         * @param attributeValue
4109         * @return matching children
4110         * /
4111            private static Element getChildByName(Node parent, String nodeName, String attributeName, String attributeValue) {
4112            if(parent==null) return null;
4113            NodeList list=parent.getChildNodes();
4114            int len=list.getLength();
4115            
4116            for(int i=0;i<len;i++) {
4117                Node node=list.item(i);
4118                if(node.getNodeType()==Node.ELEMENT_NODE && node.getNodeName().equalsIgnoreCase(nodeName)) {
4119                    Element el=(Element) node;
4120                    if(el.getAttribute(attributeName).equalsIgnoreCase(attributeValue))
4121                        return el;
4122                }
4123            }
4124            return null;
4125        }*/
4126        
4127        /**
4128             * return first direct child Elements of a Element with given Name
4129         * @param parent
4130         * @param nodeName
4131         * @return matching children
4132         */
4133            public static Element getChildByName(Node parent, String nodeName) {
4134                    return getChildByName(parent, nodeName, false);
4135            }
4136    
4137        public static Element getChildByName(Node parent, String nodeName,boolean insertBefore) {
4138            return getChildByName(parent, nodeName, insertBefore, false);
4139        }
4140            
4141        public static Element getChildByName(Node parent, String nodeName,boolean insertBefore, boolean doNotCreate) {
4142            if(parent==null) return null;
4143            NodeList list=parent.getChildNodes();
4144            int len=list.getLength();
4145            
4146            for(int i=0;i<len;i++) {
4147                Node node=list.item(i);
4148                
4149                if(node.getNodeType()==Node.ELEMENT_NODE && node.getNodeName().equalsIgnoreCase(nodeName)) {
4150                    return (Element) node;
4151                }
4152            }
4153            if(doNotCreate) return null;
4154            
4155            Element newEl = parent.getOwnerDocument().createElement(nodeName);
4156            if(insertBefore)parent.insertBefore(newEl, parent.getFirstChild());
4157            else parent.appendChild(newEl);
4158            
4159            
4160    
4161            
4162            return newEl;
4163        }
4164        
4165        
4166        
4167    
4168            /**
4169             * return all direct child Elements of a Element with given Name
4170         * @param parent
4171         * @param nodeName
4172         * @return matching children
4173         */
4174        public static Element[] getChildren(Node parent, String nodeName) {
4175            if(parent==null) return new Element[0];
4176            NodeList list=parent.getChildNodes();
4177            int len=list.getLength();
4178            ArrayList rtn=new ArrayList();
4179            
4180            for(int i=0;i<len;i++) {
4181                Node node=list.item(i);
4182                if(node.getNodeType()==Node.ELEMENT_NODE && node.getNodeName().equalsIgnoreCase(nodeName)) {
4183                    rtn.add(node);
4184                }
4185            }
4186            return (Element[]) rtn.toArray(new Element[rtn.size()]);
4187        }
4188    }