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

项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP schema violation
 */
@Test
public void removeUserSchema() {
    thrown.expect(ValidationJsonException.class);
    thrown.expect(MatcherUtil.validationMatcher("groups", "last-member-of-group"));
    final GroupLdapRepository groupRepository = new GroupLdapRepository() {
        @Override
        public GroupOrg findById(final String name) {
            // The group has only the user user we want to remove
            return new GroupOrg("dc=" + name, name, Collections.singleton("flast1"));
        }

    };
    groupRepository.setLdapCacheRepository(Mockito.mock(LdapCacheRepository.class));

    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.SchemaViolationException(new SchemaViolationException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());
    removeUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP desynchronization
 */
@Test
public void removeUserSync() {
    final GroupLdapRepository groupRepository = new GroupLdapRepository() {
        @Override
        public GroupOrg findById(final String name) {
            // The group has only the user user we want to remove
            return new GroupOrg("dc=" + name, name, Collections.singleton("flast1"));
        }

    };
    groupRepository.setLdapCacheRepository(Mockito.mock(LdapCacheRepository.class));
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());
    removeUser(groupRepository);
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * Test for DIRSERVER-191
 */
@Test
public void testAddAllIntName() 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.addAll( 0, new LdapName( "cn=zero,cn=zero.5" ) ) );
    assertNotSame( aName, aName.add( new Dn( "cn=zero,cn=zero.5" ) ) );
    assertNotSame( jName.toString(), aName.toString() );

    assertSame( jName, jName.addAll( 2, new LdapName( "cn=zero,cn=zero.5" ) ) );
    assertNotSame( aName, aName.add( new Dn( "cn=zero,cn=zero.5" ) ) );
    assertNotSame( jName.toString(), aName.toString() );

    assertSame( jName, jName.addAll( jName.size(), new LdapName( "cn=zero,cn=zero.5" ) ) );
    assertNotSame( aName, aName.add( new Dn( "cn=zero,cn=zero.5" ) ) );
    assertNotSame( jName.toString(), aName.toString() );
}
项目:Android_Code_Arbiter    文件:JndiLdapAdditionalSignature.java   
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);
}
项目:smart-id-java-client    文件:AuthenticationResponseValidator.java   
private AuthenticationIdentity constructAuthenticationIdentity(X509Certificate certificate) {
  AuthenticationIdentity identity = new AuthenticationIdentity();
  try {
    LdapName ln = new LdapName(certificate.getSubjectDN().getName());
    for(Rdn rdn : ln.getRdns()) {
      if(rdn.getType().equalsIgnoreCase("GIVENNAME")) {
        identity.setGivenName(rdn.getValue().toString());
      } else if(rdn.getType().equalsIgnoreCase("SURNAME")) {
        identity.setSurName(rdn.getValue().toString());
      } else if(rdn.getType().equalsIgnoreCase("SERIALNUMBER")) {
        identity.setIdentityCode(rdn.getValue().toString().split("-")[1]);
      } else if(rdn.getType().equalsIgnoreCase("C")) {
        identity.setCountry(rdn.getValue().toString());
      }

    }
    return identity;
  } catch (InvalidNameException e) {
    logger.error("Error getting authentication identity from the certificate", e);
    throw new TechnicalErrorException("Error getting authentication identity from the certificate", e);
  }
}
项目:nifi-registry    文件: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;
    }
}
项目:photon-model    文件:CertificateUtil.java   
/**
 * Extracts from DN a given attribute.
 * @param dn
 *         The entire DN
 * @param attribute
 *         The attribute to extract
 * @return the attribute value or null if not found an attribute with the given dn.
 */
