use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class CouchbaseEntryManager method countEntries.
@Override
public <T> int countEntries(String baseDN, Class<T> entryClass, Filter filter, SearchScope scope) {
if (StringHelper.isEmptyString(baseDN)) {
throw new MappingException("Base DN to find entries is null");
}
// Check entry class
checkEntryClass(entryClass, false);
String[] objectClasses = getTypeObjectClasses(entryClass);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
// Find entries
Filter searchFilter;
if (objectClasses.length > 0) {
searchFilter = addObjectClassFilter(filter, objectClasses);
} else {
searchFilter = filter;
}
// Prepare properties types to allow build filter properly
Map<String, PropertyAnnotation> propertiesAnnotationsMap = prepareEntryPropertiesTypes(entryClass, propertiesAnnotations);
ConvertedExpression convertedExpression;
try {
convertedExpression = toCouchbaseFilter(searchFilter, propertiesAnnotationsMap);
} catch (SearchException ex) {
throw new EntryPersistenceException(String.format("Failed to convert filter %s to expression", searchFilter));
}
PagedResult<JsonObject> searchResult;
try {
searchResult = searchImpl(toCouchbaseKey(baseDN).getKey(), getScanConsistency(convertedExpression), convertedExpression.expression(), scope, null, null, null, SearchReturnDataType.COUNT, 0, 0, 0);
} catch (Exception ex) {
throw new EntryPersistenceException(String.format("Failed to calculate the number of entries with baseDN: %s, filter: %s", baseDN, searchFilter), ex);
}
return searchResult.getTotalEntriesCount();
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class CouchbaseEntryManager method authenticate.
@Override
public <T> boolean authenticate(String baseDN, Class<T> entryClass, String userName, String password) {
if (StringHelper.isEmptyString(baseDN)) {
throw new MappingException("Base DN to find entries is null");
}
// Check entry class
checkEntryClass(entryClass, false);
String[] objectClasses = getTypeObjectClasses(entryClass);
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
// Find entries
Filter searchFilter = Filter.createEqualityFilter(Filter.createLowercaseFilter(CouchbaseOperationService.UID), StringHelper.toLowerCase(userName));
if (objectClasses.length > 0) {
searchFilter = addObjectClassFilter(searchFilter, objectClasses);
}
// Prepare properties types to allow build filter properly
Map<String, PropertyAnnotation> propertiesAnnotationsMap = prepareEntryPropertiesTypes(entryClass, propertiesAnnotations);
ConvertedExpression convertedExpression;
try {
convertedExpression = toCouchbaseFilter(searchFilter, propertiesAnnotationsMap);
} catch (SearchException ex) {
throw new EntryPersistenceException(String.format("Failed to convert filter %s to expression", searchFilter));
}
try {
PagedResult<JsonObject> searchResult = searchImpl(toCouchbaseKey(baseDN).getKey(), getScanConsistency(convertedExpression), convertedExpression.expression(), SearchScope.SUB, CouchbaseOperationService.UID_ARRAY, null, null, SearchReturnDataType.SEARCH, 0, 1, 1);
if ((searchResult == null) || (searchResult.getEntriesCount() != 1)) {
return false;
}
String bindDn = searchResult.getEntries().get(0).getString(CouchbaseOperationService.DN);
return authenticate(bindDn, password);
} catch (SearchException ex) {
throw new AuthenticationException(String.format("Failed to find user DN: %s", userName), ex);
} catch (Exception ex) {
throw new AuthenticationException(String.format("Failed to authenticate user: %s", userName), ex);
}
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class CouchbaseEntryManager method removeImpl.
protected <T> int removeImpl(String dn, Class<T> entryClass, Filter filter, int count) {
// Check entry class
checkEntryClass(entryClass, false);
String[] objectClasses = getTypeObjectClasses(entryClass);
Filter searchFilter;
if (objectClasses.length > 0) {
LOG.trace("Filter: {}", filter);
searchFilter = addObjectClassFilter(filter, objectClasses);
} else {
searchFilter = filter;
}
// Find entries
LOG.trace("-------------------------------------------------------");
LOG.trace("Filter: {}", filter);
LOG.trace("objectClasses count: {} ", objectClasses.length);
LOG.trace("objectClasses: {}", objectClasses.toString());
LOG.trace("Search filter: {}", searchFilter);
// Prepare properties types to allow build filter properly
List<PropertyAnnotation> propertiesAnnotations = getEntryPropertyAnnotations(entryClass);
Map<String, PropertyAnnotation> propertiesAnnotationsMap = prepareEntryPropertiesTypes(entryClass, propertiesAnnotations);
ParsedKey keyWithInum = toCouchbaseKey(dn);
ConvertedExpression convertedExpression;
try {
convertedExpression = toCouchbaseFilter(searchFilter, propertiesAnnotationsMap);
} catch (SearchException ex) {
throw new EntryDeleteException(String.format("Failed to convert filter %s to expression", searchFilter), ex);
}
try {
int processed = getOperationService().delete(keyWithInum.getKey(), getScanConsistency(convertedExpression), convertedExpression.expression(), count);
return processed;
} catch (Exception ex) {
throw new EntryDeleteException(String.format("Failed to delete entries with key: %s, expression: %s", keyWithInum.getKey(), convertedExpression), ex);
}
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class CouchbaseFilterConverter method convertToCouchbaseFilter.
public ConvertedExpression convertToCouchbaseFilter(Filter genericFilter, Map<String, PropertyAnnotation> propertiesAnnotationsMap, Function<? super Filter, Boolean> processor) throws SearchException {
Filter currentGenericFilter = genericFilter;
FilterType type = currentGenericFilter.getType();
if (FilterType.RAW == type) {
LOG.warn("RAW Ldap filter to Couchbase convertion will be removed in new version!!!");
currentGenericFilter = ldapFilterConverter.convertRawLdapFilterToFilter(currentGenericFilter.getFilterString());
type = currentGenericFilter.getType();
}
boolean requiredConsistency = isRequiredConsistency(currentGenericFilter, propertiesAnnotationsMap);
if (processor != null) {
processor.apply(currentGenericFilter);
}
if ((FilterType.NOT == type) || (FilterType.AND == type) || (FilterType.OR == type)) {
Filter[] genericFilters = currentGenericFilter.getFilters();
ConvertedExpression[] expFilters = new ConvertedExpression[genericFilters.length];
if (genericFilters != null) {
// We can replace only multiple OR with IN
boolean canJoinOrFilters = FilterType.OR == type;
List<Filter> joinOrFilters = new ArrayList<Filter>();
String joinOrAttributeName = null;
for (int i = 0; i < genericFilters.length; i++) {
Filter tmpFilter = genericFilters[i];
expFilters[i] = convertToCouchbaseFilter(tmpFilter, propertiesAnnotationsMap, processor);
// Check if we can replace OR with IN
if (!canJoinOrFilters) {
continue;
}
if (tmpFilter.getMultiValued() != null) {
canJoinOrFilters = false;
continue;
}
if ((FilterType.EQUALITY != tmpFilter.getType()) || (tmpFilter.getFilters() != null)) {
canJoinOrFilters = false;
continue;
}
Boolean isMultiValuedDetected = determineMultiValuedByType(tmpFilter.getAttributeName(), propertiesAnnotationsMap);
if (!Boolean.FALSE.equals(isMultiValuedDetected) && !Boolean.FALSE.equals(currentGenericFilter.getMultiValued())) {
canJoinOrFilters = false;
continue;
}
if (joinOrAttributeName == null) {
joinOrAttributeName = tmpFilter.getAttributeName();
joinOrFilters.add(tmpFilter);
continue;
}
if (!joinOrAttributeName.equals(tmpFilter.getAttributeName())) {
canJoinOrFilters = false;
continue;
}
joinOrFilters.add(tmpFilter);
}
if (FilterType.NOT == type) {
return ConvertedExpression.build(Expression.par(expFilters[0].expression().not()), expFilters[0].consistency());
} else if (FilterType.AND == type) {
for (int i = 0; i < expFilters.length; i++) {
requiredConsistency |= expFilters[i].consistency();
}
Expression result = expFilters[0].expression();
for (int i = 1; i < expFilters.length; i++) {
result = result.and(expFilters[i].expression());
}
return ConvertedExpression.build(Expression.par(result), requiredConsistency);
} else if (FilterType.OR == type) {
for (int i = 0; i < expFilters.length; i++) {
requiredConsistency |= expFilters[i].consistency();
}
if (canJoinOrFilters) {
JsonArray jsonArrayValues = JsonArray.create();
Filter lastEqFilter = null;
for (Filter eqFilter : joinOrFilters) {
lastEqFilter = eqFilter;
jsonArrayValues.add(eqFilter.getAssertionValue());
}
Expression exp = Expression.par(buildPath(lastEqFilter, propertiesAnnotationsMap, processor).getFirst().in(jsonArrayValues));
return ConvertedExpression.build(exp, requiredConsistency);
} else {
Expression result = expFilters[0].expression();
for (int i = 1; i < expFilters.length; i++) {
result = result.or(expFilters[i].expression());
}
return ConvertedExpression.build(Expression.par(result), requiredConsistency);
}
}
}
}
if (FilterType.EQUALITY == type) {
boolean hasSubFilters = ArrayHelper.isNotEmpty(currentGenericFilter.getFilters());
Boolean isMultiValuedDetected = determineMultiValuedByType(currentGenericFilter.getAttributeName(), propertiesAnnotationsMap);
String internalAttribute = toInternalAttribute(currentGenericFilter);
Pair<Expression, Expression> pairExpression = buildPath(currentGenericFilter, propertiesAnnotationsMap, processor);
if (Boolean.TRUE.equals(currentGenericFilter.getMultiValued()) || Boolean.TRUE.equals(isMultiValuedDetected)) {
return ConvertedExpression.build(Collections.anyIn(internalAttribute + "_", pairExpression.getFirst()).satisfies(pairExpression.getSecond().eq(buildTypedExpression(currentGenericFilter))), requiredConsistency);
} else if (Boolean.FALSE.equals(currentGenericFilter.getMultiValued()) || Boolean.FALSE.equals(isMultiValuedDetected) || (hasSubFilters && (isMultiValuedDetected == null))) {
return ConvertedExpression.build(pairExpression.getSecond().eq(buildTypedExpression(currentGenericFilter)), requiredConsistency);
} else {
Expression nameExpression = pairExpression.getSecond();
Expression exp1 = Expression.par(Expression.path(nameExpression).eq(buildTypedExpression(currentGenericFilter)));
Expression exp2 = Expression.par(Expression.path(buildTypedExpression(currentGenericFilter)).in(nameExpression));
return ConvertedExpression.build(Expression.par(exp1.or(exp2)), requiredConsistency);
}
}
if (FilterType.LESS_OR_EQUAL == type) {
String internalAttribute = toInternalAttribute(currentGenericFilter);
Pair<Expression, Expression> pairExpression = buildPath(currentGenericFilter, propertiesAnnotationsMap, processor);
if (isMultiValue(currentGenericFilter, propertiesAnnotationsMap)) {
return ConvertedExpression.build(Collections.anyIn(internalAttribute + "_", pairExpression.getFirst()).satisfies(pairExpression.getSecond().lte(buildTypedExpression(currentGenericFilter))), requiredConsistency);
} else {
return ConvertedExpression.build(pairExpression.getSecond().lte(buildTypedExpression(currentGenericFilter)), requiredConsistency);
}
}
if (FilterType.GREATER_OR_EQUAL == type) {
String internalAttribute = toInternalAttribute(currentGenericFilter);
Pair<Expression, Expression> pairExpression = buildPath(currentGenericFilter, propertiesAnnotationsMap, processor);
if (isMultiValue(currentGenericFilter, propertiesAnnotationsMap)) {
return ConvertedExpression.build(Collections.anyIn(internalAttribute + "_", pairExpression.getFirst()).satisfies(pairExpression.getSecond().gte(buildTypedExpression(currentGenericFilter))), requiredConsistency);
} else {
return ConvertedExpression.build(pairExpression.getSecond().gte(buildTypedExpression(currentGenericFilter)), requiredConsistency);
}
}
if (FilterType.PRESENCE == type) {
String internalAttribute = toInternalAttribute(currentGenericFilter);
Pair<Expression, Expression> pairExpression = buildPath(currentGenericFilter, propertiesAnnotationsMap, processor);
if (isMultiValue(currentGenericFilter, propertiesAnnotationsMap)) {
return ConvertedExpression.build(Collections.anyIn(internalAttribute + "_", pairExpression.getFirst()).satisfies(pairExpression.getSecond().isNotMissing()), requiredConsistency);
} else {
return ConvertedExpression.build(pairExpression.getSecond().isNotMissing(), requiredConsistency);
}
}
if (FilterType.APPROXIMATE_MATCH == type) {
throw new SearchException("Convertion from APPROXIMATE_MATCH LDAP filter to Couchbase filter is not implemented");
}
if (FilterType.SUBSTRING == type) {
StringBuilder like = new StringBuilder();
if (currentGenericFilter.getSubInitial() != null) {
like.append(currentGenericFilter.getSubInitial());
}
like.append("%");
String[] subAny = currentGenericFilter.getSubAny();
if ((subAny != null) && (subAny.length > 0)) {
for (String any : subAny) {
like.append(any);
like.append("%");
}
}
if (currentGenericFilter.getSubFinal() != null) {
like.append(currentGenericFilter.getSubFinal());
}
String internalAttribute = toInternalAttribute(currentGenericFilter);
Pair<Expression, Expression> pairExpression = buildPath(currentGenericFilter, propertiesAnnotationsMap, processor);
if (isMultiValue(currentGenericFilter, propertiesAnnotationsMap)) {
return ConvertedExpression.build(Collections.anyIn(internalAttribute + "_", pairExpression.getFirst()).satisfies(pairExpression.getSecond().like(Expression.s(escapeValue(like.toString())))), requiredConsistency);
} else {
return ConvertedExpression.build(pairExpression.getSecond().like(Expression.s(escapeValue(like.toString()))), requiredConsistency);
}
}
if (FilterType.LOWERCASE == type) {
return ConvertedExpression.build(StringFunctions.lower(currentGenericFilter.getAttributeName()), requiredConsistency);
}
throw new SearchException(String.format("Unknown filter type '%s'", type));
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class SqlOperationServiceImpl method searchImpl.
private <O> PagedResult<EntryData> searchImpl(TableMapping tableMapping, String key, ConvertedExpression expression, SearchScope scope, String[] attributes, OrderSpecifier<?>[] orderBy, SqlBatchOperationWraper<O> batchOperationWraper, SearchReturnDataType returnDataType, int start, int count, int pageSize) throws SearchException {
BatchOperation<O> batchOperation = null;
if (batchOperationWraper != null) {
batchOperation = (BatchOperation<O>) batchOperationWraper.getBatchOperation();
}
RelationalPathBase<Object> tableRelationalPath = buildTableRelationalPath(tableMapping);
Expression<?> attributesExp = buildSelectAttributes(attributes);
SQLQuery<?> sqlSelectQuery;
if (expression == null) {
sqlSelectQuery = sqlQueryFactory.select(attributesExp).from(tableRelationalPath);
} else {
Predicate whereExp = (Predicate) expression.expression();
sqlSelectQuery = sqlQueryFactory.select(attributesExp).from(tableRelationalPath).where(whereExp);
}
SQLQuery<?> baseQuery = sqlSelectQuery;
if (orderBy != null) {
baseQuery = sqlSelectQuery.orderBy(orderBy);
}
List<EntryData> searchResultList = new LinkedList<EntryData>();
String queryStr = null;
if ((SearchReturnDataType.SEARCH == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) {
List<EntryData> lastResult = null;
if (pageSize > 0) {
boolean collectSearchResult;
SQLQuery<?> query;
int currentLimit;
try {
int resultCount = 0;
int lastCountRows = 0;
do {
collectSearchResult = true;
currentLimit = pageSize;
if (count > 0) {
currentLimit = Math.min(pageSize, count - resultCount);
}
query = baseQuery.limit(currentLimit).offset(start + resultCount);
queryStr = query.getSQL().getSQL();
LOG.debug("Executing query: '" + queryStr + "'");
try (ResultSet resultSet = query.getResults()) {
lastResult = getEntryDataList(tableMapping, resultSet);
}
lastCountRows = lastResult.size();
if (batchOperation != null) {
collectSearchResult = batchOperation.collectSearchResult(lastCountRows);
}
if (collectSearchResult) {
searchResultList.addAll(lastResult);
}
if (batchOperation != null) {
List<O> entries = batchOperationWraper.createEntities(lastResult);
batchOperation.performAction(entries);
}
resultCount += lastCountRows;
if (((count > 0) && (resultCount >= count)) || (lastCountRows < currentLimit)) {
break;
}
} while (lastCountRows > 0);
} catch (QueryException ex) {
throw new SearchException(String.format("Failed to build search entries query. Key: '%s', expression: '%s'", key, expression.expression()), ex);
} catch (SQLException | EntryConvertationException ex) {
throw new SearchException(String.format("Failed to execute query '%s' with key: '%s'", queryStr, key), ex);
}
} else {
try {
SQLQuery<?> query = baseQuery;
if (count > 0) {
query = query.limit(count);
}
if (start > 0) {
query = query.offset(start);
}
queryStr = query.getSQL().getSQL();
LOG.debug("Execution query: '" + queryStr + "'");
try (ResultSet resultSet = query.getResults()) {
lastResult = getEntryDataList(tableMapping, resultSet);
searchResultList.addAll(lastResult);
}
} catch (QueryException ex) {
String sqlExpression = queryStr;
if (StringHelper.isNotEmpty(sqlExpression)) {
sqlExpression = expression.expression().toString();
}
throw new SearchException(String.format("Failed to build search entries query. Key: '%s', expression: '%s'", key, sqlExpression), ex);
} catch (SQLException | EntryConvertationException ex) {
throw new SearchException("Failed to search entries. Query: '" + queryStr + "'", ex);
}
}
}
PagedResult<EntryData> result = new PagedResult<EntryData>();
result.setEntries(searchResultList);
result.setEntriesCount(searchResultList.size());
result.setStart(start);
if ((SearchReturnDataType.COUNT == returnDataType) || (SearchReturnDataType.SEARCH_COUNT == returnDataType)) {
SQLQuery<?> sqlCountSelectQuery;
if (expression == null) {
sqlCountSelectQuery = sqlQueryFactory.select(Expressions.as(ExpressionUtils.count(Wildcard.all), "TOTAL")).from(tableRelationalPath);
} else {
Predicate whereExp = (Predicate) expression.expression();
sqlCountSelectQuery = sqlQueryFactory.select(Expressions.as(ExpressionUtils.count(Wildcard.all), "TOTAL")).from(tableRelationalPath).where(whereExp);
}
try {
queryStr = sqlCountSelectQuery.getSQL().getSQL();
LOG.debug("Calculating count. Execution query: '" + queryStr + "'");
try (ResultSet countResult = sqlCountSelectQuery.getResults()) {
if (!countResult.next()) {
throw new SearchException("Failed to calculate count entries. Query: '" + queryStr + "'");
}
result.setTotalEntriesCount(countResult.getInt("TOTAL"));
}
} catch (QueryException ex) {
throw new SearchException(String.format("Failed to build count search entries query. Key: '%s', expression: '%s'", key, expression.expression()), ex);
} catch (SQLException ex) {
throw new SearchException("Failed to calculate count entries. Query: '" + queryStr + "'", ex);
}
}
return result;
}
Aggregations