Java Code Examples for javax.naming.directory.Attributes

The following are top voted examples for showing how to use javax.naming.directory.Attributes. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: open-rmbt   File: LookupService.java   View source code 7 votes vote down vote up
String getDnsAttributes(String ip) {
	try {
		Hashtable<String, String> env = new Hashtable<>();
		env.put("java.naming.factory.initial",
				"com.sun.jndi.dns.DnsContextFactory");
		// TODO don't specify ws1, instead use ns servers for s.maxmind.com
		env.put("java.naming.provider.url", "dns://ws1.maxmind.com/");

		DirContext ictx = new InitialDirContext(env);
		Attributes attrs = ictx.getAttributes(licenseKey + "." + ip
				+ ".s.maxmind.com", new String[] { "txt" });
		// System.out.println(attrs.get("txt").get());
		String str = attrs.get("txt").get().toString();
		return str;
	} catch (NamingException e) {
		// TODO fix this to handle exceptions
		System.out.println("DNS error");
		return null;
	}

}
 
Example 2
Project: directory-ldap-api   File: LdifUtilsTest.java   View source code 6 votes vote down vote up
/**
 * Test a conversion of an attributes from a LDIF file
 * @throws org.apache.directory.api.ldap.model.ldif.LdapLdifException
 */
@Test
public void testConvertAttributesfromLdif() throws LdapException, LdapLdifException
{
    Attributes attributes = new BasicAttributes( true );

    Attribute oc = new BasicAttribute( "objectclass" );
    oc.add( "top" );
    oc.add( "person" );
    oc.add( "inetorgPerson" );

    attributes.put( oc );

    attributes.put( "cn", "Saarbrucken" );
    attributes.put( "sn", "test" );

    String ldif = LdifUtils.convertToLdif( attributes, ( Dn ) null, 15 );
    Attributes result = LdifUtils.getJndiAttributesFromLdif( ldif );
    assertEquals( attributes, result );
}
 
Example 3
Project: directory-ldap-api   File: TriggerUtils.java   View source code 6 votes vote down vote up
/**
 * Defines the Administration point and administrative role for the TriggerExecution specific point
 * @param apCtx The administrative point context
 * @throws NamingException If the operation failed
 */
public static void defineTriggerExecutionSpecificPoint( LdapContext apCtx ) throws NamingException
{
    Attributes ap = apCtx.getAttributes( "", new String[] { SchemaConstants.ADMINISTRATIVE_ROLE_AT } );
    Attribute administrativeRole = ap.get( SchemaConstants.ADMINISTRATIVE_ROLE_AT );
    
    if ( administrativeRole == null
        || !AttributeUtils.containsValueCaseIgnore( administrativeRole, SchemaConstants.TRIGGER_EXECUTION_SPECIFIC_AREA ) )
    {
        Attributes changes = new BasicAttributes( SchemaConstants.ADMINISTRATIVE_ROLE_AT,
            SchemaConstants.TRIGGER_EXECUTION_SPECIFIC_AREA, true );
        apCtx.modifyAttributes( "", DirContext.ADD_ATTRIBUTE, changes );
    }
}
 
Example 4
Project: CustomWorldGen   File: ServerAddress.java   View source code 6 votes vote down vote up
/**
 * Returns a server's address and port for the specified hostname, looking up the SRV record if possible
 */
private static String[] getServerAddress(String p_78863_0_)
{
    try
    {
        String s = "com.sun.jndi.dns.DnsContextFactory";
        Class.forName("com.sun.jndi.dns.DnsContextFactory");
        Hashtable<String, String> hashtable = new Hashtable();
        hashtable.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
        hashtable.put("java.naming.provider.url", "dns:");
        hashtable.put("com.sun.jndi.dns.timeout.retries", "1");
        DirContext dircontext = new InitialDirContext(hashtable);
        Attributes attributes = dircontext.getAttributes("_minecraft._tcp." + p_78863_0_, new String[] {"SRV"});
        String[] astring = attributes.get("srv").get().toString().split(" ", 4);
        return new String[] {astring[3], astring[2]};
    }
    catch (Throwable var6)
    {
        return new String[] {p_78863_0_, Integer.toString(25565)};
    }
}
 
