类javax.naming.ldap.LdapName源码实例Demo

下面列出了怎么用javax.naming.ldap.LdapName的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: spring-ldap   文件: LdapTestUtils.java
@SuppressWarnings("deprecation")
private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
       try {
           LdapName baseDn = (LdapName)
                   context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);

           LdifParser parser = new LdifParser(ldifFile);
           parser.open();
           while (parser.hasMoreRecords()) {
               LdapAttributes record = parser.getRecord();

               LdapName dn = record.getName();

               if(baseDn != null) {
                   dn = LdapUtils.removeFirst(dn, baseDn);
               }

               if(!rootNode.isEmpty()) {
                   dn = LdapUtils.prepend(dn, rootNode);
               }
               context.bind(dn, null, record);
           }
       } catch (Exception e) {
           throw new UncategorizedLdapException("Failed to populate LDIF", e);
       }
   }
 
源代码2 项目: yawl   文件: LDAPSourceExtended.java
private Role createRole(LdapName dn, Attributes attr) throws NamingException {
    // Must attributes
    String cn = getAttributeAsString(attr, ATTR_COMMON_NAME);
    
    // May attributes
    String description = getAttributeAsString(attr, ATTR_DESCRIPTION);
    String notes = getAttributeAsString(attr, ATTR_NOTES);
    String displayName = getAttributeAsString(attr, ATTR_DISPLAYNAME);
    String yawlInternalId = getAttributeAsString(attr, ATTR_YAWL_INTERNAL_ID);
    
    Role role = new Role(cn);
    role.setDescription(description);
    role.setNotes(notes);
    if (isNotNullOrEmpty(yawlInternalId)) {
        role.setID(yawlInternalId);
    } else {
        role.setID(UUID.nameUUIDFromBytes(dn.toString().getBytes()).toString());
    }
    if (isNotNullOrEmpty(displayName)) {
        role.setLabel(displayName);
    }
    return role;
}
 
/**
 * Removes the cache entry given the user name.
 *
 * @param userName the User name to remove.
 * @return true if removal was successful.
 */
protected boolean removeFromUserCache(String userName) {
    try {
        Cache<String, LdapName> userDnCache = createOrGetUserDnCache();
        if (userDnCache == null) {
            // User cache may be null while initializing.
            // Return true as removal result is successful when there is no cache. Nothing was held.
            return true;
        }
        return userDnCache.remove(userName);
    } catch (IllegalStateException e) {
        // There is no harm ignoring the removal, as the cache(local) is already is of no use.
        log.error("Error occurred while removing User DN from cache having search base : " + userSearchBase, e);
        return true;
    }
}
 
源代码4 项目: spring-ldap   文件: NameAwareAttribute.java
public void initValuesAsNames() {
    if(hasValuesAsNames()) {
        return;
    }

    Map<Name, String> newValuesAsNames = new HashMap<Name, String>();
    for (Object value : values) {
        if (value instanceof String) {
            String s = (String) value;
            try {
                newValuesAsNames.put(LdapUtils.newLdapName(s), s);
            } catch (InvalidNameException e) {
                throw new IllegalArgumentException("This instance has values that are not valid distinguished names; " +
                        "cannot handle Name values", e);
            }
        } else if (value instanceof LdapName) {
            newValuesAsNames.put((LdapName) value, value.toString());
        } else {
            throw new IllegalArgumentException("This instance has non-string attribute values; " +
                    "cannot handle Name values");
        }
    }

    this.valuesAsNames = newValuesAsNames;
}
 
源代码5 项目: nifi   文件: CertificateUtils.java
/**
 * Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
 * <p>
 * Example:
 * <p>
 * CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
 * CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
 * CN=test1, O=testOrg, C=US compared to                           -> false
 * compared to                           -> true
 *
 * @param dn1 the first DN to compare
 * @param dn2 the second DN to compare
 * @return true if the DNs are equivalent, false otherwise
 */
public static boolean compareDNs(String dn1, String dn2) {
    if (dn1 == null) {
        dn1 = "";
    }

    if (dn2 == null) {
        dn2 = "";
    }

    if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
        return dn1.equals(dn2);
    }
    try {
        List<Rdn> rdn1 = new LdapName(dn1).getRdns();
        List<Rdn> rdn2 = new LdapName(dn2).getRdns();

        return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
    } catch (InvalidNameException e) {
        logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
        return false;
    }
}
 
