org.apache.directory.api.ldap.model.ldif.LdifReader Java Examples

The following examples show how to use org.apache.directory.api.ldap.model.ldif.LdifReader. 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: MiniKdc.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a principal in the KDC with the specified user and password.
 *
 * @param principal principal name, do not include the domain.
 * @param password password.
 * @throws Exception thrown if the principal could not be created.
 */
public synchronized void createPrincipal(String principal, String password)
        throws Exception {
  String orgName= conf.getProperty(ORG_NAME);
  String orgDomain = conf.getProperty(ORG_DOMAIN);
  String baseDn = "ou=users,dc=" + orgName.toLowerCase(Locale.ENGLISH)
                  + ",dc=" + orgDomain.toLowerCase(Locale.ENGLISH);
  String content = "dn: uid=" + principal + "," + baseDn + "\n" +
          "objectClass: top\n" +
          "objectClass: person\n" +
          "objectClass: inetOrgPerson\n" +
          "objectClass: krb5principal\n" +
          "objectClass: krb5kdcentry\n" +
          "cn: " + principal + "\n" +
          "sn: " + principal + "\n" +
          "uid: " + principal + "\n" +
          "userPassword: " + password + "\n" +
          "krb5PrincipalName: " + principal + "@" + getRealm() + "\n" +
          "krb5KeyVersionNumber: 0";

  for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
    ds.getAdminSession().add(new DefaultEntry(ds.getSchemaManager(),
            ldifEntry.getEntry()));
  }
}
 
Example #2
Source File: OutboundLdapConnectionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeClass
@CreateDS(
    name = "WildFlyDS",
    factory = InMemoryDirectoryServiceFactory.class,
    partitions = @CreatePartition(name = "wildfly", suffix = "dc=wildfly,dc=org"),
    allowAnonAccess = true
)
@CreateLdapServer(
    transports = @CreateTransport(protocol = "LDAP", address = "localhost", port = 10389),
    allowAnonymousAccess = true
)
public static void setUpLdap() throws Exception {
    directoryService = DSAnnotationProcessor.getDirectoryService();
    final SchemaManager schemaManager = directoryService.getSchemaManager();
    final InputStream ldif = OutboundLdapConnectionTestCase.class
            .getResourceAsStream("/" + OutboundLdapConnectionTestCase.class.getSimpleName() + ".ldif");
    for (LdifEntry ldifEntry : new LdifReader(ldif)) {
        directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
    }
    ldapServer = ServerAnnotationProcessor.getLdapServer(directoryService);
}
 
Example #3
Source File: LdapRoleMappingU2GTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeClass
@CreateDS(
        name = "WildFlyDS",
        factory = org.jboss.as.test.integration.mgmt.access.ldap.InMemoryDirectoryServiceFactory.class,
        partitions = @CreatePartition(name = "wildfly", suffix = "dc=wildfly,dc=org"),
        allowAnonAccess = true
)
@CreateLdapServer(
        transports = @CreateTransport(protocol = "LDAP", address = "localhost", port = 10389),
        allowAnonymousAccess = true
)
public static void setUp() throws Exception {
    directoryService = DSAnnotationProcessor.getDirectoryService();
    SchemaManager schemaManager = directoryService.getSchemaManager();
    InputStream ldif = LdapRoleMappingU2GTestCase.class.getResourceAsStream("/" + LdapRoleMappingU2GTestCase.class.getSimpleName() + ".ldif");
    for (LdifEntry ldifEntry : new LdifReader(ldif)) {
        directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
    }
    ldapServer = ServerAnnotationProcessor.getLdapServer(directoryService);

    startServer();
}
 
Example #4
Source File: LdapRoleMappingG2UTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeClass
@CreateDS(
        name = "WildFlyDS",
        factory = org.jboss.as.test.integration.mgmt.access.ldap.InMemoryDirectoryServiceFactory.class,
        partitions = @CreatePartition(name = "wildfly", suffix = "dc=wildfly,dc=org"),
        allowAnonAccess = true
)
@CreateLdapServer(
        transports = @CreateTransport(protocol = "LDAP", address = "localhost", port = 10389),
        allowAnonymousAccess = true
)
public static void setUp() throws Exception {
    directoryService = DSAnnotationProcessor.getDirectoryService();
    SchemaManager schemaManager = directoryService.getSchemaManager();
    InputStream ldif = LdapRoleMappingG2UTestCase.class.getResourceAsStream("/" + LdapRoleMappingG2UTestCase.class.getSimpleName() + ".ldif");
    for (LdifEntry ldifEntry : new LdifReader(ldif)) {
        directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
    }
    ldapServer = ServerAnnotationProcessor.getLdapServer(directoryService);

    startServer();
}
 
