List of usage examples for javax.naming.directory BasicAttributes BasicAttributes
public BasicAttributes(String attrID, Object val)
From source file:SerObjWithCodebase.java
public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java SerObjWithCodebase <codebase URL>"); System.exit(-1);//from ww w . j ava2 s. c om } String codebase = args[0]; // Set up environment for creating initial context Hashtable<String, Object> env = new Hashtable<String, Object>(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); try { // Create the initial context DirContext ctx = new InitialDirContext(env); // Create object to be bound Flower f = new Flower("rose", "pink"); // Perform bind and specify codebase ctx.bind("cn=Flower", f, new BasicAttributes("javaCodebase", codebase)); // Check that it is bound Flower f2 = (Flower) ctx.lookup("cn=Flower"); System.out.println(f2); // Close the context when we're done ctx.close(); } catch (NamingException e) { System.out.println("Operation failed: " + e); } }
From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java
public void createGroup(String cn, String ou, String[] memberDns) { Attributes group = new BasicAttributes("cn", cn); Attribute members = new BasicAttribute("member"); Attribute orgUnit = new BasicAttribute("ou", ou); for (String memberDn : memberDns) { members.add(memberDn);//from w ww. ja v a 2 s .c o m } Attribute objectClass = new BasicAttribute("objectClass"); objectClass.add("top"); objectClass.add("groupOfNames"); group.put(objectClass); group.put(members); group.put(orgUnit); try { serverContext.createSubcontext("cn=" + cn + ",ou=groups", group); } catch (NameAlreadyBoundException ignore) { // System.out.println(" group " + cn + " already exists."); } catch (NamingException ne) { log.error("Failed to create group", ne); } }
From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java
public void createOu(String name) { Attributes ou = new BasicAttributes("ou", name); Attribute objectClass = new BasicAttribute("objectClass"); objectClass.add("top"); objectClass.add("organizationalUnit"); ou.put(objectClass);/* w w w . ja va2s .c o m*/ try { serverContext.createSubcontext("ou=" + name, ou); } catch (NameAlreadyBoundException ignore) { log.warn("ou " + name + " already exists."); } catch (NamingException ne) { log.error("Failed to create ou: ", ne); } }
From source file:LDAPTest.java
/** * Saves the changes that the user made. *//*from w ww . j av a2 s . c o m*/ public void saveEntry() { try { if (dataPanel == null) return; if (context == null) context = getContext(); if (uidField.getText().equals(uid)) // update existing entry { String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com"; Attributes editedAttrs = dataPanel.getEditedAttributes(); NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll(); while (attrEnum.hasMore()) { Attribute attr = attrEnum.next(); String id = attr.getID(); Attribute editedAttr = editedAttrs.get(id); if (editedAttr != null && !attr.get().equals(editedAttr.get())) context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, new BasicAttributes(id, editedAttr.get())); } } else // create new entry { String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com"; attrs = dataPanel.getEditedAttributes(); Attribute objclass = new BasicAttribute("objectClass"); objclass.add("uidObject"); objclass.add("person"); attrs.put(objclass); attrs.put("uid", uidField.getText()); context.createSubcontext(dn, attrs); } findEntry(); } catch (NamingException e) { JOptionPane.showMessageDialog(LDAPFrame.this, e); e.printStackTrace(); } catch (IOException e) { JOptionPane.showMessageDialog(LDAPFrame.this, e); e.printStackTrace(); } }
From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java
public void createUser(String uid, String cn, String password) { Attributes user = new BasicAttributes("uid", uid); user.put("cn", cn); user.put("userPassword", password); Attribute objectClass = new BasicAttribute("objectClass"); user.put(objectClass);/*from w w w . j a v a2 s .c om*/ objectClass.add("top"); objectClass.add("person"); objectClass.add("organizationalPerson"); objectClass.add("inetOrgPerson"); user.put("sn", uid); try { serverContext.createSubcontext("uid=" + uid + ",ou=people", user); } catch (NameAlreadyBoundException ignore) { // System.out.println(" user " + uid + " already exists."); } catch (NamingException ne) { System.err.println("Failed to create user."); ne.printStackTrace(); } }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java
/** * Check correct user attribute values in the LDAP when using OTP algorithm. *///from www . ja v a 2 s . co m private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException { final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); final LdapContext ctx = new InitialLdapContext(env, null); NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke")); if (namingEnum.hasMore()) { SearchResult sr = (SearchResult) namingEnum.next(); Attributes attrs = sr.getAttributes(); assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence, new Integer(attrs.get("telephoneNumber").get().toString())); assertEquals("Unexpected hash value in LDAP attribute", Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString()); } else { fail("User not found in LDAP"); } namingEnum.close(); ctx.close(); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Store new links using the LDAP staticAttributeId strategy. * * @see org.nuxeo.ecm.directory.Reference#addLinks(List, String) *//*w w w .j ava 2s.c o m*/ @Override public void addLinks(List<String> sourceIds, String targetId) throws DirectoryException { String attributeId = getStaticAttributeId(); if (attributeId == null && !sourceIds.isEmpty()) { log.warn("trying to edit a non-static reference: ignoring"); return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // compute the target dn to add to all the matching source // entries SearchResult ldapEntry = targetSession.getLdapEntry(targetId); if (ldapEntry == null) { throw new DirectoryException( String.format("could not add links to unexisting %s in directory %s", targetId, ldapTargetDirectory.getName())); } String targetAttributeValue; if (staticAttributeIdIsDn) { targetAttributeValue = ldapEntry.getNameInNamespace(); } else { targetAttributeValue = targetId; } for (String sourceId : sourceIds) { // fetch the entry to be able to run the security policy // implemented in an entry adaptor DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false); if (sourceEntry == null) { log.warn(String.format( "entry %s in directory %s not found: could not add link to %s in directory %s", sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName())); continue; } if (BaseSession.isReadOnlyEntry(sourceEntry)) { // skip this entry since it cannot be edited to add the // reference to targetId log.warn(String.format( "entry %s in directory %s is readonly: could not add link to %s in directory %s", sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName())); continue; } ldapEntry = sourceSession.getLdapEntry(sourceId); String sourceDn = ldapEntry.getNameInNamespace(); Attribute storedAttr = ldapEntry.getAttributes().get(attributeId); if (storedAttr.contains(targetAttributeValue)) { // no need to readd continue; } try { // add the new dn Attributes attrs = new BasicAttributes(attributeId, targetAttributeValue); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.addLinks([%s], %s): LDAP modifyAttributes dn='%s'" + " mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", StringUtils.join(sourceIds, ", "), targetId, sourceDn, attrs, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrs); // robustly clean any existing empty marker now that we // are sure that the list in not empty if (storedAttr.contains(emptyRefMarker)) { Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.addLinks(%s, %s): LDAP modifyAttributes dn='%s'" + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", StringUtils.join(sourceIds, ", "), targetId, sourceDn, cleanAttrs.toString(), this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, cleanAttrs); } } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static part log.warn(String.format("cannot add dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrap the exception throw new DirectoryException(e); } } } } } catch (NamingException e) { throw new DirectoryException("addLinks failed: " + e.getMessage(), e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given source id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String) */// ww w . ja v a 2 s . c o m @Override public void removeLinksForSource(String sourceId) throws DirectoryException { LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { if (sourceSession.isReadOnly() || attributeId == null) { // do not try to do anything on a read only server or to a // purely dynamic reference return; } // get the dn of the entry that matches sourceId SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId); if (sourceLdapEntry == null) { throw new DirectoryException( String.format("cannot edit the links hold by missing entry '%s' in directory '%s'", sourceId, ldapSourceDirectory.getName())); } String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace()); Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId); if (oldAttr == null) { // consider it as an empty attribute to simplify the following // code oldAttr = new BasicAttribute(attributeId); } Attribute attrToRemove = new BasicAttribute(attributeId); NamingEnumeration<?> oldAttrs = oldAttr.getAll(); String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn()); try { while (oldAttrs.hasMore()) { String targetKeyAttr = oldAttrs.next().toString(); if (staticAttributeIdIsDn) { String dn = pseudoNormalizeDn(targetKeyAttr); if (forceDnConsistencyCheck) { String id = getIdForDn(targetSession, dn); if (id != null && targetSession.hasEntry(id)) { // this is an entry managed by the current // reference attrToRemove.add(dn); } } else if (dn.endsWith(targetBaseDn)) { // this is an entry managed by the current // reference attrToRemove.add(dn); } } else { attrToRemove.add(targetKeyAttr); } } } finally { oldAttrs.close(); } try { if (attrToRemove.size() == oldAttr.size()) { // use the empty ref marker to avoid empty attr String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' " + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]", sourceId, sourceDn, emptyAttribute, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE, emptyAttribute); } else if (attrToRemove.size() > 0) { // remove the attribute managed by the current reference Attributes attrsToRemove = new BasicAttributes(); attrsToRemove.put(attrToRemove); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' " + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", sourceId, sourceDn, attrsToRemove, this)); } sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove); } } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static part log.warn(String.format("cannot remove dynamic reference in field %s for source %s", getFieldName(), sourceId)); } else { // this is a real schma configuration problem, wrapup the // exception throw new DirectoryException(e); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) */// www . j a v a 2 s. co m @Override public void removeLinksForTarget(String targetId) throws DirectoryException { if (!isStatic()) { // nothing to do: dynamic references cannot be updated return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // get the dn of the target that matches targetId String targetAttributeValue; if (staticAttributeIdIsDn) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId); if (targetLdapEntry == null) { String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute(); if (!rdnAttribute.equals(targetSession.idAttribute)) { log.warn(String.format( "cannot remove links to missing entry %s in directory %s for reference %s", targetId, ldapTargetDirectory.getName(), this)); return; } // the entry might have already been deleted, try to // re-forge it if possible (might not work if scope is // subtree) targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId, ldapTargetDirectory.getDescriptor().getSearchBaseDn()); } else { targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } } else { targetAttributeValue = targetId; } // build a LDAP query to find entries that point to the target String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue); String sourceFilter = ldapSourceDirectory.getBaseFilter(); if (sourceFilter != null && !"".equals(sourceFilter)) { searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter); } SearchControls scts = new SearchControls(); scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope()); scts.setReturningAttributes(new String[] { attributeId }); // find all source entries that point to the target key and // clean // those references if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' " + " filter='%s' scope='%s' [%s]", targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext .search(sourceSession.searchBaseDn, searchFilter, scts); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); Attribute attr = attrs.get(attributeId); try { if (attr.size() == 1) { // the attribute holds the last reference, put // the // empty ref. marker before removing the // attribute // since empty attribute are often not allowed // by // the server schema if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.ADD_ATTRIBUTE, emptyAttribute); } // remove the reference to the target key attrs = new BasicAttributes(); attr = new BasicAttribute(attributeId); attr.add(targetAttributeValue); attrs.put(attr); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.REMOVE_ATTRIBUTE, attrs); } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static // part log.warn(String.format("cannot remove dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrapup the exception throw new DirectoryException(e); } } } } finally { results.close(); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e); } }