Example 5
Project: jerrydog   File: JNDIRealm.java   View source code 6 votes vote down vote up
/**
 * Return a String representing the value of the specified attribute.
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the required value
 *
 * @exception NamingException if a directory server error occurs
 */
private String getAttributeValue(String attrId, Attributes attrs)
    throws NamingException {

    if (debug >= 3)
        log("  retrieving attribute " + attrId);

    if (attrId == null || attrs == null)
        return null;

    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return (null);
    Object value = attr.get();
    if (value == null)
        return (null);
    String valueString = null;
    if (value instanceof byte[])
        valueString = new String((byte[]) value);
    else
        valueString = value.toString();
    
    return valueString;
}
 
Example 6
Project: joai-project   File: LdapClient.java   View source code 6 votes vote down vote up
/**
 * Converts a JNDI SearchResult into our LdapEntry object.
 */

private LdapEntry decodeSearchResult(
	SearchResult sr,
	String contextBase,
	String[] attrNames)
throws LdapException
{
	// print dn == distinguished name
	String dn;
	if (sr.getName() == null || sr.getName().length() == 0)
		dn = contextBase;
	else dn = sr.getName() + "," + contextBase;

	Attributes attrraw = sr.getAttributes();
	return decodeAttributes( dn, attrNames, attrraw);
}
 
Example 7
Project: lams   File: WARDirContext.java   View source code 6 votes vote down vote up
/**
 * Retrieves all of the attributes associated with a named object. 
 * 
 * @return the set of attributes associated with name. 
 * Returns an empty attribute set if name has no attributes; never null.
 * @param name the name of the object from which to retrieve attributes
 * @exception NamingException if a naming exception is encountered
 */
public Attributes getAttributes(Name name, String[] attrIds)
    throws NamingException {
    
    Entry entry = null;
    if (name.isEmpty())
        entry = entries;
    else
        entry = treeLookup(name);
    if (entry == null)
        throw new NamingException
            (sm.getString("resources.notFound", name));
    
    ZipEntry zipEntry = entry.getEntry();

    ResourceAttributes attrs = new ResourceAttributes();
    attrs.setCreationDate(new Date(zipEntry.getTime()));
    attrs.setName(entry.getName());
    if (!zipEntry.isDirectory())
        attrs.setResourceType("");
    attrs.setContentLength(zipEntry.getSize());
    attrs.setLastModified(zipEntry.getTime());
    
    return attrs;
    
}
 
Example 8
Project: hadoop   File: TestLdapGroupsMapping.java   View source code 5 votes vote down vote up
@Before
public void setupMocks() throws NamingException {
  mockContext = mock(DirContext.class);
  doReturn(mockContext).when(mappingSpy).getDirContext();
          
  SearchResult mockUserResult = mock(SearchResult.class);
  // We only ever call hasMoreElements once for the user NamingEnum, so 
  // we can just have one return value
  when(mockUserNamingEnum.hasMoreElements()).thenReturn(true);
  when(mockUserNamingEnum.nextElement()).thenReturn(mockUserResult);
  when(mockUserResult.getNameInNamespace()).thenReturn("CN=some_user,DC=test,DC=com");
  
  SearchResult mockGroupResult = mock(SearchResult.class);
  // We're going to have to define the loop here. We want two iterations,
  // to get both the groups
  when(mockGroupNamingEnum.hasMoreElements()).thenReturn(true, true, false);
  when(mockGroupNamingEnum.nextElement()).thenReturn(mockGroupResult);
  
  // Define the attribute for the name of the first group
  Attribute group1Attr = new BasicAttribute("cn");
  group1Attr.add(testGroups[0]);
  Attributes group1Attrs = new BasicAttributes();
  group1Attrs.put(group1Attr);
  
  // Define the attribute for the name of the second group
  Attribute group2Attr = new BasicAttribute("cn");
  group2Attr.add(testGroups[1]);
  Attributes group2Attrs = new BasicAttributes();
  group2Attrs.put(group2Attr);
  
  // This search result gets reused, so return group1, then group2
  when(mockGroupResult.getAttributes()).thenReturn(group1Attrs, group2Attrs);
}
 
