org.apache.directory.shared.ldap.entry.ServerEntry Java Examples

The following examples show how to use org.apache.directory.shared.ldap.entry.ServerEntry. 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: MembershipSelectorTest.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@BeforeClass
public void setUpServer() throws Exception {
  (server = EmbeddedLdapServer.newDefaultServer()).start();
  connFactory = server.getConnectionFactory();

  // first 100 users don't belong to any group
  for (int i = 0; i < 100; i++) {
    server.addDefaultLdapUser(i);
  }

  // next 200 users are members of group1/group2
  final List<String> group1Members = new ArrayList<>(100);
  final List<String> group2Members = new ArrayList<>(100);
  for (int i = 100; i < 300; i++) {
    final ServerEntry entry = server.addDefaultLdapUser(i, Pair.of("givenName", "gn-" + i));
    if (i % 2 == 0) {
      group1Members.add(entry.getDn().toString());
    } else {
      group2Members.add(entry.getDn().toString());
    }
    group1Members.add(entry.getDn().toString());
  }
  server.addDefaultLdapGroup("group1", group1Members);
  server.addDefaultLdapGroup("group2", group2Members);
}
 
Example #2
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Adds a new user which matches the default schema pattern, which is:
 *
 * <ul>
 *   <li>objectClass=inetOrgPerson
 *   <li>rdn - uid={id}
 *   <li>cn={name}
 *   <li>mail={mail}
 *   <li>sn={@literal <none>}
 *   <li>other.foreach(pair -> {pair.first}={pair.second})
 * </ul>
 *
 * @return newly created and added entry instance
 * @throws Exception when any error occurs
 */
public ServerEntry addDefaultLdapUser(String id, String name, String mail, Pair... other)
    throws Exception {
  final ServerEntry entry = newEntry("uid", id);
  entry.put("objectClass", "inetOrgPerson");
  entry.put("uid", id);
  entry.put("cn", name);
  entry.put("mail", mail);
  entry.put("sn", "<none>");
  for (Pair pair : other) {
    if (pair.second instanceof byte[]) {
      entry.put(pair.first.toString(), (byte[]) pair.second);
    } else {
      entry.put(pair.first.toString(), pair.second.toString());
    }
  }
  addEntry(entry);
  return entry;
}
 
Example #3
Source File: EmbeddedADS.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Add a new set of index on the given attributes
 *
 * @param partition The partition on which we want to add index
 * @param attrs     The list of attributes to index
 */
private void addIndex(Partition partition, String... attrs) {
  // Index some attributes on the apache partition
  HashSet<Index<?, ServerEntry, Long>> indexedAttributes = new HashSet<>();

  for (String attribute : attrs) {
    indexedAttributes.add(new JdbmIndex<String, ServerEntry>(attribute));
  }

  ((JdbmPartition) partition).setIndexedAttributes(indexedAttributes);
}
 
Example #4
Source File: ApacheDirectoryPartitionManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void addAdminPassword(ServerEntry adminEntry, String password,
                              PasswordAlgorithm algorithm,
                              final boolean kdcEnabled)
        throws DirectoryServerException {

    try {
        String passwordToStore = "{" + algorithm.getAlgorithmName() + "}";
        if (algorithm != PasswordAlgorithm.PLAIN_TEXT && !kdcEnabled) {
            MessageDigest md = MessageDigest.getInstance(algorithm.getAlgorithmName());
            md.update(password.getBytes());
            byte[] bytes = md.digest();
            String hash = Base64.encode(bytes);
            passwordToStore = passwordToStore + hash;

        } else {

            if (kdcEnabled) {
                logger.warn(
                        "KDC enabled. Enforcing passwords to be plain text. Cause - KDC " +
                                "cannot operate with hashed passwords.");
            }

            passwordToStore = password;
        }

        adminEntry.put("userPassword", passwordToStore.getBytes());

    } catch (NoSuchAlgorithmException e) {
        throwDirectoryServerException("Could not find matching hash algorithm - " +
                algorithm.getAlgorithmName(), e);
    }

}
 