public static String getAttributeFromDN(String dn, String attribute) {
    try {
        LdapName subjectDn = new LdapName(dn);

        for (Rdn rdn : subjectDn.getRdns()) {
            if (rdn.getType().equals(attribute)) {
                return rdn.getValue().toString();
            }
        }
    } catch (InvalidNameException e) {
        throw new IllegalArgumentException(e);
    }

    return null;
}
项目:alfresco-mt-support    文件:EnhancedLDAPUserRegistry.java   
protected NodeMapper buildGroupMapper(final boolean disjoint, final LdapName groupDistinguishedNamePrefix,
        final LdapName userDistinguishedNamePrefix)
{
    return (searchResult) -> {
        final UidNodeDescription nodeDescription = this.mapToNode(searchResult, this.groupIdAttributeName, this.groupAttributeMapping,
                this.groupAttributeDefaults);

        final String groupName = AuthorityType.GROUP.getPrefixString() + nodeDescription.getId();
        nodeDescription.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, groupName);

        final Collection<String> groupChildren = this.lookupGroupChildren(searchResult, groupName, disjoint,
                groupDistinguishedNamePrefix, userDistinguishedNamePrefix);
        nodeDescription.getChildAssociations().addAll(groupChildren);

        return nodeDescription;
    };
}
项目:engerek    文件:TestExpressionFunctions.java   
@Test
public void testComposeDn() throws Exception {
    final String TEST_NAME = "testComposeDn";
    TestUtil.displayTestTile(TEST_NAME);
    BasicExpressionFunctions basic = createBasicFunctions();

    assertEquals("cn=foo,o=bar", basic.composeDn("cn","foo","o","bar"));
    assertEquals("cn=foo,o=bar", basic.composeDn("cn",PrismTestUtil.createPolyString("foo"),"o","bar"));
    assertEquals("cn=foo,o=bar", basic.composeDn("cn",PrismTestUtil.createPolyStringType("foo"),"o","bar"));
    assertEquals("cn=foo,o=bar", basic.composeDn("cn","foo",new Rdn("o","bar")));
    assertEquals("cn=foo,ou=baz,o=bar", basic.composeDn(new Rdn("cn","foo"),"ou","baz",new Rdn("o","bar")));
    assertEquals("cn=foo,ou=baz,o=bar", basic.composeDn(new Rdn("cn","foo"),"ou","baz","o","bar"));
    assertEquals("cn=foo,ou=baz,o=bar", basic.composeDn(new Rdn("cn","foo"),new LdapName("ou=baz,o=bar")));
    assertEquals("cn=foo,ou=baz,o=bar", basic.composeDn("cn","foo",new LdapName("ou=baz,o=bar")));
    assertEquals("cn=foo\\,foo,ou=baz,o=bar", basic.composeDn("cn","foo,foo",new LdapName("ou=baz,o=bar")));
    assertEquals("cn=foo\\=foo,ou=baz,o=bar", basic.composeDn("cn","foo=foo",new LdapName("ou=baz,o=bar")));
    assertEquals(null, basic.composeDn(null));
    assertEquals(null, basic.composeDn());
    assertEquals(null, basic.composeDn(""));
    assertEquals(null, basic.composeDn("   "));
}
项目:engerek    文件:TestExchangeConnectorLow.java   
private String distributionGroupOU() throws InvalidNameException {
    LdapName container = new LdapName(getContainer());
    List<String> ous = new ArrayList<>();
    List<String> dcs = new ArrayList<>();
    String retval = "";
    for (Rdn rdn : container.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("OU")) {
            ous.add(rdn.getValue().toString());
        } else if (rdn.getType().equalsIgnoreCase("DC")) {
            dcs.add(rdn.getValue().toString());
        }
    }
    for (int i = dcs.size()-1; i >= 0; i--) {
        if (!retval.isEmpty()) {
            retval += ".";
        }
        retval += dcs.get(i);
    }
    for (int i = 0; i < ous.size(); i++) {
        retval += "/" + ous.get(i);
    }
    return retval;
}
项目:cibet    文件:RemoteEjbIT.java   
@Test
public void invokeRemoteEJBHandlerName() throws Throwable {
   log.debug("start invokeRemoteEJBHandlerName()");
   TEntity entity = new TEntity("ja", 88, "mys");
   Object[] params = new Object[] { "kll", 15, 34, "wossel".getBytes(), entity, new Long(900L) };

   URL url = Thread.currentThread().getContextClassLoader().getResource("jndi_.properties");
   log.debug("url=" + url);
   Properties properties = new Properties();
   properties.load(url.openStream());

   Method m = RemoteEJBImpl.class.getMethod("testInvoke", String.class, int.class, int.class, byte[].class,
         TEntity.class, Long.class);
   Name name = new LdapName("CN=Steve Kille,O=Isode Limited,C=GB");

   Constructor<RemoteEjbInvocationHandler> constr = RemoteEjbInvocationHandler.class
         .getDeclaredConstructor(Object.class, Hashtable.class, Name.class);
   constr.setAccessible(true);
   RemoteEjbInvocationHandler handler = constr.newInstance(new RemoteEJBImpl(), properties, name);

   List<Object> result = (List<Object>) handler.invoke(new Object(), m, params);
   assertNotNull(result);
   assertEquals(6, result.size());
}
项目:enmasse    文件:SaslDelegatingLogin.java   
private boolean populateUserAndRolesFromCert(X509Certificate certificate) throws InvalidNameException {
    LdapName ldapName = new LdapName(certificate.getSubjectDN().getName());

    // Find the first CN that maps to a valid user as supplied in the config
    Optional<String> validCN = ldapName.getRdns().stream()
        .filter(rdn -> rdn.getType().equalsIgnoreCase("CN"))
        .map(rdn -> String.valueOf(rdn.getValue()))
        .filter(n -> validCertUsers.containsKey(n)).findFirst();

    if(validCN.isPresent()) {
        String name = validCN.get();
        user = name; roles.addAll(validCertUsers.get(name));
        return true;
    } else {
        return false;
    }
}
项目:laverca    文件:CmsSignature.java   
/**
 * Convenience method. Equivalent to calling getSignerCert and
 * then parsing out the CN from the certificate's Subject field.
 * @return Signer CN or null if there's a problem.
 */