Example 9
Project: directory-ldap-api   File: LdifAttributesReader.java   View source code 5 votes vote down vote up
/**
 * Parse an AttributeType/AttributeValue
 *
 * @param attributes The entry where to store the value
 * @param line The line to parse
 * @param lowerLine The same line, lowercased
 * @throws LdapLdifException If anything goes wrong
 */
private void parseAttribute( Attributes attributes, String line, String lowerLine ) throws LdapLdifException
{
    int colonIndex = line.indexOf( ':' );

    String attributeType = lowerLine.substring( 0, colonIndex );

    // We should *not* have a Dn twice
    if ( "dn".equals( attributeType ) )
    {
        LOG.error( I18n.err( I18n.ERR_12002_ENTRY_WITH_TWO_DNS ) );
        throw new LdapLdifException( I18n.err( I18n.ERR_12003_LDIF_ENTRY_WITH_TWO_DNS ) );
    }

    Object attributeValue = parseValue( attributeType, line, colonIndex );

    // Update the entry
    javax.naming.directory.Attribute attribute = attributes.get( attributeType );

    if ( attribute == null )
    {
        attributes.put( attributeType, attributeValue );
    }
    else
    {
        attribute.add( attributeValue );
    }
}
 
Example 10
Project: directory-ldap-api   File: LdifUtils.java   View source code 5 votes vote down vote up
/**
 * Convert a LDIF String to a JNDI attributes.
 *
 * @param ldif The LDIF string containing an attribute value
 * @return An Attributes instance
 * @exception LdapLdifException If the LDIF String cannot be converted to an Attributes
 */
public static Attributes getJndiAttributesFromLdif( String ldif ) throws LdapLdifException
{
    try ( LdifAttributesReader reader = new LdifAttributesReader() )
    {
        return AttributeUtils.toAttributes( reader.parseEntry( ldif ) );
    }
    catch ( IOException ioe )
    {
        throw new LdapLdifException( ioe.getMessage(), ioe );
    }
}
 
Example 11
Project: directory-ldap-api   File: LdifUtilsTest.java   View source code 5 votes vote down vote up
/**
 * Tests that unsafe characters are encoded using UTF-8 charset. 
 * @throws LdapException 
 * 
 * @throws NamingException
 */
@Test
public void testConvertToLdifEncoding() throws LdapException
{
    Attributes attributes = new BasicAttributes( "cn", "Saarbr\u00FCcken" );
    String ldif = LdifUtils.convertToLdif( attributes );
    assertEquals( "cn:: U2FhcmJyw7xja2Vu\n", ldif );
}
 
Example 12
Project: directory-ldap-api   File: LdifUtilsTest.java   View source code 5 votes vote down vote up
/**
 * Tests that null values are correctly encoded 
 * 
 * @throws NamingException
 */
@Test
public void testConvertToLdifAttrWithNullValues() throws LdapException
{
    Attributes attributes = new BasicAttributes( "cn", null );
    String ldif = LdifUtils.convertToLdif( attributes );
    assertEquals( "cn:\n", ldif );
}
 
Example 13
Project: Equella   File: GroupSearch.java   View source code 5 votes vote down vote up
public List<GroupBean> getGroupsFromNames(DirContext ctx, Collection<Name> ldapgroupnames)
{
	List<GroupBean> alist = new ArrayList<GroupBean>();

	for( Name groupname : ldapgroupnames )
	{
		Attributes gattr = ldap.getAttributes(ctx, groupname, ldap.getGroupAttributes());
		GroupBean gbean = ldap.getGroupBeanFromResult(new LDAPResult(groupname, gattr));
		if( gbean != null )
		{
			alist.add(gbean);
		}
	}
	return alist;
}
 
