use of javax.naming.ldap.SortControl in project Openfire by igniterealtime.
the class LdapManager method retrieveList.
/**
* Generic routine for retrieving a list of results from the LDAP server. It's meant to be very
* flexible so that just about any query for a list of results can make use of it without having
* to reimplement their own calls to LDAP. This routine also accounts for sorting settings,
* paging settings, any other global settings, and alternate DNs.
*
* The passed in filter string needs to be pre-prepared! In other words, nothing will be changed
* in the string before it is used as a string.
*
* @param attribute LDAP attribute to be pulled from each result and placed in the return results.
* Typically pulled from this manager.
* @param searchFilter Filter to use to perform the search. Typically pulled from this manager.
* @param startIndex Number/index of first result to include in results. (-1 for no limit)
* @param numResults Number of results to include. (-1 for no limit)
* @param suffixToTrim An arbitrary string to trim from the end of every attribute returned. null to disable.
* @param escapeJIDs Use JID-escaping for returned results (e.g. usernames)
* @return A simple list of strings (that should be sorted) of the results.
*/
public List<String> retrieveList(String attribute, String searchFilter, int startIndex, int numResults, String suffixToTrim, boolean escapeJIDs) {
List<String> results = new ArrayList<>();
int pageSize = -1;
String pageSizeStr = properties.get("ldap.pagedResultsSize");
if (pageSizeStr != null) {
try {
pageSize = Integer.parseInt(pageSizeStr);
/* radix -1 is invalid */
} catch (NumberFormatException e) {
// poorly formatted number, ignoring
}
}
Boolean clientSideSort = false;
String clientSideSortStr = properties.get("ldap.clientSideSorting");
if (clientSideSortStr != null) {
clientSideSort = Boolean.valueOf(clientSideSortStr);
}
LdapContext ctx = null;
LdapContext ctx2 = null;
try {
ctx = getContext(baseDN);
// Set up request controls, if appropriate.
List<Control> baseTmpRequestControls = new ArrayList<>();
if (!clientSideSort) {
// Server side sort on username field.
baseTmpRequestControls.add(new SortControl(new String[] { attribute }, Control.NONCRITICAL));
}
if (pageSize > 0) {
// Server side paging.
baseTmpRequestControls.add(new PagedResultsControl(pageSize, Control.NONCRITICAL));
}
Control[] baseRequestControls = baseTmpRequestControls.toArray(new Control[baseTmpRequestControls.size()]);
ctx.setRequestControls(baseRequestControls);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { attribute });
// If server side sort, we'll skip the initial ones we don't want, and stop when we've hit
// the amount we do want.
int skip = -1;
int lastRes = -1;
if (!clientSideSort) {
if (startIndex != -1) {
skip = startIndex;
}
if (numResults != -1) {
lastRes = startIndex + numResults;
}
}
byte[] cookie;
int count = 0;
// Run through all pages of results (one page is also possible ;) )
do {
cookie = null;
NamingEnumeration<SearchResult> answer = ctx.search("", searchFilter, searchControls);
// Examine all of the results on this page
while (answer.hasMoreElements()) {
count++;
if (skip > 0 && count <= skip) {
answer.next();
continue;
}
if (lastRes != -1 && count > lastRes) {
answer.next();
break;
}
// Get the next result.
String result = (String) answer.next().getAttributes().get(attribute).get();
// Remove suffixToTrim if set
if (suffixToTrim != null && suffixToTrim.length() > 0 && result.endsWith(suffixToTrim)) {
result = result.substring(0, result.length() - suffixToTrim.length());
}
// Add this to the result.
results.add(escapeJIDs ? JID.escapeNode(result) : result);
}
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (Control control : controls) {
if (control instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
cookie = prrc.getCookie();
}
}
}
// Close the enumeration.
answer.close();
// Re-activate paged results; affects nothing if no paging support
List<Control> tmpRequestControls = new ArrayList<>();
if (!clientSideSort) {
// Server side sort on username field.
tmpRequestControls.add(new SortControl(new String[] { attribute }, Control.NONCRITICAL));
}
if (pageSize > 0) {
// Server side paging.
tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
}
Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
ctx.setRequestControls(requestControls);
} while (cookie != null && (lastRes == -1 || count <= lastRes));
// Add groups found in alternate DN
if (alternateBaseDN != null && (lastRes == -1 || count <= lastRes)) {
ctx2 = getContext(alternateBaseDN);
ctx2.setRequestControls(baseRequestControls);
// Run through all pages of results (one page is also possible ;) )
do {
cookie = null;
NamingEnumeration<SearchResult> answer = ctx2.search("", searchFilter, searchControls);
// Examine all of the results on this page
while (answer.hasMoreElements()) {
count++;
if (skip > 0 && count <= skip) {
answer.next();
continue;
}
if (lastRes != -1 && count > lastRes) {
answer.next();
break;
}
// Get the next result.
String result = (String) answer.next().getAttributes().get(attribute).get();
// Remove suffixToTrim if set
if (suffixToTrim != null && suffixToTrim.length() > 0 && result.endsWith(suffixToTrim)) {
result = result.substring(0, result.length() - suffixToTrim.length());
}
// Add this to the result.
results.add(escapeJIDs ? JID.escapeNode(result) : result);
}
// Examine the paged results control response
Control[] controls = ctx2.getResponseControls();
if (controls != null) {
for (Control control : controls) {
if (control instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
cookie = prrc.getCookie();
}
}
}
// Close the enumeration.
answer.close();
// Re-activate paged results; affects nothing if no paging support
List<Control> tmpRequestControls = new ArrayList<>();
if (!clientSideSort) {
// Server side sort on username field.
tmpRequestControls.add(new SortControl(new String[] { attribute }, Control.NONCRITICAL));
}
if (pageSize > 0) {
// Server side paging.
tmpRequestControls.add(new PagedResultsControl(pageSize, cookie, Control.CRITICAL));
}
Control[] requestControls = tmpRequestControls.toArray(new Control[tmpRequestControls.size()]);
ctx2.setRequestControls(requestControls);
} while (cookie != null && (lastRes == -1 || count <= lastRes));
}
// If client-side sorting is enabled, sort and trim.
if (clientSideSort) {
Collections.sort(results);
if (startIndex != -1 || numResults != -1) {
if (startIndex == -1) {
startIndex = 0;
}
if (numResults == -1) {
numResults = results.size();
}
int endIndex = Math.min(startIndex + numResults, results.size() - 1);
results = results.subList(startIndex, endIndex);
}
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
} finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
if (ctx2 != null) {
ctx2.setRequestControls(null);
ctx2.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return results;
}
use of javax.naming.ldap.SortControl in project pentaho-kettle by pentaho.
the class LDAPConnection method getAttributes.
public Attributes getAttributes() throws KettleException {
byte[] cookie = null;
while (!getSearchResult().hasMoreElements()) {
if (isPagingUsed()) {
// and pass back cookie to next page
try {
// examine response controls
Control[] rc = getInitialContext().getResponseControls();
if (rc != null) {
for (int i = 0; i < rc.length; i++) {
if (rc[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prc = (PagedResultsResponseControl) rc[i];
cookie = prc.getCookie();
}
}
}
// pass the cookie back for the next page
if (isSortingAttributes()) {
getInitialContext().setRequestControls(new Control[] { new SortControl(getSortingAttributesKeys(), Control.NONCRITICAL), new PagedResultsControl(GetPagingSize(), cookie, Control.CRITICAL) });
} else {
getInitialContext().setRequestControls(new Control[] { new PagedResultsControl(GetPagingSize(), cookie, Control.CRITICAL) });
}
if ((cookie != null) && (cookie.length != 0)) {
// get search result for the page
this.results = getInitialContext().search(getSearchBase(), getFilter(), getSearchControls());
} else {
return null;
}
} catch (Exception e) {
throw new KettleException(BaseMessages.getString(PKG, "LDAPInput.Exception.ErrorPaging"), e);
}
while (!getSearchResult().hasMoreElements()) {
return null;
}
} else {
// we have already returned all the result
return null;
}
}
try {
SearchResult searchResult = getSearchResult().next();
Attributes results = searchResult.getAttributes();
results.put("dn", searchResult.getNameInNamespace());
return results;
} catch (Exception e) {
throw new KettleException(BaseMessages.getString(PKG, "LDAPConnection.Exception.GettingAttributes"), e);
}
}
use of javax.naming.ldap.SortControl in project camunda-bpm-platform by camunda.
the class LdapIdentityProviderSession method applyRequestControls.
protected void applyRequestControls(AbstractQuery<?, ?> query) {
try {
List<Control> controls = new ArrayList<Control>();
List<QueryOrderingProperty> orderBy = query.getOrderingProperties();
if (orderBy != null) {
for (QueryOrderingProperty orderingProperty : orderBy) {
String propertyName = orderingProperty.getQueryProperty().getName();
if (UserQueryProperty.USER_ID.getName().equals(propertyName)) {
controls.add(new SortControl(ldapConfiguration.getUserIdAttribute(), Control.CRITICAL));
} else if (UserQueryProperty.EMAIL.getName().equals(propertyName)) {
controls.add(new SortControl(ldapConfiguration.getUserEmailAttribute(), Control.CRITICAL));
} else if (UserQueryProperty.FIRST_NAME.getName().equals(propertyName)) {
controls.add(new SortControl(ldapConfiguration.getUserFirstnameAttribute(), Control.CRITICAL));
} else if (UserQueryProperty.LAST_NAME.getName().equals(propertyName)) {
controls.add(new SortControl(ldapConfiguration.getUserLastnameAttribute(), Control.CRITICAL));
}
}
}
initialContext.setRequestControls(controls.toArray(new Control[0]));
} catch (Exception e) {
throw new IdentityProviderException("Exception while setting paging settings", e);
}
}
use of javax.naming.ldap.SortControl in project teiid by teiid.
the class LDAPQueryExecution method setRequestControls.
/**
* Set the standard request controls
*/
private void setRequestControls(byte[] cookie) throws TranslatorException {
List<Control> ctrl = new ArrayList<Control>();
SortKey[] keys = searchDetails.getSortKeys();
try {
if (keys != null) {
ctrl.add(new SortControl(keys, Control.NONCRITICAL));
}
if (this.executionFactory.usePagination()) {
ctrl.add(new PagedResultsControl(this.executionContext.getBatchSize(), cookie, Control.CRITICAL));
}
if (!ctrl.isEmpty()) {
this.ldapCtx.setRequestControls(ctrl.toArray(new Control[ctrl.size()]));
// $NON-NLS-1$
LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Sort/pagination controls were created successfully.");
}
} catch (NamingException ne) {
final String msg = // $NON-NLS-1$
LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError") + " : " + // $NON-NLS-1$
ne.getExplanation();
throw new TranslatorException(ne, msg);
} catch (IOException e) {
throw new TranslatorException(e);
}
}
use of javax.naming.ldap.SortControl in project Openfire by igniterealtime.
the class LdapGroupTester method getGroups.
/**
* Returns fist N groups found in LDAP. The returned groups are only able to return their name,
* description and count of members. Count of members is considering all values that were found
* in the member field.
*
* @param maxGroups max number of groups to return.
* @return fist N groups found in the LDAP.
*/
public Collection<Group> getGroups(int maxGroups) {
Collection<Group> groups = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[] { new SortControl(new String[] { manager.getGroupNameField() }, Control.NONCRITICAL) };
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// Attributes to return for each group
String[] standardAttributes = new String[3];
standardAttributes[0] = manager.getGroupNameField();
standardAttributes[1] = manager.getGroupDescriptionField();
standardAttributes[2] = manager.getGroupMemberField();
searchControls.setReturningAttributes(standardAttributes);
// Limit results to those we'll need to process
searchControls.setCountLimit(maxGroups);
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
Attributes attributes = ((SearchResult) answer.next()).getAttributes();
String groupName = (String) attributes.get(manager.getGroupNameField()).get();
String description = "";
int elements = 0;
try {
description = ((String) attributes.get(manager.getGroupDescriptionField()).get());
} catch (NullPointerException e) {
// Do nothing since the group description field was not found
} catch (Exception e) {
Log.error("Error retrieving group description", e);
}
Attribute memberField = attributes.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
ne.next();
elements = elements + 1;
}
}
// Build Group with found information
groups.add(new Group(groupName, description, elements));
}
// Close the enumeration.
answer.close();
} catch (Exception e) {
Log.error(e.getMessage(), e);
} finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
} catch (Exception ex) {
Log.debug("An exception occurred while trying to close a LDAP context after trying to retrieve groups.", ex);
}
}
return groups;
}
Aggregations