Example #5
Source File: ApacheDirectoryPartitionManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void addPartitionAttributes(String partitionDN, List<String> objectClasses,
                                    String realm, String dc)
        throws DirectoryServerException {

    try {
        DN adminDN = new DN(partitionDN);
        ServerEntry serverEntry = this.directoryService.newEntry(adminDN);

        addObjectClasses(serverEntry, objectClasses);

        serverEntry.add("o", realm);

        if (dc == null) {
            logger.warn("Domain component not found for partition with DN - " + partitionDN +
                    ". Not setting domain component.");
        } else {
            serverEntry.add("dc", dc);
        }

        addAccessControlAttributes(serverEntry);

        this.directoryService.getAdminSession().add(serverEntry);

    } catch (Exception e) {

        String msg = "Could not add partition attributes for partition - " + partitionDN;
        throwDirectoryServerException(msg, e);
    }

}
 
Example #6
Source File: ApacheDirectoryPartitionManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private static void addObjectClasses(ServerEntry serverEntry, List<String> objectClasses)
        throws DirectoryServerException {

    for (String objectClass : objectClasses) {
        try {
            serverEntry.add("objectClass", objectClass);
        } catch (LdapException e) {
            throwDirectoryServerException("Could not add class to partition " +
                    serverEntry.getDn().getName(), e);
        }
    }
}
 
Example #7
Source File: LDAPServer.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add a new set of index on the given attributes
 *
 * @param partition
 *            The partition on which we want to add index
 * @param attrs
 *            The list of attributes to index
 */
private void addIndex(Partition partition, String... attrs) {
	// Index some attributes on the apache partition
	HashSet<Index<?, ServerEntry, Long>> indexedAttributes = new HashSet<Index<?, ServerEntry, Long>>();

	for (String attribute : attrs) {
		indexedAttributes.add(new JdbmIndex<String, ServerEntry>(attribute));
	}

	((JdbmPartition) partition).setIndexedAttributes(indexedAttributes);
}
 
Example #8
Source File: AuthenticationTest.java    From codenvy with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Ups ldap test server & initializes the following directory structure:
 *
 * <pre>
 * dc=codenvy,dc=com
 *   ou=developers
 *     cn=mike
 *      -objectClass=inetOrgPerson
 *      -uid=user1
 *      -cn=mike
 *      -sn=mike
 *      -userPassword=sha(mike)
 *     cn=john
 *      -objectClass=inetOrgPerson
 *      -uid=user2
 *      -cn=john
 *      -sn=john
 *      -userPassword=sha(john)
 *   ou=managers
 *     cn=brad
 *      -objectClass=inetOrgPerson
 *      -uid=user3
 *      -cn=brad
 *      -sn=brad
 *      -userPassword=sha(brad)
 *     cn=ivan
 *      -objectClass=inetOrgPerson
 *      -uid=user4
 *      -cn=ivan
 *      -sn=ivan
 *      -userPassword=sha(ivan)
 * </pre>
 */
