Java Code Examples for javax.naming.directory.Attributes#get()

The following examples show how to use javax.naming.directory.Attributes#get() . 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: LdapManager.java    From fess with Apache License 2.0 6 votes vote down vote up
protected List<Object> getAttributeValueList(final List<SearchResult> result, final String name) {
    try {
        for (final SearchResult srcrslt : result) {
            final Attributes attrs = srcrslt.getAttributes();

            final Attribute attr = attrs.get(name);
            if (attr == null) {
                continue;
            }

            final List<Object> attrList = new ArrayList<>();
            for (int i = 0; i < attr.size(); i++) {
                final Object attrValue = attr.get(i);
                if (attrValue != null) {
                    attrList.add(attrValue);
                }
            }
            return attrList;
        }
        return Collections.emptyList();
    } catch (final NamingException e) {
        throw new LdapOperationException("Failed to parse attribute values for " + name, e);
    }
}
 
Example 2
Source File: ApacheKDCServer.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void enableKerberoseSchema() throws DirectoryServerException {
    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs;
    try {
        krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");

        boolean isKrb5KdcDisabled = false;
        if (krb5kdcAttrs.get("m-disabled") != null) {
            isKrb5KdcDisabled = "TRUE".equalsIgnoreCase((String) krb5kdcAttrs.get("m-disabled").get());
        }

        // if krb5kdc is disabled then enable it
        if (isKrb5KdcDisabled) {
            Attribute disabled = new BasicAttribute("m-disabled");
            ModificationItem[] mods =
                    new ModificationItem[]{new ModificationItem(
                            DirContext.REMOVE_ATTRIBUTE, disabled)};
            schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
        }
    } catch (NamingException e) {
        String msg = "An error occurred while enabling Kerberos schema.";
        logger.error(msg, e);
        throw new DirectoryServerException(msg, e);
    }
}
 
Example 3
Source File: LdapCertificateRepo.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected List<X509CRL> getCRLsFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
    try {
        List<X509CRL> crls = new ArrayList<>();
        NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute attribute = attrs.get(tmpAttrName);
            if (attribute != null) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(
                        (byte[]) attribute.get()));
                crls.add(crl);
            }
        }
        return crls;
    } catch (CertificateException | NamingException | CRLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 4
Source File: LdapService.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
   public boolean getDisabledBoolean(Attributes attrs) {
String ldapDisabledAttrStr = Configuration.get(ConfigurationKeys.LDAP_DISABLED_ATTR);
if (ldapDisabledAttrStr.startsWith("!")) {
    ldapDisabledAttrStr = ldapDisabledAttrStr.substring(1);
    Attribute ldapDisabledAttr = attrs.get(ldapDisabledAttrStr);
    Boolean booleanValue = getAsBoolean(ldapDisabledAttr);
    if (booleanValue != null) {
	return !booleanValue;
    } else {
	// if there is no value, assume not disabled
	return false;
    }
} else {
    return getAsBoolean(attrs.get(ldapDisabledAttrStr));
}

   }
 
Example 5
Source File: LdapName.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 6
Source File: GatekeeperLdapLookupService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Override
public GatekeeperSearchUserEntry mapFromAttributes(Attributes attributes) throws NamingException {
    Attribute idAttr    =   attributes.get(ldapUserId);
    Attribute mailAttr  =   attributes.get(ldapUserEmail);
    Attribute nameAttr  =   attributes.get(ldapUserName);

    String id   =   idAttr      != null ? ((String) idAttr.get()).toLowerCase() : null;
    String mail =   mailAttr    != null ? (String) mailAttr.get() : null;
    String name =   nameAttr    != null ? (String) nameAttr.get() : null;


    return new GatekeeperSearchUserEntry(id, mail, name);
}
 
Example 7
Source File: AbstractVerifierFix.java    From steady with Apache License 2.0 5 votes vote down vote up
static String[] extractCNs(final String subjectPrincipal) throws SSLException {
    if (subjectPrincipal == null) {
        return null;
    }
    final List<String> cns = new ArrayList<String>();
    try {
        final LdapName subjectDN = new LdapName(subjectPrincipal);
        final List<Rdn> rdns = subjectDN.getRdns();
        for (int i = rdns.size() - 1; i >= 0; i--) {
            final Rdn rds = rdns.get(i);
            final Attributes attributes = rds.toAttributes();
            final Attribute cn = attributes.get("cn");
            if (cn != null) {
                try {
                    final Object value = cn.get();
                    if (value != null) {
                        cns.add(value.toString());
                    }
                } catch (NamingException ignore) {
                }
            }
        }
    } catch (InvalidNameException e) {
        throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
    }
    return cns.isEmpty() ? null : cns.toArray(new String[ cns.size() ]);
}
 
Example 8
Source File: J_AbstractVerifier_F.java    From steady with Apache License 2.0 5 votes vote down vote up
static String[] extractCNs(final String subjectPrincipal) throws SSLException {
    if (subjectPrincipal == null) {
        return null;
    }
    final List<String> cns = new ArrayList<String>();
    try {
        final LdapName subjectDN = new LdapName(subjectPrincipal);
        final List<Rdn> rdns = subjectDN.getRdns();
        for (int i = rdns.size() - 1; i >= 0; i--) {
            final Rdn rds = rdns.get(i);
            final Attributes attributes = rds.toAttributes();
            final Attribute cn = attributes.get("cn");
            if (cn != null) {
                try {
                    final Object value = cn.get();
                    if (value != null) {
                        cns.add(value.toString());
                    }
                } catch (NamingException ignore) {
                }
            }
        }
    } catch (InvalidNameException e) {
        throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
    }
    return cns.isEmpty() ? null : cns.toArray(new String[ cns.size() ]);
}
 
Example 9
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAttribute() throws Exception {
	final Attributes fixtureAttrs = new BasicAttributes();
	fixtureAttrs.put(new BasicAttribute("abc", "123"));
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(fixtureAttrs, null);
			setUpdateMode(true);
		}
	}
	tested = new TestableDirContextAdapter();

	tested.setUpdateMode(true);
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValue("abc", null);
	Attributes attrs = tested.getAttributes();
	Attribute attr = attrs.get("abc");
	assertThat((String) attr.get()).isEqualTo("123");

	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(1);
	assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
	attr = mods[0].getAttribute();
	assertThat((String) attr.getID()).isEqualTo("abc");
	String[] modNames = tested.getNamesOfModifiedAttributes();
	assertThat(modNames.length).isEqualTo(1);
	assertThat(modNames[0]).isEqualTo("abc");

	tested.update();
	mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(0);
	modNames = tested.getNamesOfModifiedAttributes();
	assertThat(modNames.length).isEqualTo(0);
	attrs = tested.getAttributes();
	attr = attrs.get("abc");
	assertThat(attr).isNull();
}
 