Example 14
Project: lazycat   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * Add values of a specified attribute to a list
 *
 * @param attrId
 *            Attribute name
 * @param attrs
 *            Attributes containing the new values
 * @param values
 *            ArrayList containing values found so far
 *
 * @exception NamingException
 *                if a directory server error occurs
 */
private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values)
		throws NamingException {

	if (containerLog.isTraceEnabled())
		containerLog.trace("  retrieving values for attribute " + attrId);
	if (attrId == null || attrs == null)
		return values;
	if (values == null)
		values = new ArrayList<String>();
	Attribute attr = attrs.get(attrId);
	if (attr == null)
		return values;
	NamingEnumeration<?> e = attr.getAll();
	try {
		while (e.hasMore()) {
			String value = (String) e.next();
			values.add(value);
		}
	} catch (PartialResultException ex) {
		if (!adCompat)
			throw ex;
	} finally {
		e.close();
	}
	return values;
}
 
Example 15
Project: openjdk-jdk10   File: NamingManager.java   View source code 5 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;
                }
            };
        }
    };
}
 
Example 16
Project: tomcat7   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * Use the distinguished name to locate the directory
 * entry for the user with the specified username and
 * return a User object; otherwise return <code>null</code>.
 *
 * @param context The directory context
 * @param username The username
 * @param attrIds String[]containing names of attributes to
 * @param dn Distinguished name of the user
 * retrieve.
 *
 * @exception NamingException if a directory server error occurs
 */
