001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.tag;
020
021import java.io.IOException;
022import java.net.MalformedURLException;
023import java.net.URL;
024import java.security.cert.X509Certificate;
025import java.sql.Connection;
026import java.sql.Driver;
027import java.sql.SQLException;
028import java.util.ArrayList;
029import java.util.Arrays;
030import java.util.Enumeration;
031import java.util.Iterator;
032import java.util.List;
033import java.util.Locale;
034import java.util.Map;
035import java.util.Map.Entry;
036import java.util.TimeZone;
037
038import javax.servlet.ServletConfig;
039import javax.servlet.jsp.tagext.Tag;
040
041import lucee.commons.collection.MapFactory;
042import lucee.commons.db.DBUtil;
043import lucee.commons.digest.MD5;
044import lucee.commons.io.CompressUtil;
045import lucee.commons.io.IOUtil;
046import lucee.commons.io.SystemUtil;
047import lucee.commons.io.cache.Cache;
048import lucee.commons.io.cache.Cache2;
049import lucee.commons.io.log.LoggerAndSourceData;
050import lucee.commons.io.log.log4j.Log4jUtil;
051import lucee.commons.io.res.Resource;
052import lucee.commons.io.res.filter.DirectoryResourceFilter;
053import lucee.commons.io.res.filter.ExtensionResourceFilter;
054import lucee.commons.io.res.filter.NotResourceFilter;
055import lucee.commons.io.res.filter.OrResourceFilter;
056import lucee.commons.io.res.filter.ResourceFilter;
057import lucee.commons.io.res.util.ResourceUtil;
058import lucee.commons.lang.ClassException;
059import lucee.commons.lang.ClassUtil;
060import lucee.commons.lang.ExceptionUtil;
061import lucee.commons.lang.IDGenerator;
062import lucee.commons.lang.StringUtil;
063import lucee.commons.net.JarLoader;
064import lucee.commons.surveillance.HeapDumper;
065import lucee.runtime.CFMLFactory;
066import lucee.runtime.CFMLFactoryImpl;
067import lucee.runtime.Mapping;
068import lucee.runtime.MappingImpl;
069import lucee.runtime.PageContextImpl;
070import lucee.runtime.PageSource;
071import lucee.runtime.PageSourceImpl;
072import lucee.runtime.cache.CacheConnection;
073import lucee.runtime.cfx.customtag.CFXTagClass;
074import lucee.runtime.cfx.customtag.CPPCFXTagClass;
075import lucee.runtime.cfx.customtag.JavaCFXTagClass;
076import lucee.runtime.config.AdminSync;
077import lucee.runtime.config.Config;
078import lucee.runtime.config.ConfigImpl;
079import lucee.runtime.config.ConfigServer;
080import lucee.runtime.config.ConfigServerImpl;
081import lucee.runtime.config.ConfigWeb;
082import lucee.runtime.config.ConfigWebAdmin;
083import lucee.runtime.config.ConfigWebFactory;
084import lucee.runtime.config.ConfigWebImpl;
085import lucee.runtime.config.ConfigWebUtil;
086import lucee.runtime.config.DebugEntry;
087import lucee.runtime.config.DeployHandler;
088import lucee.runtime.config.Password;
089import lucee.runtime.config.RemoteClient;
090import lucee.runtime.config.RemoteClientImpl;
091import lucee.runtime.db.DataSource;
092import lucee.runtime.db.DataSourceImpl;
093import lucee.runtime.db.DataSourceManager;
094import lucee.runtime.debug.DebuggerPro;
095import lucee.runtime.engine.CFMLEngineImpl;
096import lucee.runtime.engine.ExecutionLogFactory;
097import lucee.runtime.engine.ThreadLocalPageContext;
098import lucee.runtime.exp.ApplicationException;
099import lucee.runtime.exp.DatabaseException;
100import lucee.runtime.exp.DeprecatedException;
101import lucee.runtime.exp.PageException;
102import lucee.runtime.exp.PageExceptionImpl;
103import lucee.runtime.exp.SecurityException;
104import lucee.runtime.ext.tag.DynamicAttributes;
105import lucee.runtime.ext.tag.TagImpl;
106import lucee.runtime.extension.Extension;
107import lucee.runtime.extension.ExtensionImpl;
108import lucee.runtime.extension.ExtensionProvider;
109import lucee.runtime.functions.cache.Util;
110import lucee.runtime.gateway.GatewayEngineImpl;
111import lucee.runtime.gateway.GatewayEntry;
112import lucee.runtime.gateway.GatewayEntryImpl;
113import lucee.runtime.gateway.GatewayUtil;
114import lucee.runtime.i18n.LocaleFactory;
115import lucee.runtime.instrumentation.InstrumentationUtil;
116import lucee.runtime.listener.AppListenerUtil;
117import lucee.runtime.listener.ApplicationListener;
118import lucee.runtime.monitor.IntervallMonitor;
119import lucee.runtime.monitor.Monitor;
120import lucee.runtime.monitor.RequestMonitor;
121import lucee.runtime.net.http.CertificateInstaller;
122import lucee.runtime.net.http.ReqRspUtil;
123import lucee.runtime.net.mail.SMTPException;
124import lucee.runtime.net.mail.SMTPVerifier;
125import lucee.runtime.net.mail.Server;
126import lucee.runtime.net.mail.ServerImpl;
127import lucee.runtime.net.proxy.ProxyData;
128import lucee.runtime.net.proxy.ProxyDataImpl;
129import lucee.runtime.op.Caster;
130import lucee.runtime.op.Decision;
131import lucee.runtime.op.Duplicator;
132import lucee.runtime.op.date.DateCaster;
133import lucee.runtime.orm.ORMConfiguration;
134import lucee.runtime.orm.ORMConfigurationImpl;
135import lucee.runtime.reflection.Reflector;
136import lucee.runtime.rest.RestUtil;
137import lucee.runtime.security.SecurityManager;
138import lucee.runtime.security.SecurityManagerImpl;
139import lucee.runtime.spooler.ExecutionPlan;
140import lucee.runtime.spooler.SpoolerEngine;
141import lucee.runtime.spooler.SpoolerEngineImpl;
142import lucee.runtime.spooler.SpoolerTask;
143import lucee.runtime.spooler.remote.RemoteClientTask;
144import lucee.runtime.type.Array;
145import lucee.runtime.type.ArrayImpl;
146import lucee.runtime.type.Collection;
147import lucee.runtime.type.Collection.Key;
148import lucee.runtime.type.KeyImpl;
149import lucee.runtime.type.Query;
150import lucee.runtime.type.QueryImpl;
151import lucee.runtime.type.Struct;
152import lucee.runtime.type.StructImpl;
153import lucee.runtime.type.dt.DateTime;
154import lucee.runtime.type.dt.DateTimeImpl;
155import lucee.runtime.type.dt.TimeSpan;
156import lucee.runtime.type.scope.Cluster;
157import lucee.runtime.type.scope.ClusterEntryImpl;
158import lucee.runtime.type.util.ComponentUtil;
159import lucee.runtime.type.util.KeyConstants;
160import lucee.transformer.library.function.FunctionLib;
161import lucee.transformer.library.tag.TagLib;
162
163import org.apache.log4j.Level;
164import org.xml.sax.SAXException;
165
166/**
167 * 
168 */
169public final class Admin extends TagImpl implements DynamicAttributes {
170    
171    private static final short TYPE_WEB=0;
172    private static final short TYPE_SERVER=1;
173
174    private static final short ACCESS_FREE=0;
175    private static final short ACCESS_NOT_WHEN_WEB=1;
176    private static final short ACCESS_NOT_WHEN_SERVER=2;
177    private static final short ACCESS_NEVER=3;
178
179    private static final short ACCESS_READ=10;
180    private static final short ACCESS_WRITE=11;
181
182        //private static final String USAGE_SYNC = "synchronisation";
183        //private static final String USAGE_CLUSTER = "cluster";
184        public static final String[] ORM_JARS = new String[]{"antlr.jar","dom4j.jar","hibernate.jar","javassist.jar","jta.jar","slf4j-api.jar","lucee-sl4j.jar"};
185        public static final String[] CACHE_JARS = new String[]{"ehcache.jar"};
186        public static final String[] CFX_JARS = new String[]{"com.naryx.tagfusion.cfx.jar"};
187        public static final String[] UPDATE_JARS = new String[]{"lucee-inst.jar","ehcache.jar","antlr.jar","dom4j.jar","hibernate.jar","javassist.jar","jta.jar","slf4j-api.jar","lucee-sl4j.jar","metadata-extractor.jar","icepdf-core.jar","com.naryx.tagfusion.cfx.jar"};
188
189        
190        private static final Collection.Key DEBUG = KeyConstants._debug;
191        //private static final Collection.Key DEBUG_TEMPLATE = KeyImpl.intern("debugTemplate");
192        private static final Collection.Key DEBUG_SHOW_QUERY_USAGE = KeyImpl.intern("debugShowQueryUsage");
193        //private static final Collection.Key STR_DEBUG_TEMPLATE = KeyImpl.intern("strdebugTemplate");
194        private static final Collection.Key TEMPLATES = KeyConstants._templates;
195        private static final Collection.Key STR = KeyConstants._str;
196        private static final Collection.Key DO_STATUS_CODE = KeyImpl.intern("doStatusCode");
197        private static final Collection.Key LABEL = KeyConstants._label;
198        private static final Collection.Key FILE_ACCESS = KeyImpl.intern("file_access");
199        private static final Collection.Key IP_RANGE = KeyImpl.intern("ipRange");
200        private static final Collection.Key CUSTOM = KeyConstants._custom;
201        private static final Collection.Key READONLY = KeyImpl.intern("readOnly");
202        private static final Collection.Key LOG_ENABLED = KeyImpl.intern("logEnabled");
203        private static final Collection.Key CLASS = KeyConstants._class;
204
205        private static final Key HAS_OWN_SEC_CONTEXT = KeyImpl.intern("hasOwnSecContext");
206        private static final Key CONFIG_FILE = KeyImpl.intern("config_file");
207        private static final Key PROCEDURE = KeyImpl.intern("procedure");
208        private static final Key SERVER_LIBRARY = KeyImpl.intern("serverlibrary");
209        private static final Key KEEP_ALIVE = KeyImpl.intern("keepalive");
210        private static final Key CLIENT_SIZE = KeyImpl.intern("clientSize");
211        private static final Key SESSION_SIZE = KeyImpl.intern("sessionSize");
212        private static final Key CLIENT_ELEMENTS = KeyImpl.intern("clientElements");
213        private static final Key SESSION_ELEMENTS = KeyImpl.intern("sessionElements");
214
215        private static final short MAPPING_REGULAR = 1;
216        private static final short MAPPING_CT = 2;
217        private static final short MAPPING_CFC = 4;
218        
219        
220        
221        /*
222        others:
223        PDFRenderer.jar
224        ?
225        xmlparserv2.jar
226        
227        not needed:
228        slf4j-simple.jar
229        xdb.jar
230        
231        
232        
233        */
234        
235        
236        
237    private Struct attributes=new StructImpl();
238    private String action=null;
239    private short type;
240    private String password;
241    private ConfigWebAdmin admin;
242    private ConfigImpl config=null;
243    
244    private static final ResourceFilter FILTER_CFML_TEMPLATES=
245        new OrResourceFilter(new ResourceFilter[]{
246                new DirectoryResourceFilter(),
247                new ExtensionResourceFilter("cfm"),
248                new ExtensionResourceFilter("cfc"),
249                new ExtensionResourceFilter("cfml")
250        });
251        private AdminSync adminSync;
252        
253    
254    
255    @Override
256    public void release() {
257        super.release();
258        attributes.clear();
259    }
260    
261    @Override
262    public void setDynamicAttribute(String uri, String localName, Object value) {
263        attributes.setEL(KeyImpl.getInstance(localName),value);
264    }
265    public void setDynamicAttribute(String uri, Collection.Key localName, Object value) {
266        attributes.setEL(localName,value);
267    }
268    
269    @Override
270    public int doStartTag() throws PageException {
271        //adminSync = pageContext.getAdminSync();
272        config=(ConfigImpl)pageContext.getConfig();
273
274        
275        // Action
276        Object objAction=attributes.get(KeyConstants._action);
277        if(objAction==null)throw new ApplicationException("missing attrbute action for tag admin");
278        action=StringUtil.toLowerCase(Caster.toString(objAction)).trim();
279        
280        // Generals
281        if(action.equals("getlocales")) {
282            doGetLocales();
283            return SKIP_BODY;
284        }
285        if(action.equals("gettimezones")) {
286            doGetTimeZones();
287            return SKIP_BODY;
288        }
289        if(action.equals("printdebug")) {
290                throw new DeprecatedException("action [printdebug] is no longer supported, use instead [getdebugdata]");
291        }
292        if(action.equals("getdebugdata")) {
293            doGetDebugData();
294            return SKIP_BODY;
295        }
296        if(action.equals("adddump")) {
297            doAddDump();
298            return SKIP_BODY;
299        }
300        if(action.equals("getloginsettings")) {
301                doGetLoginSettings();
302            return SKIP_BODY;
303        }
304
305        // Type
306        type=toType(getString("type","web"),true);
307        
308        // has Password
309        if(action.equals("haspassword")) {
310           //long start=System.currentTimeMillis();
311            boolean hasPassword=type==TYPE_WEB?
312                    pageContext.getConfig().hasPassword():
313                    pageContext.getConfig().hasServerPassword();
314                    
315            pageContext.setVariable(getString("admin",action,"returnVariable",true),Caster.toBoolean(hasPassword));
316            return SKIP_BODY;
317        }
318        
319        // update Password
320        else if(action.equals("updatepassword")) {
321                try{    
322                        ((ConfigWebImpl)pageContext.getConfig()).updatePassword(type!=TYPE_WEB,
323                                        getString("oldPassword",null),getString("admin",action,"newPassword",true));
324                } 
325                catch (Exception e) {
326                    throw Caster.toPageException(e);
327                }
328            return SKIP_BODY;
329        }
330        
331
332               
333        try {
334                        _doStartTag();
335                } catch (IOException e) {
336                        throw Caster.toPageException(e);
337                }
338        
339        return Tag.SKIP_BODY;
340    }
341
342    private void doAddDump() throws ApplicationException {
343                DebuggerPro debugger=(DebuggerPro) pageContext.getDebugger();
344                PageSource ps = pageContext.getCurrentTemplatePageSource();
345                debugger.addDump(ps, getString("admin",action,"dump",true));
346        }
347
348        private short toType(String strType, boolean throwError) throws ApplicationException {
349        strType=StringUtil.toLowerCase(strType).trim();
350        if("web".equals(strType))return TYPE_WEB;
351        else if("server".equals(strType))return TYPE_SERVER;
352        if(throwError)
353                throw new ApplicationException("invalid value for attribute type ["+strType+"] of tag admin","valid values are web, server");
354        return TYPE_WEB;
355        }
356
357        private void doTagSchedule() throws PageException {
358                Schedule schedule=new Schedule();
359                try {
360                        
361                        
362                        schedule.setPageContext(pageContext);
363                        schedule.setAction(getString("admin",action,"scheduleAction"));
364                        schedule.setTask(getString("task",null));
365                        schedule.setHidden(getBoolV("hidden",false));
366                        schedule.setReadonly(getBoolV("readonly",false));
367                        schedule.setOperation(getString("operation",null));
368                        schedule.setFile(getString("file",null));
369                        schedule.setPath(getString("path",null));
370                        schedule.setStartdate(getObject("startDate",null));
371                        schedule.setStarttime(getObject("startTime",null));
372                        schedule.setUrl(getString("url",null));
373                        schedule.setPublish(getBoolV("publish",false));
374                        schedule.setEnddate(getObject("endDate",null));
375                        schedule.setEndtime(getObject("endTime",null));
376                        schedule.setInterval(getString("interval",null));
377                        schedule.setRequesttimeout(new Double(getDouble("requestTimeOut",-1)));
378                        schedule.setUsername(getString("username",null));
379                        schedule.setPassword(getString("schedulePassword",null));
380                        schedule.setProxyserver(getString("proxyServer",null));
381                        schedule.setProxyuser(getString("proxyuser",null));
382                        schedule.setProxypassword(getString("proxyPassword",null));
383                        schedule.setResolveurl(getBoolV("resolveURL",false));
384                        schedule.setPort(new Double(getDouble("port",-1)));
385                        schedule.setProxyport(new Double(getDouble("proxyPort",80)));
386                        schedule.setReturnvariable(getString("returnvariable","cfschedule"));
387                        
388                        schedule.doStartTag();    
389                } 
390                finally {
391                    schedule.release();
392                    adminSync.broadcast(attributes, config);
393                    adminSync.broadcast(attributes, config);
394                }
395        }
396    
397    /*private void doTagSearch() throws PageException {
398                Search search=new Search();
399                try {
400                        
401                        search.setPageContext(pageContext);
402                        
403                        search.setName(getString("admin",action,"name"));
404                        search.setCollection(getString("admin",action,"collection"));
405                        search.setType(getString("type",null));
406                        search.setMaxrows(getDouble("maxRows",-1));
407                        search.setStartrow(getDouble("startRow",1));
408                        search.setCategory(getString("category",null));
409                        search.setCategorytree(getString("categoryTree",null));
410                        search.setStatus(getString("status",null));
411                        search.setSuggestions(getString("suggestions",null));
412                        
413                        search.doStartTag();    
414                } 
415                finally {
416                    search.release();
417                }
418        }*/
419    
420    private void doTagIndex() throws PageException {
421                Index index=new Index();
422                try {
423                        
424                        index.setPageContext(pageContext);
425                        
426                        index.setCollection(getString("admin",action,"collection"));
427                        index.setAction(getString("admin",action,"indexAction"));
428                        index.setType(getString("indexType",null));
429                        index.setTitle(getString("title",null));
430                        index.setKey(getString("key",null));
431                        index.setBody(getString("body",null));
432                        index.setCustom1(getString("custom1",null));
433                        index.setCustom2(getString("custom2",null));
434                        index.setCustom3(getString("custom3",null));
435                        index.setCustom4(getString("custom4",null));
436                        index.setUrlpath(getString("URLpath",null));
437                        index.setExtensions(getString("extensions",null));
438                        index.setQuery(getString("query",null));
439                        index.setRecurse(getBoolV("recurse",false));
440                        index.setLanguage(getString("language",null));
441                        index.setCategory(getString("category",null));
442                        index.setCategorytree(getString("categoryTree",null));
443                        index.setStatus(getString("status",null));
444                        index.setPrefix(getString("prefix",null));
445                        
446                        index.doStartTag();    
447                } 
448                finally {
449                    index.release();
450                    adminSync.broadcast(attributes, config);
451                }
452        }
453    
454
455    private void doTagCollection() throws PageException {
456        lucee.runtime.tag.Collection coll=new lucee.runtime.tag.Collection();
457                try {
458                        
459                        coll.setPageContext(pageContext);
460                        
461                        //coll.setCollection(getString("admin",action,"collection"));
462                        coll.setAction(getString("collectionAction",null));
463                        coll.setCollection(getString("collection",null));
464                        coll.setPath(getString("path",null));
465                        coll.setLanguage(getString("language",null));
466                        coll.setName(getString("name",null));
467                        
468                        
469                        coll.doStartTag();    
470                } 
471                finally {
472                    coll.release();
473                    adminSync.broadcast(attributes, config);
474                }
475        }
476    
477        /**
478     * @throws PageException
479     * 
480     */
481    private void _doStartTag() throws PageException,IOException {
482        config=(ConfigImpl)pageContext.getConfig();
483
484        // getToken
485        if(action.equals("gettoken")) {
486            doGetToken();
487            return;
488        }
489        
490
491        // schedule
492        if(action.equals("schedule")) {
493                doTagSchedule();
494            return;
495        }
496        // search
497        if(action.equals("collection")) {
498                doTagCollection();
499            return;
500        }
501        // index
502        if(action.equals("index")) {
503                doTagIndex();
504            return;
505        }
506        // cluster
507        if(action.equals("setcluster")) {
508                doSetCluster();
509            return;
510        }
511        if(action.equals("getcluster")) {
512                doGetCluster();
513            return;
514        }
515        
516        if(check("hashpassword",ACCESS_FREE)) {
517                String raw=getString("admin",action,"pw");
518                Password pw=Password.hashPassword(pageContext.getConfig(),type!=TYPE_WEB,raw);
519                
520                Password changed=((ConfigWebImpl)pageContext.getConfig()).updatePasswordIfNecessary(type==TYPE_SERVER,raw);
521                if(changed!=null) pw=changed;
522                
523                pageContext.setVariable(
524                                getString("admin",action,"returnVariable"),
525                                pw.password
526                        );
527                return; // do not remove
528        }
529        
530        try {
531            // Password
532                password = getString("password","");
533                
534                
535                Password tmp = type==TYPE_SERVER?((ConfigWebImpl)config).isServerPasswordEqual(password, true):config.isPasswordEqual(password, true); // hash password if necessary (for backward compatibility)
536                if(tmp!=null)password=tmp.password;
537                
538                // Config
539            if(type==TYPE_SERVER)
540                config=(ConfigImpl)config.getConfigServer(password);
541            
542            adminSync = config.getAdminSync();
543                admin = ConfigWebAdmin.newInstance(config,password);
544        } 
545        catch (Exception e) {
546            throw Caster.toPageException(e);
547        }
548        
549                
550        if(check("connect",ACCESS_FREE) ) {
551                Password pw=ConfigWebUtil.checkPassword(config,null,password);
552                
553                
554                        ConfigWebUtil.checkGeneralReadAccess(config,password);
555                        
556                try{
557                        if(config instanceof ConfigServer)
558                                ((PageContextImpl)pageContext).setServerPassword(password);
559                }
560                catch(Throwable t){
561                        ExceptionUtil.rethrowIfNecessary(t);
562                }
563                
564                
565                
566                
567        }
568        else if(check("getinfo",           ACCESS_FREE) && check2(ACCESS_READ  )) doGetInfo();
569        else if(check("surveillance",           ACCESS_FREE) && check2(ACCESS_READ  )) doSurveillance();
570        else if(check("getRegional",            ACCESS_FREE) && check2(ACCESS_READ  )) doGetRegional();
571        else if(check("isMonitorEnabled",       ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ  )) doIsMonitorEnabled();
572        else if(check("resetORMSetting",            ACCESS_FREE) && check2(ACCESS_READ  )) doResetORMSetting();
573        else if(check("getORMSetting",            ACCESS_FREE) && check2(ACCESS_READ  )) doGetORMSetting();
574        else if(check("getORMEngine",            ACCESS_FREE) && check2(ACCESS_READ  )) doGetORMEngine();
575        else if(check("updateORMSetting",            ACCESS_FREE) && check2(ACCESS_READ  )) doUpdateORMSetting();
576        else if(check("getApplicationListener", ACCESS_FREE) && check2(ACCESS_READ  )) doGetApplicationListener();
577        else if(check("getProxy",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetProxy();
578        else if(check("getCharset",             ACCESS_FREE) && check2(ACCESS_READ  )) doGetCharset();
579        else if(check("getComponent",           ACCESS_FREE) && check2(ACCESS_READ  )) doGetComponent();
580        else if(check("getScope",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetScope();
581        else if(check("getApplicationSetting",  ACCESS_FREE) && check2(ACCESS_READ  )) doGetApplicationSetting();
582        else if(check("getQueueSetting",        ACCESS_FREE) && check2(ACCESS_READ  )) doGetQueueSetting();
583        else if(check("getOutputSetting",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetOutputSetting();
584        else if(check("getDatasourceSetting",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetDatasourceSetting();
585        else if(check("getCustomTagSetting",    ACCESS_FREE) && check2(ACCESS_READ  )) doGetCustomTagSetting();
586        else if(check("getDatasource",          ACCESS_FREE) && check2(ACCESS_READ  )) doGetDatasource();
587        else if(check("getDatasources",         ACCESS_FREE) && check2(ACCESS_READ  )) doGetDatasources();
588        else if(check("getCacheConnections",    ACCESS_FREE) && check2(ACCESS_READ  )) doGetCacheConnections();
589        else if(check("getCacheConnection",     ACCESS_FREE) && check2(ACCESS_READ  )) doGetCacheConnection();
590        else if(check("getCacheDefaultConnection",ACCESS_FREE) && check2(ACCESS_READ  )) doGetCacheDefaultConnection();
591        else if(check("getRemoteClients",       ACCESS_FREE) && check2(ACCESS_READ  )) doGetRemoteClients();
592        else if(check("getRemoteClient",        ACCESS_FREE) && check2(ACCESS_READ  )) doGetRemoteClient();
593        else if(check("hasRemoteClientUsage",   ACCESS_FREE) && check2(ACCESS_READ  )) doHasRemoteClientUsage();
594        else if(check("getRemoteClientUsage",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetRemoteClientUsage();
595        else if(check("getSpoolerTasks",                ACCESS_FREE) && check2(ACCESS_READ  )) doGetSpoolerTasks();
596        else if(check("getPerformanceSettings", ACCESS_FREE) && check2(ACCESS_READ  )) doGetPerformanceSettings();
597        else if(check("getLogSettings", ACCESS_FREE) && check2(ACCESS_READ  )) doGetLogSettings();
598        else if(check("getCompilerSettings", ACCESS_FREE) && check2(ACCESS_READ  )) doGetCompilerSettings();
599        else if(check("updatePerformanceSettings",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdatePerformanceSettings();
600        else if(check("updateCompilerSettings",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateCompilerSettings();
601        else if(check("getGatewayentries",    ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_READ  )) doGetGatewayEntries();
602        else if(check("getGatewayentry",     ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_READ  )) doGetGatewayEntry();
603        else if(check("getRunningThreads",     ACCESS_FREE) && check2(ACCESS_READ  )) doGetRunningThreads();
604        else if(check("getMonitors",     ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ  )) doGetMonitors();
605        else if(check("getMonitor",     ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ  )) doGetMonitor();
606        else if(check("getExecutionLog",     ACCESS_FREE) && check2(ACCESS_READ  )) doGetExecutionLog();
607        else if(check("gateway",     ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_READ  )) doGateway();
608        
609        
610        
611        // alias for getSpoolerTasks
612        else if(check("getRemoteClientTasks",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetSpoolerTasks();
613        else if(check("getDatasourceDriverList",ACCESS_FREE) && check2(ACCESS_READ  )) doGetDatasourceDriverList();
614        else if(check("getDebuggingList",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetDebuggingList();
615        else if(check("getLoggedDebugData",             ACCESS_FREE) && check2(ACCESS_READ  )) doGetLoggedDebugData();
616        else if(check("getDebugSetting",                ACCESS_FREE) && check2(ACCESS_READ  )) doGetDebugSetting();
617        else if(check("getSSLCertificate",      ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ  )) doGetSSLCertificate();
618        else if(check("getPluginDirectory",             ACCESS_FREE) && check2(ACCESS_READ  )) doGetPluginDirectory();
619        else if(check("getPlugins",             ACCESS_FREE) && check2(ACCESS_READ  )) doGetPlugins();
620        else if(check("updatePlugin",           ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdatePlugin();
621        else if(check("removePlugin",           ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemovePlugin();
622        
623        else if(check("getContextDirectory",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ  )) getContextDirectory();
624        else if(check("updateContext",          ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doUpdateContext();
625        else if(check("removeContext",          ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doRemoveContext();
626        
627        else if(check("getJars",                ACCESS_FREE) && check2(ACCESS_READ  )) doGetJars();
628        else if(check("getFlds",                ACCESS_FREE) && check2(ACCESS_READ  )) doGetFLDs();
629        else if(check("getTlds",                ACCESS_FREE) && check2(ACCESS_READ  )) doGetTLDs();
630        else if(check("getMailSetting",         ACCESS_FREE) && check2(ACCESS_READ  )) doGetMailSetting();
631        else if(check("getTaskSetting",         ACCESS_FREE) && check2(ACCESS_READ  )) doGetTaskSetting();
632        else if(check("getMailServers",         ACCESS_FREE) && check2(ACCESS_READ  )) doGetMailServers();
633        else if(check("getMapping",             ACCESS_FREE) && check2(ACCESS_READ  )) doGetMapping();
634        else if(check("getMappings",            ACCESS_FREE) && check2(ACCESS_READ  )) doGetMappings();
635        else if(check("getRestMappings",            ACCESS_FREE) && check2(ACCESS_READ  )) doGetRestMappings();
636        else if(check("getRestSettings",            ACCESS_FREE) && check2(ACCESS_READ  )) doGetRestSettings();
637        else if(check("getExtensions",                  ACCESS_FREE) && check2(ACCESS_READ  )) doGetExtensions();
638        else if(check("getExtensionProviders",  ACCESS_FREE) && check2(ACCESS_READ  )) doGetExtensionProviders();
639        else if(check("getExtensionInfo",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetExtensionInfo();
640        
641        else if(check("getCustomTagMappings",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetCustomTagMappings();
642        else if(check("getComponentMappings",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetComponentMappings();
643        else if(check("getCfxTags",             ACCESS_FREE) && check2(ACCESS_READ  )) doGetCFXTags();
644        else if(check("getCPPCfxTags",         ACCESS_FREE) && check2(ACCESS_READ  )) doGetCPPCFXTags();
645        else if(check("getJavaCfxTags",         ACCESS_FREE) && check2(ACCESS_READ  )) doGetJavaCFXTags();
646        else if(check("getDebug",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetDebug();
647        else if(check("getDebugEntry",        ACCESS_FREE) && check2(ACCESS_READ  )) doGetDebugEntry();
648        else if(check("getError",               ACCESS_FREE) && check2(ACCESS_READ  )) doGetError();
649        else if(check("verifyremoteclient",     ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyRemoteClient();
650        else if(check("verifyDatasource",       ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyDatasource();
651        else if(check("verifyCacheConnection",  ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyCacheConnection();
652        else if(check("verifyMailServer",       ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyMailServer();
653        else if(check("verifyExtensionProvider",ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyExtensionProvider();
654        else if(check("verifyJavaCFX",                  ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyJavaCFX();
655        else if(check("verifyCFX",                      ACCESS_FREE) && check2(ACCESS_READ  )) doVerifyCFX();
656        
657        else if(check("resetId",                                ACCESS_FREE) && check2(ACCESS_WRITE  )) doResetId();
658        else if(check("updateLoginSettings", ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doUpdateLoginSettings();
659        else if(check("updateLogSettings", ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateLogSettings();
660        else if(check("updateJar",                      ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateJar();
661        else if(check("updateSSLCertificate",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doUpdateSSLCertificate();
662        else if(check("updateMonitorEnabled",   ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doUpdateMonitorEnabled();
663        else if(check("updateTLD",                      ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateTLD();
664        else if(check("updateFLD",                      ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateFLD();
665        else if(check("updateregional",         ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateRegional();
666        else if(check("updateApplicationListener",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateApplicationListener();
667        else if(check("updateproxy",            ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateProxy();
668        else if(check("updateCharset",         ACCESS_FREE) && check2(ACCESS_WRITE  ))  doUpdateCharset();
669        else if(check("updatecomponent",        ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateComponent();
670        else if(check("updatescope",            ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateScope();
671        else if(check("updateRestSettings",      ACCESS_FREE) && check2(ACCESS_WRITE  ))doUpdateRestSettings();
672        else if(check("updateRestMapping",      ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateRestMapping();
673        else if(check("removeRestMapping",      ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveRestMapping();
674        else if(check("updateApplicationSetting",ACCESS_FREE) && check2(ACCESS_WRITE  ))doUpdateApplicationSettings();
675        else if(check("updateQueueSetting",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  ))              doUpdateQueueSettings();
676        else if(check("updateOutputSetting",    ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateOutputSettings();
677        else if(check("updatepsq",              ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdatePSQ();
678        else if(check("updatedatasource",       ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateDatasource();
679        else if(check("updateCacheDefaultConnection",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateCacheDefaultConnection();
680        else if(check("updateCacheConnection",  ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateCacheConnection();
681        else if(check("updateremoteclient",     ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateRemoteClient();
682        else if(check("updateRemoteClientUsage",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateRemoteClientUsage();
683        else if(check("updatemailsetting",      ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateMailSetting();
684        else if(check("updatemailserver",       ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateMailServer();
685        else if(check("updatetasksetting",      ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateTaskSetting();
686        else if(check("updatemapping",          ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateMapping();
687        else if(check("updatecustomtag",        ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateCustomTag();
688        else if(check("updateComponentMapping", ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateComponentMapping();
689        else if(check("stopThread",                     ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doStopThread();
690        
691        
692        else if(check("updatejavacfx",          ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateJavaCFX();
693        else if(check("updatecppcfx",          ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateCPPCFX();
694        else if(check("updatedebug",            ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateDebug();
695        else if(check("updatedebugentry",            ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateDebugEntry();
696        else if(check("updatedebugsetting",     ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateDebugSetting();
697        
698        else if(check("updateerror",            ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateError();
699        else if(check("updateCustomTagSetting", ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateCustomTagSetting();
700        else if(check("updateExtension",                ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateExtension();
701        else if(check("updateRHExtension",              ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateRHExtension();
702        else if(check("updateExtensionProvider",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateExtensionProvider();
703        else if(check("updateExtensionInfo",    ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateExtensionInfo();
704        else if(check("updateGatewayEntry",  ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_WRITE  )) doUpdateGatewayEntry();
705        //else if(check("updateLogSettings",  ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateUpdateLogSettings();
706        else if(check("updateMonitor",  ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doUpdateMonitor();
707        else if(check("updateExecutionLog",  ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateExecutionLog();
708        
709        
710        //else if(check("removeproxy",                  ACCESS_NOT_WHEN_SERVER  )) doRemoveProxy();
711        else if(check("removeMonitor",    ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doRemoveMonitor();
712        else if(check("removejar",                      ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveJar();
713        else if(check("removeTLD",                      ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveTLD();
714        else if(check("removeFLD",                      ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveFLD();
715        else if(check("removedatasource",       ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveDatasource();
716        else if(check("removeCacheConnection",  ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveCacheConnection();
717        else if(check("removeremoteclient",     ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveRemoteClient();
718        else if(check("removeRemoteClientUsage",ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveRemoteClientUsage();
719        else if(check("removeSpoolerTask",              ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveSpoolerTask();
720        else if(check("removeAllSpoolerTask",   ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveAllSpoolerTask();
721        // alias for executeSpoolerTask
722        else if(check("removeRemoteClientTask", ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveSpoolerTask();
723        else if(check("executeSpoolerTask",             ACCESS_FREE) && check2(ACCESS_WRITE  )) doExecuteSpoolerTask();
724        // alias for executeSpoolerTask
725        else if(check("executeRemoteClientTask",ACCESS_FREE) && check2(ACCESS_WRITE  )) doExecuteSpoolerTask();
726        else if(check("removemailserver",       ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveMailServer();
727        else if(check("removemapping",          ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveMapping();
728        else if(check("removecustomtag",        ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveCustomTag();
729        else if(check("removecomponentmapping", ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveComponentMapping();
730        else if(check("removecfx",              ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveCFX();
731        else if(check("removeExtension",        ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveExtension();
732        else if(check("removeExtensionProvider",ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveExtensionProvider();
733        else if(check("removeDefaultPassword",  ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveDefaultPassword();
734        else if(check("removeGatewayEntry",     ACCESS_NOT_WHEN_SERVER) && check2(ACCESS_WRITE  )) doRemoveGatewayEntry();
735        else if(check("removeDebugEntry",               ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveDebugEntry();
736        else if(check("removeCacheDefaultConnection",ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveCacheDefaultConnection();
737        else if(check("removeLogSetting",ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveLogSetting();
738        
739        else if(check("storageGet",             ACCESS_FREE) && check2(ACCESS_READ  )) doStorageGet();
740        else if(check("storageSet",             ACCESS_FREE) && check2(ACCESS_WRITE  )) doStorageSet();
741        
742        else if(check("getdefaultpassword",     ACCESS_FREE) && check2(ACCESS_READ            )) doGetDefaultPassword();
743        else if(check("getContexts",           ACCESS_FREE) && check2(ACCESS_READ            )) doGetContexts();
744        else if(check("getContextes",           ACCESS_FREE) && check2(ACCESS_READ            )) doGetContexts();
745        else if(check("updatedefaultpassword",  ACCESS_FREE) && check2(ACCESS_WRITE            )) doUpdateDefaultPassword();
746        else if(check("hasindividualsecurity",  ACCESS_FREE) && check2(ACCESS_READ            )) doHasIndividualSecurity();
747        else if(check("resetpassword",          ACCESS_FREE) && check2(ACCESS_WRITE            )) doResetPassword();
748        else if(check("stopThread",                     ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE  )) doStopThread();
749
750        else if(check("updateAuthKey",          ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE   )) doUpdateAuthKey();
751        else if(check("removeAuthKey",          ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE   )) doRemoveAuthKey();
752        else if(check("listAuthKey",          ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE   )) doListAuthKey();
753
754        else if(check("updateAPIKey",          ACCESS_FREE) && check2(ACCESS_WRITE   )) doUpdateAPIKey();
755        else if(check("removeAPIKey",          ACCESS_FREE) && check2(ACCESS_WRITE   )) doRemoveAPIKey();
756        else if(check("getAPIKey",          ACCESS_FREE) && check2(ACCESS_READ   )) doGetAPIKey();
757        
758        else if(check("createsecuritymanager",  ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE            )) doCreateSecurityManager();
759        else if(check("getsecuritymanager",     ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ            )) doGetSecurityManager();
760        else if(check("removesecuritymanager",  ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE            )) doRemoveSecurityManager();
761        else if(check("getdefaultsecuritymanager",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ          )) doGetDefaultSecurityManager();
762        else if(check("updatesecuritymanager",  ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE            )) doUpdateSecurityManager();
763        else if(check("updatedefaultsecuritymanager",ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE       )) doUpdateDefaultSecurityManager();
764        else if(check("compileMapping",         ACCESS_FREE) && check2(ACCESS_WRITE             )) doCompileMapping();
765        else if(check("compileComponentMapping",         ACCESS_FREE) && check2(ACCESS_WRITE             )) doCompileComponentMapping();
766        else if(check("compileCTMapping",         ACCESS_FREE) && check2(ACCESS_WRITE             )) doCompileCTMapping();
767        else if(check("createArchive",         ACCESS_FREE) && check2(ACCESS_WRITE             )) doCreateArchive(MAPPING_REGULAR);
768        else if(check("createComponentArchive",         ACCESS_FREE) && check2(ACCESS_WRITE             )) doCreateArchive(MAPPING_CFC);
769        else if(check("createCTArchive",         ACCESS_FREE) && check2(ACCESS_WRITE             )) doCreateArchive(MAPPING_CT);
770        else if(check("reload",                         ACCESS_FREE) && check2(ACCESS_WRITE            )) doReload();
771        
772
773        else if(check("getResourceProviders",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetResourceProviders();
774        else if(check("updateResourceProvider", ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateResourceProvider();
775        else if(check("updateDefaultResourceProvider", ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateDefaultResourceProvider();
776        else if(check("removeResourceProvider", ACCESS_FREE) && check2(ACCESS_WRITE  )) doRemoveResourceProvider();
777        
778        else if(check("getClusterClass",                ACCESS_FREE) && check2(ACCESS_READ  )) doGetClusterClass();
779        else if(check("updateClusterClass",     ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateClusterClass();
780        
781        else if(check("getAdminSyncClass",              ACCESS_FREE) && check2(ACCESS_READ  )) doGetAdminSyncClass();
782        else if(check("updateAdminSyncClass",   ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateAdminSyncClass();
783        
784        else if(check("getVideoExecuterClass",   ACCESS_FREE) && check2(ACCESS_READ  )) doGetVideoExecuterClass();
785        else if(check("updateVideoExecuterClass",ACCESS_FREE) && check2(ACCESS_WRITE  )) doUpdateVideoExecuterClass();
786        else if(check("terminateRunningThread",ACCESS_FREE) && check2(ACCESS_WRITE  )) doTerminateRunningThread();
787        
788        else if(check("updateLabel",                ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doUpdateLabel();
789        else if(check("restart",                ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doRestart();
790        else if(check("runUpdate",              ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doRunUpdate();
791        else if(check("removeUpdate",           ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doRemoveUpdate();
792        else if(check("getUpdate",              ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doGetUpdate();
793        else if(check("listPatches",              ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ     )) listPatches();
794        else if(check("needNewJars",              ACCESS_NOT_WHEN_WEB) && check2(ACCESS_READ     )) needNewJars();
795        else if(check("updateJars",              ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doUpdateJars();
796        else if(check("updateupdate",           ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doUpdateUpdate();
797        else if(check("getSerial",              ACCESS_FREE) && check2(ACCESS_READ     )) doGetSerial();
798        else if(check("updateSerial",           ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doUpdateSerial();
799        else if(check("heapDump",            ACCESS_NOT_WHEN_WEB) && check2(ACCESS_WRITE     )) doHeapDump();
800        else if(check("securitymanager",        ACCESS_FREE) && check2(ACCESS_READ             )) doSecurityManager();
801        
802        
803        
804        else throw new ApplicationException("invalid action ["+action+"] for tag admin");
805            
806    }
807
808        private boolean check2(short accessRW) throws SecurityException {
809        if(accessRW==ACCESS_READ) ConfigWebUtil.checkGeneralReadAccess(config,password);
810                else if(accessRW==ACCESS_WRITE) ConfigWebUtil.checkGeneralWriteAccess(config,password);
811                /*else if(accessRW==CHECK_PW) {
812                        ConfigWebUtil.checkGeneralReadAccess(config,password);
813                        ConfigWebUtil.checkPassword(config,null,password);
814                }*/
815        return true;
816    }
817        private boolean check(String action, short access) throws ApplicationException {
818        if( this.action.equalsIgnoreCase(action)) {
819            if(access==ACCESS_FREE) {
820            }
821            else if(access==ACCESS_NOT_WHEN_SERVER) {
822                throwNoAccessWhenServer();
823            }
824            
825            else if(access==ACCESS_NOT_WHEN_WEB) {
826                throwNoAccessWhenWeb();
827            }
828            else if(access==ACCESS_NEVER) {
829                throwNoAccessWhenServer();
830                throwNoAccessWhenServer();
831            }
832            return true;
833        }
834        return false;
835    }
836    
837
838    private void doRunUpdate() throws PageException {
839        try{
840                doUpdateJars();
841        }
842        catch(Throwable t){
843                        ExceptionUtil.rethrowIfNecessary(t);
844                }
845        admin.runUpdate(password);
846        adminSync.broadcast(attributes, config);
847    }
848    
849    private void doRemoveUpdate() throws PageException {
850        boolean onlyLatest = getBoolV("onlyLatest", false);
851        
852
853        if(onlyLatest)  admin.removeLatestUpdate(password);
854        else                    admin.removeUpdate(password);
855        adminSync.broadcast(attributes, config);
856    }
857    
858    private void doRestart() throws PageException {
859        admin.restart(password);
860        adminSync.broadcast(attributes, config);
861    }
862    
863    private void doCreateArchive(short mappingType) throws PageException {
864        String virtual = getString("admin",action,"virtual").toLowerCase();
865        String strFile = getString("admin",action,"file");
866        Resource file = ResourceUtil.toResourceNotExisting(pageContext, strFile);
867        
868        boolean addCFMLFiles = getBoolV("addCFMLFiles", true);
869        boolean addNonCFMLFiles=getBoolV("addNonCFMLFiles", true);
870        
871        // compile
872        MappingImpl mapping = (MappingImpl) doCompileMapping(mappingType,virtual, true);
873        
874        // class files 
875        if(mapping==null)throw new ApplicationException("there is no mapping for ["+virtual+"]");
876        if(!mapping.hasPhysical())throw new ApplicationException("mapping ["+virtual+"] has no physical directory");
877        
878        Resource classRoot = mapping.getClassRootDirectory();
879        Resource temp = SystemUtil.getTempDirectory().getRealResource("mani-"+IDGenerator.stringId());
880                Resource mani = temp.getRealResource("META-INF/MANIFEST.MF");
881                
882        try {
883                if(file.exists())file.delete();
884                if(!file.exists())file.createFile(true);
885                
886                ResourceFilter filter;
887                
888                
889                // include everything, no filter needed
890                if(addCFMLFiles && addNonCFMLFiles)filter=null;
891                // CFML Files but no other files
892                else if(addCFMLFiles) {
893                        if(mappingType==MAPPING_CFC)filter=new ExtensionResourceFilter(new String[]{"class","cfc","MF"},true,true);
894                        else filter=new ExtensionResourceFilter(new String[]{"class","cfm","cfml","cfc","MF"},true,true);
895                }
896                // No CFML Files, but all other files
897                else if(addNonCFMLFiles) {
898                        filter=new NotResourceFilter(new ExtensionResourceFilter(new String[]{"cfm","cfml","cfc"},false,true));
899                }
900                // no files at all
901                else  {
902                        filter=new ExtensionResourceFilter(new String[]{"class","MF"},true,true);
903                }
904                
905                
906                // create manifest
907                StringBuilder manifest=new StringBuilder();
908                
909                // id
910                manifest.append("mapping-id: \"");
911                        manifest.append(MD5.getDigestAsString(mapping.getStrPhysical()));
912                manifest.append("\"\n");
913                
914                
915                manifest.append("mapping-type: \"");
916                if(mappingType==MAPPING_CFC)manifest.append("cfc");
917                else if(mappingType==MAPPING_CT)manifest.append("ct");
918                else manifest.append("regular");
919                manifest.append("\"\n");
920                
921                manifest.append("mapping-virtual-path: \"");
922                manifest.append(mapping.getVirtual());
923                manifest.append("\"\n");
924                
925                // Hidden
926                manifest.append("mapping-hidden: ");
927                        manifest.append(mapping.isHidden());
928                manifest.append("\n");
929                // Physical First
930                manifest.append("mapping-physical-first: ");
931                        manifest.append(mapping.isPhysicalFirst());
932                manifest.append("\n");
933                // Readonly
934                manifest.append("mapping-readonly: ");
935                        manifest.append(mapping.isReadonly());
936                manifest.append("\n");
937                // Top Level
938                manifest.append("mapping-top-level: ");
939                        manifest.append(mapping.isTopLevel());
940                manifest.append("\n");
941                
942                // Trusted
943                manifest.append("mapping-inspect: \"");
944                        manifest.append(ConfigWebUtil.inspectTemplate(mapping.getInspectTemplateRaw(), ""));
945                        manifest.append("\"\n");
946                
947                
948
949                
950                mani.createFile(true);
951                IOUtil.write(mani, manifest.toString(), "UTF-8", false);
952                
953                // source files
954                Resource[] sources;
955                        if(!addCFMLFiles && !addNonCFMLFiles) sources=new Resource[]{temp,classRoot};
956                        else sources=new Resource[]{temp,mapping.getPhysical(),classRoot};
957                        
958                        CompressUtil.compressZip(ResourceUtil.listResources(sources,filter), file, filter);
959                        
960                        
961                        
962                        
963                        if(getBoolV("append", false)) {
964                                if(mappingType==MAPPING_CFC) {
965                                        admin.updateComponentMapping(
966                                                        mapping.getVirtual(),
967                                        mapping.getStrPhysical(),
968                                        strFile,
969                                        mapping.isPhysicalFirst()?"physical":"archive",
970                                        mapping.getInspectTemplateRaw());
971                             }
972                                else if(mappingType==MAPPING_CT) {
973                                        admin.updateCustomTag(
974                                                        mapping.getVirtual(),
975                                        mapping.getStrPhysical(),
976                                        strFile,
977                                        mapping.isPhysicalFirst()?"physical":"archive",
978                                        mapping.getInspectTemplateRaw());
979                                        
980                                }
981                                
982                                else 
983                                        admin.updateMapping(
984                                                mapping.getVirtual(),
985                                mapping.getStrPhysical(),
986                                strFile,
987                                mapping.isPhysicalFirst()?"physical":"archive",
988                                mapping.getInspectTemplateRaw(),
989                                mapping.isTopLevel()
990                        );
991                        store();
992                        }
993                        
994                        
995                }
996        catch (IOException e) {
997                        throw Caster.toPageException(e); 
998                }
999        finally{
1000                ResourceUtil.removeEL(temp, true);
1001        }
1002        adminSync.broadcast(attributes, config);
1003    }
1004    private void doCompileMapping() throws PageException {
1005        doCompileMapping(MAPPING_REGULAR,getString("admin",action,"virtual").toLowerCase(), getBoolV("stoponerror", true));
1006        adminSync.broadcast(attributes, config);
1007    }
1008    private void doCompileComponentMapping() throws PageException {
1009        doCompileMapping(MAPPING_CFC,getString("admin",action,"virtual").toLowerCase(), getBoolV("stoponerror", true));
1010        adminSync.broadcast(attributes, config);
1011    }
1012    private void doCompileCTMapping() throws PageException {
1013        doCompileMapping(MAPPING_CT,getString("admin",action,"virtual").toLowerCase(), getBoolV("stoponerror", true));
1014        adminSync.broadcast(attributes, config);
1015    }
1016    
1017    private Mapping doCompileMapping(short mappingType,String virtual, boolean stoponerror) throws PageException {
1018        
1019        if(StringUtil.isEmpty(virtual))return null;
1020        
1021        if(!StringUtil.startsWith(virtual,'/'))virtual='/'+virtual;
1022        if(!StringUtil.endsWith(virtual,'/'))virtual+='/';
1023        
1024        Mapping[] mappings = null;
1025        if(mappingType==MAPPING_CFC)mappings=config.getComponentMappings();
1026        else if(mappingType==MAPPING_CT)mappings=config.getCustomTagMappings();
1027        else mappings=config.getMappings();
1028        
1029        
1030        
1031        for(int i=0;i<mappings.length;i++) {
1032            Mapping mapping = mappings[i];
1033            if(mapping.getVirtualLowerCaseWithSlash().equals(virtual)) {
1034                Map<String,String> errors = stoponerror?null:MapFactory.<String,String>getConcurrentMap();
1035                doCompileFile(mapping,mapping.getPhysical(),"",errors);
1036                if(errors!=null && errors.size()>0) {
1037                        StringBuilder sb=new StringBuilder();
1038                        Iterator<String> it = errors.keySet().iterator();
1039                        Object key;
1040                        while(it.hasNext()) {
1041                                key=it.next();
1042                                if(sb.length()>0)sb.append("\n\n");
1043                                sb.append(errors.get(key));
1044                                
1045                        }
1046                        throw new ApplicationException(sb.toString());
1047                }
1048                return mapping;
1049            }
1050        }
1051        return null;
1052    }
1053
1054    private void doCompileFile(Mapping mapping,Resource file,String path,Map<String,String> errors) throws PageException {
1055        if(ResourceUtil.exists(file)) {
1056            if(file.isDirectory()) {
1057                Resource[] files = file.listResources(FILTER_CFML_TEMPLATES);
1058                if(files!=null)for(int i=0;i<files.length;i++) {
1059                    String p=path+'/'+files[i].getName();
1060                    //print.ln(files[i]+" - "+p);
1061                    doCompileFile(mapping,files[i],p,errors);
1062                }
1063            }
1064            else if(file.isFile()) {
1065                PageSourceImpl ps=(PageSourceImpl) mapping.getPageSource(path);
1066                
1067                
1068                try {
1069                        
1070                    ps.clear();
1071                    ps.loadPage(pageContext); 
1072                    //pageContext.compile(ps);
1073                } catch (PageException pe) {
1074                        //PageException pe = pse.getPageException();
1075                    
1076                    String template=ps.getDisplayPath();
1077                    StringBuilder msg=new StringBuilder(pe.getMessage());
1078                    msg.append(", Error Occurred in File [");
1079                    msg.append(template);
1080                    if(pe instanceof PageExceptionImpl) {
1081                        try{
1082                        PageExceptionImpl pei=(PageExceptionImpl)pe;
1083                        Array context = pei.getTagContext(config);
1084                        if(context.size()>0){
1085                            msg.append(":");
1086                            msg.append(Caster.toString(((Struct)context.getE(1)).get("line")));
1087                        }
1088                        }
1089                        catch(Throwable t){
1090                                        ExceptionUtil.rethrowIfNecessary(t);
1091                                }
1092                        
1093                    }
1094                    msg.append("]");
1095                    if(errors!=null) errors.put(template,msg.toString());
1096                    else throw new ApplicationException(msg.toString());
1097                
1098                }
1099            }
1100        }
1101    }
1102
1103    /**
1104     * @throws PageException
1105     * 
1106     */
1107    private void doResetPassword() throws PageException {
1108        
1109        try {
1110            admin.removePassword(getString("contextPath",null));
1111        }catch (Exception e) {e.printStackTrace();} 
1112        store();
1113    }
1114    
1115
1116    private void doUpdateAPIKey() throws PageException {  
1117        admin.updateAPIKey(getString("key",null));
1118        store();
1119    }
1120    private void doRemoveAPIKey() throws PageException {  
1121        try {
1122                admin.removeAPIKey();
1123        }catch (Exception e) {} 
1124        store();
1125    }
1126    
1127    private void doGetAPIKey() throws PageException {
1128        pageContext.setVariable(
1129                 getString("admin",action,"returnVariable"),
1130                 config.getApiKey());
1131    }
1132
1133    private void doUpdateAuthKey() throws PageException {  
1134        try {
1135            admin.updateAuthKey(getString("key",null));
1136        }catch (Exception e) {} 
1137        store();
1138    }
1139    private void doRemoveAuthKey() throws PageException {  
1140        try {
1141            admin.removeAuthKeys(getString("key",null));
1142        }catch (Exception e) {} 
1143        store();
1144    }
1145    
1146    private void doListAuthKey() throws PageException {
1147        ConfigServerImpl cs=(ConfigServerImpl) config;
1148        pageContext.setVariable(
1149                 getString("admin",action,"returnVariable"),
1150                 Caster.toArray(cs.getAuthenticationKeys()));
1151    }
1152
1153    /**
1154     * @throws PageException
1155     */
1156    private void doGetContexts() throws PageException {
1157        CFMLFactory[] factories;
1158        if(config instanceof ConfigServerImpl) {
1159                ConfigServerImpl cs=(ConfigServerImpl) config;
1160                factories = cs.getJSPFactories(); 
1161        }
1162        else {
1163                ConfigWebImpl cw=(ConfigWebImpl) config;
1164                factories = new CFMLFactory[]{cw.getFactory()};
1165        }
1166        
1167        lucee.runtime.type.Query qry=
1168                new QueryImpl(
1169                                new Collection.Key[]{
1170                                                KeyConstants._path,
1171                                                KeyConstants._id,KeyConstants._hash,
1172                                                KeyConstants._label,
1173                                                HAS_OWN_SEC_CONTEXT,
1174                                                KeyConstants._url,
1175                                                CONFIG_FILE,
1176                                                CLIENT_SIZE,CLIENT_ELEMENTS,SESSION_SIZE,SESSION_ELEMENTS},
1177                                factories.length,getString("admin",action,"returnVariable"));
1178        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
1179        ConfigWebImpl cw;
1180        for(int i=0;i<factories.length;i++) {
1181                int row=i+1;
1182            CFMLFactoryImpl factory = (CFMLFactoryImpl) factories[i];
1183            cw = (ConfigWebImpl) factory.getConfig();
1184            qry.setAtEL(KeyConstants._path,row,ReqRspUtil.getRootPath(factory.getConfigWebImpl().getServletContext()));
1185            
1186            qry.setAtEL(CONFIG_FILE,row,factory.getConfigWebImpl().getConfigFile().getAbsolutePath());
1187            if(factory.getURL()!=null)qry.setAtEL(KeyConstants._url,row,factory.getURL().toExternalForm());
1188            
1189
1190            qry.setAtEL(KeyConstants._id,row,factory.getConfig().getId());
1191            qry.setAtEL(KeyConstants._hash,row,SystemUtil.hash(factory.getConfigWebImpl().getServletContext()));
1192            qry.setAtEL(KeyConstants._label,row,factory.getLabel());
1193            qry.setAtEL(HAS_OWN_SEC_CONTEXT,row,Caster.toBoolean(cw.hasIndividualSecurityManager()));
1194
1195            setScopeDirInfo(qry,row,CLIENT_SIZE,CLIENT_ELEMENTS,cw.getClientScopeDir());
1196            setScopeDirInfo(qry,row,SESSION_SIZE,SESSION_ELEMENTS,cw.getSessionScopeDir());
1197        }
1198    }
1199
1200    private void setScopeDirInfo(Query qry, int row, Key sizeName,Key elName, Resource dir) { 
1201        qry.setAtEL(sizeName,row,Caster.toDouble(ResourceUtil.getRealSize(dir)));
1202        qry.setAtEL(elName,row,Caster.toDouble(ResourceUtil.getChildCount(dir)));       
1203        }
1204
1205        private void doHasIndividualSecurity() throws PageException {
1206        pageContext.setVariable(
1207                 getString("admin",action,"returnVariable"),
1208                 Caster.toBoolean(
1209                         config.getConfigServer(password).hasIndividualSecurityManager(
1210                                 getString("admin",action,"id")
1211                                 
1212                         )
1213                 )
1214        );
1215    }
1216
1217    private void doUpdateUpdate() throws PageException {
1218        admin.updateUpdate(getString("admin",action,"updatetype"),getString("admin",action,"updatelocation"));
1219        store();
1220        adminSync.broadcast(attributes, config);
1221    }
1222    
1223    /**
1224     * @throws PageException
1225     * 
1226     */
1227    private void doUpdateSerial() throws PageException {
1228        admin.updateSerial(getString("admin",action,"serial"));
1229        store();
1230        pageContext.serverScope().reload();
1231    }
1232
1233    /**
1234     * @throws PageException
1235     * 
1236     */
1237    private void doGetSerial() throws PageException {
1238       pageContext.setVariable(
1239                getString("admin",action,"returnVariable"),
1240                config.getSerialNumber());
1241    }
1242    
1243
1244    private Resource getPluginDirectory() {
1245        return config.getConfigDir().getRealResource("context/admin/plugin");
1246    }
1247
1248    private Resource getContextDirectory() throws PageException  {
1249        ConfigServer cs = config.getConfigServer(password);
1250        Resource dist = cs.getConfigDir().getRealResource("distribution");
1251        dist.mkdirs();
1252        return dist;
1253    }
1254    
1255    private void doGetPluginDirectory() throws PageException {
1256        pageContext.setVariable(
1257                 getString("admin",action,"returnVariable"),
1258                 getPluginDirectory().getAbsolutePath());
1259     }
1260
1261    private void doUpdatePlugin() throws PageException, IOException {
1262        String strSrc = getString("admin",action,"source");
1263        Resource src = ResourceUtil.toResourceExisting(pageContext, strSrc);
1264        Resource srcDir = ResourceUtil.toResourceExisting(pageContext, "zip://"+src.getAbsolutePath());
1265        String name=ResourceUtil.getName(src.getName());
1266        if(!PluginFilter.doAccept(srcDir))
1267                throw new ApplicationException("plugin ["+strSrc+"] is invalid, missing one of the following files [Action.cfc,language.xml] in root, existing files are ["+lucee.runtime.type.util.ListUtil.arrayToList(srcDir.list(), ", ")+"]");
1268        
1269        Resource dir = getPluginDirectory();
1270        Resource trgDir = dir.getRealResource(name);
1271        if(trgDir.exists()){
1272                trgDir.remove(true);
1273        }
1274        
1275        ResourceUtil.copyRecursive(srcDir, trgDir);    
1276        store();
1277    }
1278    
1279    private void doUpdateLabel() throws PageException {
1280        if(config instanceof ConfigServer) {
1281                 if(admin.updateLabel(getString("admin",action,"hash"),getString("admin",action,"label"))) {
1282                     store();
1283                     adminSync.broadcast(attributes, config);
1284                 }
1285        }
1286    }
1287    
1288    private void doUpdateContext() throws PageException, IOException {
1289        String strSrc = getString("admin",action,"source");
1290        String strRelPath = getString("admin",action,"destination");
1291        Resource src = ResourceUtil.toResourceExisting(pageContext, strSrc);
1292        
1293        ConfigServerImpl server = (ConfigServerImpl) config.getConfigServer(password);
1294        Resource trg,p;
1295        Resource deploy = server.getConfigDir().getRealResource("web-context-deployment");
1296        deploy.mkdirs();
1297        
1298        // deploy it
1299        trg=deploy.getRealResource(strRelPath);
1300        if(trg.exists()) trg.remove(true);
1301        p = trg.getParentResource();
1302        if(!p.isDirectory())p.createDirectory(true);
1303        src.copyTo(trg, false);
1304        store();
1305        
1306        ConfigWeb[] webs = server.getConfigWebs();
1307        for(int i=0;i<webs.length;i++){
1308                ConfigWebFactory.deployWebContext(server,webs[i], true);
1309        }
1310        
1311    }
1312    
1313    
1314    private void doRemoveContext() throws PageException, IOException {
1315        String strRelPath = getString("admin",action,"destination");
1316        ConfigServerImpl server = (ConfigServerImpl) config;
1317        
1318        try {
1319                admin.removeContext(server, true,strRelPath);
1320                }
1321                catch (SAXException e) {
1322                        throw Caster.toPageException(e);
1323                }
1324                
1325        store();
1326    }
1327    
1328    private void doRemovePlugin() throws PageException, IOException {
1329        Resource dir = getPluginDirectory();
1330        String name = getString("admin",action,"name");
1331        Resource trgDir = dir.getRealResource(name);
1332        trgDir.remove(true);
1333        
1334        store();
1335    }
1336    
1337    private void doGetPlugins() throws PageException {
1338        Resource dir = getPluginDirectory();
1339        
1340        String[] list = dir.list(new PluginFilter());
1341        lucee.runtime.type.Query qry=
1342                new QueryImpl(
1343                                new Collection.Key[]{KeyConstants._name},
1344                                list.length,getString("admin",action,"returnVariable"));
1345        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
1346        
1347        for(int i=0;i<list.length;i++) {
1348            int row=i+1;
1349            qry.setAtEL(KeyConstants._name,row,list[i]);
1350        }
1351     }
1352    
1353    private void doStorageSet() throws PageException {
1354        try {
1355                        admin.storageSet(config,getString("admin",action,"key"),getObject("admin", action, "value"));
1356                } 
1357        catch (Exception e) {
1358                        throw Caster.toPageException(e);
1359                }
1360        }
1361
1362        private void doStorageGet() throws PageException {
1363       try {
1364                pageContext.setVariable(
1365                            getString("admin",action,"returnVariable"),
1366                            admin.storageGet(config,getString("admin",action,"key")));
1367                } 
1368       catch (Exception e) {
1369           throw Caster.toPageException(e);
1370                } 
1371        }
1372
1373    /**
1374     * @throws PageException
1375     * 
1376     */
1377    private void doGetDefaultPassword() throws PageException {
1378        Password password = admin.getDefaultPassword();
1379        
1380        pageContext.setVariable(
1381                getString("admin",action,"returnVariable"),
1382                password==null?"":password.password);
1383    }
1384    
1385    /**
1386     * @throws PageException
1387     * 
1388     */
1389    private void doUpdateDefaultPassword() throws PageException {
1390        try {
1391                        admin.updateDefaultPassword(getString("admin",action,"newPassword"));
1392                }
1393                catch (Exception e) {
1394                        throw Caster.toPageException(e);
1395                }
1396        store();
1397    }
1398    private void doRemoveDefaultPassword() throws PageException {
1399        admin.removeDefaultPassword();
1400        store();
1401    }
1402    
1403
1404    /* *
1405     * @throws PageException
1406     * 
1407     * /
1408    private void doUpdatePassword() throws PageException {
1409        try {
1410            ConfigWebAdmin.setPassword(config,password==null?null:Caster.toString(password),getString("admin",action,"newPassword"));
1411        } 
1412        catch (Exception e) {
1413            throw Caster.toPageException(e);
1414        }
1415        //store();
1416    }*/
1417    
1418    /**
1419     * @throws PageException
1420     * 
1421     */
1422    private void doGetDebug() throws PageException {
1423        Struct sct=new StructImpl();
1424        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
1425        
1426        sct.set(DEBUG,Caster.toBoolean(config.debug()));
1427        sct.set(KeyConstants._database,Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DATABASE)));
1428        sct.set(KeyConstants._exception,Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)));
1429        sct.set("tracing",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TRACING)));
1430        sct.set("dump",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_DUMP)));
1431        sct.set("timer",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_TIMER)));
1432        sct.set("implicitAccess",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_IMPLICIT_ACCESS)));
1433        sct.set("queryUsage",Caster.toBoolean(config.hasDebugOptions(ConfigImpl.DEBUG_QUERY_USAGE)));
1434    }
1435    
1436    private void doGetError() throws PageException {
1437        Struct sct=new StructImpl();
1438        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
1439        //sct.set("errorTemplate",config.getErrorTemplate());
1440        
1441        Struct templates=new StructImpl();
1442        Struct str=new StructImpl();
1443        sct.set(TEMPLATES, templates);
1444        sct.set(STR, str);
1445        sct.set(DO_STATUS_CODE, Caster.toBoolean(config.getErrorStatusCode()));
1446        
1447        // 500
1448        String template=config.getErrorTemplate(500);
1449        try {
1450            PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(template);
1451            if(ps!=null) templates.set("500",ps.getDisplayPath());
1452            else templates.set("500","");
1453        } catch (PageException e) {
1454                templates.set("500","");
1455        }
1456        str.set("500",template);
1457
1458        // 404
1459        template=config.getErrorTemplate(404);
1460        try {
1461            PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(template);
1462            if(ps!=null) templates.set("404",ps.getDisplayPath());
1463            else templates.set("404","");
1464        } catch (PageException e) {
1465                templates.set("404","");
1466        }
1467        str.set("404",template);
1468
1469        
1470        
1471        
1472        
1473        
1474    }
1475
1476    /**
1477     * @throws PageException
1478     * 
1479     */
1480    private void doGetDebugData() throws PageException {
1481        pageContext.setVariable(
1482                getString("admin",action,"returnVariable"),
1483                pageContext.getConfig().debug()?pageContext.getDebugger().getDebuggingData(pageContext):null);
1484    }
1485    
1486    
1487    
1488    
1489    private void doGetLoggedDebugData() throws PageException {
1490        
1491        if(config instanceof ConfigServer) return ;
1492        
1493        ConfigWebImpl cw=(ConfigWebImpl) config;
1494        
1495        
1496        pageContext.setVariable(
1497                getString("admin",action,"returnVariable"),
1498                cw.getDebuggerPool().getData(pageContext));
1499    }
1500    
1501    private void doGetInfo() throws PageException {
1502        Struct sct=new StructImpl();
1503        pageContext.setVariable(
1504                getString("admin",action,"returnVariable"),
1505                sct);
1506        
1507        
1508        if(config instanceof ConfigWebImpl){
1509                ConfigWebImpl cw=(ConfigWebImpl) config;
1510                sct.setEL(KeyConstants._label, cw.getLabel());
1511                sct.setEL(KeyConstants._hash, cw.getHash());
1512                sct.setEL(KeyConstants._root, cw.getRootDirectory().getAbsolutePath());
1513            sct.setEL("configServerDir", cw.getConfigServerDir().getAbsolutePath());
1514            sct.setEL("configWebDir", cw.getConfigDir().getAbsolutePath());
1515        }
1516        else {
1517            sct.setEL("configServerDir", config.getConfigDir().getAbsolutePath());
1518            sct.setEL("configWebDir", pageContext.getConfig().getConfigDir().getAbsolutePath());
1519        }
1520        
1521        sct.setEL(KeyConstants._config, config.getConfigFile().getAbsolutePath());
1522        
1523        // Servlets
1524        if(config instanceof ConfigServer) {
1525                ConfigServer cs=(ConfigServer) config;
1526                CFMLEngineImpl engine = (CFMLEngineImpl) cs.getCFMLEngine();
1527                Struct srv=new StructImpl(),params;
1528                
1529                
1530                ServletConfig[] configs = engine.getServletConfigs();
1531                ServletConfig sc;
1532                Enumeration e;
1533                String name,value;
1534                for(int i=0;i<configs.length;i++){
1535                        sc=configs[i];
1536                        e = sc.getInitParameterNames();
1537                        params=new StructImpl();
1538                        while(e.hasMoreElements()){
1539                                name=(String) e.nextElement();
1540                                value = sc.getInitParameter(name);
1541                                params.set(name, value);
1542                        }
1543                        srv.set(sc.getServletName(), params);
1544                }
1545                sct.set("servlets", srv);
1546        }
1547
1548            sct.setEL("javaAgentSupported", Caster.toBoolean(InstrumentationUtil.isSupported()));
1549            sct.setEL("javaAgentPath", ClassUtil.getSourcePathForClass("lucee.runtime.instrumentation.Agent", ""));
1550    }
1551
1552    /**
1553     * @throws PageException
1554     * 
1555     */
1556    private void doCreateSecurityManager() throws  PageException {
1557        admin.createSecurityManager(password,getString("admin",action,"id"));
1558        store();
1559    }
1560    
1561    private void doRemoveSecurityManager() throws  PageException {
1562        admin.removeSecurityManager(password,getString("admin",action,"id"));
1563        store();
1564    }
1565    
1566    
1567
1568    private short fb(String key) throws PageException {
1569        return getBool("admin",action,key)?SecurityManager.VALUE_YES:SecurityManager.VALUE_NO;
1570    }
1571    private short fb2(String key) throws PageException {
1572        return SecurityManagerImpl.toShortAccessRWValue(getString("admin",action,key));
1573    }
1574
1575    private void doUpdateDefaultSecurityManager() throws  PageException {
1576        
1577        admin.updateDefaultSecurity(
1578                fb("setting"),
1579                SecurityManagerImpl.toShortAccessValue(getString("admin",action,"file")),
1580                getFileAcces(),
1581                fb("direct_java_access"),
1582                fb("mail"),
1583                SecurityManagerImpl.toShortAccessValue(getString("admin",action,"datasource")),
1584                fb("mapping"),
1585                fb("remote"),
1586                fb("custom_tag"),
1587                fb("cfx_setting"),
1588                fb("cfx_usage"),
1589                fb("debugging"),
1590                fb("search"),
1591                fb("scheduled_task"),
1592                fb("tag_execute"),
1593                fb("tag_import"),
1594                fb("tag_object"),
1595                fb("tag_registry"),
1596                fb("cache"),
1597                fb("gateway"),
1598                fb("orm"),
1599                fb2("access_read"),
1600                fb2("access_write")
1601        );
1602        store();
1603        adminSync.broadcast(attributes, config);
1604    }
1605
1606    private Resource[] getFileAcces() throws PageException {
1607        Object value=attributes.get(FILE_ACCESS,null);
1608        if(value==null) return null;
1609        Array arr = Caster.toArray(value);
1610        List rtn = new ArrayList();
1611        Iterator it = arr.valueIterator();
1612        String path;
1613        Resource res;
1614        while(it.hasNext()){
1615                path=Caster.toString(it.next());
1616                if(StringUtil.isEmpty(path))continue;
1617                
1618                res=config.getResource(path);
1619                if(!res.exists())
1620                        throw new ApplicationException("path ["+path+"] does not exist");
1621                if(!res.isDirectory())
1622                        throw new ApplicationException("path ["+path+"] is not a directory");
1623                rtn.add(res);
1624        }
1625        return (Resource[])rtn.toArray(new Resource[rtn.size()]);
1626        }
1627
1628        private void doUpdateSecurityManager() throws  PageException {
1629                admin.updateSecurity(
1630                getString("admin",action,"id"),
1631                fb("setting"),
1632                SecurityManagerImpl.toShortAccessValue(getString("admin",action,"file")),
1633                getFileAcces(),
1634                fb("direct_java_access"),
1635                fb("mail"),
1636                SecurityManagerImpl.toShortAccessValue(getString("admin",action,"datasource")),
1637                fb("mapping"),
1638                fb("remote"),
1639                fb("custom_tag"),
1640                fb("cfx_setting"),
1641                fb("cfx_usage"),
1642                fb("debugging"),
1643                fb("search"),
1644                fb("scheduled_task"),
1645                fb("tag_execute"),
1646                fb("tag_import"),
1647                fb("tag_object"),
1648                fb("tag_registry"),
1649                fb("cache"),
1650                fb("gateway"),
1651                fb("orm"),
1652                fb2("access_read"),
1653                fb2("access_write")
1654        );
1655        store();
1656    }
1657
1658    
1659    
1660    /**
1661     * @throws PageException
1662     * 
1663     */
1664    private void doGetDefaultSecurityManager() throws PageException {
1665        SecurityManager dsm = config.getConfigServer(password).getDefaultSecurityManager();
1666        _fillSecData(dsm);
1667    }
1668
1669    private void doGetSecurityManager() throws PageException {
1670        SecurityManager sm = config.getConfigServer(password).getSecurityManager(getString("admin",action,"id"));
1671        _fillSecData(sm);
1672    }
1673    
1674    private void _fillSecData(SecurityManager sm) throws PageException {
1675        
1676        Struct sct=new StructImpl();
1677        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
1678        sct.set("cfx_setting",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_CFX_SETTING)==SecurityManager.VALUE_YES));
1679        sct.set("cfx_usage",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_CFX_USAGE)==SecurityManager.VALUE_YES));
1680        sct.set("custom_tag",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_CUSTOM_TAG)==SecurityManager.VALUE_YES));
1681        sct.set(KeyConstants._datasource,_fillSecDataDS(sm.getAccess(SecurityManager.TYPE_DATASOURCE)));
1682        sct.set("debugging",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_DEBUGGING)==SecurityManager.VALUE_YES));
1683        sct.set("direct_java_access",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_DIRECT_JAVA_ACCESS)==SecurityManager.VALUE_YES));
1684        sct.set("mail",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_MAIL)==SecurityManager.VALUE_YES));
1685        sct.set(KeyConstants._mapping,Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_MAPPING)==SecurityManager.VALUE_YES));
1686        sct.set("remote",Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_REMOTE)==SecurityManager.VALUE_YES));
1687        sct.set("setting",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_SETTING)==SecurityManager.VALUE_YES));
1688        sct.set("search",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_SEARCH)==SecurityManager.VALUE_YES));
1689        sct.set("scheduled_task",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_SCHEDULED_TASK)==SecurityManager.VALUE_YES));
1690        sct.set(KeyConstants._cache,Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_CACHE)==SecurityManager.VALUE_YES));
1691        sct.set("gateway",Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_GATEWAY)==SecurityManager.VALUE_YES));
1692        sct.set(KeyConstants._orm,Caster.toBoolean(sm.getAccess(SecurityManagerImpl.TYPE_ORM)==SecurityManager.VALUE_YES));
1693        
1694        sct.set("tag_execute",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_EXECUTE)==SecurityManager.VALUE_YES));
1695        sct.set("tag_import",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_IMPORT)==SecurityManager.VALUE_YES));
1696        sct.set("tag_object",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_OBJECT)==SecurityManager.VALUE_YES));
1697        sct.set("tag_registry",Caster.toBoolean(sm.getAccess(SecurityManager.TYPE_TAG_REGISTRY)==SecurityManager.VALUE_YES));
1698        sct.set("access_read",SecurityManagerImpl.toStringAccessRWValue(sm.getAccess(SecurityManager.TYPE_ACCESS_READ)));
1699        sct.set("access_write",SecurityManagerImpl.toStringAccessRWValue(sm.getAccess(SecurityManager.TYPE_ACCESS_WRITE)));
1700        short accessFile = sm.getAccess(SecurityManager.TYPE_FILE);
1701        String str = SecurityManagerImpl.toStringAccessValue(accessFile);
1702        if(str.equals("yes"))str="all";
1703        sct.set(KeyConstants._file,str);
1704        
1705        Array arr=new ArrayImpl();
1706        if(accessFile!=SecurityManager.VALUE_ALL){
1707                Resource[] reses = ((SecurityManagerImpl)sm).getCustomFileAccess();
1708                for(int i=0;i<reses.length;i++){
1709                        arr.appendEL(reses[i].getAbsolutePath());
1710                }
1711        }
1712        sct.set("file_access",arr);
1713    
1714    }
1715
1716        private Double _fillSecDataDS(short access) {
1717                switch(access) {
1718                case SecurityManager.VALUE_YES: return Caster.toDouble(-1);
1719                case SecurityManager.VALUE_NO: return Caster.toDouble(0);
1720                case SecurityManager.VALUE_1: return Caster.toDouble(1);
1721                case SecurityManager.VALUE_2: return Caster.toDouble(2);
1722                case SecurityManager.VALUE_3: return Caster.toDouble(3);
1723                case SecurityManager.VALUE_4: return Caster.toDouble(4);
1724                case SecurityManager.VALUE_5: return Caster.toDouble(5);
1725                case SecurityManager.VALUE_6: return Caster.toDouble(6);
1726                case SecurityManager.VALUE_7: return Caster.toDouble(7);
1727                case SecurityManager.VALUE_8: return Caster.toDouble(8);
1728                case SecurityManager.VALUE_9: return Caster.toDouble(9);
1729                case SecurityManager.VALUE_10: return Caster.toDouble(10);
1730                }
1731                return Caster.toDouble(-1);
1732        }
1733
1734        /**
1735     * @throws PageException
1736     * 
1737     */
1738        private void doUpdateDebug() throws PageException {
1739                
1740        admin.updateDebug(
1741                        Caster.toBoolean(getString("debug",""),null),
1742                        Caster.toBoolean(getString("database",""),null),
1743                        Caster.toBoolean(getString("exception",""),null),
1744                        Caster.toBoolean(getString("tracing",""),null),
1745                        Caster.toBoolean(getString("dump",""),null),
1746                        Caster.toBoolean(getString("timer",""),null),
1747                        Caster.toBoolean(getString("implicitAccess",""),null),
1748                        Caster.toBoolean(getString("queryUsage",""),null)
1749                        );
1750        
1751        
1752        
1753        admin.updateDebugTemplate(getString("admin",action,"debugTemplate"));
1754        store();
1755        adminSync.broadcast(attributes, config);
1756    }
1757
1758        private void doGetDebugSetting() throws PageException {
1759                Struct sct=new StructImpl();
1760                sct.set("maxLogs", Caster.toDouble(config.getDebugMaxRecordsLogged()));
1761                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
1762        
1763    }
1764        private void doUpdateDebugSetting() throws PageException {
1765                String str = getString("admin",action,"maxLogs");
1766                int maxLogs;
1767                if(StringUtil.isEmpty(str,true))maxLogs=-1;
1768                else
1769                        maxLogs=Caster.toIntValue(str);
1770        admin.updateDebugSetting(maxLogs);
1771        store();
1772        adminSync.broadcast(attributes, config);
1773    }
1774    
1775    private void doUpdateDebugEntry() throws PageException {
1776        try {
1777                        admin.updateDebugEntry(
1778                                        getString("admin","updateDebugEntry","debugtype"),
1779                                        getString("admin","updateDebugEntry","iprange"),
1780                                        getString("admin","updateDebugEntry","label"),
1781                                        getString("admin","updateDebugEntry","path"),
1782                                        getString("admin","updateDebugEntry","fullname"),
1783                                        getStruct("admin","updateDebugEntry","custom")
1784                                );
1785                } catch (IOException e) {
1786                        throw Caster.toPageException(e);
1787                }
1788        
1789        store();
1790        adminSync.broadcast(attributes, config);
1791    }
1792    
1793    private void doGetDebugEntry() throws PageException {
1794        DebugEntry[] entries = config.getDebugEntries();
1795        
1796        String rtn = getString("admin",action,"returnVariable");
1797        lucee.runtime.type.Query qry=
1798                new QueryImpl(new Collection.Key[]{KeyConstants._id,LABEL,IP_RANGE,READONLY,KeyConstants._type,CUSTOM},entries.length,rtn);
1799        pageContext.setVariable(rtn,qry);
1800        DebugEntry de;
1801        for(int i=0;i<entries.length;i++) {
1802            int row=i+1;
1803            de=entries[i];
1804            qry.setAtEL(KeyConstants._id,row,de.getId());
1805            qry.setAtEL(LABEL,row,de.getLabel());
1806            qry.setAtEL(IP_RANGE,row,de.getIpRangeAsString());
1807            qry.setAtEL(KeyConstants._type,row,de.getType());
1808            qry.setAtEL(READONLY,row,Caster.toBoolean(de.isReadOnly()));
1809            qry.setAtEL(CUSTOM,row,de.getCustom());
1810        }
1811    }
1812    
1813    
1814    private void doUpdateError() throws PageException {
1815
1816        admin.updateErrorTemplate(500,getString("admin",action,"template500"));
1817        admin.updateErrorTemplate(404,getString("admin",action,"template404"));
1818        admin.updateErrorStatusCode(getBoolObject("admin",action,"statuscode"));
1819        store();
1820        adminSync.broadcast(attributes, config);
1821    }
1822
1823    /**
1824     * @throws PageException
1825     * 
1826     */
1827    private void doUpdateJavaCFX() throws PageException {
1828        String name=getString("admin",action,"name");
1829        if(StringUtil.startsWithIgnoreCase(name,"cfx_"))name=name.substring(4);
1830        admin.updateJavaCFX(
1831                name,
1832                getString("admin",action,"class")
1833        );
1834        store();
1835        adminSync.broadcast(attributes, config);
1836    }
1837
1838    private void doVerifyJavaCFX() throws PageException {
1839        String name=getString("admin",action,"name");
1840        admin.verifyJavaCFX(
1841                name,
1842                getString("admin",action,"class")
1843        );
1844    }
1845    private void doVerifyCFX() throws PageException {
1846        String name=getString("admin",action,"name");
1847        if(StringUtil.startsWithIgnoreCase(name,"cfx_"))name=name.substring(4);
1848        admin.verifyCFX(name);
1849    }
1850    
1851
1852    private void doUpdateCPPCFX() throws PageException {
1853        String name=getString("admin",action,"name");
1854        String procedure=getString("admin",action,"procedure");
1855        String serverLibrary=getString("admin",action,"serverLibrary");
1856        boolean keepAlive=getBool("admin",action,"keepAlive");
1857        
1858        
1859        if(StringUtil.startsWithIgnoreCase(name,"cfx_"))name=name.substring(4);
1860        admin.updateCPPCFX(name,procedure,serverLibrary,keepAlive);
1861        store();
1862        adminSync.broadcast(attributes, config);
1863    }
1864    
1865    
1866
1867    /**
1868     * @throws PageException
1869     * 
1870     */
1871    private void doRemoveCFX() throws PageException {
1872        admin.removeCFX(
1873                getString("admin",action,"name")
1874        );
1875        store();
1876        adminSync.broadcast(attributes, config);
1877    }
1878    private void doRemoveExtension() throws PageException {
1879        admin.removeExtension(
1880                getString("admin",action,"provider"),
1881                getString("admin",action,"id")
1882        );
1883        store();
1884        //adminSync.broadcast(attributes, config);
1885    }
1886    
1887    
1888
1889    /**
1890     * @throws PageException
1891     * 
1892     */
1893    private void doGetJavaCFXTags() throws PageException {
1894        Map map = config.getCFXTagPool().getClasses();
1895        lucee.runtime.type.Query qry=new QueryImpl(new Collection.Key[]{
1896                        KeyConstants._displayname,
1897                        KeyConstants._sourcename,
1898                        KeyConstants._readonly,
1899                        KeyConstants._class,
1900                        KeyConstants._name,
1901                        KeyConstants._isvalid},0,"query");
1902        Iterator it = map.keySet().iterator();
1903        
1904        int row=0;
1905        while(it.hasNext()) {
1906            CFXTagClass tag=(CFXTagClass) map.get(it.next());
1907            if(tag instanceof JavaCFXTagClass) {
1908                row++;
1909                qry.addRow(1);
1910                JavaCFXTagClass jtag =(JavaCFXTagClass) tag;
1911                qry.setAt(KeyConstants._displayname,row,tag.getDisplayType());
1912                qry.setAt(KeyConstants._sourcename,row,tag.getSourceName());
1913                qry.setAt(KeyConstants._readonly,row,Caster.toBoolean(tag.isReadOnly()));
1914                qry.setAt(KeyConstants._isvalid,row,Caster.toBoolean(tag.isValid()));
1915                qry.setAt(KeyConstants._name,row,jtag.getName());
1916                qry.setAt(KeyConstants._class,row,jtag.getStrClass());
1917            }
1918            
1919        }
1920        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
1921    }
1922    
1923    private void doGetCPPCFXTags() throws PageException {
1924        Map map = config.getCFXTagPool().getClasses();
1925        lucee.runtime.type.Query qry=new QueryImpl(new Collection.Key[]{
1926                        KeyConstants._displayname,
1927                        KeyConstants._sourcename,
1928                        KeyConstants._readonly,
1929                        PROCEDURE,
1930                        KeyConstants._name,
1931                        KeyConstants._isvalid,
1932                        SERVER_LIBRARY,
1933                        KEEP_ALIVE},0,"query");
1934        Iterator it = map.keySet().iterator();
1935        
1936        int row=0;
1937        while(it.hasNext()) {
1938            CFXTagClass tag=(CFXTagClass) map.get(it.next());
1939            if(tag instanceof CPPCFXTagClass) {
1940                row++;
1941                qry.addRow(1);
1942                CPPCFXTagClass ctag =(CPPCFXTagClass) tag;
1943                qry.setAt(KeyConstants._displayname,row,tag.getDisplayType());
1944                qry.setAt(KeyConstants._sourcename,row,tag.getSourceName());
1945                qry.setAt(KeyConstants._readonly,row,Caster.toBoolean(tag.isReadOnly()));
1946                qry.setAt(KeyConstants._isvalid,row,Caster.toBoolean(tag.isValid()));
1947                qry.setAt(KeyConstants._name,row,ctag.getName());
1948                qry.setAt(PROCEDURE,row,ctag.getProcedure());
1949                qry.setAt(SERVER_LIBRARY,row,ctag.getServerLibrary());
1950                qry.setAt(KEEP_ALIVE,row,Caster.toBoolean(ctag.getKeepAlive()));
1951            }
1952            
1953        }
1954        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
1955    }
1956    
1957    /**
1958     * @throws PageException
1959     * 
1960     */
1961    private void doGetCFXTags() throws PageException {
1962        Map map = config.getCFXTagPool().getClasses();
1963        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"displayname","sourcename","readonly","isvalid","name","procedure_class","keep_alive"},map.size(),"query");
1964        Iterator it = map.keySet().iterator();
1965        
1966        int row=0;
1967        while(it.hasNext()) {
1968            row++;
1969            CFXTagClass tag=(CFXTagClass) map.get(it.next());
1970            
1971            qry.setAt("displayname",row,tag.getDisplayType());
1972            qry.setAt("sourcename",row,tag.getSourceName());
1973            qry.setAt("readonly",row,Caster.toBoolean(tag.isReadOnly()));
1974            qry.setAt("isvalid",row,Caster.toBoolean(tag.isValid()));
1975            
1976            if(tag instanceof CPPCFXTagClass) {
1977                CPPCFXTagClass ctag =(CPPCFXTagClass) tag;
1978                qry.setAt(KeyConstants._name,row,ctag.getName());
1979                qry.setAt("procedure_class",row,ctag.getProcedure());
1980                qry.setAt("keepalive",row,Caster.toBoolean(ctag.getKeepAlive()));
1981            }
1982            else if(tag instanceof JavaCFXTagClass) {
1983                JavaCFXTagClass jtag =(JavaCFXTagClass) tag;
1984                qry.setAt(KeyConstants._name,row,jtag.getName());
1985                qry.setAt("procedure_class",row,jtag.getStrClass());
1986            }
1987            
1988        }
1989        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
1990    } 
1991    
1992    
1993    /**
1994     * @throws PageException
1995     */
1996    private void doUpdateComponentMapping() throws PageException {
1997        admin.updateComponentMapping(
1998                        getString("virtual",""),
1999                getString("physical",""),
2000                getString("archive",""),
2001                getString("primary","physical"),
2002                ConfigWebUtil.inspectTemplate(getString("inspect",""), ConfigImpl.INSPECT_UNDEFINED)
2003        );
2004        store();
2005        adminSync.broadcast(attributes, config);
2006    }
2007
2008    /**
2009     * @throws PageException
2010     * 
2011     */
2012    private void doRemoveComponentMapping() throws PageException {
2013        admin.removeComponentMapping(
2014                getString("admin",action,"virtual")
2015        );
2016        store();
2017        adminSync.broadcast(attributes, config);
2018    }
2019    
2020    
2021
2022    /**
2023     * @throws PageException
2024     */
2025    private void doUpdateCustomTag() throws PageException {
2026        admin.updateCustomTag(
2027                getString("admin",action,"virtual"),
2028                getString("admin",action,"physical"),
2029                getString("admin",action,"archive"),
2030                getString("admin",action,"primary"),
2031                ConfigWebUtil.inspectTemplate(getString("inspect",""), ConfigImpl.INSPECT_UNDEFINED)
2032        );
2033        store();
2034        adminSync.broadcast(attributes, config);
2035    }
2036
2037    /**
2038     * @throws PageException
2039     * 
2040     */
2041    private void doRemoveCustomTag() throws PageException {
2042        admin.removeCustomTag(
2043                getString("admin",action,"virtual")
2044        );
2045        store();
2046        adminSync.broadcast(attributes, config);
2047    }
2048
2049    /**
2050     * @throws PageException
2051     * 
2052     */
2053    private void doGetCustomTagMappings() throws PageException {
2054        Mapping[] mappings = config.getCustomTagMappings();
2055        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"archive","strarchive","physical","strphysical","virtual","hidden","physicalFirst","readonly","inspect"},mappings.length,"query");
2056        
2057        
2058        for(int i=0;i<mappings.length;i++) {
2059            MappingImpl m=(MappingImpl) mappings[i];
2060            int row=i+1;
2061            qry.setAt("archive",row,m.getArchive());
2062            qry.setAt("strarchive",row,m.getStrArchive());
2063            qry.setAt("physical",row,m.getPhysical());
2064            qry.setAt("strphysical",row,m.getStrPhysical());
2065            qry.setAt("virtual",row,m.getVirtual());
2066            qry.setAt("hidden",row,Caster.toBoolean(m.isHidden()));
2067            qry.setAt("physicalFirst",row,Caster.toBoolean(m.isPhysicalFirst()));
2068            qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly()));
2069            qry.setAt("inspect",row,ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), ""));
2070        }
2071        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2072    }
2073    
2074    private void doGetComponentMappings() throws PageException {
2075        Mapping[] mappings = config.getComponentMappings();
2076        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"archive","strarchive","physical","strphysical","virtual","hidden","physicalFirst","readonly","inspect"},mappings.length,"query");
2077        
2078        
2079        for(int i=0;i<mappings.length;i++) {
2080            MappingImpl m=(MappingImpl) mappings[i];
2081            int row=i+1;
2082            qry.setAt("archive",row,m.getArchive());
2083            qry.setAt("strarchive",row,m.getStrArchive());
2084            qry.setAt("physical",row,m.getPhysical());
2085            qry.setAt("strphysical",row,m.getStrPhysical());
2086            qry.setAt("virtual",row,m.getVirtual());
2087            qry.setAt("hidden",row,Caster.toBoolean(m.isHidden()));
2088            qry.setAt("physicalFirst",row,Caster.toBoolean(m.isPhysicalFirst()));
2089            qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly()));
2090            qry.setAt("inspect",row,ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), ""));
2091        }
2092        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2093    }
2094    
2095
2096    /**
2097     * @throws PageException
2098     * 
2099     */
2100    private void doRemoveMapping() throws PageException {
2101        admin.removeMapping(
2102                getString("admin",action,"virtual")
2103        );
2104        store();
2105        adminSync.broadcast(attributes, config);
2106    }
2107
2108    /**
2109     * @throws PageException
2110     * 
2111     */
2112    private void doUpdateRestMapping() throws PageException {
2113        admin.updateRestMapping(
2114                getString("admin",action,"virtual"),
2115                getString("admin",action,"physical"),
2116                getBool("admin",action,"default")
2117        );
2118        store();
2119        adminSync.broadcast(attributes, config);
2120        
2121        RestUtil.release(config.getRestMappings());
2122    }
2123    
2124    private void doRemoveRestMapping() throws PageException {
2125        admin.removeRestMapping(
2126                getString("admin",action,"virtual")
2127        );
2128        store();
2129        adminSync.broadcast(attributes, config);
2130        RestUtil.release(config.getRestMappings());
2131    }
2132    
2133    private void doUpdateMapping() throws PageException {
2134        admin.updateMapping(
2135                getString("admin",action,"virtual"),
2136                getString("admin",action,"physical"),
2137                getString("admin",action,"archive"),
2138                getString("admin",action,"primary"),
2139                ConfigWebUtil.inspectTemplate(getString("inspect",""), ConfigImpl.INSPECT_UNDEFINED),
2140                Caster.toBooleanValue(getString("toplevel","true"))
2141        );
2142        store();
2143        adminSync.broadcast(attributes, config);
2144    }
2145
2146    /**
2147     * @throws PageException
2148     * 
2149     */
2150    private void doGetMapping() throws PageException {
2151        
2152        
2153        Mapping[] mappings = config.getMappings();
2154        Struct sct=new StructImpl();
2155        String virtual=getString("admin",action,"virtual");
2156        
2157        for(int i=0;i<mappings.length;i++) {
2158            MappingImpl m=(MappingImpl) mappings[i];
2159            if(!m.getVirtual().equals(virtual)) continue;
2160            
2161            sct.set("archive",m.getArchive());
2162            sct.set("strarchive",m.getStrArchive());
2163            sct.set("physical",m.getPhysical());
2164            sct.set("strphysical",m.getStrPhysical());
2165            sct.set("virtual",m.getVirtual());
2166            sct.set(KeyConstants._hidden,Caster.toBoolean(m.isHidden()));
2167            sct.set("physicalFirst",Caster.toBoolean(m.isPhysicalFirst()));
2168            sct.set("readonly",Caster.toBoolean(m.isReadonly()));
2169            sct.set("inspect",ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), ""));
2170            sct.set("toplevel",Caster.toBoolean(m.isTopLevel()));
2171
2172            pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
2173            return;
2174        }
2175        throw new ApplicationException("there is no mapping with virtual ["+virtual+"]");
2176    }
2177    
2178
2179    private void doGetExtensionProviders() throws PageException {
2180        ExtensionProvider[] providers = config.getExtensionProviders();
2181        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"url","isReadOnly"},providers.length,"query");
2182        
2183        ExtensionProvider provider;
2184        for(int i=0;i<providers.length;i++) {
2185                provider=providers[i];
2186            int row=i+1;
2187            //qry.setAt("name",row,provider.getName());
2188            qry.setAt(KeyConstants._url,row,provider.getUrlAsString());
2189            qry.setAt("isReadOnly",row,Caster.toBoolean(provider.isReadOnly()));
2190            //qry.setAt("cacheTimeout",row,Caster.toDouble(provider.getCacheTimeout()/1000));
2191        }
2192        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2193    }
2194
2195    private void doGetExtensionInfo() throws PageException {
2196        Resource ed = config.getExtensionDirectory();
2197        Struct sct=new StructImpl();
2198        sct.set(KeyConstants._directory, ed.getPath());
2199        sct.set(KeyConstants._enabled, Caster.toBoolean(config.isExtensionEnabled()));
2200        
2201        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
2202    }
2203    
2204    
2205    
2206    private void doGetExtensions() throws PageException {
2207        Extension[] extensions = config.getExtensions();
2208        lucee.runtime.type.Query qry=new QueryImpl(new String[]{
2209                        "type","provider","id","config","version","category","description","image","label","name",
2210                        "author","codename","video","support","documentation","forum","mailinglist","network","created"},0,"query");
2211        
2212        String provider=getString("provider",null);
2213        String id=getString("id",null);
2214        Extension extension;
2215        String extProvider,extId;
2216        int row=0;
2217        for(int i=0;i<extensions.length;i++) {
2218                extension=extensions[i];
2219                if(!extension.getType().equalsIgnoreCase("all") && toType(extension.getType(), false)!=type)
2220                        continue;
2221
2222                extProvider=extension.getProvider();
2223                extId=extension.getId();
2224                if(provider!=null && !provider.equalsIgnoreCase(extProvider)) continue;
2225                if(id!=null && !id.equalsIgnoreCase(extId)) continue;
2226
2227            qry.addRow();
2228                row++;
2229            qry.setAt("provider",row,extProvider);
2230            qry.setAt(KeyConstants._id,row,extId);
2231            qry.setAt(KeyConstants._config,row,extension.getConfig(pageContext));
2232            qry.setAt(KeyConstants._version,row,extension.getVersion());
2233            
2234            qry.setAt("category",row,extension.getCategory());
2235            qry.setAt(KeyConstants._description,row,extension.getDescription());
2236            qry.setAt("image",row,extension.getImage());
2237            qry.setAt(KeyConstants._label,row,extension.getLabel());
2238            qry.setAt(KeyConstants._name,row,extension.getName());
2239
2240            qry.setAt(KeyConstants._author,row,extension.getAuthor());
2241            qry.setAt("codename",row,extension.getCodename());
2242            qry.setAt("video",row,extension.getVideo());
2243            qry.setAt("support",row,extension.getSupport());
2244            qry.setAt("documentation",row,extension.getDocumentation());
2245            qry.setAt("forum",row,extension.getForum());
2246            qry.setAt("mailinglist",row,extension.getMailinglist());
2247            qry.setAt("network",row,extension.getNetwork());
2248            qry.setAt(KeyConstants._created,row,extension.getCreated());
2249            qry.setAt(KeyConstants._type,row,extension.getType());
2250            
2251        }
2252        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2253    }
2254    
2255    
2256    
2257    
2258    private void doGetMappings() throws PageException {
2259        
2260
2261        Mapping[] mappings = config.getMappings();
2262        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"archive","strarchive","physical","strphysical","virtual","hidden","physicalFirst","readonly","inspect","toplevel"},mappings.length,"query");
2263        
2264        
2265        for(int i=0;i<mappings.length;i++) {
2266            MappingImpl m=(MappingImpl) mappings[i];
2267            int row=i+1;
2268            qry.setAt("archive",row,m.getArchive());
2269            qry.setAt("strarchive",row,m.getStrArchive());
2270            qry.setAt("physical",row,m.getPhysical());
2271            qry.setAt("strphysical",row,m.getStrPhysical());
2272            qry.setAt("virtual",row,m.getVirtual());
2273            qry.setAt("hidden",row,Caster.toBoolean(m.isHidden()));
2274            qry.setAt("physicalFirst",row,Caster.toBoolean(m.isPhysicalFirst()));
2275            qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly()));
2276            qry.setAt("inspect",row,ConfigWebUtil.inspectTemplate(m.getInspectTemplateRaw(), ""));
2277            qry.setAt("toplevel",row,Caster.toBoolean(m.isTopLevel()));
2278        }
2279        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2280    }
2281    
2282    private void doGetRestMappings() throws PageException {
2283        
2284
2285        lucee.runtime.rest.Mapping[] mappings = config.getRestMappings();
2286        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"physical","strphysical","virtual","hidden","readonly","default"},mappings.length,"query");
2287        
2288        lucee.runtime.rest.Mapping m;
2289        for(int i=0;i<mappings.length;i++) {
2290            m=mappings[i];
2291            int row=i+1;
2292            qry.setAt("physical",row,m.getPhysical());
2293            qry.setAt("strphysical",row,m.getStrPhysical());
2294            qry.setAt("virtual",row,m.getVirtual());
2295            qry.setAt("hidden",row,Caster.toBoolean(m.isHidden()));
2296            qry.setAt("readonly",row,Caster.toBoolean(m.isReadonly()));
2297            qry.setAt("default",row,Caster.toBoolean(m.isDefault()));
2298        }
2299        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2300    }
2301    
2302    private void doGetRestSettings() throws PageException {
2303                Struct sct=new StructImpl();
2304                sct.set(KeyConstants._list, Caster.toBoolean(config.getRestList()));
2305                //sct.set(KeyImpl.init("allowChanges"), Caster.toBoolean(config.getRestAllowChanges()));
2306                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
2307        
2308    }
2309
2310        private void doGetResourceProviders() throws PageException {
2311        
2312                pageContext.setVariable(getString("admin",action,"returnVariable"),admin.getResourceProviders());
2313    }
2314        
2315        private void doGetClusterClass() throws PageException {
2316                pageContext.setVariable(getString("admin",action,"returnVariable"),config.getClusterClass().getName());
2317    }
2318
2319    
2320    private void doUpdateClusterClass() throws PageException {
2321        admin.updateClusterClass(getString("admin",action,"class"));
2322        store();
2323    }
2324    
2325        private void doUpdateAdminSyncClass() throws PageException {
2326                admin.updateAdminSyncClass(getString("admin",action,"class"));
2327        store();
2328        }
2329
2330        private void doGetAdminSyncClass() throws PageException {
2331                pageContext.setVariable(getString("admin",action,"returnVariable"),config.getAdminSyncClass().getName());
2332        }
2333
2334        private void doUpdateVideoExecuterClass() throws PageException {
2335                admin.updateVideoExecuterClass(getString("admin",action,"class"));
2336        store();
2337        }
2338
2339        private void doGetVideoExecuterClass() throws PageException {
2340                pageContext.setVariable(getString("admin",action,"returnVariable"),config.getVideoExecuterClass().getName());
2341        }
2342    
2343        
2344
2345    /**
2346     * @throws PageException
2347     * 
2348     */
2349    private void doRemoveMailServer() throws PageException {
2350        admin.removeMailServer(getString("admin",action,"hostname"));
2351        store();
2352        adminSync.broadcast(attributes, config);
2353    }
2354
2355    /**
2356     * @throws PageException
2357     * 
2358     */
2359    private void doUpdateMailServer() throws PageException {
2360        
2361        
2362        
2363        
2364        admin.updateMailServer(
2365                getString("admin",action,"hostname"),
2366                getString("admin",action,"dbusername"),
2367                getString("admin",action,"dbpassword"),
2368                Caster.toIntValue(getString("admin",action,"port")),
2369                getBoolV("tls", false),
2370                getBoolV("ssl", false),
2371                toTimeout(getObject("life",null),1000*60*5),
2372                toTimeout(getObject("idle",null),1000*60*5)
2373        );
2374        
2375        
2376        store();
2377        adminSync.broadcast(attributes, config);
2378    }
2379
2380    private long toTimeout(Object timeout, long defaultValue ) throws PageException {
2381        if(timeout instanceof TimeSpan)
2382                        return ((TimeSpan) timeout).getMillis();
2383                // seconds
2384                int i = Caster.toIntValue(timeout);
2385                if(i<0)
2386                        throw new ApplicationException("invalid value ["+i+"], value must be a positive integer greater or equal than 0");
2387                return i*1000;
2388        }
2389
2390        /**
2391     * @throws PageException
2392     * 
2393     */
2394    private void doUpdateMailSetting() throws PageException {
2395        //admin.setMailLog(getString("admin",action,"logfile"),getString("loglevel","ERROR"));
2396        
2397        admin.setMailSpoolEnable(getBoolObject("admin",action,"spoolenable"));
2398        
2399        /*/ spool interval
2400        String str=getString("admin",action,"maxThreads");
2401        Integer i=null;
2402        if(!StringUtil.isEmpty(str))i=Caster.toInteger(maxThreads);*/
2403        
2404     // timeout
2405        String str = getString("admin",action,"timeout");
2406        Integer i = null;
2407        if(!StringUtil.isEmpty(str))i=Caster.toInteger(str);
2408        admin.setMailTimeout(i);
2409                
2410        admin.setMailDefaultCharset(getString("admin", action, "defaultencoding"));
2411        store();
2412        adminSync.broadcast(attributes, config);
2413    }
2414    private void doUpdateTaskSetting() throws PageException {
2415        
2416        // max Threads
2417        String str=getString("admin",action,"maxThreads");
2418        Integer i=null;
2419        if(!StringUtil.isEmpty(str)){
2420                i=Caster.toInteger(str);
2421                if(i.intValue()<10) throw new ApplicationException("we need at least 10 threads to run tasks properly");
2422        }
2423        admin.setTaskMaxThreads(i);
2424        store();
2425        adminSync.broadcast(attributes, config);
2426    }
2427
2428    
2429
2430    private void listPatches() throws PageException  {
2431        try {
2432                
2433                        pageContext.setVariable(getString("admin",action,"returnVariable"),Caster.toArray(((ConfigServerImpl)config).getInstalledPatches()));
2434                } catch (Exception e) {
2435                        throw Caster.toPageException(e);
2436                }
2437    }
2438
2439    private void needNewJars() throws PageException  {
2440        boolean needNewJars = JarLoader.changed(pageContext.getConfig(), UPDATE_JARS);
2441                
2442        try {
2443                        pageContext.setVariable(getString("admin",action,"returnVariable"),needNewJars);
2444                }
2445        catch (Exception e) {
2446                        throw Caster.toPageException(e);
2447                }
2448    }
2449
2450    private void doUpdateJars() throws PageException  {
2451        try {
2452                        JarLoader.download(pageContext.getConfig(), UPDATE_JARS);
2453                } catch (IOException e) {
2454                        throw Caster.toPageException(e);
2455                }
2456        
2457    }
2458    
2459    
2460    
2461    private void doGetMailServers() throws PageException {
2462        
2463        
2464
2465        Server[] servers = config.getMailServers();
2466        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"hostname","password","username","port","authentication","readonly","tls","ssl","life","idle"},servers.length,"query");
2467        
2468        
2469        for(int i=0;i<servers.length;i++) {
2470            Server s= servers[i];
2471            int row=i+1;
2472            qry.setAt("hostname",row,s.getHostName());
2473            qry.setAt("password",row,s.isReadOnly()?"":s.getPassword());
2474            qry.setAt("username",row,s.isReadOnly()?"":s.getUsername());
2475            qry.setAt("port",row,Caster.toInteger(s.getPort()));
2476            qry.setAt("readonly",row,Caster.toBoolean(s.isReadOnly()));
2477            qry.setAt("authentication",row,Caster.toBoolean(s.hasAuthentication()));
2478            if(s instanceof ServerImpl) {
2479                ServerImpl si = (ServerImpl)s;
2480                    qry.setAt("ssl",row,Caster.toBoolean(si.isSSL()));
2481                    qry.setAt("tls",row,Caster.toBoolean(si.isTLS()));
2482                    qry.setAt("life",row,(si.getLifeTimeSpan()/1000));
2483                    qry.setAt("idle",row,(si.getIdleTimeSpan()/1000));
2484            }
2485        }
2486        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2487    }
2488    
2489    private void doGetRunningThreads() throws PageException {
2490        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"Id","Start","Timeout","ThreadType","StackTrace","TagContext",
2491                        "Label","RootPath","ConfigFile","URL"},0,"query");
2492        
2493        
2494        if(type==TYPE_WEB){
2495                fillGetRunningThreads(qry,pageContext.getConfig());
2496        }
2497        else {
2498                ConfigServer cs = pageContext.getConfig().getConfigServer(password);
2499                ConfigWeb[] webs = cs.getConfigWebs();
2500                for(int i=0;i<webs.length;i++){
2501                        fillGetRunningThreads(qry,webs[i]);
2502                }
2503        }
2504        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2505    }
2506    
2507    private static void fillGetRunningThreads(lucee.runtime.type.Query qry, ConfigWeb configWeb) throws PageException {
2508        CFMLFactoryImpl factory = ((CFMLFactoryImpl)configWeb.getFactory());
2509        Map<Integer, PageContextImpl> pcs = factory.getActivePageContexts();
2510        Iterator<PageContextImpl> it = pcs.values().iterator();
2511        PageContextImpl pc;
2512        Collection.Key key;
2513        int row=0;
2514        while(it.hasNext()) {
2515                pc=it.next();
2516            qry.addRow();
2517            row++;
2518            StackTraceElement[] st = pc.getThread().getStackTrace();
2519            configWeb.getConfigDir();
2520            configWeb.getId();
2521            configWeb.getConfigDir();
2522            qry.setAt("Id",row,new Double(pc.getId()));
2523            qry.setAt("Start",row,new DateTimeImpl(pc.getStartTime(),false));
2524            qry.setAt("Timeout",row,new Double(pc.getRequestTimeout()/1000));
2525            qry.setAt("ThreadType",row,pc.getParentPageContext()==null?"main":"child");
2526            qry.setAt("StackTrace",row,toString(st));
2527            qry.setAt("TagContext",row,PageExceptionImpl.getTagContext(pc.getConfig(), st));
2528            
2529            qry.setAt("label",row,factory.getLabel());
2530            qry.setAt("RootPath",row,ReqRspUtil.getRootPath(((ConfigWebImpl)configWeb).getServletContext()));
2531            qry.setAt("ConfigFile",row,configWeb.getConfigFile().getAbsolutePath());
2532            if(factory.getURL()!=null)qry.setAt("url",row,factory.getURL().toExternalForm());
2533            
2534        }
2535        
2536        }
2537
2538        private static String toString(StackTraceElement[] traces) {
2539        StackTraceElement trace;
2540        StringBuilder sb=new StringBuilder( traces.length * 32 );
2541        for(int i=0;i<traces.length;i++){
2542            trace=traces[i];
2543            sb.append("\tat ");
2544            sb.append(trace.toString());
2545            sb.append(':');
2546            sb.append(trace.getLineNumber());
2547            sb.append(SystemUtil.getOSSpecificLineSeparator());
2548        }
2549        return sb.toString();
2550    }
2551    
2552
2553    /**
2554     * @throws PageException
2555     * 
2556     */
2557    private void doGetMailSetting() throws PageException {
2558        Struct sct=new StructImpl();
2559        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
2560        
2561        //LoggerAndSourceData data = config.getLoggerAndSourceData("mail");
2562        //lucee.commons.io.log.Log log=ls.getLog();
2563        
2564        //String logFile="";
2565        //String logLevel="";
2566        //if(log instanceof LogResource)logFile=((LogResource)log).getResource().toString();
2567        //String logLevel=LogUtil.toStringType(data.getLevel(),"ERROR");
2568        //sct.set("strlogfile",ls.getSource());
2569        //sct.set("logfile",logFile);
2570        //sct.set("loglevel",logLevel);
2571        int maxThreads=20;
2572        SpoolerEngine engine = config.getSpoolerEngine();
2573        if(engine instanceof SpoolerEngineImpl) {
2574                maxThreads=((SpoolerEngineImpl)engine).getMaxThreads();
2575        }
2576        
2577        sct.set("spoolEnable",Caster.toBoolean(config.isMailSpoolEnable()));
2578        sct.set("spoolInterval",Caster.toInteger(config.getMailSpoolInterval()));
2579        sct.set("maxThreads",Caster.toDouble(maxThreads));
2580        sct.set("timeout",Caster.toInteger(config.getMailTimeout()));
2581                sct.set("defaultencoding", config.getMailDefaultEncoding());
2582        
2583    }
2584    
2585    private void doGetTaskSetting() throws PageException {
2586        Struct sct=new StructImpl();
2587        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
2588        
2589        int maxThreads=20;
2590        SpoolerEngine engine = config.getSpoolerEngine();
2591        if(engine instanceof SpoolerEngineImpl) {
2592                SpoolerEngineImpl ei = ((SpoolerEngineImpl)engine);
2593                maxThreads=ei.getMaxThreads();
2594        } 
2595        sct.set("maxThreads",Caster.toDouble(maxThreads));
2596        
2597    }
2598
2599    /**
2600     * @throws PageException
2601     * 
2602     */
2603    private void doGetTLDs() throws PageException {
2604        lucee.runtime.type.Query qry=new QueryImpl(
2605                        new String[]{"displayname","namespace","namespaceseparator","shortname","type","description","uri","elclass","source"},
2606                        new String[]{"varchar","varchar","varchar","varchar","varchar","varchar","varchar","varchar","varchar"},
2607                        0,"tlds");
2608       
2609
2610        TagLib[] libs = config.getTLDs();
2611        for(int i=0;i<libs.length;i++) {
2612                qry.addRow();
2613                qry.setAt("displayname", i+1, libs[i].getDisplayName());
2614                qry.setAt("namespace", i+1, libs[i].getNameSpace());
2615                qry.setAt("namespaceseparator", i+1, libs[i].getNameSpaceSeparator());
2616                qry.setAt("shortname", i+1, libs[i].getShortName());
2617                qry.setAt("type", i+1, libs[i].getType());
2618                qry.setAt("description", i+1, libs[i].getDescription());
2619                qry.setAt("uri", i+1, Caster.toString(libs[i].getUri()));
2620                qry.setAt("elclass", i+1, libs[i].getELClass());
2621                qry.setAt("source", i+1, StringUtil.emptyIfNull(libs[i].getSource()));
2622        }
2623        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2624    }
2625
2626    /**
2627     * @throws PageException
2628     * 
2629     */
2630    private void doGetFLDs() throws PageException {
2631        lucee.runtime.type.Query qry=new QueryImpl(
2632                        new String[]{"displayname","namespace","namespaceseparator","shortname","description","uri","source"},
2633                        new String[]{"varchar","varchar","varchar","varchar","varchar","varchar","varchar"},
2634                        0,"tlds");
2635       
2636
2637        FunctionLib[] libs = config.getFLDs();
2638        for(int i=0;i<libs.length;i++) {
2639                qry.addRow();
2640                qry.setAt("displayname", i+1, libs[i].getDisplayName());
2641                qry.setAt("namespace", i+1, "");// TODO support for namespace
2642                qry.setAt("namespaceseparator", i+1, "");
2643                qry.setAt("shortname", i+1, libs[i].getShortName());
2644                qry.setAt("description", i+1, libs[i].getDescription());
2645                qry.setAt("uri", i+1, Caster.toString(libs[i].getUri()));
2646                qry.setAt("source", i+1, StringUtil.emptyIfNull(libs[i].getSource()));
2647        }
2648        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2649    }
2650
2651    private void doGetRemoteClientUsage() throws PageException {
2652        lucee.runtime.type.Query qry=new QueryImpl(
2653                        new String[]{"code","displayname"},
2654                        new String[]{"varchar","varchar"},
2655                        0,"usage");
2656        Struct usages = config.getRemoteClientUsage();
2657        //Key[] keys = usages.keys();
2658        Iterator<Entry<Key, Object>> it = usages.entryIterator();
2659        Entry<Key, Object> e;
2660        int i=-1;
2661        while(it.hasNext()) {
2662                i++;
2663                e = it.next();
2664                qry.addRow();
2665                qry.setAt(KeyConstants._code, i+1, e.getKey().getString());
2666                qry.setAt(KeyConstants._displayname, i+1, e.getValue());
2667                //qry.setAt("description", i+1, usages[i].getDescription());
2668        }
2669        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2670    }
2671
2672    private void doHasRemoteClientUsage() throws PageException {
2673        
2674        Struct usages = config.getRemoteClientUsage();
2675        pageContext.setVariable(getString("admin",action,"returnVariable"),usages.isEmpty()?Boolean.FALSE:Boolean.TRUE);
2676    }
2677    
2678    
2679    
2680    private void doGetJars() throws PageException {
2681        Resource lib = config.getConfigDir().getRealResource("lib");
2682                lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name","source"},new String[]{"varchar","varchar"},0,"jars");
2683       
2684                if(lib.isDirectory()){
2685                        Resource[] children = lib.listResources(new ExtensionResourceFilter(new String[]{".jar",".zip"},false,true));
2686                        for(int i=0;i<children.length;i++){
2687                                qry.addRow();
2688                                qry.setAt("name", i+1, children[i].getName());
2689                                qry.setAt("source", i+1, children[i].getAbsolutePath());
2690                        }
2691                }
2692        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
2693    }
2694
2695    /**
2696     * @throws PageException
2697     * 
2698     */
2699    private void doUpdateDatasource() throws PageException {
2700        int allow=
2701        (getBoolV("allowed_select",false)?DataSource.ALLOW_SELECT:0)+
2702        (getBoolV("allowed_insert",false)?DataSource.ALLOW_INSERT:0)+
2703        (getBoolV("allowed_update",false)?DataSource.ALLOW_UPDATE:0)+
2704        (getBoolV("allowed_delete",false)?DataSource.ALLOW_DELETE:0)+
2705        (getBoolV("allowed_alter",false)?DataSource.ALLOW_ALTER:0)+
2706        (getBoolV("allowed_drop",false)?DataSource.ALLOW_DROP:0)+
2707        (getBoolV("allowed_revoke",false)?DataSource.ALLOW_REVOKE:0)+
2708        (getBoolV("allowed_grant",false)?DataSource.ALLOW_GRANT:0)+
2709        (getBoolV("allowed_create",false)?DataSource.ALLOW_CREATE:0);
2710        if(allow==0)allow=DataSource.ALLOW_ALL;
2711        String classname=getString("admin",action,"classname");
2712        /*Class clazz=null;
2713        try {
2714                clazz = ClassUtil.loadClass(config.getClassLoader(),classname);//Class.orName(classname);
2715        } 
2716        catch (ClassException e) {
2717                throw new DatabaseException("can't find class ["+classname+"] for jdbc driver, check if driver (jar file) is inside lib folder",e.getMessage(),null,null,null);
2718        }*/
2719        
2720        boolean literalTimestampWithTSOffset=getBoolV("literalTimestampWithTSOffset", false);
2721        
2722        
2723        String dsn=getString("admin",action,"dsn");
2724        String name=getString("admin",action,"name");
2725        String newName=getString("admin",action,"newName");
2726        String username=getString("admin",action,"dbusername");
2727        String password=getString("admin",action,"dbpassword");
2728        String host=getString("host","");
2729        String timezone=getString("timezone","");
2730        String database=getString("database","");
2731        int port=getInt("port",-1);
2732        int connLimit=getInt("connectionLimit",-1);
2733        int connTimeout=getInt("connectionTimeout",-1);
2734        long metaCacheTimeout=getLong("metaCacheTimeout",60000);
2735        boolean blob=getBoolV("blob",false);
2736        boolean clob=getBoolV("clob",false);
2737        boolean validate=getBoolV("validate",false);
2738        boolean storage=getBoolV("storage",false);
2739        boolean verify=getBoolV("verify",true);
2740        Struct custom=getStruct("custom",new StructImpl());
2741            String dbdriver = getString("dbdriver", "");
2742        
2743        //config.getDatasourceConnectionPool().remove(name);
2744        DataSource ds=null;
2745                try {
2746                        ds = new DataSourceImpl(name,classname,host,dsn,database,port,username,password,connLimit,connTimeout,metaCacheTimeout,blob,clob,allow,custom,false,validate,storage,null, dbdriver,literalTimestampWithTSOffset);
2747                } catch (ClassException e) {
2748                        throw new DatabaseException(
2749                                        "can't find class ["+classname+"] for jdbc driver, check if driver (jar file) is inside lib folder ("+e.getMessage()+")",null,null,null);
2750                }
2751        
2752        if(verify)_doVerifyDatasource(classname,ds.getDsnTranslated(),username,password);
2753        //print.out("limit:"+connLimit);
2754        admin.updateDataSource(
2755                        name,
2756                        newName,
2757                classname,
2758                dsn,
2759                username,
2760                password,
2761                host,
2762                database,
2763                port,
2764                connLimit,
2765                connTimeout,
2766                metaCacheTimeout,
2767                blob,
2768                clob,
2769                allow,
2770                validate,
2771                storage,
2772                timezone,
2773                custom,
2774                        dbdriver,
2775                        literalTimestampWithTSOffset
2776        );
2777        store();
2778        adminSync.broadcast(attributes, config);
2779    }
2780
2781    private void doUpdateCacheConnection() throws PageException {
2782        admin.updateCacheConnection(
2783                        getString("admin",action,"name"),
2784                getString("admin",action,"class"),
2785                toCacheConstant("default"),
2786                getStruct("admin", action, "custom"),
2787                getBoolV("readOnly", false),
2788                getBoolV("storage", false)
2789                
2790        );
2791        store();
2792        adminSync.broadcast(attributes, config);
2793    }
2794
2795    private void doUpdateGatewayEntry() throws PageException {
2796        String strStartupMode=getString("admin",action,"startupMode");
2797        int startup=GatewayEntryImpl.toStartup(strStartupMode,-1);
2798        if(startup==-1)
2799                throw new ApplicationException("invalid startup mode ["+strStartupMode+"], valid values are [automatic,manual,disabled]");
2800        //print.out("doUpdateGatewayEntry");
2801        admin.updateGatewayEntry(
2802                        getString("admin",action,"id"),
2803                getString("admin",action,"class"),
2804                        getString("admin",action,"cfcPath"),
2805                        getString("admin",action,"listenerCfcPath"),
2806                startup,
2807                getStruct("admin", action, "custom"),
2808                getBoolV("readOnly", false)
2809                
2810        );
2811        store();
2812        adminSync.broadcast(attributes, config);
2813    }
2814    
2815    private int toCacheConstant(String name) throws ApplicationException {
2816                String def = getString(name, null);
2817                if(StringUtil.isEmpty(def)) return ConfigImpl.CACHE_DEFAULT_NONE;
2818                def=def.trim().toLowerCase();
2819
2820                if(def.equals("object")) return ConfigImpl.CACHE_DEFAULT_OBJECT;
2821                if(def.equals("template")) return ConfigImpl.CACHE_DEFAULT_TEMPLATE;
2822                if(def.equals("query")) return ConfigImpl.CACHE_DEFAULT_QUERY;
2823                if(def.equals("resource")) return ConfigImpl.CACHE_DEFAULT_RESOURCE;
2824                if(def.equals("function")) return ConfigImpl.CACHE_DEFAULT_FUNCTION;
2825                if(def.equals("include")) return ConfigImpl.CACHE_DEFAULT_INCLUDE;
2826        
2827                throw new ApplicationException("invalid default type ["+def+"], valid default types are [object,template,query,resource,function]");
2828        }
2829
2830        private void doUpdateCacheDefaultConnection() throws PageException {
2831                admin.updateCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_OBJECT,getString("admin",action,"object"));
2832                admin.updateCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_TEMPLATE,getString("admin",action,"template"));
2833                admin.updateCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_QUERY,getString("admin",action,"query"));
2834                admin.updateCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_RESOURCE,getString("admin",action,"resource"));
2835                admin.updateCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_FUNCTION,getString("admin",action,"function"));
2836                admin.updateCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_INCLUDE,getString("admin",action,"include"));
2837        store();
2838        adminSync.broadcast(attributes, config);
2839    }
2840
2841        private void doRemoveCacheDefaultConnection() throws PageException {
2842                admin.removeCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_OBJECT);
2843                admin.removeCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_TEMPLATE);
2844                admin.removeCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_QUERY);
2845                admin.removeCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_RESOURCE);
2846                admin.removeCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_FUNCTION);
2847                admin.removeCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_INCLUDE);
2848        store();
2849        adminSync.broadcast(attributes, config);
2850    }
2851
2852
2853        private void doRemoveLogSetting() throws PageException {
2854                admin.removeLogSetting(getString("admin", "RemoveLogSettings", "name"));
2855        store();
2856        adminSync.broadcast(attributes, config);
2857    }
2858
2859        
2860        
2861    private void doRemoveResourceProvider() throws PageException {
2862        String classname=getString("admin",action,"class");
2863        
2864        Class clazz=null;
2865                try {
2866                        clazz = ClassUtil.loadClass(config.getClassLoader(),classname);
2867                } catch (ClassException e) {
2868                        throw Caster.toPageException(e);
2869                }
2870        
2871        admin.removeResourceProvider(clazz);
2872        
2873        store();
2874        adminSync.broadcast(attributes, config);
2875    }
2876    
2877    
2878    private void doUpdateResourceProvider() throws PageException {
2879        String classname=getString("admin",action,"class");
2880        
2881        Class clazz=null;
2882                try {
2883                        clazz = ClassUtil.loadClass(config.getClassLoader(),classname);
2884                } catch (ClassException e) {
2885                        throw Caster.toPageException(e);
2886                }
2887        String scheme=getString("admin",action,"scheme");
2888        
2889        Struct sctArguments = getStruct("arguments", null);
2890        if(sctArguments!=null) {
2891                
2892                admin.updateResourceProvider(scheme,clazz,sctArguments);
2893        }
2894        else {
2895                String strArguments=getString("admin",action,"arguments");
2896                admin.updateResourceProvider(scheme,clazz,strArguments);
2897        }
2898        
2899        
2900        
2901        //admin.updateResourceProvider(scheme,clazz,arguments);
2902        store();
2903        adminSync.broadcast(attributes, config);
2904    }
2905    
2906    private void doUpdateDefaultResourceProvider() throws PageException {
2907        String classname=getString("admin",action,"class");
2908        Class clazz=null;
2909                try {
2910                        clazz = ClassUtil.loadClass(config.getClassLoader(),classname);
2911                } catch (ClassException e) {
2912                        throw Caster.toPageException(e);
2913                }
2914        String arguments=getString("admin",action,"arguments");
2915        
2916        admin.updateDefaultResourceProvider(clazz,arguments);
2917        store();
2918        adminSync.broadcast(attributes, config);
2919    }
2920    
2921    
2922
2923    private void doVerifyMailServer() throws PageException {
2924        _doVerifyMailServer(
2925                    getString("admin",action,"hostname"),
2926                    getInt("admin",action,"port"),
2927                    getString("admin",action,"mailusername"),
2928                    getString("admin",action,"mailpassword")
2929        );
2930    }
2931    
2932    private void _doVerifyMailServer(String host, int port, String user, String pass) throws PageException {
2933           try {
2934            SMTPVerifier.verify(host,user,pass,port);
2935        } catch (SMTPException e) {
2936            throw Caster.toPageException(e);
2937        }
2938    }
2939
2940    /**
2941     * @throws PageException
2942     * 
2943     */
2944    private void doVerifyDatasource() throws PageException {
2945        String classname=(String) attributes.get("classname",null);
2946        String dsn=(String) attributes.get("dsn",null);
2947        if(classname!=null && dsn!=null) {
2948            _doVerifyDatasource(classname,dsn,
2949                    getString("admin",action,"dbusername"),
2950                    getString("admin",action,"dbpassword"));
2951        }
2952        else {
2953            _doVerifyDatasource(
2954                    getString("admin",action,"name"),
2955                    getString("admin",action,"dbusername"),
2956                    getString("admin",action,"dbpassword"));
2957        }
2958    }
2959    
2960    private void doVerifyRemoteClient() throws PageException {
2961        // SNSN
2962        /*SerialNumber sn = config.getSerialNumber();
2963        if(sn.getVersion()==SerialNumber.VERSION_COMMUNITY)
2964            throw new SecurityException("can not verify remote client with "+sn.getStringVersion()+" version of lucee");
2965            */
2966        ProxyData pd=null;
2967        String proxyServer=getString("proxyServer",null);
2968        if(!StringUtil.isEmpty(proxyServer)) {
2969                String proxyUsername=getString("proxyUsername",null);
2970                String proxyPassword=getString("proxyPassword",null);
2971                int proxyPort = getInt("proxyPort",-1);
2972                pd=new ProxyDataImpl();
2973                        pd.setServer(proxyServer);
2974                        if(!StringUtil.isEmpty(proxyUsername))pd.setUsername(proxyUsername);
2975                        if(!StringUtil.isEmpty(proxyPassword))pd.setPassword(proxyPassword);
2976                        if(proxyPort!=-1)pd.setPort(proxyPort);
2977        }       
2978        RemoteClient client = new RemoteClientImpl(
2979                        getString("admin",action,"label"),
2980                        type==TYPE_WEB?"web":"server",
2981                        getString("admin",action,"url"),
2982                        getString("serverUsername",null),
2983                        getString("serverPassword",null),
2984                        getString("admin",action,"adminPassword"),
2985                        pd,
2986                        getString("admin",action,"securityKey"),
2987                        getString("admin",action,"usage")
2988                        
2989        );
2990        
2991        Struct attrColl=new StructImpl();
2992        attrColl.setEL("action", "connect");
2993        try {
2994                        new RemoteClientTask(null,client,attrColl,getCallerId(),"synchronisation").execute(config);
2995                } 
2996        catch (Throwable t) {
2997                ExceptionUtil.rethrowIfNecessary(t);
2998                        throw Caster.toPageException(t);
2999                }
3000    }
3001    
3002
3003    private void _doVerifyDatasource(String classname, String connString, String username, String password) throws PageException {
3004        try {
3005                Class clazz=null;
3006                try {
3007                        clazz=Class.forName(classname);
3008                        } catch (ClassNotFoundException e) {
3009                                e.printStackTrace();
3010                        }
3011                        if(clazz==null)clazz=ClassUtil.loadClass(config.getClassLoader(),classname);
3012            _doVerifyDatasource(clazz, connString, username, password);
3013        } 
3014        catch (ClassException e) {
3015            throw Caster.toPageException(e);
3016        }
3017    }
3018
3019    private void _doVerifyDatasource(Class clazz, String dsn, String username, String password) throws PageException {
3020            if(!Reflector.isInstaneOf(clazz,Driver.class))
3021                throw new DatabaseException("class ["+clazz.getName()+"] is not a JDBC Driver","class must implement interface [java.sql.Driver]",null,null);
3022        getConnection(dsn, username, password);
3023    }
3024
3025    private void _doVerifyDatasource(String name, String username, String password) throws PageException {
3026        DataSourceManager manager = pageContext.getDataSourceManager();
3027        manager.releaseConnection(pageContext,manager.getConnection(pageContext,name, username, password));
3028        //config.getConnection(name, username, password);
3029    }
3030    
3031    
3032    private Connection getConnection(String dsn, String user, String pass) throws DatabaseException  {
3033        Connection conn=null;
3034        try {
3035                conn = DBUtil.getConnection(dsn, user, pass);
3036            conn.setAutoCommit(true);
3037        } 
3038        catch (SQLException e) {
3039            throw new DatabaseException(e,null);
3040        }
3041        return conn;
3042    }
3043    
3044    
3045
3046    /**
3047     * @throws PageException
3048     * 
3049     */
3050    private void doUpdatePSQ() throws PageException {
3051        admin.updatePSQ(getBoolObject("admin",action,"psq"));
3052        store();
3053        adminSync.broadcast(attributes, config);
3054    }
3055    
3056    private void doReload() throws PageException {
3057        store();
3058    }
3059
3060    /**
3061     * @throws PageException
3062     * 
3063     */
3064    private void doRemoveDatasource() throws PageException {
3065        admin.removeDataSource(getString("admin",action,"name"));
3066        store();
3067        adminSync.broadcast(attributes, config);
3068    }
3069    
3070    private void doTerminateRunningThread() throws PageException {
3071        int id = getInt("admin", "RemoveRunningThread", "id");
3072        
3073        if(type==TYPE_WEB){
3074                terminateRunningThread(pageContext.getConfig(),id);
3075        }
3076        else {
3077                ConfigServer cs = pageContext.getConfig().getConfigServer(password);
3078                ConfigWeb[] webs = cs.getConfigWebs();
3079                for(int i=0;i<webs.length;i++){
3080                        if(terminateRunningThread(webs[i],id))break;
3081                }
3082        }
3083    }
3084    
3085    
3086    
3087    
3088    private static boolean terminateRunningThread(ConfigWeb configWeb,int id) {
3089
3090        Map<Integer, PageContextImpl> pcs = ((CFMLFactoryImpl)configWeb.getFactory()).getActivePageContexts();
3091        Iterator<PageContextImpl> it = pcs.values().iterator();
3092        PageContextImpl pc;
3093        Collection.Key key;
3094        while(it.hasNext()) {
3095                pc=it.next();
3096            if(pc.getId()==id){
3097                CFMLFactoryImpl.terminate(pc);
3098                return true;
3099            }
3100        }
3101        return false;
3102        }
3103
3104        private void doRemoveRemoteClient() throws PageException {
3105        admin.removeRemoteClient(getString("admin",action,"url"));
3106        store();
3107    }
3108    private void doRemoveSpoolerTask() throws PageException {
3109        config.getSpoolerEngine().remove(getString("admin",action,"id"));
3110    }
3111    private void doRemoveAllSpoolerTask() {
3112        ((SpoolerEngineImpl)config.getSpoolerEngine()).removeAll();
3113    }
3114    private void doExecuteSpoolerTask() throws PageException {
3115        PageException pe = config.getSpoolerEngine().execute(getString("admin",action,"id"));
3116                if(pe!=null) throw pe;
3117    }
3118
3119    /**
3120     * @throws PageException
3121     * 
3122     */
3123    private void doGetDatasourceSetting() throws PageException {
3124        Struct sct=new StructImpl();
3125        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3126        sct.set("psq",Caster.toBoolean(config.getPSQL()));
3127    }
3128
3129    private void doGetORMSetting() throws PageException {
3130        pageContext.setVariable(getString("admin",action,"returnVariable"),config.getORMConfig().toStruct());
3131    }
3132
3133    private void doGetORMEngine() throws PageException {
3134        pageContext.setVariable(getString("admin",action,"returnVariable"),config.getORMEngineClass().getName());
3135    }
3136    
3137
3138    private void doUpdateORMSetting() throws SecurityException, PageException {
3139        ORMConfiguration oc = config.getORMConfig();
3140        Struct settings=new StructImpl();
3141        
3142        settings.set(ORMConfigurationImpl.AUTO_GEN_MAP, getBool("admin",action,"autogenmap"));
3143        settings.set(ORMConfigurationImpl.EVENT_HANDLING, getBool("admin",action,"eventHandling"));
3144        settings.set(ORMConfigurationImpl.FLUSH_AT_REQUEST_END, getBool("admin",action,"flushatrequestend"));
3145        settings.set(ORMConfigurationImpl.LOG_SQL, getBool("admin",action,"logSQL"));
3146        settings.set(ORMConfigurationImpl.SAVE_MAPPING, getBool("admin",action,"savemapping"));
3147        settings.set(ORMConfigurationImpl.USE_DB_FOR_MAPPING, getBool("admin",action,"useDBForMapping"));
3148        settings.set(ORMConfigurationImpl.SECONDARY_CACHE_ENABLED, getBool("admin",action,"secondarycacheenabled"));
3149        
3150        settings.set(ORMConfigurationImpl.CATALOG, getString("admin",action,"catalog"));
3151        settings.set(ORMConfigurationImpl.SCHEMA, getString("admin",action,"schema"));
3152        settings.set(ORMConfigurationImpl.SQL_SCRIPT, getString("admin",action,"sqlscript"));
3153        settings.set(ORMConfigurationImpl.CACHE_CONFIG, getString("admin",action,"cacheconfig"));
3154        settings.set(ORMConfigurationImpl.CACHE_PROVIDER, getString("admin",action,"cacheProvider"));
3155        settings.set(ORMConfigurationImpl.ORM_CONFIG, getString("admin",action,"ormConfig"));
3156        
3157        
3158        // dbcreate
3159        String strDbcreate=getString("admin",action,"dbcreate");
3160        String dbcreate="none";
3161        if("none".equals(strDbcreate))                          dbcreate="none";
3162        else if("update".equals(strDbcreate))           dbcreate="update";
3163        else if("dropcreate".equals(strDbcreate))       dbcreate="dropcreate";
3164                else throw new ApplicationException("invalid dbcreate definition ["+strDbcreate+"], valid dbcreate definitions are [none,update,dropcreate]");
3165        settings.set(ORMConfigurationImpl.DB_CREATE, dbcreate);
3166        
3167        // cfclocation
3168        String strCfclocation=getString("admin",action,"cfclocation");
3169        Array arrCfclocation = lucee.runtime.type.util.ListUtil.listToArray(strCfclocation, ",\n");
3170        Iterator it = arrCfclocation.valueIterator();
3171        String path;
3172        while(it.hasNext()){
3173                path=(String) it.next();
3174                ResourceUtil.toResourceExisting(config, path);
3175        }
3176        settings.set(KeyConstants._cfcLocation, arrCfclocation);
3177        
3178        admin.updateORMSetting(ORMConfigurationImpl.load(config, null, settings, null, oc));
3179        
3180        
3181        store();
3182        adminSync.broadcast(attributes, config);
3183        }
3184    
3185    private void doResetORMSetting() throws SecurityException, PageException {
3186        config.getORMConfig();
3187        admin.resetORMSetting();
3188        store();
3189        adminSync.broadcast(attributes, config);
3190        }
3191    
3192    
3193
3194    private void doUpdatePerformanceSettings() throws SecurityException, PageException {
3195        admin.updateInspectTemplate(getString("admin",action,"inspectTemplate"));
3196        
3197        admin.updateTypeChecking(getBoolObject("admin",action,"typeChecking"));
3198        store();
3199        adminSync.broadcast(attributes, config);
3200        }
3201    
3202
3203    private void doUpdateCompilerSettings() throws SecurityException, PageException {
3204        admin.updateCompilerSettings(
3205                        getBoolObject("admin", "UpdateCompilerSettings", "dotNotationUpperCase"),
3206                        getBoolObject("admin", "UpdateCompilerSettings", "suppressWSBeforeArg"),
3207                        getBoolObject("admin", "UpdateCompilerSettings", "nullSupport")
3208                                );
3209        admin.updateTemplateCharset(getString("admin",action,"templateCharset"));
3210        
3211        
3212        store();
3213        adminSync.broadcast(attributes, config);
3214        }
3215    
3216    /*private void doGetLogSetting() throws PageException {
3217        String name=getString("admin", "GetLogSetting", "name");
3218        name=name.trim().toLowerCase();
3219        Query qry=_doGetLogSettings();
3220        
3221        int records = qry.getRecordcount();
3222        for(int row=1;row<=records;row++){
3223                String n = Caster.toString(qry.getAt("name", row, null),null);
3224                if(!StringUtil.isEmpty(n) && n.trim().equalsIgnoreCase(name)) {
3225                        Struct sct=new StructImpl();
3226                        String returnVariable=getString("admin",action,"returnVariable");
3227                        pageContext.setVariable(returnVariable,sct);
3228
3229                        sct.setEL(KeyConstants._name, qry.getAt(KeyConstants._name, row, ""));
3230                        sct.setEL(KeyConstants._level, qry.getAt(KeyConstants._level, row, ""));
3231                        sct.setEL("virtualpath", qry.getAt("virtualpath", row, ""));
3232                        sct.setEL(KeyConstants._class, qry.getAt(KeyConstants._class, row, ""));
3233                        sct.setEL("maxFile", qry.getAt("maxFile", row, ""));
3234                        sct.setEL("maxFileSize", qry.getAt("maxFileSize", row, ""));
3235                        sct.setEL(KeyConstants._path, qry.getAt(KeyConstants._path, row, ""));
3236                        
3237                        return;
3238                }
3239        }
3240        throw new ApplicationException("invalig log name ["+name+"]");
3241        
3242        }*/
3243    
3244    private void doGetCompilerSettings() throws  PageException {
3245        String returnVariable=getString("admin",action,"returnVariable");
3246        Struct sct=new StructImpl();
3247        pageContext.setVariable(returnVariable,sct);
3248
3249        sct.set("DotNotationUpperCase", config.getDotNotationUpperCase()?Boolean.TRUE:Boolean.FALSE);
3250        sct.set("suppressWSBeforeArg", config.getSuppressWSBeforeArg()?Boolean.TRUE:Boolean.FALSE);
3251        sct.set("nullSupport", config.getFullNullSupport()?Boolean.TRUE:Boolean.FALSE);
3252        sct.set("templateCharset", config.getTemplateCharset());
3253    }
3254    
3255    private void doGetLogSettings() throws  PageException {
3256        String returnVariable=getString("admin",action,"returnVariable");
3257                pageContext.setVariable(returnVariable,_doGetLogSettings());
3258    }
3259    
3260    private Query _doGetLogSettings() {
3261        Map<String, LoggerAndSourceData> loggers = config.getLoggers();
3262        Query qry=new QueryImpl(
3263                                new String[]{"name","level","appenderClass","appenderArgs","layoutClass","layoutArgs","readonly"},
3264                                loggers.size(),lucee.runtime.type.util.ListUtil.last("logs", '.'));
3265        int row=0;
3266        Iterator<Entry<String, LoggerAndSourceData>> it = loggers.entrySet().iterator();
3267        Entry<String, LoggerAndSourceData> e;
3268        LoggerAndSourceData logger;
3269        while(it.hasNext()){
3270                e = it.next();
3271                logger = e.getValue();
3272                row++;
3273                qry.setAtEL("name", row, e.getKey());
3274                qry.setAtEL("level", row,logger.getLevel().toString());
3275                qry.setAtEL("appenderClass", row, logger.getAppender().getClass().getName());
3276                qry.setAtEL("appenderArgs", row, toStruct(logger.getAppenderArgs()));
3277                qry.setAtEL("layoutClass", row, logger.getLayout().getClass().getName());
3278                qry.setAtEL("layoutArgs", row, toStruct(logger.getLayoutArgs()));
3279                qry.setAtEL("readonly", row, logger.getReadOnly());
3280        }
3281        return qry;
3282        }
3283
3284        private Object toStruct(Map<String, String> map) {
3285                Struct sct=new StructImpl();
3286                if(map!=null) {
3287                        Iterator<Entry<String, String>> it = map.entrySet().iterator();
3288                        Entry<String, String> e;
3289                        while(it.hasNext()){
3290                                e = it.next();
3291                                sct.setEL(e.getKey(), e.getValue());    
3292                        }
3293                }
3294                return sct;
3295        }
3296
3297        private void doGetPerformanceSettings() throws ApplicationException, PageException {
3298                Struct sct=new StructImpl();
3299        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3300        
3301        short it = config.getInspectTemplate();
3302        String str="once";
3303        if(it==ConfigImpl.INSPECT_ALWAYS)str="always";
3304        else if(it==ConfigImpl.INSPECT_NEVER)str="never";
3305        sct.set("inspectTemplate",str);
3306        sct.set("typeChecking",config.getTypeChecking());
3307        }
3308    
3309    
3310    private void doGetCustomTagSetting() throws PageException {
3311        Struct sct=new StructImpl();
3312        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3313        sct.set("customTagDeepSearch",Caster.toBoolean(config.doCustomTagDeepSearch()));// deprecated
3314        sct.set("customTagLocalSearch",Caster.toBoolean(config.doLocalCustomTag()));// deprecated
3315        
3316        sct.set("deepSearch",Caster.toBoolean(config.doCustomTagDeepSearch()));
3317        sct.set("localSearch",Caster.toBoolean(config.doLocalCustomTag()));
3318        sct.set("customTagPathCache",Caster.toBoolean(config.useCTPathCache()));
3319        sct.set("extensions",new ArrayImpl(config.getCustomTagExtensions()));
3320    }
3321
3322    private void doGetDatasourceDriverList() throws PageException {
3323        Resource luceeContext = ResourceUtil.toResourceExisting(pageContext ,"/lucee/admin/dbdriver/");
3324        Resource[] children = luceeContext.listResources(new ExtensionResourceFilter("cfc"));
3325        String rtnVar=getString("admin",action,"returnVariable");
3326        
3327        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name"},children.length,rtnVar);
3328         
3329        
3330        for(int i=0;i<children.length;i++) {
3331                qry.setAt("name", i+1, children[i].getName());
3332        }
3333        pageContext.setVariable(rtnVar,qry);
3334        
3335    }
3336
3337        private void doGetDebuggingList() throws PageException {
3338        Resource luceeContext = ResourceUtil.toResourceExisting(pageContext ,"/lucee/templates/debugging/");
3339        Resource[] children = luceeContext.listResources(new ExtensionResourceFilter("cfm"));
3340        String rtnVar=getString("admin",action,"returnVariable");
3341        
3342        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name"},children.length,rtnVar);
3343         
3344        
3345        for(int i=0;i<children.length;i++) {
3346                qry.setAt("name", i+1, children[i].getName());
3347        }
3348        pageContext.setVariable(rtnVar,qry);
3349        
3350    }
3351        
3352        private void doGetGatewayEntries() throws PageException  {
3353                Map entries = ((ConfigWebImpl)config).getGatewayEngine().getEntries();
3354                Iterator it = entries.entrySet().iterator();
3355                lucee.runtime.type.Query qry=
3356                        new QueryImpl(new String[]{"class","id","custom","cfcPath","listenerCfcPath","startupMode","state","readOnly"}, 0, "entries");
3357        Map.Entry entry;
3358        GatewayEntry ge;
3359        //Gateway g;
3360        int row=0;
3361        while(it.hasNext()){
3362                        row++;
3363                    entry=(Entry) it.next();
3364                        ge=(GatewayEntry) entry.getValue();
3365                        //g=ge.getGateway();
3366                qry.addRow();
3367                qry.setAtEL("class", row, ge.getClassName());
3368                qry.setAtEL("id", row, ge.getId());
3369                qry.setAtEL("listenerCfcPath", row, ge.getListenerCfcPath());
3370                qry.setAtEL("cfcPath", row, ge.getCfcPath());
3371                qry.setAtEL("startupMode", row, GatewayEntryImpl.toStartup(ge.getStartupMode(),"automatic"));
3372                qry.setAtEL("custom", row, ge.getCustom());
3373                qry.setAtEL("readOnly", row, Caster.toBoolean(ge.isReadOnly()));
3374                qry.setAtEL("state",row,GatewayEngineImpl.toStringState(GatewayUtil.getState(ge), "failed"));
3375                
3376        }
3377        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3378        }
3379        
3380
3381        private void doGetMonitors() throws PageException  {
3382                if(!(config instanceof ConfigServerImpl))
3383                        throw new ApplicationException("invalid context for this action");
3384                
3385                ConfigServerImpl cs=(ConfigServerImpl) config;
3386                IntervallMonitor[] intervalls = cs.getIntervallMonitors();
3387                RequestMonitor[] requests = cs.getRequestMonitors();
3388                
3389                lucee.runtime.type.Query qry=
3390                        new QueryImpl(new Collection.Key[]{KeyConstants._name,KeyConstants._type,LOG_ENABLED,CLASS}, 0, "monitors");
3391                doGetMonitors(qry,intervalls);
3392                doGetMonitors(qry,requests);
3393                
3394        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3395        }
3396        private void doGetMonitor() throws PageException  {
3397                if(!(config instanceof ConfigServerImpl))
3398                        throw new ApplicationException("invalid context for this action");
3399                ConfigServerImpl cs=(ConfigServerImpl) config;
3400
3401                String type=getString("admin",action,"monitorType");
3402                String name=getString("admin",action,"name");
3403                type=type.trim();
3404                Monitor m;
3405                if("request".equalsIgnoreCase(type)) 
3406                        m=cs.getRequestMonitor(name);
3407                else
3408                        m=cs.getIntervallMonitor(name);
3409                
3410                Struct sct=new StructImpl();
3411                sct.setEL(KeyConstants._name, m.getName());
3412                sct.setEL(KeyConstants._type, m.getType()==Monitor.TYPE_INTERVALL?"intervall":"request");
3413                sct.setEL(LOG_ENABLED, m.isLogEnabled());
3414                sct.setEL(CLASS, m.getClazz().getName());
3415                
3416        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3417        }
3418        
3419
3420
3421        private void doGetExecutionLog() throws PageException {
3422                ExecutionLogFactory factory = config.getExecutionLogFactory();
3423                Struct sct=new StructImpl();
3424                
3425                sct.set(KeyConstants._enabled, Caster.toBoolean(config.getExecutionLogEnabled()));
3426                Class clazz = factory.getClazz();
3427                sct.set(KeyConstants._class, clazz!=null?clazz.getName():"");
3428                sct.set(KeyConstants._arguments, factory.getArgumentsAsStruct());
3429                
3430                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3431        }
3432        
3433        
3434        
3435        
3436        private void doGetMonitors(Query qry, Monitor[] monitors) {
3437                Monitor m;
3438                int row;
3439                for(int i=0;i<monitors.length;i++){
3440                        m=monitors[i];
3441                        row=qry.addRow();
3442                qry.setAtEL(KeyConstants._name, row, m.getName());
3443                qry.setAtEL(KeyConstants._type, row, m.getType()==Monitor.TYPE_INTERVALL?"intervall":"request");
3444                qry.setAtEL(LOG_ENABLED, row, m.isLogEnabled());
3445                qry.setAtEL(CLASS, row, m.getClazz().getName());
3446                }
3447                
3448        }
3449
3450        private void doGetGatewayEntry() throws PageException {
3451        
3452        String id=getString("admin",action,"id");
3453        Map entries = ((ConfigWebImpl)config).getGatewayEngine().getEntries();
3454                Iterator it = entries.keySet().iterator();
3455                GatewayEntry ge;
3456                //Gateway g;
3457                Struct sct;
3458                while(it.hasNext()) {
3459            String key=(String)it.next();
3460            if(key.equalsIgnoreCase(id)) {
3461                ge=(GatewayEntry) entries.get(key);
3462                //g=ge.getGateway();
3463                sct=new StructImpl();
3464                sct.setEL("id",ge.getId());
3465                sct.setEL("class",ge.getClassName());
3466                sct.setEL("listenerCfcPath", ge.getListenerCfcPath());
3467                sct.setEL("cfcPath",ge.getCfcPath());
3468                sct.setEL("startupMode",GatewayEntryImpl.toStartup(ge.getStartupMode(),"automatic"));
3469                sct.setEL("custom",ge.getCustom());
3470                sct.setEL("readOnly",Caster.toBoolean(ge.isReadOnly()));
3471                sct.setEL("state",GatewayEngineImpl.toStringState(GatewayUtil.getState(ge), "failed"));
3472                
3473                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3474                return;
3475            }
3476        }
3477        throw new ApplicationException("there is no gateway entry with id ["+id+"]");
3478    }
3479        
3480        private void doGateway() throws PageException {
3481        
3482                String id=getString("admin",action,"id");
3483                String act=getString("admin",action,"gatewayAction").trim().toLowerCase();
3484                if("restart".equals(act))       ((ConfigWebImpl)config).getGatewayEngine().restart(id);
3485                else if("start".equals(act))((ConfigWebImpl)config).getGatewayEngine().start(id);
3486                else if("stop".equals(act))     ((ConfigWebImpl)config).getGatewayEngine().stop(id);
3487                else throw new ApplicationException("invalid gateway action ["+act+"], valid actions are [start,stop,restart]");
3488    }
3489        
3490        
3491        
3492        private void doGetCacheConnections() throws PageException  {
3493                Map conns = config.getCacheConnections();
3494                Iterator it = conns.entrySet().iterator();
3495                lucee.runtime.type.Query qry=new QueryImpl(new String[]{"class","name","custom","default","readOnly","storage"}, 0, "connections");
3496        Map.Entry entry;
3497        CacheConnection cc;
3498        CacheConnection defObj=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_OBJECT);
3499        CacheConnection defTmp=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_TEMPLATE);
3500        CacheConnection defQry=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_QUERY);
3501        CacheConnection defRes=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_RESOURCE);
3502        CacheConnection defUDF=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_FUNCTION);
3503        CacheConnection defInc=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_INCLUDE);
3504
3505        int row=0;
3506        String def;
3507                while(it.hasNext()){
3508                        row++;
3509                    entry=(Entry) it.next();
3510                        cc=(CacheConnection) entry.getValue();
3511                qry.addRow();
3512                def="";
3513                if(cc==defObj)def="object";
3514                if(cc==defTmp)def="template";
3515                if(cc==defQry)def="query";
3516                if(cc==defRes)def="resource";
3517                if(cc==defUDF)def="function";
3518                if(cc==defInc)def="include";
3519                qry.setAtEL("class", row, cc.getClazz().getName());
3520                qry.setAtEL("name", row, cc.getName());
3521                qry.setAtEL("custom", row, cc.getCustom());
3522                qry.setAtEL("default", row, def);
3523                qry.setAtEL("readOnly", row, Caster.toBoolean(cc.isReadOnly()));
3524                qry.setAtEL("storage", row, Caster.toBoolean(cc.isStorage()));
3525                
3526        }
3527        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3528        }
3529
3530        
3531        private void doGetCacheDefaultConnection() throws PageException {
3532                int type;
3533        String strType=getString("admin", "GetCacheDefaultConnection", "cacheType");
3534        strType=strType.toLowerCase().trim();
3535        if(strType.equals("object"))
3536                type=ConfigImpl.CACHE_DEFAULT_OBJECT;
3537        else if(strType.equals("template"))
3538                type=ConfigImpl.CACHE_DEFAULT_TEMPLATE;
3539        else if(strType.equals("query"))
3540                type=ConfigImpl.CACHE_DEFAULT_QUERY;
3541        else if(strType.equals("resource"))
3542                type=ConfigImpl.CACHE_DEFAULT_RESOURCE;
3543        else if(strType.equals("function"))
3544                type=ConfigImpl.CACHE_DEFAULT_FUNCTION;
3545        else if(strType.equals("include"))
3546                type=ConfigImpl.CACHE_DEFAULT_INCLUDE;
3547        else
3548                throw new ApplicationException("inv,query,resourcealid type defintion, valid values are [object,template,query,resource,function,include]");
3549                
3550        CacheConnection cc = config.getCacheDefaultConnection(type);
3551        if(cc!=null){
3552                Struct sct=new StructImpl();
3553            
3554            sct.setEL(KeyConstants._name,cc.getName());
3555            sct.setEL("class",cc.getClazz().getName());
3556            sct.setEL("custom",cc.getCustom());
3557            sct.setEL("default",Caster.toBoolean(true));
3558            sct.setEL("readOnly",Caster.toBoolean(cc.isReadOnly()));
3559            
3560                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3561        }
3562        else throw new ApplicationException("there is no cache default connection");
3563    }
3564        
3565        private void doGetCacheConnection() throws PageException {
3566        
3567        String name=getString("admin",action,"name");
3568        Map conns = config.getCacheConnections();
3569                Iterator it = conns.keySet().iterator();
3570                CacheConnection cc;
3571                CacheConnection dObj=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_OBJECT);
3572                CacheConnection dTmp=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_TEMPLATE);
3573                CacheConnection dQry=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_QUERY);
3574                CacheConnection dRes=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_RESOURCE);
3575                CacheConnection dUDF=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_FUNCTION);
3576                CacheConnection dInc=config.getCacheDefaultConnection(ConfigImpl.CACHE_DEFAULT_INCLUDE);
3577                
3578                Struct sct;
3579                String d;
3580        while(it.hasNext()) {
3581            String key=(String)it.next();
3582            if(key.equalsIgnoreCase(name)) {
3583                cc=(CacheConnection) conns.get(key);
3584                sct=new StructImpl();
3585                d="";
3586                if(cc==dObj)d="object";
3587                else if(cc==dTmp)d="template";
3588                else if(cc==dQry)d="query";
3589                else if(cc==dRes)d="resource";
3590                else if(cc==dUDF)d="function";
3591                else if(cc==dInc)d="include";
3592                sct.setEL(KeyConstants._name,cc.getName());
3593                sct.setEL(KeyConstants._class,cc.getClazz().getName());
3594                sct.setEL(KeyConstants._custom,cc.getCustom());
3595                sct.setEL(KeyConstants._default,d);
3596                sct.setEL("readOnly",Caster.toBoolean(cc.isReadOnly()));
3597                sct.setEL("storage",Caster.toBoolean(cc.isStorage()));
3598                
3599                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3600                return;
3601            }
3602        }
3603        throw new ApplicationException("there is no cache connection with name ["+name+"]");
3604    }
3605
3606        private void doRemoveCacheConnection() throws PageException {
3607                admin.removeCacheConnection(getString("admin",action,"name"));
3608        store();
3609        adminSync.broadcast(attributes, config);
3610    }
3611        
3612        private void doRemoveGatewayEntry() throws PageException {
3613                admin.removeCacheGatewayEntry(getString("admin",action,"id"));
3614        store();
3615        adminSync.broadcast(attributes, config);
3616    }
3617        
3618        private void doRemoveDebugEntry() throws PageException {
3619                admin.removeDebugEntry(getString("admin",action,"id"));
3620        store();
3621        adminSync.broadcast(attributes, config);
3622    }
3623        
3624        private void doVerifyCacheConnection() throws PageException {
3625                
3626                
3627                try {
3628                        Cache cache = Util.getCache(pageContext.getConfig(), getString("admin",action,"name"));
3629                        if(cache instanceof Cache2)
3630                                ((Cache2)cache).verify();
3631                        else
3632                                cache.getCustomInfo();
3633                } catch (IOException e) {
3634                        throw Caster.toPageException(e);
3635                }
3636    }
3637
3638    /**
3639     * @throws PageException
3640     * 
3641     */
3642    private void doGetDatasource() throws PageException {
3643        
3644        String name=getString("admin",action,"name");
3645        Map ds = config.getDataSourcesAsMap();
3646        Iterator it = ds.keySet().iterator();
3647        
3648        while(it.hasNext()) {
3649            String key=(String)it.next();
3650            if(key.equalsIgnoreCase(name)) {
3651                DataSource d=(DataSource) ds.get(key);
3652                Struct sct=new StructImpl();
3653                
3654                sct.setEL(KeyConstants._name,key);
3655                sct.setEL(KeyConstants._host,d.getHost());
3656                sct.setEL("classname",d.getClazz().getName());
3657                sct.setEL("dsn",d.getDsnOriginal());
3658                sct.setEL("database",d.getDatabase());
3659                sct.setEL("port",d.getPort()<1?"":Caster.toString(d.getPort()));
3660                sct.setEL("dsnTranslated",d.getDsnTranslated());
3661                sct.setEL("timezone",toStringTimeZone(d.getTimeZone()));
3662                sct.setEL("password",d.getPassword());
3663                sct.setEL("passwordEncrypted",ConfigWebFactory.encrypt(d.getPassword()));
3664                sct.setEL("username",d.getUsername());
3665                sct.setEL("readonly",Caster.toBoolean(d.isReadOnly()));
3666                sct.setEL("select",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT)));
3667                sct.setEL("delete",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE)));
3668                sct.setEL("update",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE)));
3669                sct.setEL("insert",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
3670                sct.setEL("create",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE)));
3671                sct.setEL("insert",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
3672                sct.setEL("drop",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP)));
3673                sct.setEL("grant",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT)));
3674                sct.setEL("revoke",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE)));
3675                sct.setEL("alter",Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER)));
3676    
3677                sct.setEL("connectionLimit",d.getConnectionLimit()<1?"":Caster.toString(d.getConnectionLimit()));
3678                sct.setEL("connectionTimeout",d.getConnectionTimeout()<1?"":Caster.toString(d.getConnectionTimeout()));
3679                sct.setEL("metaCacheTimeout",Caster.toDouble(d.getMetaCacheTimeout()));
3680                sct.setEL("custom",d.getCustoms());
3681                sct.setEL("blob",Boolean.valueOf(d.isBlob()));
3682                sct.setEL("clob",Boolean.valueOf(d.isClob()));
3683                sct.setEL("validate",Boolean.valueOf(d.validate()));
3684                sct.setEL("storage",Boolean.valueOf(d.isStorage()));
3685
3686                    if (d instanceof DataSourceImpl) {
3687
3688                            sct.setEL("dbdriver", Caster.toString( ((DataSourceImpl)d).getDbDriver(), "" ));
3689                    }
3690                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3691                return;
3692            }
3693        }
3694        throw new ApplicationException("there is no datasource with name ["+name+"]");
3695    }
3696    private Object toStringTimeZone(TimeZone timeZone) {
3697                if(timeZone==null) return "";
3698                return timeZone.getID();
3699        }
3700
3701        private void doGetRemoteClient() throws PageException {
3702        
3703        String url=getString("admin",action,"url");
3704        RemoteClient[] clients = config.getRemoteClients();
3705        RemoteClient client;
3706        for(int i=0;i<clients.length;i++) {
3707                client=clients[i];
3708            
3709            if(client.getUrl().equalsIgnoreCase(url)) {
3710                Struct sct=new StructImpl();
3711                ProxyData pd = client.getProxyData();
3712                sct.setEL("label",client.getLabel());
3713                sct.setEL("usage",client.getUsage());
3714                sct.setEL("securityKey",client.getSecurityKey());
3715                sct.setEL("adminPassword",client.getAdminPassword());
3716                sct.setEL("ServerUsername",client.getServerUsername());
3717                sct.setEL("ServerPassword",client.getServerPassword());
3718                sct.setEL("type",client.getType());
3719                sct.setEL("url",client.getUrl());
3720                sct.setEL("proxyServer",pd==null?"":StringUtil.emptyIfNull(pd.getServer()));
3721                sct.setEL("proxyUsername",pd==null?"":StringUtil.emptyIfNull(pd.getUsername()));
3722                sct.setEL("proxyPassword",pd==null?"":StringUtil.emptyIfNull(pd.getPassword()));
3723                sct.setEL("proxyPort",pd==null?"":(pd.getPort()==-1?"":Caster.toString(pd.getPort())));
3724                
3725                
3726                pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
3727                return;
3728            }
3729        }
3730        throw new ApplicationException("there is no remote client with url ["+url+"]");
3731    }
3732    
3733    private void doGetSpoolerTasks() throws PageException {
3734        int startrow = getInt("startrow",1);
3735        if(startrow <1) startrow=1;
3736        int maxrow = getInt("maxrow",-1);
3737        String result=getString("result", null);
3738        SpoolerEngineImpl engine = (SpoolerEngineImpl) config.getSpoolerEngine();
3739        
3740        Query qry = engine.getAllTasksAsQuery(startrow,maxrow);
3741        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3742                if(!StringUtil.isEmpty(result)){
3743                        Struct sct=new StructImpl();
3744                        pageContext.setVariable(result,sct);
3745                        sct.setEL("open", engine.getOpenTaskCount());
3746                                sct.setEL("closed", engine.getClosedTaskCount());
3747                }
3748        
3749        /*
3750        SpoolerTask[] open = config.getSpoolerEngine().getOpenTasks();
3751                        SpoolerTask[] closed = config.getSpoolerEngine().getClosedTasks();
3752                        String v="VARCHAR"; 
3753                        lucee.runtime.type.Query qry=new QueryImpl(
3754                                        new String[]{"type","name","detail","id","lastExecution","nextExecution","closed","tries","exceptions","triesmax"},
3755                                        new String[]{v,v,"object",v,d,d,"boolean","int","object","int"},
3756                                        open.length+closed.length,"query");
3757
3758                int row=0;
3759                        row=doGetRemoteClientTasks(qry,open,row);
3760                        doGetRemoteClientTasks(qry,closed,row);
3761                pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3762           */  
3763        
3764        
3765        
3766    }
3767    
3768    private int doGetRemoteClientTasks(lucee.runtime.type.Query qry, SpoolerTask[] tasks, int row) {
3769        SpoolerTask task;
3770                for(int i=0;i<tasks.length;i++) {
3771                        row++;
3772                        task=tasks[i];
3773                        try{
3774                                qry.setAt("type", row, task.getType());
3775                                qry.setAt("name", row, task.subject());
3776                                qry.setAt("detail", row, task.detail());
3777                                qry.setAt("id", row, task.getId());
3778        
3779                                
3780                                qry.setAt("lastExecution", row,new DateTimeImpl(pageContext,task.lastExecution(),true));
3781                                qry.setAt("nextExecution", row,new DateTimeImpl(pageContext,task.nextExecution(),true));
3782                                qry.setAt("closed", row,Caster.toBoolean(task.closed()));
3783                                qry.setAt("tries", row,Caster.toDouble(task.tries()));
3784                                qry.setAt("triesmax", row,Caster.toDouble(task.tries()));
3785                                qry.setAt("exceptions", row,translateTime(task.getExceptions()));
3786                                
3787                                int triesMax=0;
3788                                ExecutionPlan[] plans = task.getPlans();
3789                                for(int y=0;y<plans.length;y++) {
3790                                        triesMax+=plans[y].getTries();
3791                                }
3792                                qry.setAt("triesmax", row,Caster.toDouble(triesMax));
3793                        }
3794                        catch(Throwable t){
3795                                ExceptionUtil.rethrowIfNecessary(t);
3796                        }
3797                }
3798        return row;
3799        }
3800
3801        private Array translateTime(Array exp) {
3802                exp=(Array) Duplicator.duplicate(exp,true);
3803                Iterator<Object> it = exp.valueIterator();
3804                Struct sct;
3805                while(it.hasNext()) {
3806                        sct=(Struct) it.next();
3807                        sct.setEL("time",new DateTimeImpl(pageContext,Caster.toLongValue(sct.get("time",null),0),true));
3808                }
3809                return exp;
3810        }
3811
3812        private void doGetRemoteClients() throws PageException {
3813        RemoteClient[] clients = config.getRemoteClients();
3814        RemoteClient client;
3815        ProxyData pd;
3816        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"label","usage","securityKey","adminPassword","serverUsername","serverPassword","type","url",
3817                        "proxyServer","proxyUsername","proxyPassword","proxyPort"},clients.length,"query");
3818        
3819        int row=0;
3820
3821        for(int i=0;i<clients.length;i++) {
3822            client=clients[i];
3823            pd=client.getProxyData();
3824            row=i+1;
3825            qry.setAt("label",row,client.getLabel());
3826            qry.setAt("usage",row,client.getUsage());
3827            qry.setAt("securityKey",row,client.getSecurityKey());
3828            qry.setAt("adminPassword",row,client.getAdminPassword());
3829            qry.setAt("ServerUsername",row,client.getServerUsername());
3830            qry.setAt("ServerPassword",row,client.getServerPassword());
3831            qry.setAt("type",row,client.getType());
3832            qry.setAt("url",row,client.getUrl());
3833            qry.setAt("proxyServer",row,pd==null?"":pd.getServer());
3834            qry.setAt("proxyUsername",row,pd==null?"":pd.getUsername());
3835            qry.setAt("proxyPassword",row,pd==null?"":pd.getPassword());
3836            qry.setAt("proxyPort",row,pd==null?"":Caster.toString(pd.getPort()));
3837            
3838        }
3839        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3840    }
3841
3842        private void doSetCluster()  {// MUST remove this
3843                try {
3844                        _doSetCluster();
3845                } catch (Throwable t) {
3846                        ExceptionUtil.rethrowIfNecessary(t);
3847                        //print.printST(t);
3848                }
3849        }
3850        
3851        private void _doSetCluster() throws PageException {
3852                
3853                Struct entries = Caster.toStruct(getObject("admin",action,"entries"));
3854                Struct entry;
3855                Iterator<Object> it = entries.valueIterator();
3856                Cluster cluster = pageContext.clusterScope();
3857                while(it.hasNext()) {
3858                        entry=Caster.toStruct(it.next());
3859                        cluster.setEntry(
3860                                new ClusterEntryImpl(
3861                                                KeyImpl.getInstance(Caster.toString(entry.get(KeyConstants._key))),
3862                                                Caster.toSerializable(entry.get(KeyConstants._value,null),null),
3863                                                Caster.toLongValue(entry.get(KeyConstants._time))
3864                                )
3865                        );
3866                }
3867
3868                cluster.broadcast();
3869        }
3870        
3871        
3872        private void doGetCluster() throws PageException {
3873                pageContext.setVariable(
3874                                getString("admin",action,"returnVariable"),
3875                                ((PageContextImpl)pageContext).clusterScope(false)
3876                        );
3877        }
3878        
3879        private void doGetToken() throws PageException {
3880                pageContext.setVariable(
3881                                getString("admin",action,"returnVariable"),
3882                                config.getSecurityToken()
3883                        );
3884        }
3885        
3886        
3887        
3888        
3889    /**
3890     * @throws PageException
3891     * 
3892     */
3893    private void doGetDatasources() throws PageException {
3894        
3895        
3896        Map ds = config.getDataSourcesAsMap();
3897        Iterator it = ds.keySet().iterator();
3898        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"name","host","classname","dsn","DsnTranslated","database","port",
3899                "timezone","username","password","passwordEncrypted","readonly"
3900                ,"grant","drop","create","revoke","alter","select","delete","update","insert"
3901                ,"connectionLimit","connectionTimeout","clob","blob","validate","storage","customSettings","metaCacheTimeout"},ds.size(),"query");
3902        
3903        int row=0;
3904
3905        while(it.hasNext()) {
3906            Object key=it.next();
3907            DataSource d=(DataSource) ds.get(key);
3908            row++;
3909            qry.setAt(KeyConstants._name,row,key);
3910            qry.setAt(KeyConstants._host,row,d.getHost());
3911            qry.setAt("classname",row,d.getClazz().getName());
3912            //qry.setAt("driverversion",row,getDriverVersion(d.getClazz())); 
3913            qry.setAt("dsn",row,d.getDsnOriginal());
3914            qry.setAt("database",row,d.getDatabase());
3915            qry.setAt(KeyConstants._port,row,d.getPort()<1?"":Caster.toString(d.getPort()));
3916            qry.setAt("dsnTranslated",row,d.getDsnTranslated());
3917            qry.setAt("timezone",row,toStringTimeZone(d.getTimeZone()));
3918            qry.setAt(KeyConstants._password,row,d.getPassword());
3919
3920            qry.setAt("passwordEncrypted",row,ConfigWebFactory.encrypt(d.getPassword()));
3921            qry.setAt(KeyConstants._username,row,d.getUsername());
3922            qry.setAt(KeyConstants._readonly,row,Caster.toBoolean(d.isReadOnly()));
3923            qry.setAt(KeyConstants._select,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT)));
3924            qry.setAt(KeyConstants._delete,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE)));
3925            qry.setAt(KeyConstants._update,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE)));
3926            qry.setAt(KeyConstants._create,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE)));
3927            qry.setAt(KeyConstants._insert,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
3928            qry.setAt(KeyConstants._drop,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP)));
3929            qry.setAt(KeyConstants._grant,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT)));
3930            qry.setAt(KeyConstants._revoke,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE)));
3931            qry.setAt(KeyConstants._alter,row,Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER)));
3932
3933            qry.setAt("connectionLimit",row,d.getConnectionLimit()<1?"":Caster.toString(d.getConnectionLimit()));
3934            qry.setAt("connectionTimeout",row,d.getConnectionTimeout()<1?"":Caster.toString(d.getConnectionTimeout()));
3935            qry.setAt("customSettings",row,d.getCustoms());
3936            qry.setAt("blob",row,Boolean.valueOf(d.isBlob()));
3937            qry.setAt("clob",row,Boolean.valueOf(d.isClob()));
3938            qry.setAt("validate",row,Boolean.valueOf(d.validate()));
3939            qry.setAt("storage",row,Boolean.valueOf(d.isStorage()));
3940            qry.setAt("metaCacheTimeout",row,Caster.toDouble(d.getMetaCacheTimeout()));
3941            
3942        }
3943        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
3944    }
3945
3946
3947    /**
3948     * @throws PageException
3949     * 
3950     */
3951    private void doUpdateScope() throws PageException {
3952        
3953        admin.updateScopeCascadingType(getString("admin",action,"scopeCascadingType"));
3954        admin.updateAllowImplicidQueryCall(getBoolObject("admin",action,"allowImplicidQueryCall"));
3955        admin.updateMergeFormAndUrl(getBoolObject("admin",action,"mergeFormAndUrl"));
3956        admin.updateSessionManagement(getBoolObject("admin",action,"sessionManagement"));
3957        admin.updateClientManagement(getBoolObject("admin",action,"clientManagement"));
3958        admin.updateDomaincookies(getBoolObject("admin",action,"domainCookies"));
3959        admin.updateClientCookies(getBoolObject("admin",action,"clientCookies"));
3960        //admin.updateRequestTimeout(getTimespan("admin",action,"requestTimeout"));
3961        admin.updateClientTimeout(getTimespan("admin",action,"clientTimeout"));
3962        admin.updateSessionTimeout(getTimespan("admin",action,"sessionTimeout"));
3963        admin.updateClientStorage(getString("admin",action,"clientStorage"));
3964        admin.updateSessionStorage(getString("admin",action,"sessionStorage"));
3965        admin.updateApplicationTimeout(getTimespan("admin",action,"applicationTimeout"));
3966        admin.updateSessionType(getString("admin",action,"sessionType"));
3967        admin.updateLocalMode(getString("admin",action,"localMode"));
3968        admin.updateCGIReadonly(getBoolObject("admin",action,"cgiReadonly"));
3969        store();
3970        adminSync.broadcast(attributes, config);
3971    }
3972    
3973
3974    private void doUpdateRestSettings() throws PageException {
3975
3976        admin.updateRestList(getBool("list", null));
3977        //admin.updateRestAllowChanges(getBool("allowChanges", null));
3978        store();
3979        adminSync.broadcast(attributes, config);
3980    }
3981
3982    private void doUpdateApplicationSettings() throws PageException {
3983        admin.updateRequestTimeout(getTimespan("admin",action,"requestTimeout"));
3984        admin.updateScriptProtect(getString("admin",action,"scriptProtect"));
3985        admin.updateAllowURLRequestTimeout(getBoolObject("admin",action,"allowURLRequestTimeout"));
3986        store();
3987        adminSync.broadcast(attributes, config);
3988    }
3989    private void doUpdateQueueSettings() throws PageException {
3990        admin.updateQueue(getInteger("admin",action,"max"), getInteger("admin",action,"timeout"), getBoolObject("admin",action,"enable"));
3991        store();
3992        adminSync.broadcast(attributes, config);
3993    }
3994
3995    private void doUpdateOutputSettings() throws PageException {
3996        admin.updateCFMLWriterType(getString("admin",action, "cfmlWriter"));
3997        admin.updateSuppressContent(getBoolObject("admin",action, "suppressContent"));
3998        //admin.updateShowVersion(getBoolObject("admin",action, "showVersion"));
3999        admin.updateAllowCompression(getBoolObject("admin",action, "allowCompression"));
4000        admin.updateContentLength(getBoolObject("admin",action, "contentLength"));
4001        admin.updateBufferOutput(getBoolObject("admin",action, "bufferOutput"));
4002        store();
4003        adminSync.broadcast(attributes, config);
4004    }
4005    
4006    private void doUpdateCustomTagSetting() throws PageException {
4007        admin.updateCustomTagDeepSearch(getBool("admin", action, "deepSearch"));
4008        admin.updateCustomTagLocalSearch(getBool("admin", action, "localSearch"));
4009        admin.updateCTPathCache(getBool("admin", action, "customTagPathCache"));
4010        admin.updateCustomTagExtensions(getString("admin", action, "extensions"));
4011        store();
4012        adminSync.broadcast(attributes, config);
4013    }
4014    
4015    /*private void doUpdateUpdateLogSettings() throws PageException  {
4016        int level=LogUtil.toIntType(getString("admin", "updateUpdateLogSettings", "level"), -1);
4017        String source=getString("admin", "updateUpdateLogSettings", "path");
4018        if(source.indexOf("{")==-1){
4019                Resource res = ResourceUtil.toResourceNotExisting(pageContext, source, false);
4020                String tmp=SystemUtil.addPlaceHolder(res, config, null);
4021                        
4022                
4023                if(tmp!=null) source=tmp;
4024                else source=ContractPath.call(pageContext, source);
4025        }
4026        
4027        admin.updateLogSettings(
4028                        getString("admin", "updateUpdateLogSettings", "name"),
4029                        level,
4030                        source,
4031                        getInt("admin", "updateUpdateLogSettings", "maxfile"),
4032                        getInt("admin", "updateUpdateLogSettings", "maxfilesize")
4033        );
4034        store();
4035        adminSync.broadcast(attributes, config);
4036    }*/
4037    
4038
4039
4040    private void doUpdateMonitor() throws PageException  {
4041        admin.updateMonitor(
4042                        getString("admin", "updateMonitor", "class"),
4043                        getString("admin", "updateMonitor", "monitorType"),
4044                        getString("admin", "updateMonitor", "name"),
4045                        getBool("admin", "updateMonitor", "logEnabled")
4046        );
4047        store();
4048        adminSync.broadcast(attributes, config);
4049    }
4050    
4051        private void doUpdateExecutionLog() throws PageException {
4052                admin.updateExecutionLog(
4053                        getString("admin", "updateExecutionLog", "class"),
4054                        getStruct("admin", "updateExecutionLog", "arguments"),
4055                        getBool("admin", "updateExecutionLog", "enabled")
4056        );
4057        store();
4058        adminSync.broadcast(attributes, config);
4059        }
4060    
4061
4062    private void doRemoveMonitor() throws PageException  {
4063        admin.removeMonitor(
4064                        getString("admin", "updateMonitor", "name")
4065        );
4066        store();
4067        adminSync.broadcast(attributes, config);
4068    }
4069    
4070    private void doUpdateRHExtension() throws PageException {
4071        String str = getString("admin", "UpdateExtensions", "source");
4072        Resource src = ResourceUtil.toResourceExisting(config, str);
4073        Resource trg=DeployHandler.getDeployDirectory(config).getRealResource(src.getName());
4074        
4075        try {
4076                        ResourceUtil.copy(src, trg);
4077                }
4078                catch (IOException e) {
4079                        throw Caster.toPageException(e);
4080                }
4081        //config.get
4082        DeployHandler.deploy(config);
4083        }
4084    
4085    private void doUpdateExtension() throws PageException {
4086        
4087                
4088                        admin.updateExtension(pageContext,new ExtensionImpl(
4089                                                getStruct("config", null),
4090                                        getString("admin", "UpdateExtensions", "id"),
4091                                        getString("admin", "UpdateExtensions","provider"),
4092                                        getString("admin", "UpdateExtensions","version"),
4093                                        
4094                                        getString("admin", "UpdateExtensions","name"),
4095                                        getString("label",""),
4096                                        getString("description",""),
4097                                        getString("category",""),
4098                                        getString("image",""),
4099                                        getString("author",""),
4100                                        getString("codename",""),
4101                                        getString("video",""),
4102                                        getString("support",""),
4103                                        getString("documentation",""),
4104                                        getString("forum",""),
4105                                        getString("mailinglist",""),
4106                                        getString("network",""),
4107                                        getDateTime("created",null),
4108                                        getString("admin", "UpdateExtensions","_type")
4109                                ));
4110                
4111        
4112
4113        
4114        store();
4115        //adminSync.broadcast(attributes, config);
4116    }
4117    
4118    private void doUpdateExtensionProvider() throws PageException {
4119        admin.updateExtensionProvider(
4120                        getString("admin", "UpdateExtensionProvider","url")
4121                        );
4122        store();
4123    }
4124    
4125    private void doUpdateExtensionInfo() throws PageException {
4126        admin.updateExtensionInfo(
4127                        getBool("admin", "UpdateExtensionInfo","enabled")
4128                        );
4129        store();
4130    }
4131
4132    private void doVerifyExtensionProvider() throws PageException {
4133        admin.verifyExtensionProvider(getString("admin", "VerifyExtensionProvider","url"));
4134                
4135    }
4136    private void doResetId() throws PageException {
4137        admin.resetId();
4138        store();
4139                
4140    }
4141    
4142    private void doRemoveExtensionProvider() throws PageException {
4143        admin.removeExtensionProvider(getString("admin", "RemoveExtensionProvider","url"));
4144        store();
4145    }
4146
4147    /**
4148     * @throws PageException
4149     * 
4150     */
4151    private void doGetApplicationSetting() throws PageException {
4152        
4153        Struct sct=new StructImpl();
4154        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4155        sct.set("scriptProtect",AppListenerUtil.translateScriptProtect(config.getScriptProtect()));
4156        
4157        // request timeout
4158        sct.set("requestTimeout",config.getRequestTimeout());
4159        sct.set("requestTimeout_day",Caster.toInteger(config.getRequestTimeout().getDay()));
4160        sct.set("requestTimeout_hour",Caster.toInteger(config.getRequestTimeout().getHour()));
4161        sct.set("requestTimeout_minute",Caster.toInteger(config.getRequestTimeout().getMinute()));
4162        sct.set("requestTimeout_second",Caster.toInteger(config.getRequestTimeout().getSecond()));
4163        
4164        // AllowURLRequestTimeout
4165        sct.set("AllowURLRequestTimeout",Caster.toBoolean(config.isAllowURLRequestTimeout()));
4166        
4167        
4168    }
4169    
4170    private void doGetQueueSetting() throws PageException {
4171        Struct sct=new StructImpl();
4172        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4173
4174        sct.set("max",Caster.toInteger(config.getQueueMax()));
4175        sct.set("timeout",Caster.toInteger(config.getQueueTimeout()));
4176        sct.set("enable",Caster.toBoolean(config.getQueueEnable()));
4177        
4178    }
4179    
4180    private void doGetOutputSetting() throws PageException {
4181        
4182        Struct sct=new StructImpl();
4183        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4184        sct.set("suppressContent",Caster.toBoolean(config.isSuppressContent()));
4185        sct.set("contentLength",Caster.toBoolean(config.contentLength()));
4186        //sct.set("showVersion",Caster.toBoolean(config.isShowVersion()));
4187        sct.set("allowCompression",Caster.toBoolean(config.allowCompression()));
4188        int wt = config.getCFMLWriterType();
4189        String cfmlWriter="regular";
4190        if(wt==ConfigImpl.CFML_WRITER_WS) cfmlWriter="white-space";
4191        else if(wt==ConfigImpl.CFML_WRITER_WS_PREF) cfmlWriter="white-space-pref";
4192        
4193        sct.set("cfmlWriter",cfmlWriter);
4194        sct.set("bufferOutput",Caster.toBoolean(config.getBufferOutput()));
4195        
4196    }
4197    
4198    /**
4199     * @throws PageException
4200     * 
4201     */
4202    private void doGetScope() throws PageException {
4203        String sessionType=config.getSessionType()==Config.SESSION_TYPE_J2EE?"j2ee":"cfml";
4204        String localMode=AppListenerUtil.toLocalMode(config.getLocalMode(),"classic");
4205        
4206        
4207        Struct sct=new StructImpl();
4208        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4209        sct.set("allowImplicidQueryCall",Caster.toBoolean(config.allowImplicidQueryCall()));
4210        sct.set("mergeFormAndUrl",Caster.toBoolean(config.mergeFormAndURL()));
4211        
4212        sct.set("sessiontype",sessionType);
4213        sct.set("localmode",localMode);
4214        sct.set("sessionManagement",Caster.toBoolean(config.isSessionManagement()));
4215        sct.set("clientManagement",Caster.toBoolean(config.isClientManagement()));
4216        sct.set("domainCookies",Caster.toBoolean(config.isDomainCookies()));
4217        sct.set("clientCookies",Caster.toBoolean(config.isClientCookies()));
4218        sct.set("clientStorage",config.getClientStorage());
4219        sct.set("sessionStorage",config.getSessionStorage());
4220        sct.set("cgiReadonly", config.getCGIScopeReadonly());
4221        
4222        TimeSpan ts=config.getSessionTimeout();
4223        sct.set("sessionTimeout",ts);
4224        sct.set("sessionTimeout_day",Caster.toInteger(ts.getDay()));
4225        sct.set("sessionTimeout_hour",Caster.toInteger(ts.getHour()));
4226        sct.set("sessionTimeout_minute",Caster.toInteger(ts.getMinute()));
4227        sct.set("sessionTimeout_second",Caster.toInteger(ts.getSecond()));
4228
4229        ts=config.getApplicationTimeout();
4230        sct.set("applicationTimeout",ts);
4231        sct.set("applicationTimeout_day",Caster.toInteger(ts.getDay()));
4232        sct.set("applicationTimeout_hour",Caster.toInteger(ts.getHour()));
4233        sct.set("applicationTimeout_minute",Caster.toInteger(ts.getMinute()));
4234        sct.set("applicationTimeout_second",Caster.toInteger(ts.getSecond()));
4235
4236        ts=config.getClientTimeout();
4237        sct.set("clientTimeout",ts);
4238        sct.set("clientTimeout_day",Caster.toInteger(ts.getDay()));
4239        sct.set("clientTimeout_hour",Caster.toInteger(ts.getHour()));
4240        sct.set("clientTimeout_minute",Caster.toInteger(ts.getMinute()));
4241        sct.set("clientTimeout_second",Caster.toInteger(ts.getSecond()));
4242        
4243        
4244        // scope cascading type
4245        if(config.getScopeCascadingType()==Config.SCOPE_STRICT) sct.set("scopeCascadingType","strict");
4246        else if(config.getScopeCascadingType()==Config.SCOPE_SMALL) sct.set("scopeCascadingType","small");
4247        else if(config.getScopeCascadingType()==Config.SCOPE_STANDARD) sct.set("scopeCascadingType","standard");
4248    }
4249
4250    /**
4251     * @throws PageException
4252     * 
4253     */
4254    private void doUpdateComponent() throws PageException {
4255
4256        admin.updateComponentDeepSearch(getBoolObject("admin", action, "deepSearch"));
4257        admin.updateBaseComponent(getString("admin",action,"baseComponentTemplate"));
4258        admin.updateComponentDumpTemplate(getString("admin",action,"componentDumpTemplate"));
4259        admin.updateComponentDataMemberDefaultAccess(getString("admin",action,"componentDataMemberDefaultAccess"));
4260        admin.updateTriggerDataMember(getBoolObject("admin",action,"triggerDataMember"));
4261        admin.updateComponentUseShadow(getBoolObject("admin",action,"useShadow"));
4262        admin.updateComponentDefaultImport(getString("admin",action,"componentDefaultImport"));
4263        admin.updateComponentLocalSearch(getBoolObject("admin",action,"componentLocalSearch"));
4264        admin.updateComponentPathCache(getBoolObject("admin",action,"componentPathCache"));
4265        store();
4266        adminSync.broadcast(attributes, config);
4267    }
4268
4269    /**
4270     * @throws PageException 
4271     * @throws PageException
4272     * 
4273     */
4274    private void doGetComponent() throws PageException {
4275        Struct sct=new StructImpl();
4276        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4277        // Base Component
4278        try {
4279            PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(config.getBaseComponentTemplate());
4280            if(ps!=null) sct.set("baseComponentTemplate",ps.getDisplayPath());
4281            else sct.set("baseComponentTemplate","");
4282        } catch (PageException e) {
4283            sct.set("baseComponentTemplate","");
4284        }
4285        sct.set("strBaseComponentTemplate",config.getBaseComponentTemplate());
4286        
4287        // dump template
4288        try {
4289            PageSource ps = ((PageContextImpl)pageContext).getPageSourceExisting(config.getComponentDumpTemplate());
4290            if(ps!=null) sct.set("componentDumpTemplate",ps.getDisplayPath());
4291            else sct.set("componentDumpTemplate","");
4292        } catch (PageException e) {
4293            sct.set("componentDumpTemplate","");
4294        }
4295        sct.set("strComponentDumpTemplate",config.getComponentDumpTemplate());
4296
4297        sct.set("deepSearch",Caster.toBoolean(config.doComponentDeepSearch()));
4298        sct.set("componentDataMemberDefaultAccess",ComponentUtil.toStringAccess(config.getComponentDataMemberDefaultAccess()));
4299        sct.set("triggerDataMember",Caster.toBoolean(config.getTriggerComponentDataMember()));
4300        sct.set("useShadow",Caster.toBoolean(config.useComponentShadow()));
4301        sct.set("ComponentDefaultImport",config.getComponentDefaultImport());
4302        sct.set("componentLocalSearch",config.getComponentLocalSearch());
4303        sct.set("componentPathCache",config.useComponentPathCache());
4304        
4305    }
4306
4307    /**
4308     * @throws PageException
4309     * 
4310     */
4311    private void doUpdateRegional() throws PageException {
4312        Boolean useTimeServer=getBool("usetimeserver",null);
4313        
4314        try{
4315                admin.updateLocale(getString("admin",action,"locale"));
4316                admin.updateTimeZone(getString("admin",action,"timezone"));
4317                admin.updateTimeServer(getString("admin",action,"timeserver"),useTimeServer);
4318        }
4319        finally {
4320                 store();
4321        }
4322        adminSync.broadcast(attributes, config);
4323    }
4324    private void doUpdateMonitorEnabled() throws PageException {
4325        
4326        try{
4327                admin.updateMonitorEnabled(getBool("admin","UpdateMonitorEnabled","monitorEnabled"));
4328        }
4329        finally {
4330                 store();
4331        }
4332        adminSync.broadcast(attributes, config);
4333    }
4334    
4335    
4336
4337    private void doUpdateTLD() throws PageException {
4338        try {
4339                String jar = getString("jar",null);
4340                if(!StringUtil.isEmpty(jar,true)){
4341                        Resource resJar = ResourceUtil.toResourceExisting(pageContext, jar);
4342                        admin.updateJar(resJar);
4343                }
4344                Resource resTld = ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"tld"));
4345                admin.updateTLD(resTld);
4346                } 
4347        catch (Exception e) {
4348                        throw Caster.toPageException(e);
4349                }
4350        store();
4351    }
4352    private void doUpdateFLD() throws PageException {
4353        try {
4354                String jar = getString("jar",null);
4355                if(!StringUtil.isEmpty(jar,true)){
4356                        Resource resJar = ResourceUtil.toResourceExisting(pageContext, jar);
4357                        admin.updateJar(resJar);
4358                }
4359                Resource resFld = ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"fld"));
4360                admin.updateFLD(resFld);
4361                } 
4362        catch (Exception e) {
4363                        throw Caster.toPageException(e);
4364                }
4365        store();
4366    }
4367    
4368    private void doUpdateJar() throws PageException {
4369        try {
4370                Resource resJar = ResourceUtil.toResourceExisting(pageContext, getString("admin",action,"jar"));
4371                admin.updateJar(resJar);
4372                } 
4373        catch (Exception e) {
4374                        throw Caster.toPageException(e);
4375                }
4376        store();
4377    }
4378    
4379
4380        
4381
4382
4383        private void doUpdateLoginSettings() throws PageException {
4384                boolean rememberMe = getBool("admin", "UpdateLoginSettings", "rememberme");
4385                boolean captcha = getBool("admin", "UpdateLoginSettings", "captcha");
4386                int delay = getInt("admin", "UpdateLoginSettings", "delay");
4387                admin.updateLoginSettings(captcha,rememberMe,delay);
4388                store();
4389        }
4390
4391        private void doUpdateLogSettings() throws PageException {
4392                String str = getString("admin", "UpdateLogSettings", "level", true);
4393                Level l = Log4jUtil.toLevel(str,null);
4394                if(l==null)throw new ApplicationException("invalid log level name ["+str+"], valid log level names are [INFO,DEBUG,WARN,ERROR,FATAL,TRACE]");
4395                
4396                admin.updateLogSettings(
4397                                getString("admin", "UpdateLogSettings", "name", true)
4398                                ,l
4399                                ,getString("admin", "UpdateLogSettings", "appenderClass", true)
4400                                ,Caster.toStruct(getObject("admin", "UpdateLogSettings", "appenderArgs"))
4401                                ,getString("admin", "UpdateLogSettings", "layoutClass", true)
4402                                ,Caster.toStruct(getObject("admin", "UpdateLogSettings", "layoutArgs"))
4403                );
4404                store();
4405        }
4406    
4407    
4408    
4409    private void doUpdateSSLCertificate() throws PageException {
4410        String host=getString("admin", "UpdateSSLCertificateInstall", "host");
4411        int port = getInt("port", 443);
4412        updateSSLCertificate(config, host, port);
4413    }
4414    
4415    public static void updateSSLCertificate(Config config,String host, int port) throws PageException {
4416        Resource cacerts=config.getSecurityDirectory();
4417         
4418        try {
4419                        CertificateInstaller installer = new CertificateInstaller(cacerts,host,port);
4420                        installer.installAll();
4421                } catch (Exception e) {
4422                        throw Caster.toPageException(e);
4423                }
4424    }
4425    
4426    private void doGetSSLCertificate() throws PageException {
4427        String host=getString("admin", "GetSSLCertificate", "host");
4428        int port = getInt("port", 443);
4429        pageContext.setVariable(getString("admin",action,"returnVariable"),getSSLCertificate(config,host,port));
4430    }
4431    
4432    public static Query getSSLCertificate(Config config,String host, int port) throws PageException {
4433        Resource cacerts=config.getSecurityDirectory();
4434        CertificateInstaller installer;
4435                try {
4436                        installer = new CertificateInstaller(cacerts,host,port);
4437                } catch (Exception e) {
4438                        throw Caster.toPageException(e);
4439                }
4440        X509Certificate[] certs = installer.getCertificates();
4441        X509Certificate cert;
4442        
4443        Query qry=new QueryImpl(new String[]{"subject","issuer"},certs.length,"certificates");
4444        for(int i=0;i<certs.length;i++){
4445                cert=certs[i];
4446                qry.setAtEL("subject",i+1, cert.getSubjectDN().getName());
4447                qry.setAtEL("issuer",i+1, cert.getIssuerDN().getName());
4448        }
4449        return qry;
4450    }
4451
4452    private void doRemoveJar() throws PageException {
4453        try {
4454                String name = getString("jar",null);
4455                if(StringUtil.isEmpty(name))name=getString("admin",action,"name");
4456                
4457                admin.removeJar(name);
4458                } 
4459        catch (Exception e) {
4460                        throw Caster.toPageException(e);
4461                }
4462        store();
4463    }
4464    
4465    private void doRemoveTLD() throws PageException {
4466        try {
4467                String name = getString("tld",null);
4468                if(StringUtil.isEmpty(name))name=getString("admin",action,"name");
4469                admin.removeTLD(name);
4470                } 
4471        catch (Exception e) {
4472                        throw Caster.toPageException(e);
4473                }
4474        store();
4475    }
4476    
4477
4478    
4479    private void doRemoveFLD() throws PageException {
4480        try {
4481                String name = getString("fld",null);
4482                if(StringUtil.isEmpty(name))name=getString("admin",action,"name");
4483                admin.removeFLD(name);
4484                } 
4485        catch (Exception e) {
4486                        throw Caster.toPageException(e);
4487                }
4488        store();
4489    }
4490    
4491    private void doUpdateRemoteClient() throws PageException {
4492        
4493        
4494        
4495        admin.updateRemoteClient(
4496                        getString("admin",action,"label"),
4497                        getString("admin",action,"url"),
4498                        getString("admin",action,"remotetype"),
4499                        getString("admin",action,"securityKey"),
4500                        getString("admin",action,"usage"),
4501                        getString("admin",action,"adminPassword"),
4502                        getString("ServerUsername",""),
4503                        getString("ServerPassword",""),
4504                        getString("proxyServer",""),
4505                        getString("proxyUsername",""),
4506                        getString("proxyPassword",""),
4507                        getString("proxyPort","")
4508                        
4509        );
4510        
4511        store();
4512    }
4513    private void doUpdateRemoteClientUsage() throws PageException {
4514        admin.updateRemoteClientUsage(
4515                   getString("admin",action,"code"),
4516                   getString("admin",action,"displayname")
4517                        
4518         );
4519         store();
4520     }
4521    private void doRemoveRemoteClientUsage() throws PageException {
4522        admin.removeRemoteClientUsage(
4523                   getString("admin",action,"code")
4524                        
4525         );
4526         store();
4527     }
4528
4529        private String getCallerId() throws IOException {
4530                if(type==TYPE_WEB) {
4531                        return config.getId();
4532                }
4533                if(config instanceof ConfigWebImpl){
4534                        ConfigWebImpl cwi = (ConfigWebImpl)config;
4535                        return cwi.getServerId();
4536                }
4537                if(config instanceof ConfigServer){
4538                        return config.getId();
4539                }
4540                throw new IOException("can not create id");
4541        }
4542
4543        private void doUpdateApplicationListener() throws PageException {
4544        admin.updateApplicationListener(
4545                        getString("admin",action,"listenerType"),
4546                        getString("admin",action,"listenerMode")
4547        );
4548       
4549        store();
4550        adminSync.broadcast(attributes, config);
4551    }
4552    
4553    
4554    
4555    private void doUpdateProxy() throws PageException {
4556        admin.updateProxy(
4557                        getBool("admin",action,"proxyenabled"), 
4558                        getString("admin",action,"proxyserver"), 
4559                        getInt("admin",action,"proxyport"), 
4560                        getString("admin",action,"proxyusername"), 
4561                        getString("admin",action,"proxypassword")
4562                );
4563        store();
4564    }
4565    
4566
4567        private void doUpdateCharset() throws PageException {
4568        admin.updateResourceCharset(getString("admin",action,"resourceCharset"));
4569        admin.updateTemplateCharset(getString("admin",action,"templateCharset"));
4570        admin.updateWebCharset(getString("admin",action,"webCharset"));
4571                store();
4572        adminSync.broadcast(attributes, config);
4573        }
4574
4575    /**
4576     * @throws PageException
4577     * 
4578     */
4579    private void doSecurityManager() throws PageException {
4580        String rtnVar = getString("admin",action,"returnVariable");
4581        String secType = getString("admin",action,"sectype");
4582        String secValue = getString("secvalue",null);
4583        boolean isServer=config instanceof ConfigServer;
4584        
4585        if(secValue==null) {
4586                if(isServer)    {
4587                        pageContext.setVariable(
4588                        rtnVar,
4589                        SecurityManagerImpl.toStringAccessValue(SecurityManager.VALUE_YES)
4590                );
4591                }
4592                else {
4593                        pageContext.setVariable(
4594                        rtnVar,
4595                        SecurityManagerImpl.toStringAccessValue(config.getSecurityManager().getAccess(secType))
4596                );
4597                }
4598                return;
4599        }
4600        pageContext.setVariable(
4601                rtnVar,
4602                Caster.toBoolean(
4603                        isServer ||
4604                        config.getSecurityManager().getAccess(secType) == SecurityManagerImpl.toShortAccessValue(secValue)
4605                )
4606        );
4607    }
4608
4609    /**
4610     * @throws PageException
4611     * 
4612     */
4613    private void doGetTimeZones() throws PageException {
4614        
4615        
4616        
4617        String strLocale=getString("locale","english (united kingdom)");
4618        Locale locale = LocaleFactory.getLocale(strLocale);
4619        
4620        String[] timeZones = TimeZone.getAvailableIDs();
4621        lucee.runtime.type.Query qry=new QueryImpl(new String[]{"id","display"},new String[]{"varchar","varchar"},timeZones.length,"timezones");
4622        Arrays.sort(timeZones);
4623        TimeZone timeZone;
4624        for(int i=0;i<timeZones.length;i++) {
4625            timeZone=TimeZone.getTimeZone(timeZones[i]);
4626            qry.setAt("id",i+1,timeZones[i]);
4627            qry.setAt("display",i+1,timeZone.getDisplayName(locale));
4628            
4629        }
4630        pageContext.setVariable(getString("admin",action,"returnVariable"),qry);
4631    }
4632
4633    /**
4634     * @throws PageException
4635     * 
4636     */
4637    private void doGetLocales() throws PageException {
4638        Struct sct=new StructImpl(StructImpl.TYPE_LINKED);
4639        //Array arr=new ArrayImpl();
4640        String strLocale=getString("locale","english (united kingdom)");
4641        Locale locale = LocaleFactory.getLocale(strLocale);
4642        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4643        Map locales = LocaleFactory.getLocales();
4644        Iterator it = locales.keySet().iterator();
4645       
4646        String key;
4647        Locale l;
4648        while(it.hasNext()) {
4649            key=(String)it.next();
4650            l=(Locale) locales.get(key);
4651            sct.setEL(l.toString(),l.getDisplayName(locale));
4652            //arr.append(locale.getDisplayName());
4653        }
4654        //arr.sort("textnocase","asc");
4655    }
4656    
4657    
4658    private void doGetApplicationListener() throws PageException  {
4659        Struct sct=new StructImpl();
4660        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4661        ApplicationListener appListener = config.getApplicationListener();
4662        sct.set("type",AppListenerUtil.toStringType(appListener));
4663        sct.set("mode",AppListenerUtil.toStringMode(appListener.getMode()));
4664                // replaced with encoding outputsct.set("defaultencoding", config.get DefaultEncoding());
4665    }
4666    /**
4667     * @throws PageException
4668     * 
4669     */
4670    private void doGetRegional() throws PageException  {
4671        Struct sct=new StructImpl();
4672        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4673        sct.set("locale",Caster.toString(config.getLocale()));
4674        sct.set("timezone",toStringTimeZone(config.getTimeZone()));
4675        sct.set("timeserver",config.getTimeServer());
4676        sct.set("usetimeserver",config.getUseTimeServer());
4677                // replaced with encoding outputsct.set("defaultencoding", config.get DefaultEncoding());
4678    }
4679    private void doIsMonitorEnabled() throws PageException  {
4680        if(config instanceof ConfigServerImpl) {
4681                ConfigServerImpl cs=(ConfigServerImpl) config;
4682                pageContext.setVariable(getString("admin",action,"returnVariable"),Caster.toBoolean(cs.isMonitoringEnabled()));
4683        }
4684    }
4685    
4686
4687        private void doSurveillance() throws PageException {
4688                // Server
4689                if(config instanceof ConfigServer) {
4690                        ConfigServer cs=(ConfigServer) config;
4691                        ConfigWeb[] webs = cs.getConfigWebs();
4692                        Struct sct=new StructImpl();
4693                        for(int i=0;i<webs.length;i++){
4694                                ConfigWebImpl cw=(ConfigWebImpl) webs[i];
4695                                try{
4696                                sct.setEL(cw.getId(), ((CFMLFactoryImpl)cw.getFactory()).getInfo());
4697                                }
4698                                catch(Throwable t){
4699                                        ExceptionUtil.rethrowIfNecessary(t);
4700                                }
4701                        }
4702                        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4703                        
4704                }
4705                // Web
4706                else {
4707                        CFMLFactoryImpl factory = (CFMLFactoryImpl) config.getFactory();
4708                        pageContext.setVariable(getString("admin",action,"returnVariable"),
4709                                        factory.getInfo());
4710                }
4711        }
4712        
4713        private void doStopThread() throws PageException {
4714                String contextId=getString("admin", "stopThread", "contextId");
4715                String threadId=getString("admin", "stopThread", "threadId");
4716                String stopType=getString("stopType","exception");
4717                
4718                if(!(config instanceof ConfigServer)) 
4719                        throw new ApplicationException("invalid context for this action");
4720                
4721                
4722                ConfigServer cs=(ConfigServer) config;
4723                ConfigWeb[] webs = cs.getConfigWebs();
4724                boolean has=false;
4725                for(int i=0;i<webs.length;i++){
4726                        ConfigWebImpl cw=(ConfigWebImpl) webs[i];
4727                        if(!cw.getId().equals(contextId)) continue;
4728                         ((CFMLFactoryImpl)cw.getFactory()).stopThread(threadId,stopType);
4729                         has=true;
4730                         break;
4731                }
4732                if(!has) {
4733                        for(int i=0;i<webs.length;i++){
4734                                ConfigWebImpl cw=(ConfigWebImpl) webs[i];
4735                                if(!cw.getLabel().equals(contextId)) continue;
4736                                 ((CFMLFactoryImpl)cw.getFactory()).stopThread(threadId,stopType);
4737                                 break;
4738                        }
4739                }
4740        }
4741        
4742        private void doHeapDump() throws PageException {
4743                String strDestination = getString( "admin", action, "destination" );
4744                boolean live = getBoolV( "live" ,true);
4745        Resource destination = ResourceUtil.toResourceNotExisting(pageContext, strDestination);
4746        try {
4747                        HeapDumper.dumpTo(destination, live);
4748                } catch (IOException e) {
4749                        throw Caster.toPageException(e);
4750                }
4751        }
4752    
4753    private void doGetProxy() throws PageException  {
4754        Struct sct=new StructImpl();
4755        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4756        ProxyData pd = config.getProxyData();
4757        String port=pd==null || pd.getPort()<=0?"":Caster.toString(pd.getPort());
4758        
4759        //sct.set("enabled",Caster.toBoolean(config.isProxyEnable()));
4760        sct.set("port",port);
4761        sct.set("server",pd==null?"":emptyIfNull(pd.getServer()));
4762        sct.set("username",pd==null?"":emptyIfNull(pd.getUsername()));
4763        sct.set("password",pd==null?"":emptyIfNull(pd.getPassword()));
4764    }
4765    
4766
4767
4768        private void doGetLoginSettings() throws ApplicationException, PageException {
4769                Struct sct=new StructImpl();
4770                ConfigImpl c = (ConfigImpl) ThreadLocalPageContext.getConfig(config);
4771        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4772        sct.set("captcha",Caster.toBoolean(c.getLoginCaptcha()));
4773        sct.set("delay",Caster.toDouble(c.getLoginDelay()));
4774        sct.set("rememberme",Caster.toBoolean(c.getRememberMe()));
4775        
4776        }
4777
4778
4779        private void doGetCharset() throws PageException {
4780                Struct sct=new StructImpl();
4781        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4782        sct.set("resourceCharset",config.getResourceCharset());
4783        sct.set("templateCharset",config.getTemplateCharset());
4784        sct.set("webCharset",((PageContextImpl)pageContext).getWebCharset().name());
4785        sct.set("jreCharset",SystemUtil.getCharset().name());
4786        }
4787
4788    /**
4789     * @throws PageException
4790     * 
4791     */
4792    private void doGetUpdate() throws PageException  {
4793        Struct sct=new StructImpl();
4794        pageContext.setVariable(getString("admin",action,"returnVariable"),sct);
4795        URL location = config.getUpdateLocation();
4796        if(location==null || location.toExternalForm().equals("http://www.lucee.org")) {
4797            try {
4798                location=new URL("http://stable.lucee.org");
4799            } 
4800            catch (MalformedURLException e) {}
4801        }
4802        
4803        
4804        String type=config.getUpdateType();
4805        if(StringUtil.isEmpty(type))type="manual";
4806        
4807        sct.set("location",location.toExternalForm());
4808        sct.set("type",type);
4809        
4810    }
4811    
4812
4813    /**
4814     * @throws PageException
4815     * 
4816     */
4817    private synchronized void store() throws PageException {
4818        try {
4819            admin.store();
4820        } catch (Exception e) {
4821            throw Caster.toPageException(e);
4822        } 
4823    }
4824    private String getString(String tagName, String actionName, String attributeName) throws ApplicationException {
4825        return getString(tagName, actionName, attributeName,true);
4826    }
4827    
4828    private String getString(String tagName, String actionName, String attributeName,boolean trim) throws ApplicationException {
4829        String value=getString(attributeName,null);
4830        if(value==null) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4831        return trim?value.trim():value;
4832    }
4833
4834    private double getDouble(String tagName, String actionName, String attributeName) throws ApplicationException {
4835        double value=getDouble(attributeName,Double.NaN);
4836        if(!Decision.isValid(value)) throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4837        return value;
4838    }
4839
4840    private String getString(String attributeName, String defaultValue)  {
4841        Object value=attributes.get(attributeName,null);
4842        if(value==null)return defaultValue;
4843        return Caster.toString(value,null);
4844    }
4845
4846    private DateTime getDateTime(String attributeName, DateTime defaultValue)  {
4847        Object value=attributes.get(attributeName,null);
4848        if(value==null)return defaultValue;
4849        return DateCaster.toDateAdvanced(value, null, defaultValue);
4850    }
4851    
4852    private Object getObject(String attributeName, Object defaultValue)  {
4853        return attributes.get(attributeName,defaultValue);
4854    }
4855
4856    private boolean getBool(String tagName, String actionName, String attributeName) throws PageException {
4857        Object value=attributes.get(attributeName,null);
4858        if(value==null)
4859            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4860        return Caster.toBooleanValue(value);
4861    }
4862    private Boolean getBoolObject(String tagName, String actionName, String attributeName) throws PageException {
4863        Object value=attributes.get(attributeName,null);
4864        if(value==null)
4865            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4866        if(StringUtil.isEmpty(value)) return null;
4867        return Caster.toBoolean(value);
4868    }
4869    
4870    private Integer getInteger(String tagName, String actionName, String attributeName) throws PageException {
4871        Object value=attributes.get(attributeName,null);
4872        if(value==null)
4873            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4874        if(StringUtil.isEmpty(value)) return null;
4875        return Caster.toIntValue(value);
4876    }
4877    
4878    private Object getObject(String tagName, String actionName, String attributeName) throws PageException {
4879        Object value=attributes.get(attributeName,null);
4880        if(value==null)
4881            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4882        return value;
4883    }
4884
4885    private boolean getBoolV(String attributeName, boolean defaultValue) {
4886        Object value=attributes.get(attributeName,null);
4887        if(value==null) return defaultValue;
4888        return Caster.toBooleanValue(value,defaultValue);
4889    }
4890
4891    private Boolean getBool(String attributeName, Boolean defaultValue) {
4892        Object value=attributes.get(attributeName,null);
4893        if(value==null) return defaultValue;
4894        return Caster.toBoolean(value,defaultValue);
4895    }
4896    
4897    private Struct getStruct(String attributeName, Struct defaultValue) {
4898        Object value=attributes.get(attributeName,null);
4899        if(value==null) return defaultValue;
4900        try {
4901            return Caster.toStruct(value);
4902        } catch (PageException e) {
4903            return defaultValue;
4904        }
4905    }
4906   
4907    private Struct getStruct(String tagName, String actionName, String attributeName) throws PageException {
4908        Object value=attributes.get(attributeName,null);
4909        if(value==null)
4910            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4911        return Caster.toStruct(value);
4912    }
4913    
4914    private int getInt(String tagName, String actionName, String attributeName) throws PageException {
4915        Object value=attributes.get(attributeName,null);
4916        if(value==null)
4917            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4918        return (int)Caster.toDoubleValue(value);
4919    }
4920
4921    private int getInt(String attributeName, int defaultValue) {
4922        Object value=attributes.get(attributeName,null);
4923        if(value==null) return defaultValue;
4924        return Caster.toIntValue(value,defaultValue);
4925    }
4926    private long getLong(String attributeName, long defaultValue) {
4927        Object value=attributes.get(attributeName,null);
4928        if(value==null) return defaultValue;
4929        return Caster.toLongValue(value,defaultValue);
4930    }
4931    
4932    private double getDouble(String attributeName, double defaultValue) {
4933        Object value=attributes.get(attributeName,null);
4934        if(value==null) return defaultValue;
4935        return Caster.toDoubleValue(value,true,defaultValue);
4936    }
4937    
4938    private TimeSpan getTimespan(String tagName, String actionName, String attributeName) throws PageException {
4939        Object value=attributes.get(attributeName,null);
4940        if(value==null)
4941            throw new ApplicationException("Attribute ["+attributeName+"] for tag ["+tagName+"] is required if attribute action has the value ["+actionName+"]");
4942        if(StringUtil.isEmpty(value))return null;
4943        return Caster.toTimespan(value);
4944    }
4945
4946        private Object emptyIfNull(String str) {
4947                if(str==null) return "";
4948                return str;
4949        }
4950
4951    private void throwNoAccessWhenWeb() throws ApplicationException {
4952        if(type==TYPE_WEB)throw new ApplicationException(
4953                "you have no access for action [web."+action+"]");
4954    }
4955
4956    private void throwNoAccessWhenServer() throws ApplicationException {
4957        if(type==TYPE_SERVER) {
4958            throw new ApplicationException(
4959                    "you have no access for action [server."+action+"]");
4960        }
4961    }
4962}
4963
4964
4965
4966
4967
4968final class PluginFilter implements ResourceFilter {
4969        @Override
4970        public boolean accept(Resource res) {
4971        return doAccept(res);
4972    }
4973        
4974        public static boolean doAccept(Resource res) {
4975                return res.isDirectory() && res.getRealResource("/Action.cfc").isFile() && res.getRealResource("/language.xml").isFile();
4976    }
4977
4978}