Example 10
Source File: LDAPDataDao.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
private String getNameValueFromAttribute(Attributes attrs, String attrName){
	javax.naming.directory.Attribute attr = attrs.get(attrName);
	if( attr == null ) {
		return null;
	}
	String attrString = attr.toString();
    return attrString.substring(attrString.indexOf(":") + 2);
}
 
Example 11
Source File: LdapName.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 12
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddAttributeValueAttributeWithSameValueExists()
		throws NamingException {
	tested.setAttribute(new BasicAttribute("abc", "123"));

	// Perform test
	tested.addAttributeValue("abc", "123");

	Attributes attrs = tested.getAttributes();
	Attribute attr = attrs.get("abc");
	assertThat(attr.size()).isEqualTo(1);
	assertThat((String) attr.get(0)).isEqualTo("123");
}
 
Example 13
Source File: LdapGroupSearcherFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private LdapEntry convertToLdapEntry(SearchResult searchResult, Attributes attributes, final URI referralAddress) throws NamingException {
    String simpleName = null;
    String distinguishedName = null;

    if (groupNameAttribute != null) {
        SECURITY_LOGGER.tracef("Getting groupNameAttribute=%s", groupNameAttribute);
        Attribute groupNameAttr = attributes.get(groupNameAttribute);
        if (groupNameAttr != null) {
            simpleName = (String) groupNameAttr.get();
        }
    }

    if (groupDnAttribute != null) {
        if ("dn".equals(groupDnAttribute)) {
            SECURITY_LOGGER.trace("Obtaining dn using getNameInNamespace()");
            distinguishedName = searchResult.getNameInNamespace();
        } else {
            SECURITY_LOGGER.tracef("Getting groupDnAttribute=%s", groupDnAttribute);
            Attribute groupDnAttr = attributes.get(groupDnAttribute);
            if (groupDnAttr != null) {
                distinguishedName = (String) groupDnAttr.get();
            }
        }
    }

    return new LdapEntry(simpleName, distinguishedName, referralAddress);
}
 