protected User getUserByPattern(DirContext context,
                                String username,
                                String[] attrIds,
                                String dn)
    throws NamingException {

    // If no attributes are requested, no need to look for them
    if (attrIds == null || attrIds.length == 0) {
        return new User(username, dn, null, null,null);
    }

    // Get required attributes from user entry
    Attributes attrs = null;
    try {
        attrs = context.getAttributes(dn, attrIds);
    } catch (NameNotFoundException e) {
        return null;
    }
    if (attrs == null)
        return null;

    // Retrieve value of userPassword
    String password = null;
    if (userPassword != null)
        password = getAttributeValue(userPassword, attrs);

    String userRoleAttrValue = null;
    if (userRoleAttribute != null) {
        userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
    }

    // Retrieve values of userRoleName attribute
    ArrayList<String> roles = null;
    if (userRoleName != null)
        roles = addAttributeValues(userRoleName, attrs, roles);

    return new User(username, dn, password, roles, userRoleAttrValue);
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: WARDirContext.java   View source code 5 votes vote down vote up
/**
 * Retrieves all of the attributes associated with a named object. 
 * 
 * @return the set of attributes associated with name. 
 * Returns an empty attribute set if name has no attributes; never null.
 * @param name the name of the object from which to retrieve attributes
 * @exception NamingException if a naming exception is encountered
 */
@Override
public Attributes getAttributes(Name name, String[] attrIds)
    throws NamingException {
    
    Entry entry = null;
    if (name.isEmpty())
        entry = entries;
    else
        entry = treeLookup(name);
    if (entry == null)
        return null;
    
    ZipEntry zipEntry = entry.getEntry();

    ResourceAttributes attrs = new ResourceAttributes();
    attrs.setCreationDate(new Date(zipEntry.getTime()));
    attrs.setName(entry.getName());
    if (!zipEntry.isDirectory())
        attrs.setResourceType("");
    else
        attrs.setCollection(true);
    attrs.setContentLength(zipEntry.getSize());
    attrs.setLastModified(zipEntry.getTime());
    
    return attrs;
    
}
 
Example 18
Project: lams   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * Add values of a specified attribute to a list
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the new values
 * @param values ArrayList containing values found so far
 *
 * @exception NamingException if a directory server error occurs
 */
private ArrayList<String> addAttributeValues(String attrId,
                                     Attributes attrs,
                                     ArrayList<String> values)
    throws NamingException{

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving values for attribute " + attrId);
    if (attrId == null || attrs == null)
        return values;
    if (values == null)
        values = new ArrayList<String>();
    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return (values);
    NamingEnumeration e = attr.getAll();
    try {
        while(e.hasMore()) {
            String value = (String)e.next();
            values.add(value);
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    }
    return values;
}
 
Example 19
Project: openshift-ldapsync   File: LdapGroupConverter.java   View source code 5 votes vote down vote up
@Override
public Optional<Group> convert(final String dn, final Attributes ldapGroup) throws NamingException {
    LOG.info("Working on LDAP group: {}", dn);
    GroupBuilder builder = new GroupBuilder()
            .withDn(dn)
            .withLdapServer(server.getName())
            .withOcpName(calculateOCPGroupName(ldapGroup));


    try {
        @SuppressWarnings("unchecked")
        NamingEnumeration<String> members = (NamingEnumeration<String>) ldapGroup.get(MEMBER_ATTRIBUTE).getAll();
        LOG.info("Group has members: group={}, members={}", dn, members);

        while (members.hasMoreElements()) {
            String memberDn = members.nextElement();
            LOG.debug("Working on member: {}", memberDn);

            Attributes memberEntry = server.getByDn(memberDn);

            if (isUser(memberEntry)) {
                LOG.trace("Member is an user: dn={}", memberDn);
                Optional<User> memberUser = userConverter.convert(memberDn, memberEntry);
                memberUser.ifPresent(builder::addUser);
            } else { /* need to load the new group data ... */
                LOG.trace("Member is a group: dn={}", memberDn);
                Optional<Group> memberGroup = convert(memberDn, memberEntry);
                memberGroup.ifPresent(builder::addGroup);
            }
        }
    } catch (NullPointerException e) {
        LOG.debug("LDAP Group has no members: {}", dn);
    }

    return Optional.of(builder.build());
}
 
Example 20
Project: jdk8u-jdk   File: LdapName.java   View source code 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 21
Project: lazycat   File: WARDirContext.java   View source code 5 votes vote down vote up
/**
 * Retrieves all of the attributes associated with a named object.
 * 
 * @return the set of attributes associated with name. Returns an empty
 *         attribute set if name has no attributes; never null.
 * @param name
 *            the name of the object from which to retrieve attributes
 * @exception NamingException
 *                if a naming exception is encountered
 */
@Override
public Attributes getAttributes(Name name, String[] attrIds) throws NamingException {

	Entry entry = null;
	if (name.isEmpty())
		entry = entries;
	else
		entry = treeLookup(name);
	if (entry == null)
		return null;

	ZipEntry zipEntry = entry.getEntry();

	ResourceAttributes attrs = new ResourceAttributes();
	attrs.setCreationDate(new Date(zipEntry.getTime()));
	attrs.setName(entry.getName());
	if (!zipEntry.isDirectory())
		attrs.setResourceType("");
	else
		attrs.setCollection(true);
	attrs.setContentLength(zipEntry.getSize());
	attrs.setLastModified(zipEntry.getTime());

	return attrs;

}
 
Example 22
Project: openjdk-jdk10   File: LdapName.java   View source code 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 23
Project: apache-tomcat-7.0.73-with-comment   File: FileDirContext.java   View source code 5 votes vote down vote up
/**
 * Retrieves selected attributes associated with a named object.
 * See the class description regarding attribute models, attribute type
 * names, and operational attributes.
 *
 * @return the requested attributes; never null
 * @param name the name of the object from which to retrieve attributes
 * @param attrIds the identifiers of the attributes to retrieve. null
 * indicates that all attributes should be retrieved; an empty array
 * indicates that none should be retrieved
 * @exception NamingException if a naming exception is encountered
 */
@Override
protected Attributes doGetAttributes(String name, String[] attrIds)
    throws NamingException {

    // Building attribute list
    File file = file(name);

    if (file == null)
        return null;

    return new FileResourceAttributes(file);

}
 
Example 24
Project: jerrydog   File: FileDirContext.java   View source code 5 votes vote down vote up
/**
 * Retrieves selected attributes associated with a named object. 
 * See the class description regarding attribute models, attribute type 
 * names, and operational attributes.
 * 
 * @return the requested attributes; never null
 * @param name the name of the object from which to retrieve attributes
 * @param attrIds the identifiers of the attributes to retrieve. null 
 * indicates that all attributes should be retrieved; an empty array 
 * indicates that none should be retrieved
 * @exception NamingException if a naming exception is encountered
 */
public Attributes getAttributes(String name, String[] attrIds)
    throws NamingException {

    // Building attribute list
    File file = file(name);

    if (file == null)
        throw new NamingException
            (sm.getString("resources.notFound", name));

    return new FileResourceAttributes(file);

}
 
Example 25
Project: lazycat   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * Use the distinguished name to locate the directory entry for the user
 * with the specified username and return a User object; otherwise return
 * <code>null</code>.
 *
 * @param context
 *            The directory context
 * @param username
 *            The username
 * @param attrIds
 *            String[]containing names of attributes to
 * @param dn
 *            Distinguished name of the user retrieve.
 *
 * @exception NamingException
 *                if a directory server error occurs
 */
protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn)
		throws NamingException {

	// If no attributes are requested, no need to look for them
	if (attrIds == null || attrIds.length == 0) {
		return new User(username, dn, null, null, null);
	}

	// Get required attributes from user entry
	Attributes attrs = null;
	try {
		attrs = context.getAttributes(dn, attrIds);
	} catch (NameNotFoundException e) {
		return null;
	}
	if (attrs == null)
		return null;

	// Retrieve value of userPassword
	String password = null;
	if (userPassword != null)
		password = getAttributeValue(userPassword, attrs);

	String userRoleAttrValue = null;
	if (userRoleAttribute != null) {
		userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
	}

	// Retrieve values of userRoleName attribute
	ArrayList<String> roles = null;
	if (userRoleName != null)
		roles = addAttributeValues(userRoleName, attrs, roles);

	return new User(username, dn, password, roles, userRoleAttrValue);
}
 
Example 26
Project: apache-tomcat-7.0.73-with-comment   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * Add values of a specified attribute to a list
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the new values
 * @param values ArrayList containing values found so far
 *
 * @exception NamingException if a directory server error occurs
 */
private ArrayList<String> addAttributeValues(String attrId,
                                     Attributes attrs,
                                     ArrayList<String> values)
    throws NamingException{

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving values for attribute " + attrId);
    if (attrId == null || attrs == null)
        return values;
    if (values == null)
        values = new ArrayList<String>();
    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return values;
    NamingEnumeration<?> e = attr.getAll();
    try {
        while(e.hasMore()) {
            String value = (String)e.next();
            values.add(value);
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        e.close();
    }
    return values;
}
 
Example 27
Project: openshift-ldapsync   File: LdapServer.java   View source code 5 votes vote down vote up
public Attributes getByDn(final String dn) throws NamingException {
    LdapContext ctx = new InitialLdapContext(env, null);
    Attributes result = ctx.getAttributes(dn);
    ctx.close();

    return result;
}
 
Example 28
Project: apache-tomcat-7.0.73-with-comment   File: JNDIRealm.java   View source code 5 votes vote down vote up
/**
 * Use the distinguished name to locate the directory
 * entry for the user with the specified username and
 * return a User object; otherwise return <code>null</code>.
 *
 * @param context The directory context
 * @param username The username
 * @param attrIds String[]containing names of attributes to
 * @param dn Distinguished name of the user
 * retrieve.
 *
 * @exception NamingException if a directory server error occurs
 */
protected User getUserByPattern(DirContext context,
                                String username,
                                String[] attrIds,
                                String dn)
    throws NamingException {

    // If no attributes are requested, no need to look for them
    if (attrIds == null || attrIds.length == 0) {
        return new User(username, dn, null, null,null);
    }

    // Get required attributes from user entry
    Attributes attrs = null;
    try {
        attrs = context.getAttributes(dn, attrIds);
    } catch (NameNotFoundException e) {
        return null;
    }
    if (attrs == null)
        return null;

    // Retrieve value of userPassword
    String password = null;
    if (userPassword != null)
        password = getAttributeValue(userPassword, attrs);

    String userRoleAttrValue = null;
    if (userRoleAttribute != null) {
        userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
    }

    // Retrieve values of userRoleName attribute
    ArrayList<String> roles = null;
    if (userRoleName != null)
        roles = addAttributeValues(userRoleName, attrs, roles);

    return new User(username, dn, password, roles, userRoleAttrValue);
}
 
Example 29
Project: Equella   File: MemberOfGroupSearch.java   View source code 5 votes vote down vote up
private Collection<Name> getLDAPGroupNames(DirContext ctx, Attributes useratt)
{
	Set<Name> foundGroups = new HashSet<Name>();
	if( !Check.isEmpty(memberOfField) )
	{
		Attribute attribute = useratt.get(memberOfField);
		try
		{
			NameParser parser = ctx.getNameParser(""); //$NON-NLS-1$
			if( attribute != null )
			{
				NamingEnumeration<?> enumeration = attribute.getAll();
				while( enumeration != null && enumeration.hasMore() )
				{
					String role = (String) enumeration.next();
					Name compound = parser.parse(role);
					foundGroups.add(compound);
				}
			}
		}
		catch( NamingException e )
		{
			throw new RuntimeException("Couldn't get memberField", e);
		}
	}
	return foundGroups;
}
 
Example 30
Project: openshift-ldapsync   File: LdapUserReader.java   View source code 5 votes vote down vote up
public Optional<User> load(final String dn) {
    try {
        Attributes entry = server.getByDn(dn);

        return converter.convert(dn, entry);
    } catch (NamingException e) {
        LOG.error(e.getClass().getSimpleName() + " caught: " + e.getMessage(), e);

        return Optional.empty();
    }
}
 
Example 31
Project: openjdk-jdk10   File: ContinuationDirContext.java   View source code 4 votes vote down vote up
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    res.getDirContext().modifyAttributes(res.getName(), mod_op, attrs);
}
 
Example 32
Project: directory-ldap-api   File: AttributeUtils.java   View source code 4 votes vote down vote up
/**
 * Check if the attributes is a BasicAttributes, and if so, switch
 * the case sensitivity to false to avoid tricky problems in the server.
 * (Ldap attributeTypes are *always* case insensitive)
 * 
 * @param attributes The Attributes to check
 * @return The modified Attributes
 */
public static Attributes toCaseInsensitive( Attributes attributes )
{
    if ( attributes == null )
    {
        return attributes;
    }

    if ( attributes instanceof BasicAttributes )
    {
        if ( attributes.isCaseIgnored() )
        {
            // Just do nothing if the Attributes is already case insensitive
            return attributes;
        }
        else
        {
            // Ok, bad news : we have to create a new BasicAttributes
            // which will be case insensitive
            Attributes newAttrs = new BasicAttributes( true );

            NamingEnumeration<?> attrs = attributes.getAll();

            if ( attrs != null )
            {
                // Iterate through the attributes now
                while ( attrs.hasMoreElements() )
                {
                    newAttrs.put( ( javax.naming.directory.Attribute ) attrs.nextElement() );
                }
            }

            return newAttrs;
        }
    }
    else
    {
        // we can safely return the attributes if it's not a BasicAttributes
        return attributes;
    }
}
 
Example 33
Project: openjdk-jdk10   File: ContinuationDirContext.java   View source code 4 votes vote down vote up
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    res.getDirContext().modifyAttributes(res.getString(), mod_op, attrs);
}
 
