javax.naming.directory.BasicAttributes Java Examples

The following examples show how to use javax.naming.directory.BasicAttributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch_Name_AttributesMapper_DirContextProcessor() throws Exception {
	expectGetReadOnlyContext();

	SearchControls controls = searchControlsOneLevel();
	controls.setReturningObjFlag(false);

	BasicAttributes expectedAttributes = new BasicAttributes();
	SearchResult searchResult = new SearchResult("", null, expectedAttributes);

	singleSearchResult(controls, searchResult);

	Object expectedResult = new Object();
	when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult);

	List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock, dirContextProcessorMock);

       verify(dirContextProcessorMock).preProcess(dirContextMock);
       verify(dirContextProcessorMock).postProcess(dirContextMock);
       verify(namingEnumerationMock).close();
       verify(dirContextMock).close();

       assertThat(list).isNotNull();
	assertThat(list).hasSize(1);
	assertThat(list.get(0)).isSameAs(expectedResult);
}
 
Example #2
Source File: LdapResult.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
boolean compareToSearchResult(String name) {
    boolean successful = false;

    switch (status) {
        case LdapClient.LDAP_COMPARE_TRUE:
            status = LdapClient.LDAP_SUCCESS;
            entries = new Vector<>(1,1);
            Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
            LdapEntry entry = new LdapEntry( name, attrs );
            entries.addElement(entry);
            successful = true;
            break;

        case LdapClient.LDAP_COMPARE_FALSE:
            status = LdapClient.LDAP_SUCCESS;
            entries = new Vector<>(0);
            successful = true;
            break;

        default:
            successful = false;
            break;
    }

    return successful;
}
 
Example #3
Source File: Group2Ldap.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean create(Groups group)  throws Exception{
	logger.info("create");
	try {
		Attributes attributes = new BasicAttributes();
		attributes.put(new BasicAttribute("objectClass","groupOfUniqueNames"));
		attributes.put(new BasicAttribute("cn",group.getName()));
		attributes.put(new BasicAttribute("uniqueMember","uid=dummy"));
		
		String dn="cn="+group.getName()+",dc=groups,"+ldapUtils.getBaseDN();
	
		ldapUtils.getCtx().createSubcontext(dn, attributes);
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example #4
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoChangeMultiAttributeOrderDoesNotMatter() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	tested.setAttributeValues("abc", new String[] { "qwe", "123" });

	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(0);
	String[] modNames = tested.getNamesOfModifiedAttributes();
	assertThat(modNames.length).isEqualTo(0);
}
 
Example #5
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStringAttributesWhenMultiValueAttributeExists() throws Exception {
	final Attributes attrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("234");
	attrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(attrs, null);
		}
	}
	tested = new TestableDirContextAdapter();
	String s[] = tested.getStringAttributes("abc");
	assertThat(s[0]).isEqualTo("123");
	assertThat(s[1]).isEqualTo("234");
	assertThat(s.length).isEqualTo(2);
}
 
Example #6
Source File: NamingManager.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #7
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAttributesSortedStringSetExists() throws Exception {
	final Attributes attrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("234");
	attrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(attrs, null);
		}
	}
	tested = new TestableDirContextAdapter();
	SortedSet s = tested.getAttributeSortedStringSet("abc");
	assertThat(s).isNotNull();
	assertThat(s).hasSize(2);
	Iterator it = s.iterator();
	assertThat(it.next()).isEqualTo("123");
	assertThat(it.next()).isEqualTo("234");
}
 
Example #8
Source File: LdapTemplateLookupTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testLookup_String_AttributesMapper() throws Exception {
    expectGetReadOnlyContext();

    BasicAttributes expectedAttributes = new BasicAttributes();
    when(dirContextMock.getAttributes(DEFAULT_BASE_STRING)).thenReturn(expectedAttributes);

    Object expected = new Object();
    when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected);

    Object actual = tested
            .lookup(DEFAULT_BASE_STRING, attributesMapperMock);

    verify(dirContextMock).close();

    assertThat(actual).isSameAs(expected);
}
 