@Override
public String getSignerCn() {
    try {
        X509Certificate signerCert = this.getSignerCert();
        String dn = signerCert.getSubjectX500Principal().getName();

        String cn = null;
        try {
            LdapName ldapDn = new LdapName(dn);
            List<Rdn> rdns = ldapDn.getRdns();
            for(Rdn r : rdns) {
                if("CN".equals(r.getType())) {
                    cn = r.getValue().toString();
                }
            }
        } catch(InvalidNameException e) {
            log.warn("Invalid name", e);
        }

        return cn;
    } catch(Throwable t) {
        log.error("Failed to get signer CN: " + t.getMessage());
        return null;
    }
}
项目:laverca    文件:X509Util.java   
/**
 * Parse the given RND type from the given certificate's subject
 * @param cert Certificate
 * @param rdnType RND type
 * @return parsed value as String
 */
public static String parseSubjectName(final X509Certificate cert, final String rdnType) {
    String dn = cert.getSubjectX500Principal().getName();

    String name = null;
    try {
        LdapName ldapDn = new LdapName(dn);
        List<Rdn> rdns = ldapDn.getRdns();
        for(Rdn r : rdns) {
            if(rdnType.equals(r.getType())) {
                name = r.getValue().toString();
            }
        }
    } catch(InvalidNameException e) {
        log.error(e);
    }

    return name;
}
项目:laverca    文件:Pkcs1.java   
/**
 * Get the signer CN. 
 * <p>Equivalent to calling getSignerCert and
 * then parsing out the CN from the certificate's Subject field.
 * @return Signer's CN or null if there's a problem.
 */
@Override
public String getSignerCn() {
    try {
        X509Certificate signerCert = this.getSignerCert();
        String dn = signerCert.getSubjectX500Principal().getName();

        String cn = null;
        try {
            LdapName ldapDn = new LdapName(dn);
            List<Rdn> rdns = ldapDn.getRdns();
            for (Rdn r : rdns) {
                if("CN".equals(r.getType())) {
                    cn = r.getValue().toString();
                }
            }
        } catch(InvalidNameException e) {
            log.warn("Invalid name", e);
        }

        return cn;
    } catch (Throwable t) {
        log.error("Failed to get Signer cert " + t.getMessage());
        return null;
    }
}
项目:dss    文件:DSSASN1Utils.java   
/**
 * This method can be removed the simple IssuerSerial verification can be
 * performed. In fact the hash verification is sufficient.
 *
 * @param generalNames
 * @return
 */