Example #5
Source File: LdapService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Import all of the entries from the provided LDIF stream.
 *
 * Note: The whole stream is read
 *
 * @param ldif - Stream containing the LDIF.
 * @return This Builder for subsequent changes.
 */
public Builder importLdif(final InputStream ldif) throws Exception {
    assertNotStarted();
    if (directoryService == null) {
        throw new IllegalStateException("The Directory service has not been created.");
    }
    CoreSession adminSession = directoryService.getAdminSession();
    SchemaManager schemaManager = directoryService.getSchemaManager();

    LdifReader ldifReader = new LdifReader(ldif);
    for (LdifEntry ldifEntry : ldifReader) {
        adminSession.add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
    }
    ldifReader.close();
    ldif.close();

    return this;
}
 
Example #6
Source File: MiniKdc.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a principal in the KDC with the specified user and password.
 *
 * @param principal principal name, do not include the domain.
 * @param password password.
 * @throws Exception thrown if the principal could not be created.
 */
public synchronized void createPrincipal(String principal, String password)
        throws Exception {
  String orgName= conf.getProperty(ORG_NAME);
  String orgDomain = conf.getProperty(ORG_DOMAIN);
  String baseDn = "ou=users,dc=" + orgName.toLowerCase(Locale.ENGLISH)
                  + ",dc=" + orgDomain.toLowerCase(Locale.ENGLISH);
  String content = "dn: uid=" + principal + "," + baseDn + "\n" +
          "objectClass: top\n" +
          "objectClass: person\n" +
          "objectClass: inetOrgPerson\n" +
          "objectClass: krb5principal\n" +
          "objectClass: krb5kdcentry\n" +
          "cn: " + principal + "\n" +
          "sn: " + principal + "\n" +
          "uid: " + principal + "\n" +
          "userPassword: " + password + "\n" +
          "krb5PrincipalName: " + principal + "@" + getRealm() + "\n" +
          "krb5KeyVersionNumber: 0";

  for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
    ds.getAdminSession().add(new DefaultEntry(ds.getSchemaManager(),
            ldifEntry.getEntry()));
  }
}
 
Example #7
Source File: LdapServer.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void importLdif(DirectoryService directoryService,
                        final SchemaManager schemaManager,
                        LdifReader ldifReader) throws Exception {
   try {
      for (LdifEntry ldifEntry : ldifReader) {
         checkPartition(ldifEntry);
         directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
      }
   } finally {
      try {
         ldifReader.close();
      } catch (IOException ioe) {
         // ignore
      }
   }
}
 
Example #8
Source File: LdapServer.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a single LDAP server.
 *
 * @param ldifFile
 * @throws Exception
 */
public LdapServer(String ldifFile) throws Exception {
   InMemoryDirectoryServiceFactory dsFactory = new InMemoryDirectoryServiceFactory();
   dsFactory.init("ds");

   directoryService = dsFactory.getDirectoryService();

   final SchemaManager schemaManager = directoryService.getSchemaManager();
   importLdif(directoryService, schemaManager, new LdifReader(ldifFile));

   ldapServer = new org.apache.directory.server.ldap.LdapServer();
   ldapServer.setTransports(new TcpTransport("127.0.0.1", 1024));
   ldapServer.setDirectoryService(directoryService);

   ldapServer.start();
}
 