源代码6 项目: hesperides   文件: DirectoryGroupDN.java
public static String extractCnFromDn(String dn) {
    String cn = null;
    try {
        LdapName ldapName = new LdapName(dn);
        for (Rdn rdn : ldapName.getRdns()) {
            if (rdn.getType().equalsIgnoreCase("CN")) {
                cn = (String) rdn.getValue();
            }
        }
    } catch (InvalidNameException e) {
        throw new IllegalArgumentException("Invalid DN: " + dn, e);
    }
    if (cn == null) {
        throw new IllegalArgumentException("Can't find CN in DN: " + dn);
    }
    return cn;
}
 
源代码7 项目: Openfire   文件: LdapManager.java
/**
 * Returns the BaseDN for the given groupname.
 *
 * @param groupname groupname to return its base DN.
 * @return the BaseDN for the given groupname. If no baseDN is found,
 *         this method will return {@code null}.
 */
public LdapName getGroupsBaseDN(String groupname) {
    try {
        findGroupRDN(groupname, baseDN);
        return baseDN;
    }
    catch (Exception e) {
        try {
            if (alternateBaseDN != null) {
                findGroupRDN(groupname, alternateBaseDN);
                return alternateBaseDN;
            }
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to find the base dn for group: {}", groupname, ex);
        }
    }
    return null;
}
 
源代码8 项目: spring-ldap   文件: LdapTemplateTest.java
@Test
public void testLookupContextWithName() {
	final DirContextAdapter expectedResult = new DirContextAdapter();

       final LdapName expectedName = LdapUtils.emptyLdapName();
       LdapTemplate tested = new LdapTemplate() {
		public Object lookup(Name dn) {
			assertThat(dn).isSameAs(dn);
			return expectedResult;
		}
	};

	DirContextOperations result = tested.lookupContext(expectedName);
	assertThat(result).isSameAs(expectedResult);

}
 
源代码9 项目: spring-ldap   文件: LdapUtils.java
/**
 * Find the Rdn with the requested key in the supplied Name.
 *
 * @param name the Name in which to search for the key.
 * @param key the attribute key to search for.
 * @return the rdn corresponding to the <b>first</b> occurrence of the requested key.
 * @throws NoSuchElementException if no corresponding entry is found.
 * @since 2.0
 */
public static Rdn getRdn(Name name, String key) {
    Assert.notNull(name, "name must not be null");
    Assert.hasText(key, "key must not be blank");

    LdapName ldapName = returnOrConstructLdapNameFromName(name);

    List<Rdn> rdns = ldapName.getRdns();
    for (Rdn rdn : rdns) {
        NamingEnumeration<String> ids = rdn.toAttributes().getIDs();
        while (ids.hasMoreElements()) {
            String id = ids.nextElement();
            if(key.equalsIgnoreCase(id)) {
                return rdn;
            }
        }
    }

    throw new NoSuchElementException("No Rdn with the requested key: '" + key + "'");
}
 
源代码10 项目: freehealth-connector   文件: DistinguishedName.java
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
源代码11 项目: freehealth-connector   文件: DistinguishedName.java
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
源代码12 项目: freehealth-connector   文件: DistinguishedName.java
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
源代码13 项目: athenz   文件: AuthZpeClient.java
/**
 * Set the list of Athenz CA issuers with their full DNs that
 * ZPE should honor.
 * @param issuers list of Athenz CA issuers separated by |
 */
public static void setX509CAIssuers(final String issuers) {

    if (issuers == null || issuers.isEmpty()) {
        return;
    }
    
    String[] issuerArray = issuers.split("\\|");
    for (String issuer : issuerArray) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("x509 issuer: {}", issuer);
        }
        X509_ISSUERS_NAMES.add(issuer.replaceAll("\\s+", ""));
        try {
            X509_ISSUERS_RDNS.add(new LdapName(issuer).getRdns());
        } catch (InvalidNameException ex) {
            LOG.error("Invalid issuer: {}, error: {}", issuer, ex.getMessage());
        }
    }
}
 