public static String getCanonicalizedName(final GeneralNames generalNames) {
    GeneralName[] names = generalNames.getNames();
    TreeMap<String, String> treeMap = new TreeMap<String, String>();
    for (GeneralName name : names) {
        String ldapString = String.valueOf(name.getName());
        LOG.debug("ldapString to canonicalize: {} ", ldapString);
        try {
            LdapName ldapName = new LdapName(ldapString);
            List<Rdn> rdns = ldapName.getRdns();
            for (final Rdn rdn : rdns) {
                treeMap.put(rdn.getType().toLowerCase(), String.valueOf(rdn.getValue()).toLowerCase());
            }
        } catch (InvalidNameException e) {
            throw new DSSException(e);
        }
    }
    StringBuilder stringBuilder = new StringBuilder();
    for (Entry<String, String> entry : treeMap.entrySet()) {
        stringBuilder.append(entry.getKey()).append('=').append(entry.getValue()).append('|');
    }
    final String canonicalizedName = stringBuilder.toString();
    LOG.debug("canonicalizedName: {} ", canonicalizedName);
    return canonicalizedName;
}
项目:ezbake-common-java    文件:EzSecureClientTransport.java   
@Override
public void open() throws TTransportException {
    super.open();
    // If using SSL, check the the CN of the peer against the target security id
    if (validationRequired() && targetSecurityId != null) {
            Optional<LdapName> peerId = PeerSharedData.getPeerPrincipal();
            if (!peerId.isPresent()) {
                throw new TTransportException("No Peer SSL Certificate present, but peer authentication is " +
                        "required");
            } else {
                String peerCn = X509Utils.getCn(peerId.get());
                if (!targetSecurityId.equals(peerCn)) {
                    close();
                    throw new TTransportException("SSL Certificate of server does not match security ID of " +
                            "service we are connecting to. Expected: " + targetSecurityId + ", but was: " + peerCn);
                }
            }
    }
}
项目:daq-eclipse    文件:SimpleCachedLDAPAuthorizationMap.java   
/**
 * Processes results from a directory query in the context of a given destination type and permission type. This
 * implementation should not be invoked concurrently.
 *
 * @param results
 *            the results to process
 * @param destinationType
 *            the type of the destination for which the directory results apply
 * @param permissionType
 *            the type of the permission for which the directory results apply
 *
 * @throws Exception
 *             if there is an error processing the results
 */
protected void processQueryResults(DefaultAuthorizationMap map, NamingEnumeration<SearchResult> results, DestinationType destinationType, PermissionType permissionType)
    throws Exception {

    while (results.hasMore()) {
        SearchResult result = results.next();
        AuthorizationEntry entry = null;

        try {
            entry = getEntry(map, new LdapName(result.getNameInNamespace()), destinationType);
        } catch (Exception e) {
            LOG.error("Policy not applied!  Error parsing authorization policy entry under {}", result.getNameInNamespace(), e);
            continue;
        }

        applyACL(entry, result, permissionType);
    }
}
项目:daq-eclipse    文件:SimpleCachedLDAPAuthorizationMap.java   
/**
 * Parses a DN into the equivalent {@link ActiveMQDestination}. The default implementation expects a format of
 * cn=<PERMISSION_NAME>,ou=<DESTINATION_PATTERN>,.... or ou=<DESTINATION_PATTERN>,.... for permission and
 * destination entries, respectively. For example {@code cn=admin,ou=$,ou=...} or {@code ou=$,ou=...}.
 *
 * @param dn
 *            the DN to parse
 * @param destinationType
 *            the type of the destination that we are parsing
 *
 * @return the destination that the DN represents
 *
 * @throws IllegalArgumentException
 *             if {@code destinationType} is {@link DestinationType#TEMP} or if the format of {@code dn} is
 *             incorrect for for a topic or queue
 *
 * @see #formatDestination(Rdn, DestinationType)
 */