Example #9
Source File: TestLDAPAuthentication.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void createPrincipal(String principal, String password)
    throws Exception {
  DirectoryService ds = getService();
  String baseDn = "ou=users,ou=system";
  String content = "dn: uid=" + principal + "," + baseDn + "\n" +
      "objectClass: top\n" +
      "objectClass: person\n" +
      "objectClass: inetOrgPerson\n" +
      "cn: " + principal + "\n" +
      "sn: " + principal + "\n" +
      "uid: " + principal + "\n" +
      "userPassword: " + password;

  for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
    ds.getAdminSession().add(new DefaultEntry(ds.getSchemaManager(),
        ldifEntry.getEntry()));
  }
}
 
Example #10
Source File: InMemorySchemaPartition.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws InvalidNameException, Exception {
   if (initialized) {
      return;
   }

   LOG.debug("Initializing schema partition " + getId());
   suffixDn.apply(schemaManager);
   super.doInit();

   // load schema
   final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
   for (String resourcePath : new TreeSet<>(resMap.keySet())) {
      if (resourcePath.endsWith(".ldif")) {
         URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
         LdifEntry ldifEntry;
         try (LdifReader reader = new LdifReader(resource.openStream())) {
            ldifEntry = reader.next();
         }

         Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
         // add mandatory attributes
         if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
            entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
         }
         if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
            entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
         }
         AddOperationContext addContext = new AddOperationContext(null, entry);
         super.add(addContext);
      }
   }
}
 
Example #11
Source File: LdifSchemaLoader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<Entry> loadDitContentRules( Schema... schemas ) throws LdapException, IOException
{
    List<Entry> ditContentRuleList = new ArrayList<>();

    if ( schemas == null )
    {
        return ditContentRuleList;
    }

    for ( Schema schema : schemas )
    {
        File ditContentRulesDirectory = new File( getSchemaDirectory( schema ),
            SchemaConstants.DIT_CONTENT_RULES_PATH );

        if ( !ditContentRulesDirectory.exists() )
        {
            return ditContentRuleList;
        }

        File[] ditContentRuleFiles = ditContentRulesDirectory.listFiles( ldifFilter );

        if ( ditContentRuleFiles != null )
        {
            for ( File ldifFile : ditContentRuleFiles )
            {
                LdifReader reader = new LdifReader( ldifFile );
                LdifEntry entry = reader.next();
                reader.close();

                ditContentRuleList.add( entry.getEntry() );
            }
        }
    }

    return ditContentRuleList;
}
 
Example #12
Source File: LdifSchemaLoader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<Entry> loadObjectClasses( Schema... schemas ) throws LdapException, IOException
{
    List<Entry> objectClassList = new ArrayList<>();

    if ( schemas == null )
    {
        return objectClassList;
    }

    for ( Schema schema : schemas )
    {
        // get objectClasses directory, check if exists, return if not
        File objectClassesDirectory = new File( getSchemaDirectory( schema ), SchemaConstants.OBJECT_CLASSES_PATH );

        if ( !objectClassesDirectory.exists() )
        {
            return objectClassList;
        }

        // get list of objectClass LDIF files from directory and load
        File[] objectClassFiles = objectClassesDirectory.listFiles( ldifFilter );

        if ( objectClassFiles != null )
        {
            for ( File ldifFile : objectClassFiles )
            {
                LdifReader reader = new LdifReader( ldifFile );
                LdifEntry entry = reader.next();
                reader.close();

                objectClassList.add( entry.getEntry() );
            }
        }
    }

    return objectClassList;
}
 