@BeforeMethod
public void startServer() throws Exception {
  server =
      EmbeddedLdapServer.builder()
          .setPartitionId("codenvy")
          .setPartitionDn("dc=codenvy,dc=com")
          .useTmpWorkingDir()
          .setMaxSizeLimit(1000)
          .build();
  server.start();

  // developers
  ServerEntry ouDevelopers = server.newEntry("ou", "developers");
  ouDevelopers.add("objectClass", "organizationalUnit");
  ouDevelopers.add("ou", "developers");
  server.addEntry(ouDevelopers);

  ServerEntry mike = server.newEntry("cn", "mike", ouDevelopers);
  mike.add("objectClass", "inetOrgPerson");
  mike.add("uid", "user1");
  mike.add("cn", "mike");
  mike.add("sn", "mike");
  mike.add("userPassword", encryptor.encrypt("mike".getBytes(UTF_8)));
  server.addEntry(mike);

  ServerEntry john = server.newEntry("cn", "john", ouDevelopers);
  john.add("objectClass", "inetOrgPerson");
  john.add("uid", "user2");
  john.add("cn", "john");
  john.add("sn", "john");
  john.add("userPassword", encryptor.encrypt("john".getBytes(UTF_8)));
  server.addEntry(john);

  // managers
  ServerEntry ouManagers = server.newEntry("ou", "managers");
  ouManagers.add("objectClass", "organizationalUnit");
  ouManagers.add("ou", "managers");
  server.addEntry(ouManagers);

  ServerEntry brad = server.newEntry("cn", "brad", ouManagers);
  brad.add("objectClass", "inetOrgPerson");
  brad.add("uid", "user3");
  brad.add("cn", "brad");
  brad.add("sn", "brad");
  brad.add("userPassword", encryptor.encrypt("brad".getBytes(UTF_8)));
  server.addEntry(brad);

  ServerEntry ivan = server.newEntry("cn", "ivan", ouManagers);
  ivan.add("objectClass", "inetOrgPerson");
  ivan.add("uid", "user4");
  ivan.add("cn", "ivan");
  ivan.add("sn", "ivan");
  ivan.add("userPassword", encryptor.encrypt("ivan".getBytes(UTF_8)));
  server.addEntry(ivan);
}
 
Example #9
Source File: EmbeddedADS.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the server. It creates the partition, adds the index, and
 * injects the context entries for the created partitions.
 *
 * @param workDir the directory to be used for storing the data
 * @throws Exception if there were some problems while initializing the system
 */
private void initDirectoryService(File workDir) throws Exception {
  // Initialize the LDAP service
  service = new DefaultDirectoryService();
  service.setWorkingDirectory(workDir);

  // first load the schema
  initSchemaPartition();

  // then the system partition
  // this is a MANDATORY partition
  Partition systemPartition = addPartition("system", ServerDNConstants.SYSTEM_DN);
  service.setSystemPartition(systemPartition);

  // Disable the ChangeLog system
  service.getChangeLog().setEnabled(false);
  service.setDenormalizeOpAttrsEnabled(true);

  // Now we can create as many partitions as we need
  // Create some new partitions named 'foo', 'bar' and 'apache'.
  Partition fooPartition = addPartition("foo", "dc=foo,dc=com");

  // Index some attributes on the apache partition
  addIndex(fooPartition, "objectClass", "ou", "uid");

  // And start the service
  service.startup();

  DN dnFoo = new DN("dc=foo,dc=com");
  ServerEntry entryFoo = service.newEntry(dnFoo);
  entryFoo.add("objectClass", "top", "domain", "extensibleObject");
  entryFoo.add("dc", "foo");
  service.getAdminSession().add(entryFoo);

  DN usersDN=new DN("ou=users,dc=foo,dc=com");
  ServerEntry usersEntry=service.newEntry(usersDN);
  usersEntry.add("objectClass","organizationalUnit","top");
  usersEntry.add("ou","users");
  service.getAdminSession().add(usersEntry);

}
 