Example #9
Source File: ModifyAttributesOperationRecorderTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCompensatingModificationItem_AddExistingAttribute()
        throws NamingException {
    BasicAttribute attribute = new BasicAttribute("someattr");
    attribute.add("value1");
    attribute.add("value2");
    Attributes attributes = new BasicAttributes();
    attributes.put(attribute);

    BasicAttribute modificationAttribute = new BasicAttribute("someattr");
    modificationAttribute.add("newvalue1");
    modificationAttribute.add("newvalue2");
    ModificationItem originalItem = new ModificationItem(
            DirContext.ADD_ATTRIBUTE, new BasicAttribute("someattr"));

    // Perform test
    ModificationItem result = tested.getCompensatingModificationItem(
            attributes, originalItem);

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    assertThat(result.getAttribute().get(0)).isEqualTo("value1");
    assertThat(result.getAttribute().get(1)).isEqualTo("value2");
}
 
Example #10
Source File: LdapTemplateLookupTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testLookup_String_ReturnAttributes_ContextMapper()
        throws Exception {
    expectGetReadOnlyContext();

    String[] attributeNames = new String[] { "cn" };

    BasicAttributes expectedAttributes = new BasicAttributes();
    expectedAttributes.put("cn", "Some Name");

    when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes);

    LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING);
    DirContextAdapter adapter = new DirContextAdapter(expectedAttributes,
            name);

    Object transformed = new Object();
    when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed);

    Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames,
            contextMapperMock);

    verify(dirContextMock).close();

    assertThat(actual).isSameAs(transformed);
}
 
Example #11
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeMultiAttribute_SameValue() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("qwe");
	fixtureAttrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValues("abc", new String[] { "123", "qwe" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(0);
}
 
Example #12
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveMultiAttribute() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	Attribute abc = new BasicAttribute("abc");
	abc.add("123");
	abc.add("456");
	fixtureAttrs.put(abc);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();

	tested.setUpdateMode(true);
	tested.setAttributeValues("abc", new String[] {});

	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(1);
	assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	Attribute attr = mods[0].getAttribute();
	assertThat((String) attr.getID()).isEqualTo("abc");
	assertThat(attr.size()).isEqualTo(0);
}
 
Example #13
Source File: AttributeUtils.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an {@link Entry} to an {@link Attributes}.
 *
 * @param entry
 *      the {@link Entry} to convert
 * @return
 *      the equivalent {@link Attributes}
 */
public static Attributes toAttributes( Entry entry )
{
    if ( entry != null )
    {
        Attributes attributes = new BasicAttributes( true );

        // Looping on attributes
        for ( Iterator<Attribute> attributeIterator = entry.iterator(); attributeIterator.hasNext(); )
        {
            Attribute entryAttribute = attributeIterator.next();

            attributes.put( toJndiAttribute( entryAttribute ) );
        }

        return attributes;
    }

    return null;
}
 
Example #14
Source File: ModifyAttributesOperationRecorderTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCompensatingModificationItem_AddNonExistingAttribute()
        throws NamingException {
    Attributes attributes = new BasicAttributes();

    BasicAttribute modificationAttribute = new BasicAttribute("someattr");
    modificationAttribute.add("newvalue1");
    modificationAttribute.add("newvalue2");
    ModificationItem originalItem = new ModificationItem(
            DirContext.ADD_ATTRIBUTE, modificationAttribute);

    // Perform test
    ModificationItem result = tested.getCompensatingModificationItem(
            attributes, originalItem);

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    assertThat(resultAttribute.size()).isEqualTo(0);
}
 
