List of usage examples for javax.naming NamingEnumeration close
public void close() throws NamingException;
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@SuppressWarnings("unchecked") protected Object getFieldValue(Attribute attribute, String fieldName, String entryId, boolean fetchReferences) throws DirectoryException { Field field = schemaFieldMap.get(fieldName); Type type = field.getType();//ww w . jav a 2 s. co m Object defaultValue = field.getDefaultValue(); String typeName = type.getName(); if (attribute == null) { return defaultValue; } Object value; try { value = attribute.get(); } catch (NamingException e) { throw new DirectoryException("Could not fetch value for " + attribute, e); } if (value == null) { return defaultValue; } String trimmedValue = value.toString().trim(); if ("string".equals(typeName)) { return trimmedValue; } else if ("integer".equals(typeName) || "long".equals(typeName)) { if ("".equals(trimmedValue)) { return defaultValue; } try { return Long.valueOf(trimmedValue); } catch (NumberFormatException e) { log.error(String.format( "field %s of type %s has non-numeric value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, trimmedValue)); return defaultValue; } } else if (type.isListType()) { List<String> parsedItems = new LinkedList<String>(); NamingEnumeration<Object> values = null; try { values = (NamingEnumeration<Object>) attribute.getAll(); while (values.hasMore()) { parsedItems.add(values.next().toString().trim()); } return parsedItems; } catch (NamingException e) { log.error(String.format( "field %s of type %s has non list value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, values != null ? values.toString() : trimmedValue)); return defaultValue; } finally { if (values != null) { try { values.close(); } catch (NamingException e) { log.error(e, e); } } } } else if ("date".equals(typeName)) { if ("".equals(trimmedValue)) { return defaultValue; } try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'"); dateFormat.setTimeZone(new SimpleTimeZone(0, "Z")); Date date = dateFormat.parse(trimmedValue); Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } catch (ParseException e) { log.error(String.format( "field %s of type %s has invalid value found on server: '%s' (ignoring and using default value instead)", fieldName, typeName, trimmedValue)); return defaultValue; } } else if ("content".equals(typeName)) { return Blobs.createBlob((byte[]) value); } else { throw new DirectoryException("Field type not supported in directories: " + typeName); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
protected DocumentModelList ldapResultsToDocumentModels(NamingEnumeration<SearchResult> results, boolean fetchReferences) throws DirectoryException, NamingException { DocumentModelListImpl list = new DocumentModelListImpl(); try {//from ww w . j a v a2 s.co m while (results.hasMore()) { SearchResult result = results.next(); DocumentModel entry = ldapResultToDocumentModel(result, null, fetchReferences); if (entry != null) { list.add(entry); } } } catch (SizeLimitExceededException e) { if (list.isEmpty()) { // the server did no send back the truncated results set, // re-throw the exception to that the user interface can display // the error message throw e; } // mark the collect results as a truncated result list log.debug("SizeLimitExceededException caught," + " return truncated results. Original message: " + e.getMessage() + " explanation: " + e.getExplanation()); list.setTotalSize(-2); } finally { results.close(); } log.debug("LDAP search returned " + list.size() + " results"); return list; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java
@SuppressWarnings("unchecked") protected List<String> getMandatoryAttributes(Attribute objectClassesAttribute) throws DirectoryException { try {//from w ww .ja v a 2 s . c om List<String> mandatoryAttributes = new ArrayList<String>(); DirContext schema = dirContext.getSchema(""); List<String> objectClasses = new ArrayList<String>(); if (objectClassesAttribute == null) { // use the creation classes as reference schema for this entry objectClasses.addAll(Arrays.asList(getDirectory().getDescriptor().getCreationClasses())); } else { // introspec the objectClass definitions to find the mandatory // attributes for this entry NamingEnumeration<Object> values = null; try { values = (NamingEnumeration<Object>) objectClassesAttribute.getAll(); while (values.hasMore()) { objectClasses.add(values.next().toString().trim()); } } catch (NamingException e) { throw new DirectoryException(e); } finally { if (values != null) { values.close(); } } } objectClasses.remove("top"); for (String creationClass : objectClasses) { Attributes attributes = schema.getAttributes("ClassDefinition/" + creationClass); Attribute attribute = attributes.get("MUST"); if (attribute != null) { NamingEnumeration<String> values = (NamingEnumeration<String>) attribute.getAll(); try { while (values.hasMore()) { String value = values.next(); mandatoryAttributes.add(value); } } finally { values.close(); } } } return mandatoryAttributes; } catch (NamingException e) { throw new DirectoryException("getMandatoryAttributes failed", e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches single parent, cutting the dn and trying to get the given entry. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) *//*from ww w.j a v a2 s . c om*/ @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { Set<String> sourceIds = new TreeSet<>(); String targetDn = null; // step #1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId, true); if (targetLdapEntry == null) { // no parent accessible => return empty list return EMPTY_STRING_LIST; } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + targetId, e); } // step #2: search for entries that reference parent dn in the // source directory and collect its id LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String parentDn = getParentDn(targetDn); String filterExpr = String.format("(&%s)", ldapSourceDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapSourceDirectory.getSearchControls(true); sctls.setSearchScope(SearchControls.OBJECT_SCOPE); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", targetId, parentDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(parentDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(sourceSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { sourceIds.add(value.toString()); // only supposed to get one result anyway break; } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetDn, e); } return new ArrayList<>(sourceIds); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches children, onelevel or subtree given the reference configuration. * <p>/*from w w w . ja va 2 s.c om*/ * Removes entries with same id than parent to only get real children. * * @see org.nuxeo.ecm.directory.Reference#getTargetIdsForSource(String) */ // TODO: optimize reusing the same ldap session (see LdapReference optim // method) @Override public List<String> getTargetIdsForSource(String sourceId) throws DirectoryException { Set<String> targetIds = new TreeSet<>(); String sourceDn = null; // step #1: fetch the dn of the sourceId entry in the source // directory by the static dn valued strategy LDAPDirectory sourceDir = getSourceLDAPDirectory(); try (LDAPSession sourceSession = (LDAPSession) sourceDir.getSession()) { SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId, true); if (sourceLdapEntry == null) { throw new DirectoryException(sourceId + " does not exist in " + sourceDirectoryName); } sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + sourceId, e); } // step #2: search for entries with sourceDn as base dn and collect // their ids LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String filterExpr = String.format("(&%s)", ldapTargetDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapTargetDirectory.getSearchControls(true); sctls.setSearchScope(getScope()); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getTargetIdsForSource(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", sourceId, sourceDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = targetSession.dirContext.search(sourceDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(targetSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { // always remove self as child String targetId = value.toString(); if (!sourceId.equals(targetId)) { targetIds.add(targetId); } } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + sourceDn, e); } return new ArrayList<>(targetIds); }
From source file:org.springframework.ejb.support.JndiEnvironmentBeanDefinitionReader.java
/** * Creates new JNDIBeanFactory/*from ww w . j a v a 2 s . c o m*/ * @param root likely to be "java:comp/env" */ public JndiEnvironmentBeanDefinitionReader(BeanDefinitionRegistry beanFactory, String root) throws BeansException { // We'll take everything from the NamingContext and dump it in a // Properties object, so that the superclass can efficiently manipulate it // after we've closed the context. HashMap m = new HashMap(); Context initCtx = null; try { initCtx = new InitialContext(); // Parameterize NamingEnumeration bindings = initCtx.listBindings(root); // Orion 1.5.2 doesn't seem to regard anything under a / // as a true subcontext, so we need to search all bindings // Not all that fast, but it doesn't matter while (bindings.hasMore()) { Binding binding = (Binding) bindings.next(); logger.debug("Name: " + binding.getName()); logger.debug("Type: " + binding.getClassName()); logger.debug("Value: " + binding.getObject()); m.put(binding.getName(), binding.getObject()); } bindings.close(); PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(beanFactory); propReader.registerBeanDefinitions(m, BEANS_PREFIX); } catch (NamingException ex) { logger.debug("----- NO PROPERTIES FOUND " + ex); } finally { try { if (initCtx != null) { initCtx.close(); } } catch (NamingException ex) { // IGNORE OR THROW RTE? } } }
From source file:org.springframework.ldap.core.DirContextAdapter.java
private void closeNamingEnumeration(NamingEnumeration enumeration) { try {/* w ww.j a va2 s.c o m*/ if (enumeration != null) { enumeration.close(); } } catch (NamingException e) { // Never mind this } }
From source file:org.springframework.ldap.core.LdapTemplate.java
/** * Delete all subcontexts including the current one recursively. * // w w w .j ava2 s .c o m * @param ctx The context to use for deleting. * @param name The starting point to delete recursively. * @throws NamingException if any error occurs */ protected void deleteRecursively(DirContext ctx, DistinguishedName name) { NamingEnumeration enumeration = null; try { enumeration = ctx.listBindings(name); while (enumeration.hasMore()) { Binding binding = (Binding) enumeration.next(); DistinguishedName childName = new DistinguishedName(binding.getName()); childName.prepend((DistinguishedName) name); deleteRecursively(ctx, childName); } ctx.unbind(name); if (log.isDebugEnabled()) { log.debug("Entry " + name + " deleted"); } } catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } finally { try { enumeration.close(); } catch (Exception e) { // Never mind this } } }
From source file:org.springframework.ldap.core.LdapTemplate.java
/** * Close the supplied NamingEnumeration if it is not null. Swallow any * exceptions, as this is only for cleanup. * /*from w w w . jav a 2 s . c o m*/ * @param results the NamingEnumeration to close. */ private void closeNamingEnumeration(NamingEnumeration results) { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } }
From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java
public List<String> getAllPersonNames() { DirContext ctx = createAnonymousContext(); LinkedList<String> list = new LinkedList<String>(); NamingEnumeration<?> results = null; try {//w w w . j a v a 2 s.c o m SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", "(objectclass=person)", controls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get("cn"); String cn = (String) attr.get(); list.add(cn); } } catch (NamingException e) { throw new RuntimeException(e); } 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 list; }