Example 34
Project: directory-ldap-api   File: LdifAttributesReader.java   View source code 4 votes vote down vote up
/**
 * A method which parses a ldif string and returns a list of Attributes.
 *
 * @param ldif The ldif string
 * @return A list of Attributes, or an empty List
 * @throws LdapLdifException If something went wrong
 */
public Attributes parseAttributes( String ldif ) throws LdapLdifException
{
    lines = new ArrayList<String>();
    position = 0;

    LOG.debug( "Starts parsing ldif buffer" );

    if ( Strings.isEmpty( ldif ) )
    {
        return new BasicAttributes( true );
    }

    StringReader strIn = new StringReader( ldif );
    reader = new BufferedReader( strIn );

    try
    {
        readLines();

        Attributes attributes = parseAttributes();

        if ( LOG.isDebugEnabled() )
        {
            if ( attributes == null )
            {
                LOG.debug( "Parsed no entry." );
            }
            else
            {
                LOG.debug( "Parsed one entry." );
            }
        }

        return attributes;
    }
    catch ( LdapLdifException ne )
    {
        LOG.error( I18n.err( I18n.ERR_12008_CANNOT_PARSE_LDIF_BUFFER, ne.getLocalizedMessage() ) );
        throw new LdapLdifException( I18n.err( I18n.ERR_12009_ERROR_PARSING_LDIF_BUFFER ), ne );
    }
    finally
    {
        try
        {
            reader.close();
        }
        catch ( IOException ioe )
        {
            throw new LdapLdifException( I18n.err( I18n.ERR_12024_CANNOT_CLOSE_FILE ), ioe );
        }
    }
}
 