Example #15
Source File: RebindOperationExecutorTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testPerformOperation() {
    LdapName expectedOriginalDn = LdapUtils.newLdapName(
            "cn=john doe");
    LdapName expectedTempDn = LdapUtils.newLdapName(
            "cn=john doe_temp");
    Object expectedObject = new Object();
    BasicAttributes expectedAttributes = new BasicAttributes();
    RebindOperationExecutor tested = new RebindOperationExecutor(
            ldapOperationsMock, expectedOriginalDn, expectedTempDn,
            expectedObject, expectedAttributes);

    // perform test
    tested.performOperation();
    verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn);
    verify(ldapOperationsMock)
            .bind(expectedOriginalDn, expectedObject, expectedAttributes);
}
 
Example #16
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch_String_SearchControls_ContextMapper_DirContextProcessor() throws Exception {
	expectGetReadOnlyContext();

	SearchControls controls = searchControlsRecursive();

	Object expectedObject = new Object();
	SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());

	singleSearchResultWithStringBase(controls, searchResult);

	Object expectedResult = expectedObject;
	when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);

	List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock,
			dirContextProcessorMock);

       verify(dirContextProcessorMock).preProcess(dirContextMock);
       verify(dirContextProcessorMock).postProcess(dirContextMock);
       verify(namingEnumerationMock).close();
       verify(dirContextMock).close();

	assertThat(list).isNotNull();
	assertThat(list).hasSize(1);
	assertThat(list.get(0)).isSameAs(expectedResult);
}
 
Example #17
Source File: LDAPTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that org.jivesoftware.openfire.ldap.LdapManager#getRelativeDNFromResult(javax.naming.directory.SearchResult)
 * can handle a result that contains multiple RDN values.
 */
@Test
public void testGetRelativeDNFromResultMultiValue() throws Exception
{
    // Setup test fixture.
    final SearchResult input = new SearchResult( "cn=bender,ou=people", null, new BasicAttributes(), true );

    // Execute system under test.
    final Rdn[] result = LdapManager.getRelativeDNFromResult( input );

    // Verify result.
    assertEquals( 2, result.length );
    assertEquals( "cn", result[0].getType() );
    assertEquals( "bender", result[0].getValue() );
    assertEquals( "ou", result[1].getType() );
    assertEquals( "people", result[1].getValue() );
}
 
Example #18
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch_AttributesMapper() throws Exception {
	expectGetReadOnlyContext();

	SearchControls controls = searchControlsOneLevel();
	controls.setReturningObjFlag(false);

	BasicAttributes expectedAttributes = new BasicAttributes();
	SearchResult searchResult = new SearchResult("", null, expectedAttributes);

	singleSearchResult(controls, searchResult);

	Object expectedResult = new Object();
	when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult);

	List list = tested.search(nameMock, "(ou=somevalue)", 1, attributesMapperMock);

       verify(namingEnumerationMock).close();
       verify(dirContextMock).close();

	assertThat(list).isNotNull();
	assertThat(list).hasSize(1);
	assertThat(list.get(0)).isSameAs(expectedResult);
}
 
Example #19
Source File: NamingManager.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #20
Source File: TriggerUtils.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
/**
 * Create the Trigger execution subentry
 * 
 * @param apCtx The administration point context
 * @param subentryCN The CN used by the suentry
 * @param subtreeSpec The subtree specification
 * @param prescriptiveTriggerSpec The prescriptive trigger specification
 * @throws NamingException If the operation failed
 */
public static void createTriggerExecutionSubentry(
    LdapContext apCtx,
    String subentryCN,
    String subtreeSpec,
    String prescriptiveTriggerSpec ) throws NamingException
{
    Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true );
    Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT );
    subentry.put( objectClass );
    objectClass.add( SchemaConstants.TOP_OC );
    objectClass.add( SchemaConstants.SUBENTRY_OC );
    objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC );
    subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec );
    subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec );
    apCtx.createSubcontext( "cn=" + subentryCN, subentry );
}
 
