use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class SpannerFilterConverter method convertToSqlFilterImpl.
private ConvertedExpression convertToSqlFilterImpl(TableMapping tableMapping, Filter genericFilter, Map<String, PropertyAnnotation> propertiesAnnotationsMap, Map<String, ValueWithStructField> queryParameters, Map<String, Join> joinTables, Function<? super Filter, Boolean> processor, boolean skipAlias) throws SearchException {
if (genericFilter == null) {
return null;
}
Filter currentGenericFilter = genericFilter;
FilterType type = currentGenericFilter.getType();
if (FilterType.RAW == type) {
LOG.warn("RAW Ldap filter to SQL convertion will be removed in new version!!!");
currentGenericFilter = ldapFilterConverter.convertRawLdapFilterToFilter(currentGenericFilter.getFilterString());
LOG.debug(String.format("Converted RAW filter: %s", currentGenericFilter));
type = currentGenericFilter.getType();
}
if (processor != null) {
processor.apply(currentGenericFilter);
}
if ((FilterType.NOT == type) || (FilterType.AND == type) || (FilterType.OR == type)) {
Filter[] genericFilters = currentGenericFilter.getFilters();
Expression[] expFilters = new Expression[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] = convertToSqlFilterImpl(tableMapping, tmpFilter, propertiesAnnotationsMap, queryParameters, joinTables, processor, skipAlias).expression();
// 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)) {
if (!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(new NotExpression(expFilters[0]), queryParameters, joinTables);
} else if (FilterType.AND == type) {
Expression result = expFilters[0];
for (int i = 1; i < expFilters.length; i++) {
result = new AndExpression(result, expFilters[i]);
}
return ConvertedExpression.build(new Parenthesis(result), queryParameters, joinTables);
} else if (FilterType.OR == type) {
if (canJoinOrFilters) {
ExpressionList expressionList = new ExpressionList();
for (Expression expFilter : expFilters) {
expressionList.addExpressions(((EqualsTo) expFilter).getRightExpression());
}
Expression inExpression = new InExpression(buildExpression(tableMapping, joinOrFilters.get(0), false, false, propertiesAnnotationsMap, queryParameters, joinTables, processor, skipAlias), expressionList);
return ConvertedExpression.build(inExpression, queryParameters, joinTables);
} else {
Expression result = expFilters[0];
for (int i = 1; i < expFilters.length; i++) {
result = new OrExpression(result, expFilters[i]);
}
return ConvertedExpression.build(new Parenthesis(result), queryParameters, joinTables);
}
}
}
}
// Generic part for rest of expression types
String internalAttribute = toInternalAttribute(currentGenericFilter);
boolean multiValued = isMultiValue(tableMapping, internalAttribute, currentGenericFilter, propertiesAnnotationsMap);
boolean hasChildTableForAttribute = tableMapping.hasChildTableForAttribute(internalAttribute.toLowerCase());
Expression leftExpression = buildExpression(tableMapping, currentGenericFilter, multiValued, !hasChildTableForAttribute, propertiesAnnotationsMap, queryParameters, joinTables, processor, skipAlias);
if (FilterType.EQUALITY == type) {
Expression variableExpression = buildVariableExpression(tableMapping, internalAttribute, currentGenericFilter.getAssertionValue(), queryParameters);
Expression expression = new EqualsTo(leftExpression, variableExpression);
if (multiValued) {
if (hasChildTableForAttribute) {
// JOIN jansClnt_Interleave_jansRedirectURI jansRedirectURI ON doc.doc_id = jansRedirectURI.doc_id
// WHERE jansRedirectURI.jansRedirectURI = '10'
addJoinTable(tableMapping, internalAttribute, joinTables);
} else {
// EXISTS (SELECT _jansRedirectURI FROM UNNEST(doc.jansRedirectURI) _jansRedirectURI WHERE _jansRedirectURI = '10')
expression = buildExistsInArrayExpression(internalAttribute, expression);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
if (FilterType.LESS_OR_EQUAL == type) {
Expression variableExpression = buildVariableExpression(tableMapping, internalAttribute, currentGenericFilter.getAssertionValue(), queryParameters);
Expression expression = new MinorThanEquals().withLeftExpression(leftExpression).withRightExpression(variableExpression);
if (multiValued) {
if (hasChildTableForAttribute) {
addJoinTable(tableMapping, internalAttribute, joinTables);
} else {
expression = buildExistsInArrayExpression(internalAttribute, expression);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
if (FilterType.GREATER_OR_EQUAL == type) {
Expression variableExpression = buildVariableExpression(tableMapping, internalAttribute, currentGenericFilter.getAssertionValue(), queryParameters);
Expression expression = new GreaterThanEquals().withLeftExpression(leftExpression).withRightExpression(variableExpression);
if (multiValued) {
if (hasChildTableForAttribute) {
addJoinTable(tableMapping, internalAttribute, joinTables);
} else {
expression = buildExistsInArrayExpression(internalAttribute, expression);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
if (FilterType.PRESENCE == type) {
Expression expression = new IsNullExpression().withLeftExpression(leftExpression).withNot(true);
if (multiValued) {
if (hasChildTableForAttribute) {
addJoinTable(tableMapping, internalAttribute, joinTables);
} else {
expression = buildExistsInArrayExpression(internalAttribute, expression);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
if (FilterType.APPROXIMATE_MATCH == type) {
throw new SearchException("Convertion from APPROXIMATE_MATCH LDAP filter to SQL 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 likeValue = like.toString();
Expression variableExpression = buildVariableExpression(tableMapping, internalAttribute, likeValue, queryParameters);
Expression expression = new LikeExpression().withLeftExpression(leftExpression).withRightExpression(variableExpression);
if (multiValued) {
if (hasChildTableForAttribute) {
addJoinTable(tableMapping, internalAttribute, joinTables);
} else {
expression = buildExistsInArrayExpression(internalAttribute, expression);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
return ConvertedExpression.build(expression, queryParameters, joinTables);
}
if (FilterType.LOWERCASE == type) {
net.sf.jsqlparser.expression.Function lowerFunction = new net.sf.jsqlparser.expression.Function();
lowerFunction.setName("LOWER");
lowerFunction.setParameters(new ExpressionList(leftExpression));
return ConvertedExpression.build(lowerFunction, queryParameters, joinTables);
}
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 LdapEntryManager method removeSubtreeThroughIteration.
private void removeSubtreeThroughIteration(String dn) {
SearchScope scope = SearchScope.SUB;
SearchResult searchResult = null;
try {
searchResult = getOperationService().search(dn, toLdapFilter(Filter.createPresenceFilter("objectClass")), toLdapSearchScope(scope), null, 0, 0, 0, null, "dn");
if (!ResultCode.SUCCESS.equals(searchResult.getResultCode())) {
throw new EntryPersistenceException(String.format("Failed to find sub-entries of entry '%s' for removal", dn));
}
} catch (SearchScopeException ex) {
throw new AuthenticationException(String.format("Failed to convert scope: %s", scope), ex);
} catch (SearchException ex) {
throw new EntryDeleteException(String.format("Failed to find sub-entries of entry '%s' for removal", dn), ex);
}
List<String> removeEntriesDn = new ArrayList<String>(searchResult.getEntryCount());
for (SearchResultEntry searchResultEntry : searchResult.getSearchEntries()) {
removeEntriesDn.add(searchResultEntry.getDN());
}
Collections.sort(removeEntriesDn, LINE_LENGHT_COMPARATOR);
for (String removeEntryDn : removeEntriesDn) {
remove(removeEntryDn);
}
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class LdapOperationServiceImpl method searchImpl.
private <T> SearchResult searchImpl(String dn, Filter filter, SearchScope scope, LdapBatchOperationWraper<T> batchOperationWraper, int start, int searchLimit, int count, Control[] controls, String... attributes) throws SearchException {
SearchRequest searchRequest;
BatchOperation<T> ldapBatchOperation = null;
if (batchOperationWraper != null) {
ldapBatchOperation = (BatchOperation<T>) batchOperationWraper.getBatchOperation();
}
if (LOG.isTraceEnabled()) {
// Find whole tree search. This can be very slow
if (StringHelper.equalsIgnoreCase(dn, "o=jans")) {
LOG.trace("Search in whole LDAP tree", new Exception());
}
}
if (attributes == null) {
searchRequest = new SearchRequest(dn, scope, filter);
} else {
searchRequest = new SearchRequest(dn, scope, filter, attributes);
}
boolean useSizeLimit = count > 0;
if (useSizeLimit) {
// Use paged result to limit search
searchLimit = count;
}
SearchResult searchResult = null;
List<SearchResult> searchResultList = new ArrayList<SearchResult>();
List<SearchResultEntry> searchResultEntries = new ArrayList<SearchResultEntry>();
List<SearchResultReference> searchResultReferences = new ArrayList<SearchResultReference>();
if ((searchLimit > 0) || (start > 0)) {
if (searchLimit == 0) {
// Default page size
searchLimit = 100;
}
boolean collectSearchResult;
LDAPConnection ldapConnection = null;
try {
ldapConnection = getConnectionPool().getConnection();
ASN1OctetString cookie = null;
SimplePagedResponse simplePagedResponse = null;
if (start > 0) {
try {
simplePagedResponse = scrollSimplePagedResultsControl(ldapConnection, dn, filter, scope, controls, start);
cookie = simplePagedResponse.getCookie();
} catch (InvalidSimplePageControlException ex) {
throw new LDAPSearchException(ex.getResultCode(), "Failed to scroll to specified start", ex);
} catch (LDAPException ex) {
throw new LDAPSearchException(ex.getResultCode(), "Failed to scroll to specified start", ex);
}
}
if ((cookie != null) && (cookie.getValueLength() == 0)) {
SearchResult searchResultTemp = simplePagedResponse.getLastSearchResult();
return new SearchResult(searchResultTemp.getMessageID(), searchResultTemp.getResultCode(), searchResultTemp.getDiagnosticMessage(), searchResultTemp.getMatchedDN(), searchResultTemp.getReferralURLs(), searchResultEntries, searchResultReferences, searchResultEntries.size(), searchResultReferences.size(), searchResultTemp.getResponseControls());
}
do {
collectSearchResult = true;
searchRequest.setControls(new Control[] { new SimplePagedResultsControl(searchLimit, cookie) });
setControls(searchRequest, controls);
searchResult = ldapConnection.search(searchRequest);
if (ldapBatchOperation != null) {
collectSearchResult = ldapBatchOperation.collectSearchResult(searchResult.getEntryCount());
}
if (collectSearchResult) {
searchResultList.add(searchResult);
searchResultEntries.addAll(searchResult.getSearchEntries());
searchResultReferences.addAll(searchResult.getSearchReferences());
}
if (ldapBatchOperation != null) {
List<T> entries = batchOperationWraper.createEntities(searchResult);
ldapBatchOperation.performAction(entries);
}
cookie = null;
try {
SimplePagedResultsControl c = SimplePagedResultsControl.get(searchResult);
if (c != null) {
cookie = c.getCookie();
}
} catch (LDAPException ex) {
LOG.error("Error while accessing cookies" + ex.getMessage());
}
if (useSizeLimit) {
break;
}
} while ((cookie != null) && (cookie.getValueLength() > 0));
} catch (LDAPException ex) {
throw new SearchException("Failed to scroll to specified start", ex, ex.getResultCode().intValue());
} finally {
if (ldapConnection != null) {
getConnectionPool().releaseConnection(ldapConnection);
}
}
if (!collectSearchResult) {
return new SearchResult(searchResult.getMessageID(), searchResult.getResultCode(), searchResult.getDiagnosticMessage(), searchResult.getMatchedDN(), searchResult.getReferralURLs(), searchResultEntries, searchResultReferences, searchResultEntries.size(), searchResultReferences.size(), searchResult.getResponseControls());
}
if (!searchResultList.isEmpty()) {
SearchResult searchResultTemp = searchResultList.get(0);
return new SearchResult(searchResultTemp.getMessageID(), searchResultTemp.getResultCode(), searchResultTemp.getDiagnosticMessage(), searchResultTemp.getMatchedDN(), searchResultTemp.getReferralURLs(), searchResultEntries, searchResultReferences, searchResultEntries.size(), searchResultReferences.size(), searchResultTemp.getResponseControls());
}
} else {
setControls(searchRequest, controls);
try {
searchResult = getConnectionPool().search(searchRequest);
} catch (LDAPSearchException ex) {
throw new SearchException(ex.getMessage(), ex, ex.getResultCode().intValue());
}
}
return searchResult;
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class LdapEntryManager 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 count entries is null");
}
// Check entry class
checkEntryClass(entryClass, false);
String[] objectClasses = getTypeObjectClasses(entryClass);
// Find entries
Filter searchFilter = Filter.createEqualityFilter(LdapOperationService.UID, userName);
if (objectClasses.length > 0) {
searchFilter = addObjectClassFilter(searchFilter, objectClasses);
}
SearchScope scope = SearchScope.SUB;
try {
SearchResult searchResult = getOperationService().search(baseDN, toLdapFilter(searchFilter), toLdapSearchScope(scope), null, 0, 1, 1, null, LdapOperationService.UID_ARRAY);
if ((searchResult == null) || (searchResult.getEntryCount() != 1)) {
return false;
}
String bindDn = searchResult.getSearchEntries().get(0).getDN();
return getOperationService().authenticate(bindDn, password, null);
} catch (ConnectionException ex) {
throw new AuthenticationException(String.format("Failed to authenticate user: %s", userName), ex);
} catch (SearchScopeException ex) {
throw new AuthenticationException(String.format("Failed to convert scope: %s", scope), ex);
} catch (SearchException ex) {
throw new AuthenticationException(String.format("Failed to find user DN: %s", userName), ex);
}
}
use of io.jans.orm.exception.operation.SearchException in project jans by JanssenProject.
the class SqlEntryManager 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 = toSqlFilter(searchFilter, propertiesAnnotationsMap);
} catch (SearchException ex) {
throw new EntryPersistenceException(String.format("Failed to convert filter '%s' to expression", searchFilter));
}
PagedResult<EntryData> searchResult;
try {
searchResult = searchImpl(toSQLKey(baseDN).getKey(), objectClasses[0], convertedExpression, 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();
}
Aggregations