Example 35
Project: directory-ldap-api   File: LdifAttributesReaderTest.java   View source code 4 votes vote down vote up
@Test
public void testLdifParserRFC2849Sample3() throws LdapLdifException, Exception
{
    String ldif = 
          "objectclass: top\n" 
        + "objectclass: person\n" 
        + "objectclass: organizationalPerson\n"
        + "cn: Gern Jensen\n" 
        + "cn: Gern O Jensen\n" 
        + "sn: Jensen\n" 
        + "uid: gernj\n"
        + "telephonenumber: +1 408 555 1212\n"
        + "description:: V2hhdCBhIGNhcmVmdWwgcmVhZGVyIHlvdSBhcmUhICBUaGlzIHZhbHVl\n"
        + " IGlzIGJhc2UtNjQtZW5jb2RlZCBiZWNhdXNlIGl0IGhhcyBhIGNvbnRyb2wgY2hhcmFjdG\n"
        + " VyIGluIGl0IChhIENSKS4NICBCeSB0aGUgd2F5LCB5b3Ugc2hvdWxkIHJlYWxseSBnZXQg\n" 
        + " b3V0IG1vcmUu";

    LdifAttributesReader reader = new LdifAttributesReader();
    Attributes attributes = reader.parseAttributes( ldif );

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

    attr = attributes.get( "cn" );
    assertTrue( attr.contains( "Gern Jensen" ) );
    assertTrue( attr.contains( "Gern O Jensen" ) );

    attr = attributes.get( "sn" );
    assertTrue( attr.contains( "Jensen" ) );

    attr = attributes.get( "uid" );
    assertTrue( attr.contains( "gernj" ) );

    attr = attributes.get( "telephonenumber" );
    assertTrue( attr.contains( "+1 408 555 1212" ) );

    attr = attributes.get( "description" );
    assertTrue( attr
        .contains( "What a careful reader you are!  This value is base-64-encoded because it has a control character in it (a CR).\r  By the way, you should really get out more."
            .getBytes( StandardCharsets.UTF_8 ) ) );
    reader.close();
}
 
Example 36
Project: openjdk-jdk10   File: ContinuationDirContext.java   View source code 4 votes vote down vote up
public DirContext createSubcontext(Name name, Attributes attrs)
        throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().createSubcontext(res.getName(), attrs);
}
 
Example 37
Project: unitimes   File: LdapAuthenticateModule.java   View source code 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 38
Project: OpenJSharp   File: AbstractLdapNamingEnumeration.java   View source code 4 votes vote down vote up
protected abstract T createItem(String dn, Attributes attrs,
Vector<Control> respCtls) throws NamingException;
 
Example 39
Project: openjdk-jdk10   File: ContinuationDirContext.java   View source code 4 votes vote down vote up
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    res.getDirContext().bind(res.getName(), obj, attrs);
}
 
Example 40
Project: Equella   File: LDAP.java   View source code 4 votes vote down vote up
public LDAPResult(Name base, Attributes a)
{
	this.baseName = base;
	this.fullName = base;
	this.attributes = a;
}