Example #21
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateWithErrorInCallbackShouldFail() throws Exception {
	when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);

	Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"),
			LdapUtils.newLdapName("dc=jayway, dc=se"));
	SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());

	singleSearchResult(searchControlsRecursive(), searchResult);

	when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password"))
               .thenReturn(authenticatedContextMock);
       doThrow(new UncategorizedLdapException("Authentication failed")).when(entryContextCallbackMock)
               .executeWithContext(authenticatedContextMock,
                       new LdapEntryIdentification(
                               LdapUtils.newLdapName("cn=john doe,dc=jayway,dc=se"), LdapUtils.newLdapName("cn=john doe")));

	boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock);

       verify(authenticatedContextMock).close();
       verify(dirContextMock).close();

       assertThat(result).isFalse();
}
 
Example #22
Source File: ApacheKDCServer.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method for creating principals.
 *
 * @param cn           the commonName of the person
 * @param principal    the kerberos principal name for the person
 * @param sn           the surName of the person
 * @param uid          the unique identifier for the person
 * @param userPassword the credentials of the person
 * @return the attributes of the person principal
 */
protected Attributes getPrincipalAttributes(String sn, String cn, String uid,
                                            String userPassword, String principal) {
    Attributes attributes = new BasicAttributes(true);
    Attribute basicAttribute = new BasicAttribute("objectClass");
    basicAttribute.add("top");
    basicAttribute.add("person"); // sn $ cn
    basicAttribute.add("inetOrgPerson"); // uid
    basicAttribute.add("krb5principal");
    basicAttribute.add("krb5kdcentry");
    attributes.put(basicAttribute);
    attributes.put("cn", cn);
    attributes.put("sn", sn);
    attributes.put("uid", uid);
    attributes.put(SchemaConstants.USER_PASSWORD_AT, userPassword);
    attributes.put(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT, principal);
    attributes.put(KerberosAttribute.KRB5_KEY_VERSION_NUMBER_AT, "0");

    return attributes;
}
 
Example #23
Source File: ChainingUserRegistrySynchronizerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private LDAPInitialDirContextFactoryImpl getMockedLDAPSearchResult(boolean withEmail) throws NamingException
{
    @SuppressWarnings("unchecked")
    NamingEnumeration<SearchResult> mockedNamingEnumeration = mock(NamingEnumeration.class);
    when(mockedNamingEnumeration.hasMore()).thenReturn(true).thenReturn(false);

    BasicAttributes attributes = new BasicAttributes();
    attributes.put(new BasicAttribute("sAMAccountName", "U1"));
    attributes.put(new BasicAttribute("givenName", "U1"));
    if (withEmail)
    {
        attributes.put(new BasicAttribute("mail", "[email protected]"));
    }
    SearchResult mockedSearchResult = new SearchResult("CN:U1", null, attributes);
    mockedSearchResult.setNameInNamespace("CN:U1");

    when(mockedNamingEnumeration.next()).thenReturn(mockedSearchResult);

    InitialDirContext mockedInitialDirContext = mock(InitialDirContext.class);
    when(mockedInitialDirContext.search((String)any(), anyString(), any(SearchControls.class))).thenReturn(mockedNamingEnumeration);

    LDAPInitialDirContextFactoryImpl mockedLdapInitialDirContextFactory = mock(LDAPInitialDirContextFactoryImpl.class);
    when(mockedLdapInitialDirContextFactory.getDefaultIntialDirContext(0)).thenReturn(mockedInitialDirContext);
    return mockedLdapInitialDirContextFactory;
}
 
Example #24
Source File: LDAPIdentityStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void add(LDAPObject ldapObject) {
    // id will be assigned by the ldap server
    if (ldapObject.getUuid() != null) {
        throw new ModelException("Can't add object with already assigned uuid");
    }

    String entryDN = ldapObject.getDn().toString();
    BasicAttributes ldapAttributes = extractAttributesForSaving(ldapObject, true);
    this.operationManager.createSubContext(entryDN, ldapAttributes);
    ldapObject.setUuid(getEntryIdentifier(ldapObject));

    if (logger.isDebugEnabled()) {
        logger.debugf("Type with identifier [%s] and dn [%s] successfully added to LDAP store.", ldapObject.getUuid(), entryDN);
    }
}
 
