Search in sources :

Example 6 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class Admin method doGetDatasource.

/**
 * @throws PageException
 */
private void doGetDatasource() throws PageException {
    String name = getString("admin", action, "name");
    Map ds = config.getDataSourcesAsMap();
    Iterator it = ds.keySet().iterator();
    while (it.hasNext()) {
        String key = (String) it.next();
        if (key.equalsIgnoreCase(name)) {
            DataSource d = (DataSource) ds.get(key);
            Struct sct = new StructImpl();
            ClassDefinition cd = d.getClassDefinition();
            sct.setEL(KeyConstants._name, key);
            sct.setEL(KeyConstants._host, d.getHost());
            sct.setEL("classname", cd.getClassName());
            sct.setEL("class", cd.getClassName());
            sct.setEL("bundleName", cd.getName());
            sct.setEL("bundleVersion", cd.getVersionAsString());
            sct.setEL("dsn", d.getDsnOriginal());
            sct.setEL("database", d.getDatabase());
            sct.setEL("port", d.getPort() < 1 ? "" : Caster.toString(d.getPort()));
            sct.setEL("dsnTranslated", d.getDsnTranslated());
            sct.setEL("timezone", toStringTimeZone(d.getTimeZone()));
            sct.setEL("password", d.getPassword());
            sct.setEL("passwordEncrypted", ConfigWebUtil.encrypt(d.getPassword()));
            sct.setEL("username", d.getUsername());
            sct.setEL("readonly", Caster.toBoolean(d.isReadOnly()));
            sct.setEL("select", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_SELECT)));
            sct.setEL("delete", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DELETE)));
            sct.setEL("update", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_UPDATE)));
            sct.setEL("insert", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
            sct.setEL("create", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_CREATE)));
            sct.setEL("insert", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_INSERT)));
            sct.setEL("drop", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_DROP)));
            sct.setEL("grant", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_GRANT)));
            sct.setEL("revoke", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_REVOKE)));
            sct.setEL("alter", Boolean.valueOf(d.hasAllow(DataSource.ALLOW_ALTER)));
            sct.setEL("connectionLimit", d.getConnectionLimit() < 1 ? "" : Caster.toString(d.getConnectionLimit()));
            sct.setEL("connectionTimeout", d.getConnectionTimeout() < 1 ? "" : Caster.toString(d.getConnectionTimeout()));
            sct.setEL("metaCacheTimeout", Caster.toDouble(d.getMetaCacheTimeout()));
            sct.setEL("custom", d.getCustoms());
            sct.setEL("blob", Boolean.valueOf(d.isBlob()));
            sct.setEL("clob", Boolean.valueOf(d.isClob()));
            sct.setEL("validate", Boolean.valueOf(d.validate()));
            sct.setEL("storage", Boolean.valueOf(d.isStorage()));
            if (d instanceof DataSourceImpl) {
                DataSourceImpl di = ((DataSourceImpl) d);
                sct.setEL("literalTimestampWithTSOffset", Boolean.valueOf(di.getLiteralTimestampWithTSOffset()));
                sct.setEL("alwaysSetTimeout", Boolean.valueOf(di.getAlwaysSetTimeout()));
                sct.setEL("dbdriver", Caster.toString(di.getDbDriver(), ""));
            }
            pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
            return;
        }
    }
    throw new ApplicationException("there is no datasource with name [" + name + "]");
}
Also used : StructImpl(lucee.runtime.type.StructImpl) ApplicationException(lucee.runtime.exp.ApplicationException) DataSourceImpl(lucee.runtime.db.DataSourceImpl) Iterator(java.util.Iterator) ClassDefinition(lucee.runtime.db.ClassDefinition) Map(java.util.Map) HashMap(java.util.HashMap) DataSource(lucee.runtime.db.DataSource) Struct(lucee.runtime.type.Struct)

Example 7 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class XMLConfigAdmin method validateStorage.