Example #10
Source File: ApacheDirectoryPartitionManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private JdbmPartition createNewPartition(String partitionId, String partitionSuffix)
        throws DirectoryServerException {
    try {
        JdbmPartition partition = new JdbmPartition();
        String partitionDirectoryName = this.workingDirectory + File.separator + partitionId;
        File partitionDirectory = new File(partitionDirectoryName);

        partition.setId(partitionId);
        partition.setSuffix(partitionSuffix);
        partition.setPartitionDir(partitionDirectory);

        Set<Index<?, ServerEntry, Long>> indexedAttrs =
                new HashSet<Index<?, ServerEntry, Long>>();

        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.1"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.2"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.3"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.4"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.5"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.6"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("1.3.6.1.4.1.18060.0.4.1.2.7"));

        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("ou"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("dc"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("objectClass"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("cn"));
        indexedAttrs.add(new JdbmIndex<String, ServerEntry>("uid"));
        partition.setIndexedAttributes(indexedAttrs);

        String message = MessageFormat.format(
                "Partition created with following attributes, partition id - {0}, Partition " +
                        "domain - {1}, Partition working directory {2}", partitionId,
                partitionSuffix, partitionDirectoryName);

        if (logger.isDebugEnabled()) {
            logger.debug(message);
        }


        return partition;

    } catch (LdapInvalidDnException e) {
        String msg = "Could not add a new partition with partition id " + partitionId +
                " and suffix " + partitionSuffix;
        logger.error(msg, e);
        throw new DirectoryServerException(msg, e);
    }
}
 
Example #11
Source File: ApacheDirectoryPartitionManager.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void addAccessControlAttributes(ServerEntry serverEntry)
        throws LdapException {
    serverEntry.add("administrativeRole", "accessControlSpecificArea");
}
 
Example #12
Source File: LdapTestServer.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the server. It creates the partition, injects the context
 * entries for the created partitions, and loads an LDIF file (
 * {@link #ldifLoadFile}) for initial entries.
 *
 * @param workDir
 *          the directory to be used for storing the data
 * @throws Exception
 *           if there were some problems while initializing the system
 */
private void initDirectoryService(File workDir) throws Exception {
  // Initialize the LDAP service
  service = new DefaultDirectoryService();
  service.setWorkingDirectory(workDir);

  // first load the schema
  initSchemaPartition();

  // then the system partition
  // this is a MANDATORY partition
  Partition systemPartition = addPartition("system",
      ServerDNConstants.SYSTEM_DN);
  service.setSystemPartition(systemPartition);

  // create the partition for testing
  Partition testingPartition = addPartition("ldapTesting",
      "ou=ldapTesting,dc=pune,dc=gemstone,dc=com");

  // Disable the shutdown hook
  service.setShutdownHookEnabled(false);
  // Disable the ChangeLog system
  service.getChangeLog().setEnabled(false);
  service.setDenormalizeOpAttrsEnabled(true);

  // And start the service
  service.startup();

  // inject the entry for testing
  if (!service.getAdminSession().exists(testingPartition.getSuffixDn())) {
    DN dnTesting = new DN("ou=ldapTesting,dc=pune,dc=gemstone,dc=com");
    ServerEntry entryTesting = service.newEntry(dnTesting);
    entryTesting.add("objectClass", "top", "domain", "extensibleObject");
    entryTesting.add("dc", "pune");
    service.getAdminSession().add(entryTesting);
  }

  // load schema from LDIF
  if (ldifLoadFile != null) {
    LdifFileLoader ldifLoader = new LdifFileLoader(
        service.getAdminSession(), ldifLoadFile);
    int numLoaded = ldifLoader.execute();
    if (numLoaded <= 0) {
      throw new Exception(
          "Failed to load any entries from " + ldifLoadFile);
    } else {
      System.out.println(
          "LDAP loaded " + numLoaded + " entries from " + ldifLoadFile);
    }
  }
}
 
Example #13
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 4 votes vote down vote up
public ServerEntry newEntry(String name, String value, ServerEntry parent) throws Exception {
  return service.newEntry(new DN(name + '=' + value + ',' + parent.getDn()));
}
 
Example #14
Source File: LdapSynchronizationFlowTest.java    From codenvy with Eclipse Public License 1.0 4 votes vote down vote up
private static UserImpl asUser(ServerEntry entry) {
  return new UserImpl(
      entry.get("uid").get(0).toString(),
      entry.get("mail").get(0).toString(),
      entry.get("cn").get(0).toString());
}
 
Example #15
Source File: LdapTestServer.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the server. It creates the partition, injects the context
 * entries for the created partitions, and loads an LDIF file (
 * {@link #ldifLoadFile}) for initial entries.
 *
 * @param workDir
 *          the directory to be used for storing the data
 * @throws Exception
 *           if there were some problems while initializing the system
 */
private void initDirectoryService(File workDir) throws Exception {
  // Initialize the LDAP service
  service = new DefaultDirectoryService();
  service.setWorkingDirectory(workDir);

  // first load the schema
  initSchemaPartition();

  // then the system partition
  // this is a MANDATORY partition
  Partition systemPartition = addPartition("system",
      ServerDNConstants.SYSTEM_DN);
  service.setSystemPartition(systemPartition);

  // create the partition for testing
  Partition testingPartition = addPartition("ldapTesting",
      "ou=ldapTesting,dc=pune,dc=gemstone,dc=com");

  // Disable the shutdown hook
  service.setShutdownHookEnabled(false);
  // Disable the ChangeLog system
  service.getChangeLog().setEnabled(false);
  service.setDenormalizeOpAttrsEnabled(true);

  // And start the service
  service.startup();

  // inject the entry for testing
  if (!service.getAdminSession().exists(testingPartition.getSuffixDn())) {
    DN dnTesting = new DN("ou=ldapTesting,dc=pune,dc=gemstone,dc=com");
    ServerEntry entryTesting = service.newEntry(dnTesting);
    entryTesting.add("objectClass", "top", "domain", "extensibleObject");
    entryTesting.add("dc", "pune");
    service.getAdminSession().add(entryTesting);
  }

  // load schema from LDIF
  if (ldifLoadFile != null) {
    LdifFileLoader ldifLoader = new LdifFileLoader(
        service.getAdminSession(), ldifLoadFile);
    int numLoaded = ldifLoader.execute();
    if (numLoaded <= 0) {
      throw new Exception(
          "Failed to load any entries from " + ldifLoadFile);
    } else {
      System.out.println(
          "LDAP loaded " + numLoaded + " entries from " + ldifLoadFile);
    }
  }
}
 
Example #16
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a new group which matches default schema pattern, which is:
 *
 * <ul>
 *   <li>objectClass=groupOfNames
 *   <li>rdn - ou={name}
 *   <li>cn={name}
 *   <li>members.foreach(m -> member={m})
 * </ul>
 *
 * @param name a name of a group
 * @return newly created and added group entry
 * @throws Exception when any error occurs
 */
public ServerEntry addDefaultLdapGroup(String name, List<String> members) throws Exception {
  final ServerEntry group = newEntry("ou", name);
  group.put("objectClass", "top", "groupOfNames");
  group.put("cn", name);
  group.put("ou", name);
  for (String member : members) {
    group.add("member", member);
  }
  addEntry(group);
  return group;
}
 
Example #17
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Simplifies creation of test user entry by generating id, name and mail based on given {@code
 * idx}.
 *
 * @see #addDefaultLdapUser(String, String, String, Pair[])
 */
public ServerEntry addDefaultLdapUser(int idx, Pair... other) throws Exception {
  return addDefaultLdapUser("id" + idx, "name" + idx, "mail" + idx, other);
}
 
Example #18
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Adds the {@code entry} to this directory service.
 *
 * @throws Exception when the {@code entry} can't be added
 */
public void addEntry(ServerEntry entry) throws Exception {
  service.getAdminSession().add(entry);
}
 
Example #19
Source File: EmbeddedLdapServer.java    From codenvy with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a new entry in base dn.
 *
 * <p>E.g. if {@code base_dn} is set to <i>dc=codenvy,dc=com</i> for {@code name=cn} and {@code
 * value=admin} the entity dn will be <i>cn=admin,dc=codenvy,dc=com</i>.
 *
 * <p>To add the entity attributes to directory service use {@link #addEntry(ServerEntry)}.
 *
 * @param name the name of the dn attribute e.g. 'cn'
 * @param value the value of the attribute e.g. 'admin'
 * @return a new instance of {@link ServerEntry}
 * @throws Exception when any error occurs
 */
public ServerEntry newEntry(String name, String value) throws Exception {
  return service.newEntry(new DN(name + '=' + value + ',' + baseDn.toString()));
}