Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
   * with the License.  You may obtain a copy of the License at
   *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 package org.apache.syncope.buildtools;
 
 import java.io.File;
 import java.util.List;
Start and stop an embedded ApacheDS instance alongside with Servlet Context.

See also:
http://svn.apache.org/repos/asf/directory/documentation/samples/trunk/embedded-sample/
 
 public class ApacheDSStartStopListener implements ServletContextListener {

    
Logger.
 
     private static final Logger LOG = LoggerFactory.getLogger(ApacheDSStartStopListener.class);
 
     private DirectoryService service;
 
     private LdapServer server;

    
Initialize the schema manager and add the schema partition to directory service.

Throws:
java.lang.Exception if the schema LDIF files are not found on the classpath
 
     private void initSchemaPartition(final ServletContext servletContextthrows Exception {
         final Pattern sharedLdapSchemaManagerPattern = Pattern.compile(".*apacheds-all-.*\\.jar");
         File found = null;
         for (final File jarFile : new File(servletContext.getRealPath("/WEB-INF/lib")).listFiles()) {
             if (sharedLdapSchemaManagerPattern.matcher(jarFile.getAbsolutePath()).matches()) {
                 found = jarFile;
             }
         }
         if (found == null) {
             throw new RuntimeException("No apache-ds-all JAR found under WEB-INF/lib");
         }
 
         final SchemaPartition schemaPartition = .getSchemaService().getSchemaPartition();
 
         // Init the LdifPartition
         final LdifPartition ldifPartition = new LdifPartition();
         final String workingDirectory = .getWorkingDirectory().getPath();
         ldifPartition.setWorkingDirectory(workingDirectory + "/schema");
 
         // Extract the schema on disk (a brand new one) and load the registries
         final File schemaRepository = new File(workingDirectory"schema");
         final SchemaLdifExtractor extractor = new JarSchemaLdifExtractor(new File(workingDirectory), found);
         extractor.extractOrCopy(true);
 
         schemaPartition.setWrappedPartition(ldifPartition);
 
         final SchemaLoader loader = new LdifSchemaLoader(schemaRepository);
         final SchemaManager schemaManager = new DefaultSchemaManager(loader);
         .setSchemaManager(schemaManager);
        // Enable nis so that posixAccount and posixGroup are available
        schemaManager.enable("nis");
        // We have to load the schema now, otherwise we won't be able
        // to initialize the Partitions, as we won't be able to parse 
        // and normalize their suffix DN
        schemaManager.loadAllEnabled();
        schemaPartition.setSchemaManager(schemaManager);
        final List<Throwableerrors = schemaManager.getErrors();
        if (!errors.isEmpty()) {
            throw new RuntimeException("Schema load failed : " + errors);
        }
    }

    
Add a new partition to the server.

Parameters:
partitionId The partition Id
partitionDn The partition DN
Returns:
The newly added partition
Throws:
java.lang.Exception If the partition can't be added
    private Partition addPartition(final String partitionIdfinal String partitionDnthrows Exception {
        // Create a new partition named 'foo'.
        final JdbmPartition partition = new JdbmPartition();
        partition.setId(partitionId);
        partition.setPartitionDir(new File(.getWorkingDirectory(), partitionId));
        partition.setSuffix(partitionDn);
        .addPartition(partition);
        return partition;
    }

    
Add a new set of index on the given attributes.

Parameters:
partition The partition on which we want to add index
attrs The list of attributes to index
    private void addIndex(final Partition partitionfinal String... attrs) {
        // Index some attributes on the apache partition
        final HashSet<Index<?, ServerEntryLong>> indexedAttributes = new HashSet<Index<?, ServerEntryLong>>();
        for (String attribute : attrs) {
            indexedAttributes.add(new JdbmIndex<StringServerEntry>(attribute));
        }
        ((JdbmPartitionpartition).setIndexedAttributes(indexedAttributes);
    }

    
Initialize the server. It creates the partition, adds the index, and injects the context entries for the created partitions.

Parameters:
workDir the directory to be used for storing the data
Throws:
java.lang.Exception if there were some problems while initializing
    private void initDirectoryService(final ServletContext servletContextfinal File workDirthrows Exception {
        // Initialize the LDAP service
         = new DefaultDirectoryService();
        .setWorkingDirectory(workDir);
        // first load the schema
        initSchemaPartition(servletContext);
        // then the system partition
        // this is a MANDATORY partition
        final Partition systemPartition = addPartition("system".);
        .setSystemPartition(systemPartition);
        // Disable the ChangeLog system
        .getChangeLog().setEnabled(false);
        // Now we can create as many partitions as we need
        final Partition ispPartition = addPartition("isp""o=isp");
        addIndex(ispPartition"objectClass""ou""uid");
        // And start the service
        .startup();
        // Finally, load content LDIF
        final LdifURLLoader contentLoader = new LdifURLLoader(.getAdminSession(),
                servletContext.getResource("/WEB-INF/classes/content.ldif"));
        final int numEntries = contentLoader.execute();
        .info("Successfully created {} entries"numEntries);
    }

    
Startup ApacheDS embedded.

Parameters:
sce ServletContext event
    @Override
    public void contextInitialized(final ServletContextEvent sce) {
        File workDir = (Filesce.getServletContext().getAttribute("javax.servlet.context.tempdir");
        workDir = new File(workDir"server-work");
        if (!workDir.mkdirs()) {
            throw new RuntimeException("Could not create " + workDir.getAbsolutePath());
        }
        Entry result;
        try {
            initDirectoryService(sce.getServletContext(), workDir);
             = new LdapServer();
            .setTransports(
                    new TcpTransport(Integer.valueOf(sce.getServletContext().getInitParameter("testds.port"))));
            .setDirectoryService();
            .start();
            // store directoryService in context to provide it to servlets etc.
            result = .getAdminSession().lookup(new DN("o=isp"));
        } catch (Exception e) {
            .error("Fatal error in context init"e);
            throw new RuntimeException(e);
        }
        if (result == null) {
            throw new RuntimeException("Base DN not found");
        } else {
            .info("ApacheDS startup completed succesfully");
        }
    }

    
Shutdown ApacheDS embedded.

Parameters:
scEvent ServletContext event
    @Override
    public void contextDestroyed(final ServletContextEvent scEvent) {
        try {
            if ( != null) {
                .stop();
            }
            if ( != null) {
                .shutdown();
            }
        } catch (Exception e) {
            .error("Fatal error in context shutdown"e);
            throw new RuntimeException(e);
        }
    }
New to GrepCode? Check out our FAQ X