private String validateStorage(String storage) throws ApplicationException {
    storage = storage.trim().toLowerCase();
    // empty
    if (StringUtil.isEmpty(storage, true))
        return "";
    // standard storages
    if ("cookie".equals(storage) || "memory".equals(storage) || "file".equals(storage))
        return storage;
    // aliases
    if ("ram".equals(storage))
        return "memory";
    if ("registry".equals(storage))
        return "file";
    // datasource
    DataSource ds = config.getDataSource(storage, null);
    if (ds != null) {
        if (ds.isStorage())
            return storage;
        throw new ApplicationException("datasource [" + storage + "] is not enabled to be used as session/client storage");
    }
    // cache
    CacheConnection cc = CacheUtil.getCacheConnection(ThreadLocalPageContext.get(config), storage, null);
    if (cc != null) {
        if (cc.isStorage())
            return storage;
        throw new ApplicationException("cache [" + storage + "] is not enabled to be used as session/client storage");
    }
    String sdx = StringUtil.soundex(storage);
    // check if a datasource has a similar name
    DataSource[] sources = config.getDataSources();
    for (int i = 0; i < sources.length; i++) {
        if (StringUtil.soundex(sources[i].getName()).equals(sdx))
            throw new ApplicationException("no matching storage for [" + storage + "] found, did you mean [" + sources[i].getName() + "]");
    }
    // check if a cache has a similar name
    Iterator<String> it = config.getCacheConnections().keySet().iterator();
    String name;
    while (it.hasNext()) {
        name = it.next();
        if (StringUtil.soundex(name).equals(sdx))
            throw new ApplicationException("no matching storage for [" + storage + "] found, did you mean [" + name + "]");
    }
    throw new ApplicationException("no matching storage for [" + storage + "] found");
}
Also used : ApplicationException(lucee.runtime.exp.ApplicationException) CacheConnection(lucee.runtime.cache.CacheConnection) DataSource(lucee.runtime.db.DataSource)

Example 8 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class XMLConfigWebFactory method loadDataSources.

/**
 * loads datasource settings from XMl DOM
 *
 * @param configServer
 * @param config
 * @param doc
 * @throws BundleException
 * @throws ClassNotFoundException
 */
