javax.naming.ldap.LdapName Java Examples

The following examples show how to use javax.naming.ldap.LdapName. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CertKeyToUserNameMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #2
Source File: CertificateUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #3
Source File: LDAPSourceExtended.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: LdapManagerTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: ReadOnlyLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #6
Source File: JndiLdapAdditionalSignature.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #7
Source File: NameAwareAttribute.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: DirectoryGroupDN.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: LdapManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: RebindOperationExecutorTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example #12
Source File: LdapUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * 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 + "'");
}
 
Example #13
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }
}
 
Example #14
Source File: LdapTestUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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);
       }
   }
 
Example #15
Source File: LdapUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: LDAPSourceExtended.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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>();
}
 
Example #17
Source File: LdapTemplateTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #19
Source File: LDAPSourceExtended.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #20
Source File: LdapTestUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #21
Source File: AuthZpeClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
        }
    }
}
 
Example #22
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }
}
 
Example #23
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
   }
}
 
Example #24
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifyNull() throws Exception {
	tested.setAttributeValue("memberDN", null);
	tested.setUpdateMode(true);
	assertThat(tested.isUpdateMode()).isTrue();
	tested.setAttributeValue("memberDN", new LdapName("ou=test"));

	ModificationItem[] mods = tested.getModificationItems();
	assertThat(mods.length).isEqualTo(1);
}
 
Example #25
Source File: DirContextAdapter.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
    * {@inheritDoc}
    */
   @Override
public String getNameInNamespace() {
       if(base.size() == 0) {
           return dn.toString();
       }

       try {
           LdapName result = (LdapName) dn.clone();
           result.addAll(0, base);
           return result.toString();
       } catch (InvalidNameException e) {
           throw new org.springframework.ldap.InvalidNameException(e);
       }
}
 
Example #26
Source File: CertificateManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @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;
}
 
Example #27
Source File: AbstractCommonHostnameVerifierFix.java    From steady with Apache License 2.0 5 votes vote down vote up
static String[] extractCNs(final String subjectPrincipal) throws SSLException {
    if (subjectPrincipal == null) {
        return null;
    }
    final List<String> cns = new ArrayList<String>();
    try {
        final LdapName subjectDN = new LdapName(subjectPrincipal);
        final List<Rdn> rdns = subjectDN.getRdns();
        for (int i = rdns.size() - 1; i >= 0; i--) {
            final Rdn rds = rdns.get(i);
            final Attributes attributes = rds.toAttributes();
            final Attribute cn = attributes.get("cn");
            if (cn != null) {
                try {
                    final Object value = cn.get();
                    if (value != null) {
                        cns.add(value.toString());
                    }
                } catch (NamingException ignore) {
                }
            }
        }
    } catch (InvalidNameException e) {
        throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name");
    }
    return cns.isEmpty() ? null : cns.toArray(new String[ cns.size() ]);
}
 
Example #28
Source File: LdapUtilsTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: LdapUtilsTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveFirstNoMatch() throws InvalidNameException {
    LdapName ldapName = new LdapName(EXPECTED_DN_STRING);
    LdapName result = LdapUtils.removeFirst(ldapName, new LdapName("OU=oooooo,OU=M"));

    assertThat(result).isNotSameAs(ldapName);
    assertThat(result).isEqualTo(ldapName);
}
 
Example #30
Source File: DnTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Test for DIRSERVER-191. The Dn is immutable, thus we can't add a new Rdn
 * to a Dn, it simply creates a new one.
 */
@Test
public void testAddStringName() throws LdapException, InvalidNameException
{
    LdapName jName = new LdapName( "cn=four,cn=three,cn=two,cn=one" );
    Dn aName = new Dn( "cn=four,cn=three,cn=two,cn=one" );

    assertSame( jName, jName.add( "cn=five" ) );
    assertNotSame( aName, aName.add( "cn=five" ) );
    assertNotSame( jName.toString(), aName.toString() );
}