源代码14 项目: spring-ldap   文件: LdapTestUtils.java
private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) {
    try {
        LdapName baseDn = (LdapName)
                context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY);

        LdifParser parser = new LdifParser(ldifFile);
        parser.open();
        while (parser.hasMoreRecords()) {
            LdapAttributes record = parser.getRecord();

            LdapName dn = record.getName();

            if(baseDn != null) {
                dn = LdapUtils.removeFirst(dn, baseDn);
            }

            if(!rootNode.isEmpty()) {
                dn = LdapUtils.prepend(dn, rootNode);
            }
            context.bind(dn, null, record);
        }
    } catch (Exception e) {
        throw new UncategorizedLdapException("Failed to populate LDIF", e);
    }
}
 
源代码15 项目: localization_nifi   文件: CertificateUtils.java
/**
 * Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
 *
 * Example:
 *
 * CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
 * CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
 * CN=test1, O=testOrg, C=US compared to                           -> false
 *                           compared to                           -> true
 *
 * @param dn1 the first DN to compare
 * @param dn2 the second DN to compare
 * @return true if the DNs are equivalent, false otherwise
 */
public static boolean compareDNs(String dn1, String dn2) {
    if (dn1 == null) {
        dn1 = "";
    }

    if (dn2 == null) {
        dn2 = "";
    }

    if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
        return dn1.equals(dn2);
    }
    try {
        List<Rdn> rdn1 = new LdapName(dn1).getRdns();
        List<Rdn> rdn2 = new LdapName(dn2).getRdns();

        return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
    } catch (InvalidNameException e) {
        logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
        return false;
    }
}
 
源代码16 项目: spring-ldap   文件: LdapTemplateTest.java
@Test
public void testUpdateWithIdChanged() throws NamingException {
    Object expectedObject = new Object();

    when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, dirContextMock);
    LdapName expectedOriginalName = LdapUtils.newLdapName("ou=someOu");
    LdapName expectedNewName = LdapUtils.newLdapName("ou=someOtherOu");

    ArgumentCaptor<DirContextAdapter> ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class);
    doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture());

    when(odmMock.getId(expectedObject)).thenReturn(expectedOriginalName);
    when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedNewName);

    tested.update(expectedObject);

    verify(odmMock).setId(expectedObject, expectedNewName);
    verify(dirContextMock).unbind(expectedOriginalName);
    verify(dirContextMock).bind(expectedNewName, ctxCaptor.getValue(), null);
    verify(dirContextMock, times(2)).close();
}
 
源代码17 项目: spring-ldap   文件: LdapUtils.java
/**
 * Remove the supplied path from the beginning the specified
 * <code>Name</code> if the name instance starts with
 * <code>path</code>. Useful for stripping base path suffix from a
 * <code>Name</code>. The original Name will not be affected.
 *
 * @param dn the dn to strip from.
 * @param pathToRemove the path to remove from the beginning the dn instance.
 * @return an LdapName instance that is a copy of the original name with the
 * specified path stripped from its beginning.
 * @since 2.0
 */
public static LdapName removeFirst(Name dn, Name pathToRemove) {
    Assert.notNull(dn, "dn must not be null");
    Assert.notNull(pathToRemove, "pathToRemove must not be null");

    LdapName result = newLdapName(dn);
    LdapName path = returnOrConstructLdapNameFromName(pathToRemove);

    if(path.size() == 0 || !dn.startsWith(path)) {
        return result;
    }

    for(int i = 0; i < path.size(); i++) {
        try {
            result.remove(0);
        } catch (InvalidNameException e) {
            throw convertLdapException(e);
        }
    }

    return result;
}
 
源代码18 项目: cxf   文件: CertKeyToUserNameMapper.java
/**
 * Returns Subject DN from X509Certificate
 *
 * @param cert
 * @return Subject DN as a user name
 */
@Override
public String getUserName(Certificate cert) {
    X509Certificate certificate = (X509Certificate) cert;
    String dn = certificate.getSubjectDN().getName();
    LdapName ldapDn = getLdapName(dn);

    if (key == null) {
        throw new IllegalArgumentException("Must set a key");
    }

    for (Rdn rdn : ldapDn.getRdns()) {
        if (key.equalsIgnoreCase(rdn.getType())) {
            return (String)rdn.getValue();
        }
    }

    throw new IllegalArgumentException("No " + key + " key found in certificate DN: " + dn);
}
 
