Search in sources :

Example 6 with StructImpl

use of lucee.runtime.type.StructImpl in project Lucee by lucee.

the class HttpGetWithBody method setRequestTimeout.

private void setRequestTimeout(Struct cfhttp) {
    cfhttp.setEL(CHARSET, "");
    cfhttp.setEL(ERROR_DETAIL, "");
    cfhttp.setEL(KeyConstants._filecontent, "Connection Timeout");
    cfhttp.setEL(KeyConstants._header, "");
    cfhttp.setEL(KeyConstants._mimetype, "Unable to determine MIME type of file.");
    cfhttp.setEL(RESPONSEHEADER, new StructImpl());
    cfhttp.setEL(STATUSCODE, "408 Request Time-out");
    cfhttp.setEL(STATUS_CODE, new Double(408));
    cfhttp.setEL(STATUS_TEXT, "Request Time-out");
    cfhttp.setEL(KeyConstants._text, Boolean.TRUE);
}
Also used : StructImpl(lucee.runtime.type.StructImpl)

Example 7 with StructImpl

use of lucee.runtime.type.StructImpl in project Lucee by lucee.

the class ColumnInfo method getMeta.

public static Struct getMeta(DatasourceConnection dc, String tableQualifier, String tableOwner, String tableName) throws SQLException {
    DatabaseMetaData md = dc.getConnection().getMetaData();
    Struct sct = new StructImpl();
    ResultSet columns = md.getColumns(tableQualifier, tableOwner, tableName, null);
    try {
        String name;
        while (columns.next()) {
            name = columns.getString("COLUMN_NAME");
            sct.setEL(name, new ColumnInfo(name, columns.getInt("DATA_TYPE"), columns.getBoolean("IS_NULLABLE")));
        }
    } finally {
        DBUtil.closeEL(columns);
    }
    return sct;
}
Also used : StructImpl(lucee.runtime.type.StructImpl) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData) Struct(lucee.runtime.type.Struct)

Example 8 with StructImpl

use of lucee.runtime.type.StructImpl in project Lucee by lucee.

the class Lock method doStartTag.

@Override
public int doStartTag() throws PageException {
    if (timeoutInMillis <= 0) {
        TimeSpan remaining = PageContextUtil.remainingTime(pageContext, true);
        this.timeoutInMillis = toInt(remaining.getMillis());
    }
    manager = pageContext.getConfig().getLockManager();
    // check attributes
    if (name != null && scope != SCOPE_NONE) {
        throw new LockException(LockException.OPERATION_CREATE, this.name, "invalid attribute combination", "attribute [name] and [scope] can't be used together");
    }
    if (name == null && scope == SCOPE_NONE) {
        name = "id-" + id;
    }
    String lockType = null;
    if (name == null) {
        String cid = pageContext.getConfig().getIdentification().getId();
        // Session
        if (scope == SCOPE_REQUEST) {
            lockType = "request";
            name = "__request_" + cid + "__" + ((RequestImpl) pageContext.requestScope())._getId();
        } else // Session
        if (scope == SCOPE_SESSION) {
            lockType = "session";
            name = "__session_" + cid + "__" + pageContext.sessionScope()._getId();
        } else // Application
        if (scope == SCOPE_APPLICATION) {
            lockType = "application";
            name = "__application_" + cid + "__" + ((ApplicationImpl) pageContext.applicationScope())._getId();
        } else // Server
        if (scope == SCOPE_SERVER) {
            lockType = "server";
            name = "__server_" + ((ServerImpl) pageContext.serverScope())._getId();
        }
    }
    Struct cflock = new StructImpl();
    cflock.set("succeeded", Boolean.TRUE);
    cflock.set("errortext", "");
    pageContext.setVariable(result, cflock);
    start = System.nanoTime();
    try {
        // this has to be first, otherwise LockTimeoutException has nothing to release
        ((PageContextImpl) pageContext).setActiveLock(new ActiveLock(type, name, timeoutInMillis));
        data = manager.lock(type, name, timeoutInMillis, pageContext.getId());
    } catch (LockTimeoutException e) {
        LockManagerImpl mi = (LockManagerImpl) manager;
        Boolean hasReadLock = mi.isReadLocked(name);
        Boolean hasWriteLock = mi.isWriteLocked(name);
        String msg = LockTimeoutExceptionImpl.createMessage(type, name, lockType, timeoutInMillis, hasReadLock, hasWriteLock);
        _release(pageContext, System.nanoTime() - start);
        name = null;
        cflock.set("succeeded", Boolean.FALSE);
        cflock.set("errortext", msg);
        if (throwontimeout)
            throw new LockException(LockException.OPERATION_TIMEOUT, this.name, msg);
        return SKIP_BODY;
    } catch (InterruptedException e) {
        _release(pageContext, System.nanoTime() - start);
        cflock.set("succeeded", Boolean.FALSE);
        cflock.set("errortext", e.getMessage());
        if (throwontimeout)
            throw Caster.toPageException(e);
        return SKIP_BODY;
    }
    return EVAL_BODY_INCLUDE;
}
Also used : ApplicationImpl(lucee.runtime.type.scope.ApplicationImpl) PageContextImpl(lucee.runtime.PageContextImpl) Struct(lucee.runtime.type.Struct) TimeSpan(lucee.runtime.type.dt.TimeSpan) StructImpl(lucee.runtime.type.StructImpl) ActiveLock(lucee.runtime.debug.ActiveLock) LockException(lucee.runtime.exp.LockException) LockManagerImpl(lucee.runtime.lock.LockManagerImpl) RequestImpl(lucee.runtime.type.scope.RequestImpl) LockTimeoutException(lucee.runtime.lock.LockTimeoutException)