protected ActiveMQDestination formatDestination(LdapName dn, DestinationType destinationType) {
    ActiveMQDestination destination = null;

    switch (destinationType) {
        case QUEUE:
        case TOPIC:
            // There exists a need to deal with both names representing a permission or simply a
            // destination. As such, we need to determine the proper RDN to work with based
            // on the destination type and the DN size.
            if (dn.size() == (getPrefixLengthForDestinationType(destinationType) + 2)) {
                destination = formatDestination(dn.getRdn(dn.size() - 2), destinationType);
            } else if (dn.size() == (getPrefixLengthForDestinationType(destinationType) + 1)) {
                destination = formatDestination(dn.getRdn(dn.size() - 1), destinationType);
            } else {
                throw new IllegalArgumentException("Malformed DN for representing a permission or destination entry.");
            }
            break;
        default:
            throw new IllegalArgumentException("Cannot format destination for destination type " + destinationType);
    }

    return destination;
}
项目:daq-eclipse    文件:LDAPAuthorizationMap.java   
protected Set<GroupPrincipal> getACLs(String destinationBase, SearchControls constraints, String roleBase, String roleAttribute) {
    try {
        Set<GroupPrincipal> roles = new HashSet<GroupPrincipal>();
        Set<String> acls = new HashSet<String>();
        NamingEnumeration<?> results = context.search(destinationBase, roleBase, constraints);
        while (results.hasMore()) {
            SearchResult result = (SearchResult)results.next();
            Attributes attrs = result.getAttributes();
            if (attrs == null) {
                continue;
            }
            acls = addAttributeValues(roleAttribute, attrs, acls);
        }
        for (Iterator<String> iter = acls.iterator(); iter.hasNext();) {
            String roleName = iter.next();
            LdapName ldapname = new LdapName(roleName);
            Rdn rdn = ldapname.getRdn(ldapname.size() - 1);
            LOG.debug("Found role: [" + rdn.getValue().toString() + "]");
            roles.add(new GroupPrincipal(rdn.getValue().toString()));
        }
        return roles;
    } catch (NamingException e) {
        LOG.error(e.toString());
        return new HashSet<GroupPrincipal>();
    }
}
项目:gerrit    文件:LdapGroupBackend.java   
private static String cnFor(String dn) {
  try {
    LdapName name = new LdapName(dn);
    if (!name.isEmpty()) {
      String cn = name.get(name.size() - 1);
      int index = cn.indexOf('=');
      if (index >= 0) {
        cn = cn.substring(index + 1);
      }
      return cn;
    }
  } catch (InvalidNameException e) {
    log.warn("Cannot parse LDAP dn for cn", e);
  }
  return dn;
}
项目:mariadb-connector-j    文件:HostnameVerifierImpl.java   
private static String extractCommonName(String principal) throws SSLException {
    if (principal == null) return null;
    try {
        LdapName ldapName = new LdapName(principal);

        for (Rdn rdn : ldapName.getRdns()) {
            if (rdn.getType().equalsIgnoreCase("CN")) {
                Object obj = rdn.getValue();
                if (obj != null) return obj.toString();
            }
        }
        return null;
    } catch (InvalidNameException e) {
        throw new SSLException("DN value \"" + principal + "\" is invalid");
    }
}
项目:appverse-server    文件:CertServiceImpl.java   
/**
 * Retrieves the name for the given certificate.
 * 
 * @param certificate the certificate to get its name for, cannot be <code>null</code>.
 * @return the name for the given certificate, can be <code>null</code>.
 */
@Override
public String getName(final X509Certificate certificate) {
    try {
        String dn = certificate.getSubjectX500Principal().getName();
        if ("dn".equalsIgnoreCase("cn")) {
            return dn;
        }

        LdapName ldapDN = new LdapName(dn);
        for (Rdn rdn : ldapDN.getRdns()) {
            if ("cn".equalsIgnoreCase(rdn.getType())) {
                return (String) rdn.getValue();
            }
        }
    } catch (InvalidNameException e) {
        // Ignore...
    }
    return null;
}
项目:cn1    文件:LdapContextImplTest.java   
public void test_list_LName() throws Exception {
    MockLdapClient client = new MockLdapClient();
    context = new LdapContextImpl(client, new Hashtable<Object, Object>(),
            "");

    Name name = new LdapName("cn=test,o=harmony");
    context.list(name);

    SearchOp op = (SearchOp) client.getRequest();
    assertEquals(name.toString(), op.getBaseObject());
    assertFalse(op.isTypesOnly());
    SearchControls controls = op.getControls();
    assertEquals(SearchControls.ONELEVEL_SCOPE, controls.getSearchScope());
    Filter filter = op.getFilter();
    assertEquals(Filter.PRESENT_FILTER, filter.getType());
    assertEquals("objectClass", (String) filter.getValue());

    name = new CompositeName("usr/bin");
    try {
        context.list(name);
        fail("should throws InvalidNameException");
    } catch (InvalidNameException e) {
        // expected
    }
}
项目:cn1    文件:LdapNameTest.java   
/**
 * <p>
 * Test method for 'javax.naming.ldap.LdapName.LdapName(List<Rdn>)'
 * </p>
 * <p>
 * Here we are testing the constructor method of LdapName reciving a list of
 * valid names.
 * </p>
 * <p>
 * The expected result is an instance of an object of LdapName, and also
 * that the indexing is made like the other way around.
 * </p>
 */    
