use of lucee.runtime.PageContextImpl in project Lucee by lucee.
the class Query method doStartTag.
@Override
public int doStartTag() throws PageException {
// default datasource
if (datasource == null && (dbtype == null || !dbtype.equals("query"))) {
Object obj = pageContext.getApplicationContext().getDefDataSource();
if (StringUtil.isEmpty(obj)) {
boolean isCFML = pageContext.getRequestDialect() == CFMLEngine.DIALECT_CFML;
throw new ApplicationException("attribute [datasource] is required when attribute [dbtype] is not [query] and no default datasource is defined", "you can define a default datasource as attribute [defaultdatasource] of the tag " + (isCFML ? Constants.CFML_APPLICATION_TAG_NAME : Constants.LUCEE_APPLICATION_TAG_NAME) + " or as data member of the " + (isCFML ? Constants.CFML_APPLICATION_EVENT_HANDLER : Constants.LUCEE_APPLICATION_EVENT_HANDLER) + " (this.defaultdatasource=\"mydatasource\";)");
}
datasource = obj instanceof DataSource ? (DataSource) obj : pageContext.getDataSource(Caster.toString(obj));
}
// timeout
if (datasource instanceof DataSourceImpl && ((DataSourceImpl) datasource).getAlwaysSetTimeout()) {
TimeSpan remaining = PageContextUtil.remainingTime(pageContext, true);
if (this.timeout == null || ((int) this.timeout.getSeconds()) <= 0 || timeout.getSeconds() > remaining.getSeconds()) {
// not set
this.timeout = remaining;
}
}
// timezone
if (timezone != null || (datasource != null && (timezone = datasource.getTimeZone()) != null)) {
tmpTZ = pageContext.getTimeZone();
pageContext.setTimeZone(timezone);
}
PageContextImpl pci = ((PageContextImpl) pageContext);
// cache within
if (StringUtil.isEmpty(cachedWithin)) {
Object tmp = (pageContext).getCachedWithin(ConfigWeb.CACHEDWITHIN_QUERY);
if (tmp != null)
setCachedwithin(tmp);
}
// literal timestamp with TSOffset
if (datasource instanceof DataSourceImpl)
literalTimestampWithTSOffset = ((DataSourceImpl) datasource).getLiteralTimestampWithTSOffset();
else
literalTimestampWithTSOffset = false;
previousLiteralTimestampWithTSOffset = pci.getTimestampWithTSOffset();
pci.setTimestampWithTSOffset(literalTimestampWithTSOffset);
return EVAL_BODY_BUFFERED;
}
use of lucee.runtime.PageContextImpl 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;
}
use of lucee.runtime.PageContextImpl in project Lucee by lucee.
the class TagUtil method addTagMetaData.
/**
* load metadata from cfc based custom tags and add the info to the tag
* @param cs
* @param config
*/
public static void addTagMetaData(ConfigWebImpl cw) {
if (true)
return;
PageContextImpl pc = null;
try {
pc = ThreadUtil.createPageContext(cw, DevNullOutputStream.DEV_NULL_OUTPUT_STREAM, "localhost", "/", "", new Cookie[0], new Pair[0], null, new Pair[0], new StructImpl(), false, -1);
} catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return;
}
PageContext orgPC = ThreadLocalPageContext.get();
try {
ThreadLocalPageContext.register(pc);
// MUST MOST of them are the same, so this is a huge overhead
_addTagMetaData(pc, cw, CFMLEngine.DIALECT_CFML);
_addTagMetaData(pc, cw, CFMLEngine.DIALECT_LUCEE);
} catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
} finally {
pc.getConfig().getFactory().releaseLuceePageContext(pc, true);
ThreadLocalPageContext.register(orgPC);
}
}
use of lucee.runtime.PageContextImpl in project Lucee by lucee.
the class Admin method doGetError.
private void doGetError() throws PageException {
Struct sct = new StructImpl();
pageContext.setVariable(getString("admin", action, "returnVariable"), sct);
// sct.set("errorTemplate",config.getErrorTemplate());
Struct templates = new StructImpl();
Struct str = new StructImpl();
sct.set(TEMPLATES, templates);
sct.set(STR, str);
sct.set(DO_STATUS_CODE, Caster.toBoolean(config.getErrorStatusCode()));
// 500
String template = config.getErrorTemplate(500);
try {
PageSource ps = ((PageContextImpl) pageContext).getPageSourceExisting(template);
if (ps != null)
templates.set("500", ps.getDisplayPath());
else
templates.set("500", "");
} catch (PageException e) {
templates.set("500", "");
}
str.set("500", template);
// 404
template = config.getErrorTemplate(404);
try {
PageSource ps = ((PageContextImpl) pageContext).getPageSourceExisting(template);
if (ps != null)
templates.set("404", ps.getDisplayPath());
else
templates.set("404", "");
} catch (PageException e) {
templates.set("404", "");
}
str.set("404", template);
}
use of lucee.runtime.PageContextImpl in project Lucee by lucee.
the class Admin method doCompileFile.
private void doCompileFile(Mapping mapping, Resource file, String path, Map<String, String> errors, Boolean explicitIgnoreScope) throws PageException {
if (ResourceUtil.exists(file)) {
if (file.isDirectory()) {
Resource[] files = file.listResources(FILTER_CFML_TEMPLATES);
if (files != null)
for (int i = 0; i < files.length; i++) {
String p = path + '/' + files[i].getName();
// print.ln(files[i]+" - "+p);
doCompileFile(mapping, files[i], p, errors, explicitIgnoreScope);
}
} else if (file.isFile()) {
PageSource ps = mapping.getPageSource(path);
PageContextImpl pci = (PageContextImpl) pageContext;
boolean envIgnoreScopes = pci.ignoreScopes();
try {
if (explicitIgnoreScope != null)
pci.setIgnoreScopes(explicitIgnoreScope);
((PageSourceImpl) ps).clear();
((PageSourceImpl) ps).loadPage(pageContext, explicitIgnoreScope != null);
// pageContext.compile(ps);
} catch (PageException pe) {
SystemOut.printDate(pe);
String template = ps.getDisplayPath();
StringBuilder msg = new StringBuilder(pe.getMessage());
msg.append(", Error Occurred in File [");
msg.append(template);
if (pe instanceof PageExceptionImpl) {
try {
PageExceptionImpl pei = (PageExceptionImpl) pe;
Array context = pei.getTagContext(config);
if (context.size() > 0) {
msg.append(":");
msg.append(Caster.toString(((Struct) context.getE(1)).get("line")));
}
} catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
msg.append("]");
if (errors != null)
errors.put(template, msg.toString());
else
throw new ApplicationException(msg.toString());
} finally {
pci.setIgnoreScopes(envIgnoreScopes);
}
}
}
}
Aggregations