use of lucee.runtime.type.QueryImpl in project Lucee by lucee.
the class LDAPClient method query.
/**
* @param dn
* @param strAttributes
* @param scope
* @param startrow
* @param maxrows
* @param timeout
* @param sort
* @param sortType
* @param sortDirection
* @param start
* @param separator
* @param filter
* @return
* @throws NamingException
* @throws PageException
* @throws IOException
*/
public Query query(String strAttributes, int scope, int startrow, int maxrows, int timeout, String[] sort, int sortType, int sortDirection, String start, String separator, String filter) throws NamingException, PageException, IOException {
// strAttributes=strAttributes.trim();
boolean attEQAsterix = strAttributes.trim().equals("*");
String[] attributes = attEQAsterix ? new String[] { "name", "value" } : toStringAttributes(strAttributes, ",");
// Control
SearchControls controls = new SearchControls();
controls.setReturningObjFlag(true);
controls.setSearchScope(scope);
if (!attEQAsterix)
controls.setReturningAttributes(toStringAttributes(strAttributes, ","));
if (maxrows > 0)
controls.setCountLimit(startrow + maxrows + 1);
if (timeout > 0)
controls.setTimeLimit(timeout);
InitialLdapContext context = new InitialLdapContext(env, null);
// Search
Query qry = new QueryImpl(attributes, 0, "query");
try {
NamingEnumeration results = context.search(start, filter, controls);
// Fill result
int row = 1;
if (!attEQAsterix) {
while (results.hasMoreElements()) {
SearchResult resultRow = (SearchResult) results.next();
if (row++ < startrow)
continue;
int len = qry.addRow();
NamingEnumeration rowEnum = resultRow.getAttributes().getAll();
String dn = resultRow.getNameInNamespace();
qry.setAtEL("dn", len, dn);
while (rowEnum.hasMore()) {
Attribute attr = (Attribute) rowEnum.next();
Collection.Key key = KeyImpl.init(attr.getID());
Enumeration values = attr.getAll();
Object value;
String existing, strValue;
while (values.hasMoreElements()) {
value = values.nextElement();
strValue = Caster.toString(value, null);
existing = Caster.toString(qry.getAt(key, len, null), null);
if (!StringUtil.isEmpty(existing) && !StringUtil.isEmpty(strValue)) {
value = existing + separator + strValue;
} else if (!StringUtil.isEmpty(existing))
value = existing;
qry.setAtEL(key, len, value);
}
}
if (maxrows > 0 && len >= maxrows)
break;
}
} else {
outer: while (results.hasMoreElements()) {
SearchResult resultRow = (SearchResult) results.next();
if (row++ < startrow)
continue;
Attributes attributesRow = resultRow.getAttributes();
NamingEnumeration rowEnum = attributesRow.getIDs();
while (rowEnum.hasMoreElements()) {
int len = qry.addRow();
String name = Caster.toString(rowEnum.next());
Object value = null;
try {
value = attributesRow.get(name).get();
} catch (Exception e) {
}
qry.setAtEL("name", len, name);
qry.setAtEL("value", len, value);
if (maxrows > 0 && len >= maxrows)
break outer;
}
qry.setAtEL("name", qry.size(), "dn");
}
}
} finally {
context.close();
}
// Sort
if (sort != null && sort.length > 0) {
int order = sortDirection == SORT_DIRECTION_ASC ? Query.ORDER_ASC : Query.ORDER_DESC;
for (int i = sort.length - 1; i >= 0; i--) {
String item = sort[i];
if (item.indexOf(' ') != -1)
item = ListUtil.first(item, " ", true);
qry.sort(KeyImpl.getInstance(item), order);
// keys[i] = new SortKey(item);
}
}
return qry;
}
use of lucee.runtime.type.QueryImpl in project Lucee by lucee.
the class AxisCaster method toLuceeType.
public static Object toLuceeType(PageContext pc, String customType, Object value) throws PageException {
pc = ThreadLocalPageContext.get(pc);
if (pc != null && value instanceof Pojo) {
if (!StringUtil.isEmpty(customType)) {
Component cfc = toComponent(pc, (Pojo) value, customType, null);
if (cfc != null)
return cfc;
}
/*
// try package/class name as component name
String compPath=value.getClass().getName();
Component cfc = toComponent(pc, (Pojo)value, compPath, null);
if(cfc!=null) return cfc;
// try class name as component name
compPath=ListUtil.last(compPath, '.');
cfc = toComponent(pc, (Pojo)value, compPath, null);
if(cfc!=null) return cfc;
*/
}
if (value instanceof Date || value instanceof Calendar) {
// do not change to caster.isDate
return Caster.toDate(value, null);
}
if (value instanceof Object[]) {
Object[] arr = (Object[]) value;
if (!ArrayUtil.isEmpty(arr)) {
boolean allTheSame = true;
// byte
if (arr[0] instanceof Byte) {
for (int i = 1; i < arr.length; i++) {
if (!(arr[i] instanceof Byte)) {
allTheSame = false;
break;
}
}
if (allTheSame) {
byte[] bytes = new byte[arr.length];
for (int i = 0; i < arr.length; i++) {
bytes[i] = Caster.toByteValue(arr[i]);
}
return bytes;
}
}
}
}
if (value instanceof Byte[]) {
Byte[] arr = (Byte[]) value;
if (!ArrayUtil.isEmpty(arr)) {
byte[] bytes = new byte[arr.length];
for (int i = 0; i < arr.length; i++) {
bytes[i] = arr[i].byteValue();
}
return bytes;
}
}
if (value instanceof byte[]) {
return value;
}
if (Decision.isArray(value)) {
Array a = Caster.toArray(value);
int len = a.size();
Object o;
String ct;
for (int i = 1; i <= len; i++) {
o = a.get(i, null);
if (o != null) {
ct = customType != null && customType.endsWith("[]") ? customType.substring(0, customType.length() - 2) : null;
a.setEL(i, toLuceeType(pc, ct, o));
}
}
return a;
}
if (value instanceof Map) {
Struct sct = new StructImpl();
Iterator it = ((Map) value).entrySet().iterator();
Map.Entry entry;
while (it.hasNext()) {
entry = (Entry) it.next();
sct.setEL(Caster.toString(entry.getKey()), toLuceeType(pc, null, entry.getValue()));
}
return sct;
// return StructUtil.copyToStruct((Map)value);
}
if (isQueryBean(value)) {
QueryBean qb = (QueryBean) value;
String[] strColumns = qb.getColumnList();
Object[][] data = qb.getData();
int recorcount = data.length;
Query qry = new QueryImpl(strColumns, recorcount, "QueryBean");
QueryColumn[] columns = new QueryColumn[strColumns.length];
for (int i = 0; i < columns.length; i++) {
columns[i] = qry.getColumn(strColumns[i]);
}
int row;
for (row = 1; row <= recorcount; row++) {
for (int i = 0; i < columns.length; i++) {
columns[i].set(row, toLuceeType(pc, null, data[row - 1][i]));
}
}
return qry;
}
if (Decision.isQuery(value)) {
Query q = Caster.toQuery(value);
int recorcount = q.getRecordcount();
String[] strColumns = q.getColumns();
QueryColumn col;
int row;
for (int i = 0; i < strColumns.length; i++) {
col = q.getColumn(strColumns[i]);
for (row = 1; row <= recorcount; row++) {
col.set(row, toLuceeType(pc, null, col.get(row, null)));
}
}
return q;
}
return value;
}
use of lucee.runtime.type.QueryImpl in project Lucee by lucee.
the class Query method executeDatasoure.
private QueryResult executeDatasoure(SQL sql, boolean createUpdateData, TimeZone tz) throws PageException {
DatasourceManagerImpl manager = (DatasourceManagerImpl) pageContext.getDataSourceManager();
DatasourceConnection dc = manager.getConnection(pageContext, datasource, username, password);
try {
if (lazy && !createUpdateData && cachedWithin == null && cachedAfter == null && result == null) {
if (returntype != RETURN_TYPE_QUERY)
throw new DatabaseException("only return type query is allowed when lazy is set to true", null, sql, dc);
return new SimpleQuery(pageContext, dc, sql, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), tz);
}
if (returntype == RETURN_TYPE_ARRAY)
return QueryImpl.toArray(pageContext, dc, sql, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), createUpdateData, true);
if (returntype == RETURN_TYPE_STRUCT) {
if (columnName == null)
throw new ApplicationException("attribute columnKey is required when return type is set to struct");
return QueryImpl.toStruct(pageContext, dc, sql, columnName, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), createUpdateData, true);
}
return new QueryImpl(pageContext, dc, sql, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), createUpdateData, true);
} finally {
manager.releaseConnection(pageContext, dc);
}
}
use of lucee.runtime.type.QueryImpl in project Lucee by lucee.
the class Search method doStartTag.
@Override
public int doStartTag() throws PageException {
// SerialNumber sn = pageContext.getConfig().getSerialNumber();
// if(sn.getVersion()==SerialNumber.VERSION_COMMUNITY)
// throw new SecurityException("no access to this functionality with the "+sn.getStringVersion()+" version of Lucee");
final String v = "VARCHAR", d = "DOUBLE";
String[] cols = new String[] { "title", "url", "summary", "score", "recordssearched", "key", "custom1", "custom2", "custom3", "custom4", "categoryTree", "category", "context", "size", "rank", "author", "type", "collection" };
// TODO support context
String[] types = new String[] { v, v, v, d, d, v, v, v, v, v, v, v, v, d, d, v, v, v };
SearchData data = pageContext.getConfig().getSearchEngine(pageContext).createSearchData(suggestions);
// this is already here to make sure the classloader load this sinstance
SuggestionItem item = null;
lucee.runtime.type.Query qry = new QueryImpl(cols, types, 0, "query");
SearchCollection collection;
long time = System.currentTimeMillis();
AddionalAttrs.setAddionalAttrs(contextBytes, contextPassages, contextHighlightBegin, contextHighlightEnd);
try {
for (int i = 0; i < collections.length; i++) {
collection = collections[i];
startrow = collection.search(data, qry, criteria, collection.getLanguage(), type, startrow, maxrows, categoryTree, category);
if (maxrows >= 0 && qry.getRecordcount() >= maxrows)
break;
}
pageContext.setVariable(name, qry);
} catch (SearchException se) {
throw Caster.toPageException(se);
} finally {
AddionalAttrs.removeAddionalAttrs();
}
time = System.currentTimeMillis() - time;
Double recSearched = new Double(data.getRecordsSearched());
int len = qry.getRecordcount();
for (int i = 1; i <= len; i++) {
qry.setAt("recordssearched", i, recSearched);
}
// status
if (status != null) {
Struct sct = new StructImpl();
pageContext.setVariable(status, sct);
sct.set(FOUND, new Double(qry.getRecordcount()));
sct.set(SEARCHED, recSearched);
sct.set(KeyConstants._time, new Double(time));
// TODO impl this values
Map s = data.getSuggestion();
if (s.size() > 0) {
String key;
Iterator it = s.keySet().iterator();
Struct keywords = new StructImpl();
Struct keywordScore = new StructImpl();
sct.set(KEYWORDS, keywords);
sct.set(KEYWORD_SCORE, keywordScore);
Object obj;
while (it.hasNext()) {
key = (String) it.next();
// the problem is a conflict between the SuggestionItem version from core and extension
obj = s.get(key);
if (obj instanceof SuggestionItem) {
item = (SuggestionItem) obj;
keywords.set(key, item.getKeywords());
keywordScore.set(key, item.getKeywordScore());
} else {
Class clazz = obj.getClass();
try {
keywords.set(key, clazz.getMethod("getKeywords", new Class[0]).invoke(obj, new Object[0]));
keywordScore.set(key, clazz.getMethod("getKeywordScore", new Class[0]).invoke(obj, new Object[0]));
} catch (Exception e) {
}
}
}
String query = data.getSuggestionQuery();
if (query != null) {
String html = StringUtil.replace(query, "<suggestion>", "<b>", false);
html = StringUtil.replace(html, "</suggestion>", "</b>", false);
sct.set("suggestedQueryHTML", html);
String plain = StringUtil.replace(query, "<suggestion>", "", false);
plain = StringUtil.replace(plain, "</suggestion>", "", false);
sct.set("suggestedQuery", plain);
}
}
// if(suggestions!=SUGGESTIONS_NEVER)sct.set("suggestedQuery", "");
// sct.set("keywords", "");
// sct.set("keywordScore", "");
}
return SKIP_BODY;
}
use of lucee.runtime.type.QueryImpl in project Lucee by lucee.
the class StoredProc method doEndTag.
@Override
public int doEndTag() throws PageException {
long startNS = System.nanoTime();
Object ds = datasource;
if (StringUtil.isEmpty(datasource)) {
ds = pageContext.getApplicationContext().getDefDataSource();
if (StringUtil.isEmpty(ds)) {
boolean isCFML = pageContext.getRequestDialect() == CFMLEngine.DIALECT_CFML;
throw new ApplicationException("attribute [datasource] is required, when 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\";)");
}
}
Struct res = new StructImpl();
DataSourceManager manager = pageContext.getDataSourceManager();
DatasourceConnection dc = ds instanceof DataSource ? manager.getConnection(pageContext, (DataSource) ds, username, password) : manager.getConnection(pageContext, Caster.toString(ds), username, password);
// create returnValue
returnValue(dc);
String sql = createSQL();
// add returnValue to params
if (returnValue != null) {
params.add(0, returnValue);
}
Log log = pageContext.getConfig().getLog("datasource");
SQLImpl _sql = new SQLImpl(sql);
CallableStatement callStat = null;
try {
if (// log entry added to troubleshoot LDEV-1147
log.getLogLevel() >= Log.LEVEL_DEBUG)
log.debug("LDEV1147", sql + " [" + params.size() + " params]");
callStat = dc.getConnection().prepareCall(sql);
if (blockfactor > 0)
callStat.setFetchSize(blockfactor);
if (timeout > 0)
DataSourceUtil.setQueryTimeoutSilent(callStat, timeout);
// set IN register OUT
Iterator<ProcParamBean> it = params.iterator();
ProcParamBean param;
int index = 1;
while (it.hasNext()) {
param = it.next();
param.setIndex(index);
_sql.addItems(new SQLItemImpl(param.getValue()));
if (param.getDirection() != ProcParamBean.DIRECTION_OUT) {
SQLCaster.setValue(pageContext, pageContext.getTimeZone(), callStat, index, param);
}
if (param.getDirection() != ProcParamBean.DIRECTION_IN) {
registerOutParameter(callStat, param);
}
index++;
}
String dsn = (ds instanceof DataSource) ? ((DataSource) ds).getName() : Caster.toString(ds);
// cache
boolean isFromCache = false;
Object cacheValue = null;
boolean useCache = (cachedWithin != null) || (cachedafter != null);
String cacheId = null;
CacheHandler cacheHandler = null;
if (useCache) {
cacheId = CacheHandlerCollectionImpl.createId(_sql, dsn, username, password, Query.RETURN_TYPE_STORED_PROC);
cacheHandler = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null).getInstanceMatchingObject(cachedWithin, null);
if (cacheHandler instanceof CacheHandlerPro) {
CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, cachedWithin);
if (cacheItem != null)
cacheValue = ((StoredProcCacheItem) cacheItem).getStruct();
} else if (cacheHandler != null) {
// TODO this else block can be removed when all cache handlers implement CacheHandlerPro
CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);
if (cacheItem != null)
cacheValue = ((StoredProcCacheItem) cacheItem).getStruct();
// cacheValue = pageContext.getQueryCache().get(pageContext,_sql,dsn,username,password,cachedafter);
}
}
int count = 0;
long start = System.currentTimeMillis();
if (cacheValue == null) {
// execute
boolean isResult = callStat.execute();
Struct cacheStruct = useCache ? new StructImpl() : null;
// resultsets
ProcResultBean result;
index = 1;
do {
if (isResult) {
ResultSet rs = callStat.getResultSet();
if (rs != null) {
try {
result = (ProcResultBean) results.get(index++, null);
if (result != null) {
lucee.runtime.type.Query q = new QueryImpl(rs, result.getMaxrows(), result.getName(), pageContext.getTimeZone());
count += q.getRecordcount();
setVariable(result.getName(), q);
if (useCache)
cacheStruct.set(KeyImpl.getInstance(result.getName()), q);
}
} finally {
IOUtil.closeEL(rs);
}
}
}
} while ((isResult = callStat.getMoreResults()) || (callStat.getUpdateCount() != -1));
// params
it = params.iterator();
while (it.hasNext()) {
param = it.next();
if (param.getDirection() != ProcParamBean.DIRECTION_IN) {
Object value = null;
if (!StringUtil.isEmpty(param.getVariable())) {
try {
value = SQLCaster.toCFType(callStat.getObject(param.getIndex()));
} catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
value = emptyIfNull(value);
if (param == STATUS_CODE)
res.set(STATUSCODE, value);
else
setVariable(param.getVariable(), value);
if (useCache)
cacheStruct.set(KeyImpl.getInstance(param.getVariable()), value);
}
}
}
if (cacheHandler != null) {
cacheStruct.set(COUNT, Caster.toDouble(count));
cacheHandler.set(pageContext, cacheId, cachedWithin, new StoredProcCacheItem(cacheStruct, procedure, System.currentTimeMillis() - start));
// pageContext.getQueryCache().set(pageContext,_sql,dsn,username,password,cache,cachedbefore);
}
} else if (cacheValue instanceof Struct) {
Struct sctCache = (Struct) cacheValue;
count = Caster.toIntValue(sctCache.removeEL(COUNT), 0);
Iterator<Entry<Key, Object>> cit = sctCache.entryIterator();
Entry<Key, Object> ce;
while (cit.hasNext()) {
ce = cit.next();
if (STATUS_CODE.getVariable().equals(ce.getKey().getString()))
res.set(KEY_SC, ce.getValue());
else
setVariable(ce.getKey().getString(), ce.getValue());
}
isFromCache = true;
}
// result
long exe;
setVariable(this.result, res);
res.set(KeyConstants._executionTime, Caster.toDouble(exe = (System.nanoTime() - startNS)));
res.set(KeyConstants._cached, Caster.toBoolean(isFromCache));
if (pageContext.getConfig().debug() && debug) {
boolean logdb = ((ConfigImpl) pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE);
if (logdb)
pageContext.getDebugger().addQuery(null, dsn, procedure, _sql, count, pageContext.getCurrentPageSource(), (int) exe);
}
// log
if (log.getLogLevel() >= Log.LEVEL_INFO) {
log.info(StoredProc.class.getSimpleName(), "executed [" + sql.trim() + "] in " + DecimalFormat.call(pageContext, exe / 1000000D) + " ms");
}
} catch (SQLException e) {
// log
log.error(StoredProc.class.getSimpleName(), e);
throw new DatabaseException(e, new SQLImpl(sql), dc);
} catch (PageException pe) {
// log
log.error(StoredProc.class.getSimpleName(), pe);
throw pe;
} finally {
if (callStat != null) {
try {
callStat.close();
} catch (SQLException e) {
}
}
manager.releaseConnection(pageContext, dc);
}
return EVAL_PAGE;
}
Aggregations