Example #13
Source File: InMemorySchemaPartition.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws InvalidNameException, Exception {
    if (initialized)
        return;

    LOG.debug("Initializing schema partition " + getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example #14
Source File: LdapStandaloneServer.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Imports given LDIF file to the directory using given directory service and schema manager.
 *
 * @param ldifFiles
 * @throws Exception
 */
private void importLdif(String... ldifFiles) throws Exception {
    if (ldifFiles == null) {
        System.out.println("Importing default data\n");
        importLdif(new LdifReader(LdapStandaloneServer.class.getResourceAsStream("/" + LDIF_FILENAME_JBOSS_ORG)));
    } else {
        for (String ldifFile : ldifFiles) {
            System.out.println("Importing " + ldifFile + "\n");
            importLdif(new LdifReader(ldifFile));
        }
    }
}
 
Example #15
Source File: LdapStandaloneServer.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
private void importLdif(LdifReader ldifReader) throws Exception {
    try {
        for (LdifEntry ldifEntry : ldifReader) {
            checkPartition(ldifEntry);
            System.out.print(ldifEntry.toString());
            directoryService.getAdminSession()
                    .add(new DefaultEntry(directoryService.getSchemaManager(), ldifEntry.getEntry()));
        }
    } finally {
        IOUtils.closeQuietly(ldifReader);
    }
}
 
Example #16
Source File: LdapAuthenticationBaseIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
static LdapConnection setupLdapServer(GenericContainer server, String setupFile) {
  // setup Ldap server 1
  LdapConnection connection = new LdapNetworkConnection(server.getContainerIpAddress(), server.getMappedPort(LDAP_PORT));
  try {
    connection.bind(BIND_DN, BIND_PWD);
    LdifReader reader = new LdifReader(Resources.getResource(setupFile).getFile());
    for (LdifEntry entry : reader) {
      connection.add(entry.getEntry());
    }
  } catch (LdapException e) {
    LOG.error("Setup server 1 failed " + e);
  }
  return connection;
}
 
Example #17
Source File: TestLDAPAuthentication.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void createGroup(String groupName, String memberDn) throws Exception {
  DirectoryService ds = getService();
  String baseDn = "ou=groups,ou=system";
  String content = "dn: cn=" + groupName + "," + baseDn + "\n" +
      "objectClass: top\n" +
      "objectClass: groupofnames\n" +
      "cn: " + groupName + "\n" +
      "description: " + groupName + "\n" +
      "member: " + memberDn;

  for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
    ds.getAdminSession().add(new DefaultEntry(ds.getSchemaManager(),
        ldifEntry.getEntry()));
  }
}
 
Example #18
Source File: LdifSchemaLoader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<Entry> loadDitStructureRules( Schema... schemas ) throws LdapException, IOException
{
    List<Entry> ditStructureRuleList = new ArrayList<>();

    if ( schemas == null )
    {
        return ditStructureRuleList;
    }

    for ( Schema schema : schemas )
    {
        File ditStructureRulesDirectory = new File( getSchemaDirectory( schema ),
            SchemaConstants.DIT_STRUCTURE_RULES_PATH );

        if ( !ditStructureRulesDirectory.exists() )
        {
            return ditStructureRuleList;
        }

        File[] ditStructureRuleFiles = ditStructureRulesDirectory.listFiles( ldifFilter );

        if ( ditStructureRuleFiles != null )
        {
            for ( File ldifFile : ditStructureRuleFiles )
            {
                LdifReader reader = new LdifReader( ldifFile );
                LdifEntry entry = reader.next();
                reader.close();

                ditStructureRuleList.add( entry.getEntry() );
            }
        }
    }

    return ditStructureRuleList;
}
 
Example #19
Source File: SaslKrb5LDAPSecurityTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public synchronized void createPrincipal(String principal, String password) throws Exception {
   String baseDn = getKdcServer().getSearchBaseDn();
   String content = "dn: uid=" + principal + "," + baseDn + "\n" + "objectClass: top\n" + "objectClass: person\n" + "objectClass: inetOrgPerson\n" + "objectClass: krb5principal\n"
      + "objectClass: krb5kdcentry\n" + "cn: " + principal + "\n" + "sn: " + principal + "\n"
      + "uid: " + principal + "\n" + "userPassword: " + password + "\n"
      // using businessCategory as a proxy for memberoOf attribute pending: https://issues.apache.org/jira/browse/DIRSERVER-1844
      + "businessCategory: " + "cn=admins,ou=system" + "\n"
      + "businessCategory: " + "cn=bees,ou=system" + "\n"
      + "krb5PrincipalName: " + principal + "@" + getRealm() + "\n"
      + "krb5KeyVersionNumber: 0";

   for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
      service.getAdminSession().add(new DefaultEntry(service.getSchemaManager(), ldifEntry.getEntry()));
   }
}
 