Example #25
Source File: TestJNDIRealm.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private NamingEnumeration<SearchResult> mockSearchResults(String password)
        throws NamingException {
    @SuppressWarnings("unchecked")
    NamingEnumeration<SearchResult> searchResults =
            EasyMock.createNiceMock(NamingEnumeration.class);
    EasyMock.expect(Boolean.valueOf(searchResults.hasMore()))
            .andReturn(Boolean.TRUE)
            .andReturn(Boolean.FALSE)
            .andReturn(Boolean.TRUE)
            .andReturn(Boolean.FALSE);
    EasyMock.expect(searchResults.next())
            .andReturn(new SearchResult("ANY RESULT", "",
                    new BasicAttributes(USER_PASSWORD_ATTR, password)))
            .times(2);
    EasyMock.replay(searchResults);
    return searchResults;
}
 
Example #26
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveDnAttributeSyntacticallyEqual() throws NamingException {
    BasicAttributes attributes = new BasicAttributes();
    attributes.put("uniqueMember", "cn=john doe,OU=company");

    DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups"));
    tested.setUpdateMode(true);

    tested.removeAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company"));
    ModificationItem[] modificationItems = tested.getModificationItems();
    assertThat(modificationItems.length).isEqualTo(1);

    ModificationItem modificationItem = modificationItems[0];
    assertThat(modificationItem.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
    assertThat(modificationItem.getAttribute().getID()).isEqualTo("uniqueMember");
}
 
Example #27
Source File: NamingManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new DnsContext("", null, new Hashtable<String,String>()) {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}
 
Example #28
Source File: LdapResult.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
boolean compareToSearchResult(String name) {
    boolean successful = false;

    switch (status) {
        case LdapClient.LDAP_COMPARE_TRUE:
            status = LdapClient.LDAP_SUCCESS;
            entries = new Vector<>(1,1);
            Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
            LdapEntry entry = new LdapEntry( name, attrs );
            entries.addElement(entry);
            successful = true;
            break;

        case LdapClient.LDAP_COMPARE_FALSE:
            status = LdapClient.LDAP_SUCCESS;
            entries = new Vector<>(0);
            successful = true;
            break;

        default:
            successful = false;
            break;
    }

    return successful;
}
 
Example #29
Source File: LdapManager.java    From fess with Apache License 2.0 6 votes vote down vote up
public void insert(final Group group) {
    if (!fessConfig.isLdapAdminEnabled()) {
        return;
    }

    final Supplier<Hashtable<String, String>> adminEnv = this::createAdminEnv;
    final String entryDN = fessConfig.getLdapAdminGroupSecurityPrincipal(group.getName());
    search(fessConfig.getLdapAdminGroupBaseDn(), fessConfig.getLdapAdminGroupFilter(group.getName()), null, adminEnv, result -> {
        if (!result.isEmpty()) {
            logger.info("{} exists in LDAP server.", group.getName());
            modifyGroupAttributes(group, adminEnv, entryDN, result);
        } else {
            final BasicAttributes entry = new BasicAttributes();
            addGroupAttributes(entry, group);
            final Attribute oc = fessConfig.getLdapAdminGroupObjectClassAttribute();
            entry.put(oc);
            insert(entryDN, entry, adminEnv);
        }
    });
}
 
Example #30
Source File: NamingManager.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static Context getURLContext(
        String scheme, Hashtable<?,?> environment)
        throws NamingException {
    return new InitialDirContext() {
        public Attributes getAttributes(String name, String[] attrIds)
                throws NamingException {
            return new BasicAttributes() {
                public Attribute get(String attrID) {
                    BasicAttribute ba  = new BasicAttribute(attrID);
                    ba.add("1 1 99 b.com.");
                    ba.add("0 0 88 a.com.");    // 2nd has higher priority
                    return ba;
                }
            };
        }
    };
}