Example 14
Source File: LDAPCertStore.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a map containing the values for this request. The first time
 * this method is called on an object, the LDAP request is sent,
 * the results parsed and added to a private map and also to the
 * cache of this LDAPCertStore. Subsequent calls return the private
 * map immediately.
 *
 * The map contains an entry for each requested attribute. The
 * attribute name is the key, values are byte[][]. If there are no
 * values for that attribute, values are byte[0][].
 *
 * @return                      the value Map
 * @throws NamingException      if a naming exception occurs
 */
private Map<String, byte[][]> getValueMap() throws NamingException {
    if (valueMap != null) {
        return valueMap;
    }
    if (DEBUG) {
        System.out.println("Request: " + name + ":" + requestedAttributes);
        requests++;
        if (requests % 5 == 0) {
            System.out.println("LDAP requests: " + requests);
        }
    }
    valueMap = new HashMap<>(8);
    String[] attrIds = requestedAttributes.toArray(STRING0);
    Attributes attrs;
    try {
        attrs = ctx.getAttributes(name, attrIds);
    } catch (NameNotFoundException e) {
        // name does not exist on this LDAP server
        // treat same as not attributes found
        attrs = EMPTY_ATTRIBUTES;
    }
    for (String attrId : requestedAttributes) {
        Attribute attr = attrs.get(attrId);
        byte[][] values = getAttributeValues(attr);
        cacheAttribute(attrId, values);
        valueMap.put(attrId, values);
    }
    return valueMap;
}
 
Example 15
Source File: QueryforuserAction.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * A utility class extracting LDAP attributes, not throwing an exception if the
 * attribute does not exist
 * 
 * @param attrs         list of attributes
 * @param attributename attribute name
 * @return the attribute if it exists, empty string else
 */
public static String extractAttributeIfPresent(Attributes attrs, String attributename) {
	try {
		Attribute attribute = attrs.get(attributename);
		if (attribute != null) {
			Object attributepayload = attribute.get();
			if (attributepayload != null)
				return attributepayload.toString();
		}
	} catch (NamingException e) {
		logger.severe("Exception getting attribute " + attributename + " - " + e.getMessage());
	}
	return "";
}
 
Example 16
Source File: LdapName.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 17
Source File: LDAPCertStore.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a map containing the values for this request. The first time
 * this method is called on an object, the LDAP request is sent,
 * the results parsed and added to a private map and also to the
 * cache of this LDAPCertStore. Subsequent calls return the private
 * map immediately.
 *
 * The map contains an entry for each requested attribute. The
 * attribute name is the key, values are byte[][]. If there are no
 * values for that attribute, values are byte[0][].
 *
 * @return                      the value Map
 * @throws NamingException      if a naming exception occurs
 */
private Map<String, byte[][]> getValueMap() throws NamingException {
    if (valueMap != null) {
        return valueMap;
    }
    if (DEBUG) {
        System.out.println("Request: " + name + ":" + requestedAttributes);
        requests++;
        if (requests % 5 == 0) {
            System.out.println("LDAP requests: " + requests);
        }
    }
    valueMap = new HashMap<>(8);
    String[] attrIds = requestedAttributes.toArray(STRING0);
    Attributes attrs;
    try {
        attrs = ctx.getAttributes(name, attrIds);
    } catch (NameNotFoundException e) {
        // name does not exist on this LDAP server
        // treat same as not attributes found
        attrs = EMPTY_ATTRIBUTES;
    }
    for (String attrId : requestedAttributes) {
        Attribute attr = attrs.get(attrId);
        byte[][] values = getAttributeValues(attr);
        cacheAttribute(attrId, values);
        valueMap.put(attrId, values);
    }
    return valueMap;
}
 
Example 18
Source File: LdifAttributesReaderTest.java    From directory-ldap-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testLdifAttributesReaderDirServer() throws NamingException, Exception
{
    String ldif = 
          "# -------------------------------------------------------------------\n" 
        + "#\n"
        + "#  Licensed to the Apache Software Foundation (ASF) under one\n"
        + "#  or more contributor license agreements.  See the NOTICE file\n"
        + "#  distributed with this work for additional information\n"
        + "#  regarding copyright ownership.  The ASF licenses this file\n"
        + "#  to you under the Apache License, Version 2.0 (the\n"
        + "#  \"License\"); you may not use this file except in compliance\n"
        + "#  with the License.  You may obtain a copy of the License at\n" 
        + "#  \n"
        + "#    http://www.apache.org/licenses/LICENSE-2.0\n" 
        + "#  \n"
        + "#  Unless required by applicable law or agreed to in writing,\n"
        + "#  software distributed under the License is distributed on an\n"
        + "#  \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n"
        + "#  KIND, either express or implied.  See the License for the\n"
        + "#  specific language governing permissions and limitations\n" 
        + "#  under the License. \n" 
        + "#  \n"
        + "#\n" 
        + "# EXAMPLE.COM is freely and reserved for testing according to this RFC:\n" 
        + "#\n"
        + "# http://www.rfc-editor.org/rfc/rfc2606.txt\n" 
        + "#\n"
        + "# -------------------------------------------------------------------\n" 
        + "\n" 
        + "objectclass: top\n"
        + "objectclass: organizationalunit\n" 
        + "ou: Users";

    LdifAttributesReader reader = new LdifAttributesReader();

    Attributes attributes = reader.parseAttributes( ldif );

    javax.naming.directory.Attribute attr = attributes.get( "objectclass" );
    assertTrue( attr.contains( "top" ) );
    assertTrue( attr.contains( "organizationalunit" ) );

    attr = attributes.get( "ou" );
    assertTrue( attr.contains( "Users" ) );
    reader.close();
}
 