public void testLdapNameListOfRdn006() throws Exception {
    try {
        BasicAttributes bas = new BasicAttributes();
        bas.put("test2", "test2");
        bas.put("test1", "test1");
        bas.put("test3", "test3");
        Rdn rdn1 = new Rdn(bas);
        LinkedList<Rdn> rdns = new LinkedList<Rdn>();
        rdns.add(rdn1);
        LdapName ln = new LdapName(rdns);
        assertEquals("test1=test1+test2=test2+test3=test3", ln.getAll().nextElement());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:cn1    文件:LdapNameTest.java   
/**
 * <p>
 * Test method for 'javax.naming.ldap.LdapName.toString()'
 * </p>
 * <p>
 * Here we are testing if the method returns the correct string for an
 * LdapName according to RFC 2253.
 * </p>
 * <p>
 * The expected results is a representation of this LDAP as we created it,
 * in this case the in the String are three names, the ldapname should
 * return the strings in the LIFO way.
 * </p>
 */
public void testToString002() throws Exception {
    LinkedList<Rdn> test = new LinkedList<Rdn>();
    test.add(new Rdn("c1=common"));
    test.add(new Rdn("c2=common"));
    test.add(new Rdn("c3=common"));
    LdapName ln = new LdapName(test);
    String comp = "";
    for (Rdn rdn : test) {
        if (test.getFirst() == rdn) {
            comp = rdn.toString();
        } else {
            comp = rdn.toString() + "," + comp;
        }
    }
    assertEquals(comp, ln.toString());
}
项目:cn1    文件:LdapNameTest.java   
/**
 * <p>
 * Test method for 'javax.naming.ldap.LdapName.getAll()'
 * </p>
 * <p>
 * Here we are testing if this method correctly returns all the RDNs that
 * make up this LdapName as Strings.
 * </p>
 * <p>
 * The expected result is if a non empty name returns a non-null
 * enumeration, and ordered like it should be.
 * </p>
 */
public void testGetAll003() throws Exception {
    LinkedList<Rdn> test = new LinkedList<Rdn>();
    Rdn a = new Rdn("cn", "test");
    Rdn b = new Rdn("uid", "test");
    Rdn c = new Rdn("l", "test");
    Rdn d = new Rdn("st", "test");
    test.add(0, a);
    test.add(1, b);
    test.add(2, c);
    test.add(3, d);
    LdapName ln = new LdapName(test);
    Enumeration<String> e = ln.getAll();
    for (Rdn rdn : test) {
        assertEquals(rdn.toString(), e.nextElement());
    }
}
项目:wildfly-core    文件:LdapKeyStoreService.java   
LdapKeyStoreService(String searchPath, String filterAlias, String filterCertificate,
                    String filterIterate, LdapName createPath, String createRdn, Attributes createAttributes,
                    String aliasAttribute, String certificateAttribute, String certificateType,
                    String certificateChainAttribute, String certificateChainEncoding,
                    String keyAttribute, String keyType) {
    this.searchPath = searchPath;
    this.filterAlias = filterAlias;
    this.filterCertificate = filterCertificate;
    this.filterIterate = filterIterate;
    this.createPath = createPath;
    this.createRdn = createRdn;
    this.createAttributes = createAttributes;
    this.aliasAttribute = aliasAttribute;
    this.certificateAttribute = certificateAttribute;
    this.certificateType = certificateType;
    this.certificateChainAttribute = certificateChainAttribute;
    this.certificateChainEncoding = certificateChainEncoding;
    this.keyAttribute = keyAttribute;
    this.keyType = keyType;
}
项目:plugin-id-ldap    文件:UserLdapRepository.java   
@Override
public void move(final UserOrg user, final CompanyOrg company) {
    final LdapName newDn = org.springframework.ldap.support.LdapUtils.newLdapName(buildDn(user.getId(), company.getDn()));
    final LdapName oldDn = org.springframework.ldap.support.LdapUtils.newLdapName(user.getDn());
    template.rename(oldDn, newDn);
    user.setDn(newDn.toString());
    user.setCompany(company.getId());
    ldapCacheRepository.update(user);

    // Also, update the groups of this user
    user.getGroups().forEach(g -> groupLdapRepository.updateMemberDn(g, oldDn.toString(), newDn.toString()));
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a not managed LDAP desynchronization
 */
@Test(expected = org.springframework.ldap.AttributeInUseException.class)
public void addUserSyncError() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());

    addUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP desynchronization
 */
@Test
public void addUserSync1() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("value #0 already exists")))
            .when(ldapTemplate).modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());

    addUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP desynchronization
 */