源代码19 项目: yawl   文件: LDAPSourceExtended.java
private void initMaps() {
    // init maps
    // this map contains <UID, DN> pairs to resolve a uid to a DN used  
    _uid2dnMap = new HashMap<String, String>();
    _inputMap = new HashMap<LdapName, Attributes>();
    _participantsWithDNasKey = new HashMap<String, Participant>();
    _participantsWithIDasKey = new HashMap<String, Participant>();
    _rolesWithDNasKey = new HashMap<String, Role>();
    _rolesWithIDasKey = new HashMap<String, Role>();
    _orgGroupsWithDNasKey = new HashMap<String, OrgGroup>();
    _orgGroupsWithIDasKey = new HashMap<String, OrgGroup>();
    _capabilitiesWithDNasKey = new HashMap<String, Capability>();
    _capabilitiesWithIDasKey = new HashMap<String, Capability>();
    _positionsWithDNasKey = new HashMap<String, Position>();
    _positionsWithIDasKey = new HashMap<String, Position>();
}
 
源代码20 项目: yawl   文件: LDAPSourceExtended.java
private Position createPosition(LdapName dn, Attributes attr) throws NamingException {
    // Must attributes
    String cn = getAttributeAsString(attr, ATTR_COMMON_NAME);
    
    // May attributes
    String description = getAttributeAsString(attr, ATTR_DESCRIPTION);
    String notes = getAttributeAsString(attr, ATTR_NOTES);
    String displayName = getAttributeAsString(attr, ATTR_DISPLAYNAME);        
    String yawlInternalId = getAttributeAsString(attr, ATTR_YAWL_INTERNAL_ID);
    
    Position position = new Position(cn);
    if (isNotNullOrEmpty(yawlInternalId)) {
        position.setID(yawlInternalId);
    } else {
        position.setID(UUID.nameUUIDFromBytes(dn.toString().getBytes()).toString());
    }
    position.setDescription(description);
    position.setNotes(notes);
    if (isNotNullOrEmpty(displayName)) {
        position.setLabel(displayName);
    }
    return position;
}
 
源代码21 项目: spring-ldap   文件: RebindOperationExecutorTest.java
@Test
public void testCommit() {
    LdapName expectedOriginalDn = LdapUtils.newLdapName(
            "cn=john doe");
    LdapName expectedTempDn = LdapUtils.newLdapName(
            "cn=john doe_temp");
    Object expectedObject = new Object();
    BasicAttributes expectedAttributes = new BasicAttributes();
    RebindOperationExecutor tested = new RebindOperationExecutor(
            ldapOperationsMock, expectedOriginalDn, expectedTempDn,
            expectedObject, expectedAttributes);

    // perform test
    tested.commit();
    verify(ldapOperationsMock).unbind(expectedTempDn);
}
 
源代码22 项目: Openfire   文件: LdapManagerTest.java
/**
 * Test if {@link LdapManager#getProviderURL(LdapName)} generates a URL using basic attributes (happy-flow test).
 */
@Test
public void testGetProviderURL() throws Exception
{
    // Setup fixture.
    final Map<String, String> properties = new HashMap<>();
    properties.put("ldap.host", "localhost");
    properties.put("ldap.port", "389");
    final LdapManager manager = new LdapManager( properties );
    final LdapName name = new LdapName("ou=people,dc=example,dc=org");

    // Execute system under test.
    final String result = manager.getProviderURL( name );

    // Verify result.
    assertEquals("ldaps://localhost:389/ou=people,dc=example,dc=org", result);
}
 
public void ldapInjectionSunApi(String input) throws NamingException {
    //Stub instances
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://ldap.example.com");
    props.put(Context.REFERRAL, "ignore");

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[]{"givenName", "sn"});
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    //Two context instances mostly usable with sun specific API
    LdapCtx            context5 = null;
    EventDirContext    context6 = null; //LdapCtx is the only known class to implements to this interface

    NamingEnumeration<SearchResult> answers;
    answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context5.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context5.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);

    answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", ctrls);
    answers = context6.search(new LdapName("dc=People,dc=example,dc=com"), "(uid=" + input + ")", new Object[0], ctrls);
    answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", ctrls);
    answers = context6.search("dc=People,dc=example,dc=com", "(uid=" + input + ")", new Object[0], ctrls);
}
 