Example 19
Source File: LdapAuthenticateModule.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
 * Perform actual authentication the user
 */
public boolean doAuthenticate(HashMap userProps) throws Exception {
	if (ApplicationProperties
			.getProperty("tmtbl.authenticate.ldap.provider") == null)
		throw new Exception("Ldap provider is not set.");

	String principal = ApplicationProperties
			.getProperty("tmtbl.authenticate.ldap.principal");
	if (principal == null)
		throw new Exception("Ldap principal is not set.");

	String query = ApplicationProperties
			.getProperty("tmtbl.authenticate.ldap.query");
	if (query == null)
		throw new Exception("Ldap query is not set.");

	String n = (String) userProps.get("username");
	String p = (String) userProps.get("password");

	Hashtable<String, String> env = getEnv();
	env.put(Context.SECURITY_PRINCIPAL, principal.replaceAll("%", n));
	env.put(Context.SECURITY_CREDENTIALS, p);
	InitialDirContext cx = new InitialDirContext(env);

	String idAttributeName = ApplicationProperties.getProperty(
			"tmtbl.authenticate.ldap.externalId", "uid");
	Attributes attributes = cx.getAttributes(query.replaceAll("%", n),
			new String[] { idAttributeName });

	Attribute idAttribute = attributes.get(idAttributeName);
	if (idAttribute != null) {
		sLog.debug("Ldap authentication passed ... ");
		setAuthSucceeded(true);
		iExternalUid = (String) idAttribute.get();
		try {
			if (iExternalUid != null
					&& ApplicationProperties
							.getProperty("tmtbl.authenticate.ldap.externalId.format") != null)
				iExternalUid = new DecimalFormat(
						ApplicationProperties
								.getProperty("tmtbl.authenticate.ldap.externalId.format"))
						.format(Long.parseLong(iExternalUid));
		} catch (NumberFormatException e) {
		}
		setUser(n);
		return true;
	}

	return false;
}
 
Example 20
Source File: LdapExternalUidLookup.java    From unitime with Apache License 2.0 4 votes vote down vote up
@Override
public UserInfo doLookup(String searchId) throws Exception {
	
	String query = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.identify");
	if (query == null) return null;
	
       DirContext ctx = null;
       try {
           ctx = getDirContext();
           
   		String idAttributeName = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.externalId","uid");
   		String loginAttributeName = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid");
   		Attributes attributes = ctx.getAttributes(query.replaceAll("%", searchId), new String[] {idAttributeName, loginAttributeName, "cn", "givenName", "sn", "mail"});
           Attribute idAttribute = attributes.get(idAttributeName);
           if (idAttribute == null) return null;
           
       	UserInfo user = new UserInfo();
       	user.setExternalId((String)idAttribute.get());
       	user.setUserName((String)attributes.get(loginAttributeName).get());
       	if (attributes.get("cn") != null)
       		user.setName((String)attributes.get("cn").get());
       	if (attributes.get("givenName") != null)
       		user.setFirstName((String)attributes.get("givenName").get());
       	if (attributes.get("cn") != null)
       		user.setName((String)attributes.get("cn").get());
       	if (attributes.get("sn") != null)
       		user.setLastName((String)attributes.get("sn").get());
       	if (attributes.get("mail") != null) {
       		user.setEmail((String)attributes.get("mail").get());
       	} else {
           	String email = user.getUserName() + "@";
           	for (String x: query.split(","))
           		if (x.startsWith("dc=")) email += (email.endsWith("@") ? "" : ".") + x.substring(3);
           	if (!email.endsWith("@")) user.setEmail(email);
       	}
       	
       	return user;			
	} finally {
		if (ctx != null) ctx.close();
	}
}