List of usage examples for javax.naming NamingEnumeration close
public void close() throws NamingException;
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser getIfValidUser(String cn, String password) { LDAPUser user = null;/* w w w.j a v a 2 s . c o m*/ NamingEnumeration results = null; DirContext ctx = null; try { ctx = getAuthContext(cn, password); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf", "createTimestamp" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user.setUsername((String) attributes.get("cn").get()); if (attributes.get("sn") != null) user.setSurname((String) attributes.get("sn").get()); if (attributes.get("givenName") != null) user.setGivenname((String) attributes.get("givenName").get()); if (attributes.get("title") != null) user.setTitle((String) attributes.get("title").get()); if (attributes.get("registeredAddress") != null) user.setPreferredMail((String) attributes.get("registeredAddress").get(0)); if (attributes.get("mail") != null) { String mails = ""; for (int i = 0; i < attributes.get("mail").size(); i++) { if (i != 0) mails = mails + ", "; mails = mails + (String) attributes.get("mail").get(i); } user.setAdditionalMails(mails); } if (attributes.get("memberOf") != null) { for (int i = 0; i < attributes.get("memberOf").size(); i++) { user.addGroup((String) attributes.get("memberOf").get(i)); } } if (attributes.get("createTimestamp") != null) { String time = (String) attributes.get("createTimestamp").get(); DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss"); user.setCreationTime(ldapData.parse(time)); } } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } catch (ParseException ex) { _log.error(ex); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return user; }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java
private boolean ldapAuthorizationVerification(String user) { M_log.debug("ldapAuthorizationVerification(): called"); boolean isAuthorized = false; DirContext dirContext = null; NamingEnumeration listOfPeopleInAuthGroup = null; NamingEnumeration allSearchResultAttributes = null; NamingEnumeration simpleListOfPeople = null; Hashtable<String, String> env = new Hashtable<String, String>(); if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) { env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY); env.put(Context.PROVIDER_URL, providerURL); } else {// ww w . j av a 2 s . c o m M_log.error( " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file"); return isAuthorized; } try { dirContext = new InitialDirContext(env); String[] attrIDs = { "member" }; SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(attrIDs); searchControls.setReturningObjFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBase = OU_GROUPS; String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))"; listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls); String positiveMatch = "uid=" + user + ","; outerloop: while (listOfPeopleInAuthGroup.hasMore()) { SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next(); allSearchResultAttributes = (searchResults.getAttributes()).getAll(); while (allSearchResultAttributes.hasMoreElements()) { Attribute attr = (Attribute) allSearchResultAttributes.nextElement(); simpleListOfPeople = attr.getAll(); while (simpleListOfPeople.hasMoreElements()) { String val = (String) simpleListOfPeople.nextElement(); if (val.indexOf(positiveMatch) != -1) { isAuthorized = true; break outerloop; } } } } return isAuthorized; } catch (NamingException e) { M_log.error("Problem getting attribute:" + e); return isAuthorized; } finally { try { if (simpleListOfPeople != null) { simpleListOfPeople.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ", e); } try { if (allSearchResultAttributes != null) { allSearchResultAttributes.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ", e); } try { if (listOfPeopleInAuthGroup != null) { listOfPeopleInAuthGroup.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ", e); } try { if (dirContext != null) { dirContext.close(); } } catch (NamingException e) { M_log.error("Problem occurred while closing the \"dirContext\" object", e); } } }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will query the LDAP for the supplied dn, matching attributes and * return attributes. This method will always perform a one level search. The * resulting <code>Iterator</code> is a deep copy of the original search * results. If matchAttrs is empty or null then all objects in the target * context are returned. If retAttrs is null then all attributes will be * returned. If retAttrs is an empty array then no attributes will be * returned. See {@link javax.naming.DirContext#search(String, Attributes, * String[])}./*from w w w . j a v a2 s . c o m*/ * * @param dn <code>String</code> name to search in * @param matchAttrs <code>Attributes</code> attributes to match * @param retAttrs <code>String[]</code> attributes to return * @param handler <code>SearchResultHandler[]</code> to post process results * * @return <code>Iterator</code> - of LDAP search results * * @throws NamingException if the LDAP returns an error */ protected Iterator<SearchResult> searchAttributes(final String dn, final Attributes matchAttrs, final String[] retAttrs, final SearchResultHandler... handler) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("One level search with the following parameters:"); this.logger.debug(" dn = " + dn); this.logger.debug(" matchAttrs = " + matchAttrs); this.logger.debug(" retAttrs = " + (retAttrs == null ? "all attributes" : Arrays.toString(retAttrs))); this.logger.debug(" handler = " + Arrays.toString(handler)); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.search(dn, matchAttrs, retAttrs); if (handler != null && handler.length > 0) { final SearchCriteria sc = new SearchCriteria(); if (ctx != null && !"".equals(ctx.getNameInNamespace())) { sc.setDn(ctx.getNameInNamespace()); } else { sc.setDn(dn); } sc.setMatchAttrs(matchAttrs); sc.setReturnAttrs(retAttrs); if (handler != null && handler.length > 0) { for (int j = 0; j < handler.length; j++) { if (j == 0) { results = handler[j].process(sc, en, this.config.getHandlerIgnoreExceptions()); } else { results = handler[j].process(sc, results); } } } } else { results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); } break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will query the LDAP with the supplied dn, filter, filter arguments, * and search controls. This method will perform a search whose scope is * defined in the search controls. The resulting <code>Iterator</code> is a * deep copy of the original search results. If filterArgs is null, then no * variable substitution will occur. See {@link * javax.naming.DirContext#search( String, String, Object[], SearchControls)}. * * @param dn <code>String</code> name to begin search at * @param filter <code>String</code> expression to use for the search * @param filterArgs <code>Object[]</code> to substitute for variables in * the filter//from w w w. j a v a 2 s . co m * @param searchControls <code>SearchControls</code> to perform search with * @param handler <code>SearchResultHandler[]</code> to post process results * * @return <code>Iterator</code> - of LDAP search results * * @throws NamingException if the LDAP returns an error */ protected Iterator<SearchResult> search(final String dn, final String filter, final Object[] filterArgs, final SearchControls searchControls, final SearchResultHandler... handler) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("Search with the following parameters:"); this.logger.debug(" dn = " + dn); this.logger.debug(" filter = " + filter); this.logger.debug(" filterArgs = " + Arrays.toString(filterArgs)); this.logger.debug(" searchControls = " + searchControls); this.logger.debug(" handler = " + Arrays.toString(handler)); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<SearchResult> results = null; LdapContext ctx = null; NamingEnumeration<SearchResult> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.search(dn, filter, filterArgs, searchControls); if (handler != null && handler.length > 0) { final SearchCriteria sc = new SearchCriteria(); if (ctx != null && !"".equals(ctx.getNameInNamespace())) { sc.setDn(ctx.getNameInNamespace()); } else { sc.setDn(dn); } sc.setFilter(filter); sc.setFilterArgs(filterArgs); if (searchControls != null) { sc.setReturnAttrs(searchControls.getReturningAttributes()); } for (int j = 0; j < handler.length; j++) { if (j == 0) { results = handler[j].process(sc, en, this.config.getHandlerIgnoreExceptions()); } else { results = handler[j].process(sc, results); } } } else { results = SR_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); } break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the field value of the specified field for the specified id. * @see IExternalStorage#getField(java.lang.String, java.lang.String) *///from w ww . j av a 2 s .co m public Object getField(String id, String field) throws UserException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; Object oValue = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attribute '"); sbFailed.append(field); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration oAttrEnum = oAttributes.getAll(); if (oAttrEnum.hasMore()) { Attribute oAttribute = (Attribute) oAttrEnum.next(); oValue = oAttribute.get(); } } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not retrieve field: " + field, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return oValue; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * * @param callback//from w w w. j a v a 2 s .c om * the callback * @param searchBase * the base DN for the search * @param query * the query * @param returningAttributes * the attributes to include in search results * @throws org.alfresco.error.AlfrescoRuntimeException */ private void processQuery(SearchCallback callback, String searchBase, String query, String[] returningAttributes) { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(returningAttributes); if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger.debug("Processing query"); LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase); LDAPMultiBaseUserRegistry.logger.debug(" Return result limit: " + searchControls.getCountLimit()); LDAPMultiBaseUserRegistry.logger.debug(" DerefLink: " + searchControls.getDerefLinkFlag()); LDAPMultiBaseUserRegistry.logger .debug(" Return named object: " + searchControls.getReturningObjFlag()); LDAPMultiBaseUserRegistry.logger.debug(" Time limit for search: " + searchControls.getTimeLimit()); LDAPMultiBaseUserRegistry.logger .debug(" Attributes to return: " + returningAttributes.length + " items."); for (String ra : returningAttributes) { LDAPMultiBaseUserRegistry.logger.debug(" Attribute: " + ra); } } InitialDirContext ctx = null; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize); do { searchResults = ctx.search(searchBase, query, searchControls); while (searchResults.hasMore()) { result = searchResults.next(); callback.process(result); // Close the contexts, see ALF-20682 Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } result = null; } } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize)); } catch (NamingException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } catch (ParseException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } finally { if (result != null) { try { Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } } }
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Gathers attributes from JNDI storage to the supplied attributes object. * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes) *//* w w w . ja va 2 s . c o m*/ public void process(String sUserId, IAttributes oAttributes) throws AttributeException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); if (_listGather.size() > 0) { String[] saAttributes = _listGather.toArray(new String[0]); oScope.setReturningAttributes(saAttributes); } String searchFilter = resolveSearchQuery(sUserId); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(sUserId); _logger.error(sbFailed.toString(), e); throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown: " + sUserId); return; } if (oNamingEnumeration.hasMore()) { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oSearchedAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oSearchedAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); String sMappedName = _htMapper.get(sAttributeName); if (sMappedName != null) sAttributeName = sMappedName; if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); oAttributes.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; oAttributes.put(sAttributeName, oValue); } } } } catch (AttributeException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch attributes for user: " + sUserId, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e); } } } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) *///from w w w . j a v a2s . co m public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java
private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id) throws OAException { String sReturn = null;/*w w w . j a v a2 s.co m*/ NamingEnumeration oNamingEnumeration = null; try { if (sIDAttribute == null) { _logger.error("No attribute name to map from supplied"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbQuery = new StringBuffer("("); sbQuery.append(sIDAttribute); sbQuery.append("="); sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id)); sbQuery.append(")"); String sSearchQuery = sbQuery.toString(); String sSearchFor = sMapperAttribute; if (sSearchFor == null) sSearchFor = "*"; SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); oScope.setReturningAttributes(new String[] { sSearchFor }); try { oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(sSearchQuery); sbFailed.append(" while searching for attributes for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } if (!oNamingEnumeration.hasMore()) { _logger.debug("No result when searching for: " + sSearchQuery); } else { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); if (sMapperAttribute == null) { sReturn = oSearchResult.getName(); sReturn += "," + _sDNBase; } else { Attributes oSearchedAttributes = oSearchResult.getAttributes(); Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute); if (attrMapping == null) { _logger.debug("Mapping attribute not found: " + sMapperAttribute); } else { Object oValue = attrMapping.get(); if (!(oValue instanceof String)) { StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '"); sbError.append(_sMapperAttribute); sbError.append("' has a value which is not of type 'String'"); _logger.error(sbError.toString()); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } sReturn = (String) oValue; } } } } catch (OAException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch mapping attribute for id: " + id, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for id: " + id, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for id: " + id, e); } } } return sReturn; }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
@Override public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName) throws Exception { LdapContext ldapContext = null; NamingEnumeration<SearchResult> enu = null; try {//from www . j av a2 s. co m LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider .getConfiguration(companyId, ldapServerId); String baseDN = ldapServerConfiguration.baseDN(); ldapContext = _portalLDAP.getContext(ldapServerId, companyId); if (ldapContext == null) { _log.error("Unable to bind to the LDAP server"); return null; } String filter = ldapServerConfiguration.authSearchFilter(); if (_log.isDebugEnabled()) { _log.debug("Search filter before transformation " + filter); } filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" }, new String[] { String.valueOf(companyId), emailAddress, screenName }); LDAPUtil.validateFilter(filter); if (_log.isDebugEnabled()) { _log.debug("Search filter after transformation " + filter); } Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName")); userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName); SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { userMappingsScreenName }, false, false); enu = ldapContext.search(baseDN, filter, searchControls); if (enu.hasMoreElements()) { if (_log.isDebugEnabled()) { _log.debug("Search filter returned at least one result"); } Binding binding = enu.nextElement(); Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, binding.getNameInNamespace()); return importUser(ldapServerId, companyId, ldapContext, attributes, null); } else { return null; } } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn("Problem accessing LDAP server " + e.getMessage()); } if (_log.isDebugEnabled()) { _log.debug(e, e); } throw new SystemException("Problem accessing LDAP server " + e.getMessage()); } finally { if (enu != null) { enu.close(); } if (ldapContext != null) { ldapContext.close(); } } }