源代码24 项目: spring-ldap   文件: LdapUtilsTest.java
@Test
public void testRemoveFirstEmptyBase() throws InvalidNameException {
    LdapName ldapName = new LdapName(EXPECTED_DN_STRING);
    LdapName result = LdapUtils.removeFirst(ldapName, LdapUtils.emptyLdapName());

    assertThat(result).isNotSameAs(ldapName);
    assertThat(result).isEqualTo(ldapName);
}
 
源代码25 项目: Openfire   文件: CertificateManagerTest.java
/**
 *
 * @see <a href="https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java>https://stackoverflow.com/questions/2914521/how-to-extract-cn-from-x509certificate-in-java</a>
 */
public static Set<String> parse( String distinguishedName, String identifier ) throws Exception
{
    final Set<String> result = new HashSet<>();

    final LdapName ln = new LdapName( distinguishedName);
    for( final Rdn rdn : ln.getRdns() )
    {
        if( rdn.getType().equalsIgnoreCase( identifier ) )
        {
            result.add( rdn.getValue().toString() );
        }
    }
    return result;
}
 
源代码26 项目: Openfire   文件: LdapGroupProvider.java
@Override
public Group getGroup(String groupName) throws GroupNotFoundException {
    try {
        LdapName groupDN = manager.findGroupAbsoluteDN(groupName);
        return getGroupByDN(groupDN, new HashSet<>(Collections.singleton(groupDN.toString())));
    }
    catch (Exception e) {
        Log.error("Unable to load group: {}", groupName, e);
        throw new GroupNotFoundException("Group with name " + groupName + " not found.", e);
    }
}
 
private static String escapeDn(String dn) throws InvalidNameException {
    final LdapName dnName = new LdapName(dn);
    final List<Rdn> escaped = new ArrayList<>(dnName.size());
    for(Rdn rdn: dnName.getRdns()) {
        escaped.add(new Rdn(rdn.getType(), escapeForwardSlash(rdn.getValue())));
    }
    return new LdapName(escaped).toString();
}
 
源代码28 项目: openjdk-8   文件: LdapCtx.java
public Name composeName(Name name, Name prefix)
    throws NamingException
{
    Name result;

    // Handle compound names.  A pair of LdapNames is an easy case.
    if ((name instanceof LdapName) && (prefix instanceof LdapName)) {
        result = (Name)(prefix.clone());
        result.addAll(name);
        return new CompositeName().add(result.toString());
    }
    if (!(name instanceof CompositeName)) {
        name = new CompositeName().add(name.toString());
    }
    if (!(prefix instanceof CompositeName)) {
        prefix = new CompositeName().add(prefix.toString());
    }

    int prefixLast = prefix.size() - 1;

    if (name.isEmpty() || prefix.isEmpty() ||
            name.get(0).equals("") || prefix.get(prefixLast).equals("")) {
        return super.composeName(name, prefix);
    }

    result = (Name)(prefix.clone());
    result.addAll(name);

    if (parentIsLdapCtx) {
        String ldapComp = concatNames(result.get(prefixLast + 1),
                                      result.get(prefixLast));
        result.remove(prefixLast + 1);
        result.remove(prefixLast);
        result.add(prefixLast, ldapComp);
    }
    return result;
}
 
@Test
public void testGetTemporaryDN_MultivalueDN() {
    LdapName expectedOriginalName = LdapUtils.newLdapName(
            "cn=john doe+sn=doe, ou=somecompany, c=SE");
    DefaultTempEntryRenamingStrategy tested = new DefaultTempEntryRenamingStrategy();

    Name result = tested.getTemporaryName(expectedOriginalName);
    assertThat(result.toString()).isEqualTo("cn=john doe+sn=doe_temp,ou=somecompany,c=SE");
}
 
源代码30 项目: spring-ldap   文件: LdapTemplate.java
/**
    * {@inheritDoc}
    */
   @Override
public <T> T lookup(final String dn, final String[] attributes, final ContextMapper<T> mapper) {
	return executeReadOnly(new ContextExecutor<T>() {
		public T executeWithContext(DirContext ctx) throws javax.naming.NamingException {
			Attributes filteredAttributes = ctx.getAttributes(dn, attributes);
			LdapName name = LdapUtils.newLdapName(dn);
			DirContextAdapter contextAdapter = new DirContextAdapter(filteredAttributes, name);
			return mapper.mapFromContext(contextAdapter);
		}
	});
}
 
 类所在包
 同包方法