Java 类javax.naming.directory.Attributes 实例源码

项目:directory-ldap-api    文件:LdifUtilsTest.java   
/**
 * 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 );
}
项目:openjdk-jdk10    文件:NamingManager.java   
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;
                }
            };
        }
    };
}
项目:CustomWorldGen    文件:ServerAddress.java   
/**
 * 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)};
    }
}
项目:open-rmbt    文件:LookupService.java   
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;
    }

}
项目:jerrydog    文件:JNDIRealm.java   
/**
 * 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;
}
项目:joai-project    文件:LdapClient.java   
/**
 * 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);
}
项目:lams    文件:WARDirContext.java   
/**
 * 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;

}
项目:hadoop    文件:TestLdapGroupsMapping.java   
@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);
}
项目:directory-ldap-api    文件:LdifAttributesReader.java   
/**
 * 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 );
    }
}
项目:directory-ldap-api    文件:LdifUtils.java   
/**
 * 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 );
    }
}
项目:directory-ldap-api    文件:LdifUtilsTest.java   
/**
 * 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 );
}
项目:directory-ldap-api    文件:LdifUtilsTest.java   
/**
 * 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 );
}
项目:Equella    文件:GroupSearch.java   
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;
}
项目:lazycat    文件:JNDIRealm.java   
/**
 * 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;
}
项目:directory-ldap-api    文件:TriggerUtils.java   
/**
 * 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 );
    }
}
项目:tomcat7    文件:JNDIRealm.java   
/**
 * 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);
}
项目:apache-tomcat-7.0.73-with-comment    文件:WARDirContext.java   
/**
 * 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;

}
项目:lams    文件:JNDIRealm.java   
/**
 * 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;
}
项目:openshift-ldapsync    文件:LdapGroupConverter.java   
@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());
}
项目:jdk8u-jdk    文件:LdapName.java   
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;
}
项目:lazycat    文件:WARDirContext.java   
/**
 * 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;

}
项目:openjdk-jdk10    文件:LdapName.java   
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;
}
项目:apache-tomcat-7.0.73-with-comment    文件:FileDirContext.java   
/**
 * 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);

}
项目:jerrydog    文件:FileDirContext.java   
/**
 * 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);

}
项目:lazycat    文件:JNDIRealm.java   
/**
 * 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);
}
项目:apache-tomcat-7.0.73-with-comment    文件:JNDIRealm.java   
/**
 * 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;
}
项目:openshift-ldapsync    文件:LdapServer.java   
public Attributes getByDn(final String dn) throws NamingException {
    LdapContext ctx = new InitialLdapContext(env, null);
    Attributes result = ctx.getAttributes(dn);
    ctx.close();

    return result;
}
项目:apache-tomcat-7.0.73-with-comment    文件:JNDIRealm.java   
/**
 * 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);
}
项目:Equella    文件:MemberOfGroupSearch.java   
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;
}
项目:openshift-ldapsync    文件:LdapUserReader.java   
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();
    }
}
项目:openjdk-jdk10    文件:ContinuationDirContext.java   
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    res.getDirContext().modifyAttributes(res.getName(), mod_op, attrs);
}
项目:directory-ldap-api    文件:AttributeUtils.java   
/**
 * 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;
    }
}
项目:openjdk-jdk10    文件:ContinuationDirContext.java   
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    res.getDirContext().modifyAttributes(res.getString(), mod_op, attrs);
}
项目:directory-ldap-api    文件:LdifAttributesReader.java   
/**
 * 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 );
        }
    }
}
项目:directory-ldap-api    文件:LdifAttributesReaderTest.java   
@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();
}
项目:openjdk-jdk10    文件:ContinuationDirContext.java   
public DirContext createSubcontext(Name name, Attributes attrs)
        throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().createSubcontext(res.getName(), attrs);
}
项目:unitimes    文件:LdapAuthenticateModule.java   
/**
 * 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;
}
项目:OpenJSharp    文件:AbstractLdapNamingEnumeration.java   
protected abstract T createItem(String dn, Attributes attrs,
Vector<Control> respCtls) throws NamingException;
项目:openjdk-jdk10    文件:ContinuationDirContext.java   
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException  {
    DirContextNamePair res = getTargetContext(name);
    res.getDirContext().bind(res.getName(), obj, attrs);
}
项目:Equella    文件:LDAP.java   
public LDAPResult(Name base, Attributes a)
{
    this.baseName = base;
    this.fullName = base;
    this.attributes = a;
}