@Test
public void addUserSync2() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.AttributeInUseException(new AttributeInUseException("ATTRIBUTE_OR_VALUE_EXISTS")))
            .when(ldapTemplate).modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());

    addUser(groupRepository);
}
项目:plugin-id-ldap    文件:GroupLdapRepositoryTest.java   
/**
 * Mock a managed LDAP schema violation
 */
@Test
public void removeUserNotMember() {
    final GroupLdapRepository groupRepository = newGroupLdapRepository();
    final LdapTemplate ldapTemplate = Mockito.mock(LdapTemplate.class);
    groupRepository.setTemplate(ldapTemplate);
    Mockito.doThrow(new org.springframework.ldap.SchemaViolationException(new SchemaViolationException("any"))).when(ldapTemplate)
            .modifyAttributes(ArgumentMatchers.any(LdapName.class), ArgumentMatchers.any());
    removeUser(groupRepository);
}
项目:ipack    文件:Signer.java   
private static String getSubjectName(final X509Certificate cert)
        throws InvalidNameException {
    final String fullSubjectDn = cert.getSubjectX500Principal().getName();
    final LdapName fullSubjectLn = new LdapName(fullSubjectDn);
    for (final Rdn rdn: fullSubjectLn.getRdns()) {
        if ("CN".equalsIgnoreCase(rdn.getType())) {
            return rdn.getValue().toString();
        }
    }

    throw new InvalidNameException("Common name not found");
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * Test for DIRSERVER-191
 */
@Test
public void testName() throws LdapException, InvalidNameException
{
    LdapName jName = new javax.naming.ldap.LdapName( "cn=four,cn=three,cn=two,cn=one" );
    Dn aName = new Dn( "cn=four,cn=three,cn=two,cn=one" );
    assertEquals( jName.toString(), "cn=four,cn=three,cn=two,cn=one" );
    assertEquals( aName.toString(), "cn=four,cn=three,cn=two,cn=one" );
    assertEquals( jName.toString(), aName.toString() );
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * Test for DIRSERVER-191
 */
@Test
public void testGetPrefixName() 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" );

    assertEquals( jName.getPrefix( 0 ).toString(), aName.getAncestorOf( "cn=four,cn=three,cn=two,cn=one" )
        .toString() );
    assertEquals( jName.getPrefix( 1 ).toString(), aName.getAncestorOf( "cn=four,cn=three,cn=two" ).toString() );
    assertEquals( jName.getPrefix( 2 ).toString(), aName.getAncestorOf( "cn=four,cn=three" ).toString() );
    assertEquals( jName.getPrefix( 3 ).toString(), aName.getAncestorOf( "cn=four" ).toString() );
    assertEquals( jName.getPrefix( 4 ).toString(), aName.getAncestorOf( "" ).toString() );
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * Test for DIRSERVER-191
 */
@Test
public void testGetSuffix() 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" );

    assertEquals( jName.getSuffix( 0 ).toString(), aName.getDescendantOf( "" ).toString() );
    assertEquals( jName.getSuffix( 1 ).toString(), aName.getDescendantOf( "cn=one" ).toString() );
    assertEquals( jName.getSuffix( 2 ).toString(), aName.getDescendantOf( "cn=two,cn=one" ).toString() );
    assertEquals( jName.getSuffix( 3 ).toString(), aName.getDescendantOf( "cn=three,cn=two,cn=one" ).toString() );
    assertEquals( jName.getSuffix( 4 ).toString(), aName.getDescendantOf( "cn=four,cn=three,cn=two,cn=one" )
        .toString() );
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * 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() );
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * Test for DIRSERVER-191
 */
@Test
public void testAddAllName() 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.addAll( new LdapName( "cn=seven,cn=six" ) ) );
    assertNotSame( aName, aName.add( new Dn( "cn=seven,cn=six" ) ) );
    assertNotSame( jName.toString(), aName.toString() );
}
项目:directory-ldap-api    文件:DnTest.java   
/**
 * Test for DIRSERVER-191
 */
@Test
public void testStartsWithName() 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" );

    assertEquals( jName.startsWith( new LdapName( "cn=seven,cn=six,cn=five" ) ),
        aName.isDescendantOf( new Dn( "cn=seven,cn=six,cn=five" ) ) );
    assertEquals( jName.startsWith( new LdapName( "cn=three,cn=two,cn=one" ) ),
        aName.isDescendantOf( new Dn( "cn=three,cn=two,cn=one" ) ) );
}