Example 9 with StructImpl

use of lucee.runtime.type.StructImpl in project Lucee by lucee.

the class Query method setExecutionTime.

private void setExecutionTime(long exe) {
    Struct sct = new StructImpl();
    sct.setEL(KeyConstants._executionTime, new Double(exe));
    pageContext.undefinedScope().setEL(CFQUERY, sct);
}
Also used : StructImpl(lucee.runtime.type.StructImpl) QueryStruct(lucee.runtime.type.query.QueryStruct) Struct(lucee.runtime.type.Struct)

Example 10 with StructImpl

use of lucee.runtime.type.StructImpl in project Lucee by lucee.

the class Query method doEndTag.

@Override
public int doEndTag() throws PageException {
    if (hasChangedPSQ)
        pageContext.setPsq(orgPSQ);
    String strSQL = bodyContent.getString().trim();
    if (strSQL.isEmpty())
        throw new DatabaseException("no sql string defined, inside query tag", null, null, null);
    try {
        // cannot use attribute params and queryparam tag
        if (!items.isEmpty() && params != null)
            throw new DatabaseException("you cannot use the attribute params and sub tags queryparam at the same time", null, null, null);
        // create SQL
        SQL sql;
        if (params != null) {
            if (params instanceof Argument)
                sql = QueryParamConverter.convert(strSQL, (Argument) params);
            else if (Decision.isArray(params))
                sql = QueryParamConverter.convert(strSQL, Caster.toArray(params));
            else if (Decision.isStruct(params))
                sql = QueryParamConverter.convert(strSQL, Caster.toStruct(params));
            else
                throw new DatabaseException("value of the attribute [params] has to be a struct or a array", null, null, null);
        } else {
            sql = items.isEmpty() ? new SQLImpl(strSQL) : new SQLImpl(strSQL, items.toArray(new SQLItem[items.size()]));
        }
        // lucee.runtime.type.Query query=null;
        QueryResult queryResult = null;
        String cacheHandlerId = null;
        String cacheId = null;
        long exe = 0;
        boolean useCache = (cachedWithin != null) || (cachedAfter != null);
        CacheHandler cacheHandler = null;
        if (useCache) {
            cacheId = CacheHandlerCollectionImpl.createId(sql, datasource != null ? datasource.getName() : null, username, password, returntype);
            CacheHandlerCollectionImpl coll = (CacheHandlerCollectionImpl) pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null);
            cacheHandler = coll.getInstanceMatchingObject(cachedWithin, null);
            if (cacheHandler == null && cachedAfter != null)
                cacheHandler = coll.getTimespanInstance(null);
            if (cacheHandler != null) {
                // cacheHandlerId specifies to queryResult the cacheType and therefore whether the query is cached or
                cacheHandlerId = cacheHandler.id();
                if (cacheHandler instanceof CacheHandlerPro) {
                    CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, (cachedWithin != null) ? cachedWithin : cachedAfter);
                    if (cacheItem instanceof QueryResultCacheItem)
                        queryResult = ((QueryResultCacheItem) cacheItem).getQueryResult();
                } else {
                    // FUTURE this else block can be removed when all cache handlers implement CacheHandlerPro
                    CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);
                    if (cacheItem instanceof QueryResultCacheItem) {
                        QueryResultCacheItem queryCachedItem = (QueryResultCacheItem) cacheItem;
                        Date cacheLimit = cachedAfter;
                        if (cacheLimit == null || queryCachedItem.isCachedAfter(cacheLimit))
                            queryResult = queryCachedItem.getQueryResult();
                    }
                }
            } else {
                List<String> patterns = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null).getPatterns();
                throw new ApplicationException("cachedwithin value [" + cachedWithin + "] is invalid, valid values are for example [" + ListUtil.listToList(patterns, ", ") + "]");
            }
        // query=pageContext.getQueryCache().getQuery(pageContext,sql,datasource!=null?datasource.getName():null,username,password,cachedafter);
        }
        // cache not found, process and cache result if needed
        if (queryResult == null) {
            // QoQ
            if ("query".equals(dbtype)) {
                lucee.runtime.type.Query q = executeQoQ(sql);
                if (returntype == RETURN_TYPE_ARRAY)
                    // TODO this should be done in queryExecute itself so we not have to convert afterwards
                    queryResult = QueryArray.toQueryArray(q);
                else if (returntype == RETURN_TYPE_STRUCT) {
                    if (columnName == null)
                        throw new ApplicationException("attribute columnKey is required when return type is set to struct");
                    // TODO this should be done in queryExecute itself so we not have to convert
                    queryResult = QueryStruct.toQueryStruct(q, columnName);
                // afterwards
                } else
                    queryResult = (QueryResult) q;
            } else // ORM and Datasource
            {
                long start = System.nanoTime();
                Object obj;
                if ("orm".equals(dbtype) || "hql".equals(dbtype))
                    obj = executeORM(sql, returntype, ormoptions);
                else
                    obj = executeDatasoure(sql, result != null, pageContext.getTimeZone());
                if (obj instanceof QueryResult) {
                    queryResult = (QueryResult) obj;
                } else {
                    if (setReturnVariable) {
                        rtn = obj;
                    } else if (!StringUtil.isEmpty(name)) {
                        pageContext.setVariable(name, obj);
                    }
                    if (result != null) {
                        Struct sct = new StructImpl();
                        sct.setEL(KeyConstants._cached, Boolean.FALSE);
                        long time = System.nanoTime() - start;
                        sct.setEL(KeyConstants._executionTime, Caster.toDouble(time / 1000000));
                        sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(time));
                        sct.setEL(KeyConstants._SQL, sql.getSQLString());
                        if (Decision.isArray(obj)) {
                        } else
                            sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(1));
                        pageContext.setVariable(result, sct);
                    } else
                        setExecutionTime((System.nanoTime() - start) / 1000000);
                    return EVAL_PAGE;
                }
            }
            if (cachedWithin != null) {
                CacheItem cacheItem = QueryResultCacheItem.newInstance(queryResult, tags, datasource, null);
                if (cacheItem != null)
                    cacheHandler.set(pageContext, cacheId, cachedWithin, cacheItem);
            }
            exe = queryResult.getExecutionTime();
        } else {
            queryResult.setCacheType(cacheHandlerId);
        }
        if (pageContext.getConfig().debug() && debug) {
            boolean logdb = ((ConfigImpl) pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE);
            if (logdb) {
                boolean debugUsage = DebuggerImpl.debugQueryUsage(pageContext, queryResult);
                DebuggerImpl di = (DebuggerImpl) pageContext.getDebugger();
                di.addQuery(debugUsage ? queryResult : null, datasource != null ? datasource.getName() : null, name, sql, queryResult.getRecordcount(), getPageSource(), exe);
            }
        }
        if (setReturnVariable) {
            rtn = queryResult;
        } else if ((queryResult.getColumncount() + queryResult.getRecordcount()) > 0 && !StringUtil.isEmpty(name)) {
            pageContext.setVariable(name, queryResult);
        }
        // Result
        if (result != null) {
            Struct sct = new StructImpl();
            sct.setEL(KeyConstants._cached, Caster.toBoolean(queryResult.isCached()));
            if ((queryResult.getColumncount() + queryResult.getRecordcount()) > 0) {
                String list = ListUtil.arrayToList(queryResult instanceof lucee.runtime.type.Query ? ((lucee.runtime.type.Query) queryResult).getColumnNamesAsString() : CollectionUtil.toString(queryResult.getColumnNames(), false), ",");
                sct.setEL(KeyConstants._COLUMNLIST, list);
            }
            int rc = queryResult.getRecordcount();
            if (rc == 0)
                rc = queryResult.getUpdateCount();
            sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(rc));
            sct.setEL(KeyConstants._executionTime, Caster.toDouble(queryResult.getExecutionTime() / 1000000));
            sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(queryResult.getExecutionTime()));
            sct.setEL(KeyConstants._SQL, sql.getSQLString());
            // GENERATED KEYS
            lucee.runtime.type.Query qi = Caster.toQuery(queryResult, null);
            if (qi != null) {
                lucee.runtime.type.Query qryKeys = qi.getGeneratedKeys();
                if (qryKeys != null) {
                    StringBuilder generatedKey = new StringBuilder(), sb;
                    Collection.Key[] columnNames = qryKeys.getColumnNames();
                    QueryColumn column;
                    for (int c = 0; c < columnNames.length; c++) {
                        column = qryKeys.getColumn(columnNames[c]);
                        sb = new StringBuilder();
                        int size = column.size();
                        for (int row = 1; row <= size; row++) {
                            if (row > 1)
                                sb.append(',');
                            sb.append(Caster.toString(column.get(row, null)));
                        }
                        if (sb.length() > 0) {
                            sct.setEL(columnNames[c], sb.toString());
                            if (generatedKey.length() > 0)
                                generatedKey.append(',');
                            generatedKey.append(sb);
                        }
                    }
                    if (generatedKey.length() > 0)
                        sct.setEL(GENERATEDKEY, generatedKey.toString());
                }
            }
            // sqlparameters
            SQLItem[] params = sql.getItems();
            if (params != null && params.length > 0) {
                Array arr = new ArrayImpl();
                sct.setEL(SQL_PARAMETERS, arr);
                for (int i = 0; i < params.length; i++) {
                    arr.append(params[i].getValue());
                }
            }
            pageContext.setVariable(result, sct);
        } else // cfquery.executiontime
        {
            setExecutionTime(exe / 1000000);
        }
        // listener
        ((ConfigWebImpl) pageContext.getConfig()).getActionMonitorCollector().log(pageContext, "query", "Query", exe, queryResult);
        // log
        Log log = pageContext.getConfig().getLog("datasource");
        if (log.getLogLevel() >= Log.LEVEL_INFO) {
            log.info("query tag", "executed [" + sql.toString().trim() + "] in " + DecimalFormat.call(pageContext, exe / 1000000D) + " ms");
        }
    } catch (PageException pe) {
        // log
        pageContext.getConfig().getLog("datasource").error("query tag", pe);
        throw pe;
    } finally {
        ((PageContextImpl) pageContext).setTimestampWithTSOffset(previousLiteralTimestampWithTSOffset);
        if (tmpTZ != null) {
            pageContext.setTimeZone(tmpTZ);
        }
    }
    return EVAL_PAGE;
}
Also used : SQLImpl(lucee.runtime.db.SQLImpl) Argument(lucee.runtime.type.scope.Argument) SimpleQuery(lucee.runtime.type.query.SimpleQuery) ArrayImpl(lucee.runtime.type.ArrayImpl) DebuggerImpl(lucee.runtime.debug.DebuggerImpl) SQLItem(lucee.runtime.db.SQLItem) QueryStruct(lucee.runtime.type.query.QueryStruct) Struct(lucee.runtime.type.Struct) QueryResult(lucee.runtime.type.query.QueryResult) CacheHandlerPro(lucee.runtime.cache.tag.CacheHandlerPro) PageException(lucee.runtime.exp.PageException) Log(lucee.commons.io.log.Log) PageContextImpl(lucee.runtime.PageContextImpl) QueryResultCacheItem(lucee.runtime.cache.tag.query.QueryResultCacheItem) Date(java.util.Date) SQL(lucee.runtime.db.SQL) Array(lucee.runtime.type.Array) QueryArray(lucee.runtime.type.query.QueryArray) ApplicationException(lucee.runtime.exp.ApplicationException) StructImpl(lucee.runtime.type.StructImpl) QueryColumn(lucee.runtime.type.QueryColumn) CacheHandlerCollectionImpl(lucee.runtime.cache.tag.CacheHandlerCollectionImpl) QueryResultCacheItem(lucee.runtime.cache.tag.query.QueryResultCacheItem) CacheItem(lucee.runtime.cache.tag.CacheItem) CacheHandler(lucee.runtime.cache.tag.CacheHandler) DatabaseException(lucee.runtime.exp.DatabaseException) ConfigImpl(lucee.runtime.config.ConfigImpl) Key(lucee.runtime.type.Collection.Key)

Aggregations

StructImpl (lucee.runtime.type.StructImpl)251 Struct (lucee.runtime.type.Struct)216 PageException (lucee.runtime.exp.PageException)40 Entry (java.util.Map.Entry)34 Key (lucee.runtime.type.Collection.Key)28 Array (lucee.runtime.type.Array)25 ArrayImpl (lucee.runtime.type.ArrayImpl)24 ApplicationException (lucee.runtime.exp.ApplicationException)21 IOException (java.io.IOException)19 Map (java.util.Map)19 Resource (lucee.commons.io.res.Resource)18 Iterator (java.util.Iterator)17 PageContextImpl (lucee.runtime.PageContextImpl)14 QueryImpl (lucee.runtime.type.QueryImpl)13 Collection (lucee.runtime.type.Collection)11 Query (lucee.runtime.type.Query)11 DateTimeImpl (lucee.runtime.type.dt.DateTimeImpl)11 HashMap (java.util.HashMap)9 PageSource (lucee.runtime.PageSource)8 Element (org.w3c.dom.Element)8