Example #20
Source File: InMemorySchemaPartition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws Exception {
    if (initialized)
        return;

    LOG.debug("Initializing schema partition " + getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<String>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example #21
Source File: InMemorySchemaPartition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws Exception {
    if (initialized)
        return;

    LOG.debug("Initializing schema partition " + getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<String>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example #22
Source File: InMemorySchemaPartition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws Exception {
    if (initialized)
        return;

    LOG.debug("Initializing schema partition " + getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<String>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example #23
Source File: InMemorySchemaPartition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Partition initialization - loads schema entries from the files on classpath.
 *
 * @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
 */
@Override
protected void doInit() throws Exception {
    if (initialized)
        return;

    LOG.debugf("Initializing schema partition %s", getId());
    suffixDn.apply(schemaManager);
    super.doInit();

    // load schema
    final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
    for (String resourcePath : new TreeSet<String>(resMap.keySet())) {
        if (resourcePath.endsWith(".ldif")) {
            URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
            LdifReader reader = new LdifReader(resource.openStream());
            LdifEntry ldifEntry = reader.next();
            reader.close();

            Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
            // add mandatory attributes
            if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
                entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
            }
            if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
                entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
            }
            AddOperationContext addContext = new AddOperationContext(null, entry);
            super.add(addContext);
        }
    }
}
 
Example #24
Source File: LdapTestSuite.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void processLdif(final SchemaManager schemaManager, final CoreSession adminSession, final String ldifName) throws LdapException, IOException {
    InputStream ldifInput = LdapTestSuite.class.getResourceAsStream(ldifName);
    LdifReader ldifReader = new LdifReader(ldifInput);
    for (LdifEntry ldifEntry : ldifReader) {
        adminSession.add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
    }
    ldifReader.close();
    ldifInput.close();
}
 
Example #25
Source File: LDAPEmbeddedServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void importLdifContent(DirectoryService directoryService, String ldifContent) throws Exception {
    LdifReader ldifReader = new LdifReader(IOUtils.toInputStream(ldifContent));

    try {
        for (LdifEntry ldifEntry : ldifReader) {
            try {
                directoryService.getAdminSession().add(new DefaultEntry(directoryService.getSchemaManager(), ldifEntry.getEntry()));
            } catch (LdapEntryAlreadyExistsException ignore) {
                log.info("Entry " + ldifEntry.getDn() + " already exists. Ignoring.");
            }
        }
    } finally {
        ldifReader.close();
    }
}
 
Example #26
Source File: JarLdifSchemaLoader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<Entry> loadDitContentRules( Schema... schemas ) throws LdapException, IOException
{
    List<Entry> ditContentRulesList = new ArrayList<>();

    if ( schemas == null )
    {
        return ditContentRulesList;
    }

    for ( Schema schema : schemas )
    {
        String start = getSchemaDirectoryString( schema )
            + SchemaConstants.DIT_CONTENT_RULES_PATH + "/" + "m-oid=";
        String end = "." + LDIF_EXT;

        for ( String resourcePath : RESOURCE_MAP.keySet() )
        {
            if ( resourcePath.startsWith( start ) && resourcePath.endsWith( end ) )
            {
                URL resource = getResource( resourcePath, "ditContentRule LDIF file" );
                LdifReader reader = new LdifReader( resource.openStream() );
                LdifEntry entry = reader.next();
                reader.close();

                ditContentRulesList.add( entry.getEntry() );
            }
        }
    }

    return ditContentRulesList;
}
 
Example #27
Source File: LdifUtilsTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertEntryNoControls() throws Exception
{
    LdifReader reader = new LdifReader();

    String expected =
        "dn: ou=test\n" +
            "ObjectClass: top\n" +
            "ObjectClass: metaTop\n" +
            "ObjectClass: metaSyntax\n" +
            "m-oid: 1.2.3.4\n" +
            "m-description: description\n\n";

    List<LdifEntry> entries = reader.parseLdif( expected );
    LdifEntry expectedEntry = entries.get( 0 );

    LdifEntry entry = new LdifEntry();

    entry.setDn( "ou=test" );
    entry.addAttribute( "ObjectClass", "top", "metaTop", "metaSyntax" );
    entry.addAttribute( "m-oid", "1.2.3.4" );
    entry.addAttribute( "m-description", "description" );

    String converted = LdifUtils.convertToLdif( entry );

    assertNotNull( converted );

    entries = reader.parseLdif( converted );
    LdifEntry convertedEntry = entries.get( 0 );

    assertEquals( expectedEntry, convertedEntry );
    
    reader.close();
}
 
Example #28
Source File: LdifUtilsTest.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertEntryOneControl() throws Exception
{
    LdifReader reader = new LdifReader();

    String expected =
        "dn: ou=test\n" +
            "control: 2.16.840.1.113730.3.4.2 false\n" +
            "changetype: add\n" +
            "ObjectClass: top\n" +
            "ObjectClass: metaTop\n" +
            "ObjectClass: metaSyntax\n" +
            "m-oid: 1.2.3.4\n" +
            "m-description: description\n\n";

    List<LdifEntry> entries = reader.parseLdif( expected );
    LdifEntry expectedEntry = entries.get( 0 );

    LdifEntry entry = new LdifEntry();

    entry.setDn( "ou=test" );
    entry.addAttribute( "ObjectClass", "top", "metaTop", "metaSyntax" );
    entry.addAttribute( "m-oid", "1.2.3.4" );
    entry.addAttribute( "m-description", "description" );

    ManageDsaITImpl control = new ManageDsaITImpl();

    entry.addControl( control );

    String converted = LdifUtils.convertToLdif( entry );

    assertNotNull( converted );

    entries = reader.parseLdif( converted );
    LdifEntry convertedEntry = entries.get( 0 );

    assertEquals( expectedEntry, convertedEntry );
    reader.close();
}
 
Example #29
Source File: SingleLdifSchemaLoader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the Schema object from a Single LDIF file
 * 
 * @param in The input stream to process
 * @throws LdapException If the schemas can't be initialized
 * @throws IOException If we had an issue processing the InputStream
 */
private void initializeSchemas( InputStream in ) throws LdapException, IOException
{
    try ( LdifReader ldifReader = new LdifReader( in ) )
    {
        Schema currentSchema = null;

        while ( ldifReader.hasNext() )
        {
            LdifEntry ldifEntry = ldifReader.next();
            String dn = ldifEntry.getDn().getName();
            
            if ( SCHEMA_START_PATTERN.matcher( dn ).matches() )
            {
                Schema schema = getSchema( ldifEntry.getEntry() );
                schemaMap.put( schema.getSchemaName(), schema );
                currentSchema = schema;
            }
            else
            {
                if ( currentSchema == null )
                {
                    throw new LdapException( I18n.err( I18n.ERR_16076_NOT_A_SCHEMA_DEFINITION ) );
                }
                
                loadSchemaObject( currentSchema.getSchemaName(), ldifEntry );
            }
        }
    }
}
 
Example #30
Source File: JarLdifSchemaLoader.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Scans for LDIF files just describing the various schema contained in
 * the schema repository.
 *
 * @throws LdapException If the schema can't be initialized
 * @throws IOException If the file cannot be read
 */
private void initializeSchemas() throws IOException, LdapException
{
    if ( LOG.isDebugEnabled() )
    {
        LOG.debug( I18n.msg( I18n.MSG_16006_INITIALIZING_SCHEMA ) );
    }

    Pattern pat = Pattern.compile( "schema" + SEPARATOR_PATTERN + "ou=schema"
        + SEPARATOR_PATTERN + "cn=[a-z0-9-_]*\\." + LDIF_EXT );

    for ( String file : RESOURCE_MAP.keySet() )
    {
        if ( pat.matcher( file ).matches() )
        {
            URL resource = getResource( file, "schema LDIF file" );

            try ( InputStream in = resource.openStream() )
            {
                try ( LdifReader reader = new LdifReader( in ) )
                {
                    LdifEntry entry = reader.next();
                    Schema schema = getSchema( entry.getEntry() );
                    schemaMap.put( schema.getSchemaName(), schema );

                    if ( LOG.isDebugEnabled() )
                    {
                        LOG.debug( I18n.msg( I18n.MSG_16007_SCHEMA_INITIALIZED, schema ) );
                    }
                }
            }
            catch ( LdapException le )
            {
                LOG.error( I18n.err( I18n.ERR_16009_LDIF_LOAD_FAIL, file ), le );
                throw le;
            }
        }
    }
}