private static void loadDataSources(ConfigServerImpl configServer, ConfigImpl config, Document doc, Log log) {
    // load JDBC Driver defintion
    {
        Element jdbc = getChildByName(doc.getDocumentElement(), "jdbc");
        Element[] drivers = getChildren(jdbc, "driver");
        Map<String, JDBCDriver> map = new HashMap<String, JDBCDriver>();
        // first add the server drivers, so they can be overwritten
        if (configServer != null) {
            JDBCDriver[] sds = configServer.getJDBCDrivers();
            for (JDBCDriver sd : sds) {
                map.put(sd.cd.toString(), sd);
            }
        }
        ClassDefinition cd;
        String label;
        for (Element driver : drivers) {
            cd = getClassDefinition(driver, "", config.getIdentification());
            label = getAttr(driver, "label");
            // check if label exists
            if (StringUtil.isEmpty(label)) {
                log.error("Datasource", "missing label for jdbc driver [" + cd.getClassName() + "]");
                continue;
            }
            // check if it is a bundle
            if (!cd.isBundle()) {
                log.error("Datasource", "jdbc driver [" + label + "] does not describe a bundle");
                continue;
            }
            map.put(cd.toString(), new JDBCDriver(label, cd));
        }
        config.setJDBCDrivers(map.values().toArray(new JDBCDriver[map.size()]));
    }
    // When set to true, makes JDBC use a representation for DATE data that
    // is compatible with the Oracle8i database.
    System.setProperty("oracle.jdbc.V8Compatible", "true");
    boolean hasCS = configServer != null;
    Map<String, DataSource> datasources = new HashMap<String, DataSource>();
    // Copy Parent datasources as readOnly
    if (hasCS) {
        Map<String, DataSource> ds = configServer.getDataSourcesAsMap();
        Iterator<Entry<String, DataSource>> it = ds.entrySet().iterator();
        Entry<String, DataSource> entry;
        while (it.hasNext()) {
            entry = it.next();
            if (!entry.getKey().equals(QOQ_DATASOURCE_NAME))
                datasources.put(entry.getKey(), entry.getValue().cloneReadOnly());
        }
    }
    // Default query of query DB
    try {
        setDatasource(config, datasources, QOQ_DATASOURCE_NAME, new ClassDefinitionImpl("org.hsqldb.jdbcDriver", "hsqldb", "1.8.0", config.getIdentification()), "hypersonic-hsqldb", "", -1, "jdbc:hsqldb:.", "sa", "", DEFAULT_MAX_CONNECTION, -1, 60000, true, true, DataSource.ALLOW_ALL, false, false, null, new StructImpl(), "", ParamSyntax.DEFAULT, false, false);
    } catch (Exception e) {
        log.error("Datasource", e);
    }
    SecurityManager sm = config.getSecurityManager();
    short access = sm.getAccess(SecurityManager.TYPE_DATASOURCE);
    int accessCount = -1;
    if (access == SecurityManager.VALUE_YES)
        accessCount = -1;
    else if (access == SecurityManager.VALUE_NO)
        accessCount = 0;
    else if (access >= SecurityManager.VALUE_1 && access <= SecurityManager.VALUE_10) {
        accessCount = access - SecurityManager.NUMBER_OFFSET;
    }
    // Databases
    Element databases = getChildByName(doc.getDocumentElement(), "data-sources");
    // if(databases==null)databases=doc.createElement("data-sources");
    // PSQ
    String strPSQ = getAttr(databases, "psq");
    if (StringUtil.isEmpty(strPSQ)) {
        // prior version was buggy, was the opposite
        strPSQ = getAttr(databases, "preserve-single-quote");
        if (!StringUtil.isEmpty(strPSQ)) {
            Boolean b = Caster.toBoolean(strPSQ, null);
            if (b != null)
                strPSQ = b.booleanValue() ? "false" : "true";
        }
    }
    if (access != SecurityManager.VALUE_NO && !StringUtil.isEmpty(strPSQ)) {
        config.setPSQL(toBoolean(strPSQ, true));
    } else if (hasCS)
        config.setPSQL(configServer.getPSQL());
    // Data Sources
    Element[] dataSources = getChildren(databases, "data-source");
    if (accessCount == -1)
        accessCount = dataSources.length;
    if (dataSources.length < accessCount)
        accessCount = dataSources.length;
    // if(hasAccess) {
    ClassDefinition cd;
    for (int i = 0; i < accessCount; i++) {
        Element dataSource = dataSources[i];
        if (dataSource.hasAttribute("database")) {
            try {
                cd = getClassDefinition(dataSource, "", config.getIdentification());
                if (!cd.isBundle()) {
                    JDBCDriver jdbc = config.getJDBCDriverByClassName(cd.getClassName(), null);
                    if (jdbc != null)
                        cd = jdbc.cd;
                }
                setDatasource(config, datasources, getAttr(dataSource, "name"), cd, getAttr(dataSource, "host"), getAttr(dataSource, "database"), Caster.toIntValue(getAttr(dataSource, "port"), -1), getAttr(dataSource, "dsn"), getAttr(dataSource, "username"), ConfigWebUtil.decrypt(getAttr(dataSource, "password")), Caster.toIntValue(getAttr(dataSource, "connectionLimit"), DEFAULT_MAX_CONNECTION), Caster.toIntValue(getAttr(dataSource, "connectionTimeout"), -1), Caster.toLongValue(getAttr(dataSource, "metaCacheTimeout"), 60000), toBoolean(getAttr(dataSource, "blob"), true), toBoolean(getAttr(dataSource, "clob"), true), Caster.toIntValue(getAttr(dataSource, "allow"), DataSource.ALLOW_ALL), toBoolean(getAttr(dataSource, "validate"), false), toBoolean(getAttr(dataSource, "storage"), false), getAttr(dataSource, "timezone"), toStruct(getAttr(dataSource, "custom")), getAttr(dataSource, "dbdriver"), ParamSyntax.toParamSyntax(dataSource, ParamSyntax.DEFAULT), toBoolean(getAttr(dataSource, "literal-timestamp-with-tsoffset"), false), toBoolean(getAttr(dataSource, "always-set-timeout"), false));
            } catch (Exception e) {
                log.error("Datasource", e);
            }
        }
    }
    // }
    config.setDataSources(datasources);
}
Also used : SecurityManager(lucee.runtime.security.SecurityManager) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) ClassDefinition(lucee.runtime.db.ClassDefinition) FunctionLibException(lucee.transformer.library.function.FunctionLibException) PageException(lucee.runtime.exp.PageException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SecurityException(lucee.runtime.exp.SecurityException) TagLibException(lucee.transformer.library.tag.TagLibException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SQLException(java.sql.SQLException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) SAXException(org.xml.sax.SAXException) ClassException(lucee.commons.lang.ClassException) MalformedURLException(java.net.MalformedURLException) ExpressionException(lucee.runtime.exp.ExpressionException) ApplicationException(lucee.runtime.exp.ApplicationException) lucee.aprint(lucee.aprint) DataSource(lucee.runtime.db.DataSource) DumpWriterEntry(lucee.runtime.dump.DumpWriterEntry) Entry(java.util.Map.Entry) GatewayEntry(lucee.runtime.gateway.GatewayEntry) ClassDefinitionImpl(lucee.transformer.library.ClassDefinitionImpl) StructImpl(lucee.runtime.type.StructImpl) JDBCDriver(lucee.runtime.db.JDBCDriver) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 9 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class ScopeContext method getClientScope.

public Client getClientScope(PageContext pc) throws PageException {
    ApplicationContext appContext = pc.getApplicationContext();
    // get Context
    Map<String, Scope> context = getSubMap(cfClientContexts, appContext.getName());
    // get Client
    boolean isMemory = false;
    String storage = appContext.getClientstorage();
    if (StringUtil.isEmpty(storage, true)) {
        storage = ConfigImpl.DEFAULT_STORAGE_CLIENT;
    } else if ("ram".equalsIgnoreCase(storage)) {
        storage = "memory";
        isMemory = true;
    } else if ("registry".equalsIgnoreCase(storage)) {
        storage = "file";
    } else {
        storage = storage.toLowerCase();
        if ("memory".equals(storage))
            isMemory = true;
    }
    Client existing = (Client) context.get(pc.getCFID());
    Client client = appContext.getClientCluster() ? null : existing;
    // client=doMemory?(Client) context.get(pc.getCFID()):null;
    if (client == null || client.isExpired() || !client.getStorage().equalsIgnoreCase(storage)) {
        if ("file".equals(storage)) {
            client = ClientFile.getInstance(appContext.getName(), pc, getLog());
        } else if ("cookie".equals(storage))
            client = ClientCookie.getInstance(appContext.getName(), pc, getLog());
        else if ("memory".equals(storage)) {
            if (existing != null)
                client = existing;
            client = ClientMemory.getInstance(pc, getLog());
        } else {
            DataSource ds = pc.getDataSource(storage, null);
            if (ds != null) {
                if (INVIDUAL_STORAGE_KEYS) {
                    try {
                        client = (Client) IKStorageScopeSupport.getInstance(Scope.SCOPE_CLIENT, new IKHandlerDatasource(), appContext.getName(), storage, pc, existing, getLog());
                    } catch (PageException pe) {
                        // code above could fail when an old scope is loaded, remember client scope can be easy be
                        // 180 days old
                        client = ClientDatasource.getInstance(storage, pc, getLog());
                    }
                } else
                    client = ClientDatasource.getInstance(storage, pc, getLog());
            } else {
                if (INVIDUAL_STORAGE_KEYS) {
                    try {
                        client = (Client) IKStorageScopeSupport.getInstance(Scope.SCOPE_CLIENT, new IKHandlerCache(), appContext.getName(), storage, pc, existing, getLog());
                    } catch (PageException pe) {
                        // code above could fail when an old scope is loaded, remember client scope can be easy be
                        // 180 days old
                        client = ClientCache.getInstance(storage, appContext.getName(), pc, existing, getLog(), null);
                    }
                } else
                    client = ClientCache.getInstance(storage, appContext.getName(), pc, existing, getLog(), null);
            }
            if (client == null) {
                // datasource not enabled for storage
                if (ds != null)
                    throw new ApplicationException("datasource [" + storage + "] is not enabled to be used as session/client storage, you have to enable it in the Lucee administrator.");
                CacheConnection cc = CacheUtil.getCacheConnection(pc, storage, null);
                if (cc != null)
                    throw new ApplicationException("cache [" + storage + "] is not enabled to be used  as a session/client storage, you have to enable it in the Lucee administrator.");
                throw new ApplicationException("there is no cache or datasource with name [" + storage + "] defined.");
            }
        }
        client.setStorage(storage);
        context.put(pc.getCFID(), client);
    } else
        getLog().log(Log.LEVEL_INFO, "scope-context", "use existing client scope for " + appContext.getName() + "/" + pc.getCFID() + " from storage " + storage);
    client.touchBeforeRequest(pc);
    return client;
}
Also used : PageException(lucee.runtime.exp.PageException) ApplicationContext(lucee.runtime.listener.ApplicationContext) ApplicationException(lucee.runtime.exp.ApplicationException) StorageScope(lucee.runtime.type.scope.storage.StorageScope) MemoryScope(lucee.runtime.type.scope.storage.MemoryScope) CacheConnection(lucee.runtime.cache.CacheConnection) IKHandlerCache(lucee.runtime.type.scope.storage.IKHandlerCache) DataSource(lucee.runtime.db.DataSource) IKHandlerDatasource(lucee.runtime.type.scope.storage.IKHandlerDatasource)

Example 10 with DataSource

use of lucee.runtime.db.DataSource in project Lucee by lucee.

the class IKHandlerDatasource method store.

@Override
public void store(IKStorageScopeSupport storageScope, PageContext pc, String appName, final String name, String cfid, MapPro<Key, IKStorageScopeItem> data, Log log) {
    DatasourceConnection dc = null;
    ConfigImpl ci = (ConfigImpl) ThreadLocalPageContext.getConfig(pc);
    DatasourceConnectionPool pool = ci.getDatasourceConnectionPool();
    try {
        pc = ThreadLocalPageContext.get(pc);
        DataSource ds;
        if (pc != null)
            ds = pc.getDataSource(name);
        else
            ds = ci.getDataSource(name);
        dc = pool.getDatasourceConnection(null, ds, null, null);
        SQLExecutor executor = SQLExecutionFactory.getInstance(dc);
        IKStorageValue existingVal = loadData(pc, appName, name, storageScope.getTypeAsString(), storageScope.getType(), log);
        IKStorageValue sv = new IKStorageValue(IKStorageScopeSupport.prepareToStore(data, existingVal, storageScope.lastModified()));
        executor.update(ci, cfid, appName, dc, storageScope.getType(), sv, storageScope.getTimeSpan(), log);
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
        ScopeContext.error(log, t);
    } finally {
        if (dc != null)
            pool.releaseDatasourceConnection(dc);
    }
}
Also used : DatasourceConnection(lucee.runtime.db.DatasourceConnection) DatasourceConnectionPool(lucee.runtime.db.DatasourceConnectionPool) SQLExecutor(lucee.runtime.type.scope.storage.db.SQLExecutor) ConfigImpl(lucee.runtime.config.ConfigImpl) DataSource(lucee.runtime.db.DataSource)

Aggregations

DataSource (lucee.runtime.db.DataSource)27 PageException (lucee.runtime.exp.PageException)9 Struct (lucee.runtime.type.Struct)9 DatasourceConnection (lucee.runtime.db.DatasourceConnection)8 ApplicationException (lucee.runtime.exp.ApplicationException)8 ConfigImpl (lucee.runtime.config.ConfigImpl)7 StructImpl (lucee.runtime.type.StructImpl)7 SQLException (java.sql.SQLException)5 Map (java.util.Map)5 Log (lucee.commons.io.log.Log)5 Entry (java.util.Map.Entry)4 CacheConnection (lucee.runtime.cache.CacheConnection)4 ClassDefinition (lucee.runtime.db.ClassDefinition)4 DataSourceManager (lucee.runtime.db.DataSourceManager)4 DatasourceConnectionPool (lucee.runtime.db.DatasourceConnectionPool)4 ApplicationContext (lucee.runtime.listener.ApplicationContext)4 QueryImpl (lucee.runtime.type.QueryImpl)4 SQLExecutor (lucee.runtime.type.scope.storage.db.SQLExecutor)4 HashMap (java.util.HashMap)3 Iterator (java.util.Iterator)3