directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Directory Server v1.5 > 4.3. Embedding ApacheDS as a Web Application
Date Thu, 12 Nov 2009 23:19:00 GMT
<html>
<head>
    <base href="http://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1519/1/1/_/styles/combined.css?spaceKey=DIRxSRVx11&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background-color: white" bgcolor="white">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
     <h2><a href="http://cwiki.apache.org/confluence/display/DIRxSRVx11/4.3.+Embedding+ApacheDS+as+a+Web+Application">4.3.
Embedding ApacheDS as a Web Application</a></h2>
     <h4>Page <b>edited</b> by             <a href="http://cwiki.apache.org/confluence/display/~seelmann">Stefan
Seelmann</a>
    </h4>
     
          <br/>
     <div class="notificationGreySide">
         <style type='text/css'>/*<![CDATA[*/
table.ScrollbarTable  {border: none;padding: 3px;width: 100%;padding: 3px;margin: 0px;background-color:
#f0f0f0}
table.ScrollbarTable td.ScrollbarPrevIcon {text-align: center;width: 16px;border: none;}
table.ScrollbarTable td.ScrollbarPrevName {text-align: left;border: none;}
table.ScrollbarTable td.ScrollbarParent {text-align: center;border: none;}
table.ScrollbarTable td.ScrollbarNextName {text-align: right;border: none;}
table.ScrollbarTable td.ScrollbarNextIcon {text-align: center;width: 16px;border: none;}

/*]]>*/</style><div class="Scrollbar"><table class='ScrollbarTable'><tr><td
class='ScrollbarPrevIcon'><a href="/confluence/display/DIRxSRVx11/4.2.+Using+ApacheDS+for+unit+tests"><img
border='0' align='middle' src='/confluence/images/icons/back_16.gif' width='16' height='16'></a></td><td
width='33%' class='ScrollbarPrevName'><a href="/confluence/display/DIRxSRVx11/4.2.+Using+ApacheDS+for+unit+tests">4.2.
Using ApacheDS for unit tests</a>&nbsp;</td><td width='33%' class='ScrollbarParent'><sup><a
href="/confluence/display/DIRxSRVx11/4.+Embedding+ApacheDS"><img border='0' align='middle'
src='/confluence/images/icons/up_16.gif' width='8' height='8'></a></sup><a
href="/confluence/display/DIRxSRVx11/4.+Embedding+ApacheDS">4. Embedding ApacheDS</a></td><td
width='33%' class='ScrollbarNextName'>&nbsp;</td></tr></table></div>

<h1><a name="4.3.EmbeddingApacheDSasaWebApplication-EmbeddingApacheDSasaWebApplication"></a>Embedding
ApacheDS as a Web Application</h1>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td><b>ApacheDS 1.5.5</b><br
/>This site was updated for ApacheDS 1.5.5.</td></tr></table></div>

<p>My initial aim was to demonstrate embedding ApacheDS in a very simple, but nevertheless
impressive way. I thought about embedding the server in Apache Tomcat first. But then I got
a better plan: Creating a standard web application which wraps ApacheDS and can be deployed
on any compliant application server. ApacheDS in a war-archive&#33;</p>


<div>
<ul>
    <li><a href='#4.3.EmbeddingApacheDSasaWebApplication-SolutionOutline'>Solution
Outline</a></li>
    <li><a href='#4.3.EmbeddingApacheDSasaWebApplication-Step1%3AThewebcomponentwhichstartsandstopstheserver'>Step
1: The web component which starts and stops the server</a></li>
    <li><a href='#4.3.EmbeddingApacheDSasaWebApplication-PackagingandDeployingtheWebApp'>Packaging
and Deploying the WebApp</a></li>
    <li><a href='#4.3.EmbeddingApacheDSasaWebApplication-Step2%3AAddingfunctionality%3AAservletwhichdisplaystheRootDSE'>Step
2: Adding functionality: A servlet which displays the Root DSE</a></li>
</ul></div>



<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16"
height="16" align="absmiddle" alt="" border="0"></td><td><b>Version check</b><br
/><p>Although the concepts depicted below apply to all version of ApacheDS (even
before 1.0), the configuration for starting and stopping the embedded server uses the style
introduced with ApacheDS 1.5.5. Be sure that you use this version of the server, or a later
one. </p></td></tr></table></div>

<h2><a name="4.3.EmbeddingApacheDSasaWebApplication-SolutionOutline"></a>Solution
Outline</h2>

<div class='panelMacro'><table class='noteMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/warning.gif" width="16" height="16"
align="absmiddle" alt="" border="0"></td><td><b>Proof of concept character</b><br
/><p>Although it works well, please note that this is just an example on how to embed
ApacheDS in an application&#33; If you plan to run the server as LDAP production system,
this is not the first option to consider. Some more steps have to be done, especially in the
area of configuration.</p></td></tr></table></div>

<p>The solution is quite simple. A web application carries all the necessary jar files
for ApacheDS within the lib-directory of the WEB-INF folder. When the web application is started
by the servlet container, appropriate code has to be executed to start ApacheDS. And the server
has to be stopped, if the web application goes down (for instance if the server shuts down).
There are (at least) two standard compliant ways to acomplish this:</p>
<ul>
	<li>A Servlet (automatically started with the web application, using the lifecycle
methods <em>init</em> and <em>destroy</em>)</li>
	<li>A ServletContextListener</li>
</ul>


<p>In the following we have choosen the second option.</p>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-AServletContextListenertostartandstopApacheDS"></a>A
Servlet Context Listener to start and stop ApacheDS</h3>

<p>A servlet context listener receives notifications about changes to the servlet context
of the web application it is part of. Documentation of the ServletContextListener interface
can be found <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html"
title="javadoc of javax.servlet.ServletContextListener" rel="nofollow">here</a>.
To receive notification events, the implementation class must be configured in the deployment
descriptor for the web application. The two life cycle methods <em>contextInitialized</em>
and <em>contextDestroyed</em> are suitable to start and stop ApacheDS.</p>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-Aclientwithin"></a>A
client within</h3>

<p>After the server has been started from the Listener, it will be accessible from the
outside via the network using LDAP.  In order to demonstrate how to interact with the server
from within the VM, a simple servlet is shown. It allows you to communicate with the embedded
server via web browser. This is so simple, because the server already lives within a web application,
only a servlet has to added to act as an entry point. Our sample servlet will display the
Root DSE of the server.</p>

<p>The following class diagram visualizes the complete example. The gray elements will
be developed in two steps and use Servlet and ApacheDS API.</p>

<p><img src="/confluence/download/attachments/55251/ApacheDS_WebApp_UML.png" align="absmiddle"
border="0" /></p>

<h2><a name="4.3.EmbeddingApacheDSasaWebApplication-Step1%3AThewebcomponentwhichstartsandstopstheserver"></a>Step
1: The web component which starts and stops the server</h2>

<p>The ApacheDS core is comprised of JavaBeans components, and can easily be instantiated
started and stopped with simple Java code. This is done by the following listener.</p>

<p>The class <a href="http://svn.apache.org/repos/asf/directory/samples/trunk/apacheds-archetype-webapp/src/main/resources/archetype-resources/src/main/java/StartStopListener.java"
title="Download StartStopListener.java" rel="nofollow">StartStopListener</a> implements
<em>ServletContextListener</em> and therefore contains the following two life
cycle methods:</p>
<ul>
	<li><em>contextInitialized()</em> is executed if the web application is
started by the servlet container, it starts ApacheDS embedded</li>
	<li><em>contextDestroyed()</em> is executed if the web application is stopped
by the servlet container, it stops the embedded server</li>
</ul>


<p>The <em>contextInitialized</em> method creates a <em>DefaultDirectoryService</em>
object. It configures the LDAP protocol and determines an appropriate working directory for
the server. This directory is need to persist the partition data (entries). Our example uses
a simple yet portable way for this task: the context attribute <em>javax.servlet.context.tempdir</em>.</p>

<p>Afterwards the method starts network protocol and directory service.</p>

<p>Finally the DirectoryService component is stored in the application context of the
web application. This is done in order to provided it to embedded clients in the same web
app (see the servlet below for an example).</p>

<p>The method <em>contextDestroyed</em> simply stops the protocol and shuts
down the service.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>StartStopListener.java</b></div><div
class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">package</span> org.apache.directory.samples.embed.webapp;

<span class="code-keyword">import</span> java.io.File;

<span class="code-keyword">import</span> javax.servlet.ServletContext;
<span class="code-keyword">import</span> javax.servlet.ServletContextEvent;
<span class="code-keyword">import</span> javax.servlet.ServletContextListener;

<span class="code-keyword">import</span> org.apache.directory.server.core.DefaultDirectoryService;
<span class="code-keyword">import</span> org.apache.directory.server.core.DirectoryService;
<span class="code-keyword">import</span> org.apache.directory.server.ldap.LdapServer;
<span class="code-keyword">import</span> org.apache.directory.server.protocol.shared.transport.TcpTransport;

/**
 * A Servlet context listener to start and stop ApacheDS.
 * 
 * @author &lt;a href=<span class="code-quote">"mailto:dev@directory.apache.org"</span>&gt;Apache
Directory Project&lt;/a&gt;
 */
<span class="code-keyword">public</span> class StartStopListener <span class="code-keyword">implements</span>
ServletContextListener
{
    <span class="code-keyword">private</span> DirectoryService directoryService;

    <span class="code-keyword">private</span> LdapServer ldapServer;

    /**
     * Startup ApacheDS embedded.
     */
    <span class="code-keyword">public</span> void contextInitialized( ServletContextEvent
evt )
    {
        <span class="code-keyword">try</span>
        {
            directoryService = <span class="code-keyword">new</span> DefaultDirectoryService();
            directoryService.setShutdownHookEnabled( <span class="code-keyword">true</span>
);

            ldapServer = <span class="code-keyword">new</span> LdapServer();
            ldapServer.setDirectoryService( directoryService );
            ldapServer.setAllowAnonymousAccess( <span class="code-keyword">true</span>
);

            <span class="code-comment">// Set LDAP port to 10389
</span>            TcpTransport ldapTransport = <span class="code-keyword">new</span>
TcpTransport( 10389 );
            ldapServer.setTransports( ldapTransport );

            <span class="code-comment">// Determine an appropriate working directory
</span>            ServletContext servletContext = evt.getServletContext();
            File workingDir = ( File ) servletContext.getAttribute( <span class="code-quote">"javax.servlet.context.tempdir"</span>
);
            directoryService.setWorkingDirectory( workingDir );

            directoryService.startup();
            ldapServer.start();

            <span class="code-comment">// Store directoryService in context to provide
it to servlets etc.
</span>            servletContext.setAttribute( DirectoryService.JNDI_KEY, directoryService
);
        }
        <span class="code-keyword">catch</span> ( Exception e )
        {
            <span class="code-keyword">throw</span> <span class="code-keyword">new</span>
RuntimeException( e );
        }
    }

    /**
     * Shutdown ApacheDS embedded.
     */
    <span class="code-keyword">public</span> void contextDestroyed( ServletContextEvent
evt )
    {
        <span class="code-keyword">try</span>
        {
            ldapServer.stop();
            directoryService.shutdown();
        }
        <span class="code-keyword">catch</span> ( Exception e )
        {
            <span class="code-keyword">throw</span> <span class="code-keyword">new</span>
RuntimeException( e );
        }
    }
}
</pre>
</div></div>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-Deploymentdescriptor"></a>Deployment
descriptor</h3>

<p>In order to execute the listener code, the class has to be defined in the deployment
descriptor of a web application, as depicted below:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>web.xml</b></div><div class="codeContent
panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span>
encoding=<span class="code-quote">"UTF-8"</span>?&gt;</span>
&lt;!DOCTYPE web-app PUBLIC <span class="code-quote">"-//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN"</span>
<span class="code-quote">"http://java.sun.com/dtd/web-app_2_3.dtd"</span>&gt;
<span class="code-tag">&lt;web-app&gt;</span>
  <span class="code-tag">&lt;display-name&gt;</span>ApacheDS embedded
in a WebApp<span class="code-tag">&lt;/display-name&gt;</span>
  <span class="code-tag">&lt;description&gt;</span>
    A simple yet portable way to run ApacheDS within a servlet
    container
  <span class="code-tag">&lt;/description&gt;</span>

  <span class="code-tag">&lt;listener&gt;</span>
    <span class="code-tag">&lt;listener-class&gt;</span>
      org.apache.directory.samples.embed.webapp.StartStopListener
    <span class="code-tag">&lt;/listener-class&gt;</span>
  <span class="code-tag">&lt;/listener&gt;</span>
<span class="code-tag">&lt;/web-app&gt;</span>
</pre>
</div></div>

<h2><a name="4.3.EmbeddingApacheDSasaWebApplication-PackagingandDeployingtheWebApp"></a>Packaging
and Deploying the WebApp</h2>

<p>A standard web archive (war-File) is needed in order to deploy the application to
a servlet container. The easiest way to create such a web archive including all dependencies
is to use an Maven archetype we provide.</p>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-CreatingtheWebAppusingtheApacheDSMavenArchetype"></a>Creating
the WebApp using the ApacheDS Maven Archetype</h3>

<p>We assume you have Java Subversion and Maven 2.0.9 installed on your system.</p>

<p>To use the archetype you'll need to check it out and install it to your local repository:</p>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>svn co http://svn.apache.org/repos/asf/directory/samples/trunk/apacheds-archetype-webapp
cd apacheds-archetype-webapp
mvn install
</pre>
</div></div>

<p>Then change to your preferred location to create the new project and execute following
command: </p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>mvn archetype:generate -DarchetypeGroupId=org.apache.directory.samples \
                       -DarchetypeArtifactId=apacheds-archetype-webapp \
                       -DarchetypeVersion=1.5.5-SNAPSHOT \
                       -DgroupId=org.apache.directory.samples.embed.webapp \
                       -DartifactId=ApacheDS -Dversion=1.0-SNAPSHOT 
</pre>
</div></div>

<p>Then change to the created directory and run the following command:</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>mvn package 
</pre>
</div></div>

<p>This creates an <em>ApacheDS.war</em> file below the target folder.</p>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-RunonembeddedJetty"></a>Run
on embedded Jetty</h3>

<p>The fastest way to run the web application is to use the Maven Jetty plugin:</p>

<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent
panelContent">
<pre>mvn jetty:run
</pre>
</div></div>



<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-DeployingonApacheTomcat"></a>Deploying
on Apache Tomcat</h3>

<p>In order to run the application within Tomcat, simply put the <em>ApacheDS.war</em>
file in the <em>webapps</em> directory of your Tomcat installation and start the
server. If you have the manager application enabled (as described <a href="http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html"
title="tomcat.apache.org" rel="nofollow">here</a>), you can see and "manage" (start/stop)
ApacheDS within its list view:</p>

<p><img src="/confluence/download/attachments/55251/TomcatManagerAppInBrowser.png"
align="absmiddle" border="0" /></p>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-ConnectingtoApacheDSfromtheoutside"></a>Connecting
to ApacheDS from the outside</h3>

<p>ApacheDS is up and running within the servlet container. Besides the administration
tool listing, it seems to be invisible. But because we have configured network access via
port 10389, you can easily access the server with an arbitrary LDAP client from outside.</p>

<p>One option is a command line tool like <em>ldapsearch</em> (see <a
href="http://directory.apache.org/apacheds/1.5/apacheds-v15-basic-users-guide.html" title="ApacheDS
Basic User's Guide" rel="nofollow">ApacheDS Basic User's Guide</a> for details on
how to connect to ApacheDS with such tools in general). Here is an example how to connect
as administrator (simple bind) and fetch the Root DSE of our embedded ApacheDS instance:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-none">
$ ldapsearch -h localhost -p 10389 -D "uid=admin,ou=system" -w secret \\
    -b "" -s base "(objectClass=*)" * +
version: 1
dn:
supportedControl: 2.16.840.1.113730.3.4.3
supportedControl: 2.16.840.1.113730.3.4.7
supportedControl: 1.3.6.1.4.1.4203.1.10.1
supportedControl: 2.16.840.1.113730.3.4.2
supportedControl: 1.3.6.1.4.1.18060.0.0.1
namingContexts: ou=system
namingContexts: ou=schema
supportedLDAPVersion: 3
objectClass: extensibleObject
objectClass: top
supportedFeatures: 1.3.6.1.4.1.4203.1.5.1
supportedExtension: 1.3.6.1.4.1.1466.20036
subschemaSubentry: cn=schema
vendorName: Apache Software Foundation
vendorVersion: 1.5.4
$
</pre>
</div></div>
<p>Another choice are graphical LDAP clients (see <a href="http://directory.apache.org/apacheds/1.5/apacheds-v15-basic-users-guide.html"
title="ApacheDS Basic User's Guide" rel="nofollow">ApacheDS Basic User's Guide</a>
for details on how to connect to ApacheDS with such tools in general).</p>

<p>With our popular Eclipse RCP application <a href="http://directory.apache.org/studio/"
title="directory.apache.org" rel="nofollow">Directory studio</a> for instance, connecting
goes like this:<br/>
In the Connections view, select "New connection ...". Within a wizard dialog, you provide
the connection data (host name, port, bind DN and password).</p>

<p><img src="/confluence/download/attachments/55251/DirectoryStudio1.png" align="absmiddle"
border="0" /></p>

<p><img src="/confluence/download/attachments/55251/DirectoryStudio2.png" align="absmiddle"
border="0" /></p>

<p>After successfully connecting to the embedded ApacheDS, you can browse the tree,
add and manipulate entries and so on. If you check the connection properties, you can study
the Root DSE as well.</p>

<p><img src="/confluence/download/attachments/55251/DirectoryStudio3.png" align="absmiddle"
border="0" /></p>

<h3><a name="4.3.EmbeddingApacheDSasaWebApplication-OtherWebApplicationServers"></a>Other
Web Application Servers</h3>

<p>The web application described here has been successfully deployed on</p>
<ul>
	<li>Apache Tomcat 5.5.20 and 6.0.18 (<a href="http://tomcat.apache.org" title="tomcat.apache.org"
rel="nofollow">Homepage</a>)</li>
	<li>IBM WebSphere Application Server 6.1 (<a href="http://www.ibm.com/software/webservers/appserv/was/"
title="www.ibm.com" rel="nofollow">Homepage</a>)</li>
	<li>Jetty 6.1.0 (<a href="http://jetty.mortbay.org" title="jetty.mortbay.org" rel="nofollow">Homepage</a>)</li>
</ul>


<p>Here is a screen shot of the web based administration console of WebSphere Application
Server 6.1 with the ApacheDS.war deployed and running, no changes in the deployment archive
were needed. </p>

<p><img src="/confluence/download/attachments/55251/WebSphereAdminConsoleInBrowser.png"
align="absmiddle" border="0" /></p>

<h2><a name="4.3.EmbeddingApacheDSasaWebApplication-Step2%3AAddingfunctionality%3AAservletwhichdisplaystheRootDSE"></a>Step
2: Adding functionality: A servlet which displays the Root DSE</h2>

<p>To finish with, here is a simple example on how to access the server internally (Note:
the servlet was already created by the maven archetype).</p>

<p>The following servlet, which will be deployed together with the other class in the
web archive, connects to ApacheDS directly, i.e. via the internal JNDI provider. No network
access is needed.  In the <em>doGet</em> method it performs a search operation
against the Root DSE of the server, as the examples above do. </p>


<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>RootDseServlet.java</b></div><div
class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">package</span> org.apache.directory.samples.embed.webapp;

<span class="code-keyword">import</span> java.io.PrintWriter;
<span class="code-keyword">import</span> java.util.Hashtable;

<span class="code-keyword">import</span> javax.naming.Context;
<span class="code-keyword">import</span> javax.naming.NamingEnumeration;
<span class="code-keyword">import</span> javax.naming.directory.Attribute;
<span class="code-keyword">import</span> javax.naming.directory.Attributes;
<span class="code-keyword">import</span> javax.naming.directory.DirContext;
<span class="code-keyword">import</span> javax.naming.directory.InitialDirContext;
<span class="code-keyword">import</span> javax.naming.directory.SearchControls;
<span class="code-keyword">import</span> javax.naming.directory.SearchResult;
<span class="code-keyword">import</span> javax.servlet.ServletContext;
<span class="code-keyword">import</span> javax.servlet.ServletException;
<span class="code-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="code-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="code-keyword">import</span> javax.servlet.http.HttpServletResponse;

<span class="code-keyword">import</span> org.apache.directory.server.core.DirectoryService;
<span class="code-keyword">import</span> org.apache.directory.server.core.jndi.CoreContextFactory;

/**
 * A servlet which displays the Root DSE of the embedded server.
 * 
 * @author &lt;a href=<span class="code-quote">"mailto:dev@directory.apache.org"</span>&gt;Apache
Directory
 *         Project&lt;/a&gt;
 */
<span class="code-keyword">public</span> class RootDseServlet <span class="code-keyword">extends</span>
HttpServlet {

    <span class="code-keyword">private</span> <span class="code-keyword">static</span>
<span class="code-keyword">final</span> <span class="code-object">long</span>
serialVersionUID = 1L;

    <span class="code-keyword">protected</span> void doGet(HttpServletRequest
req, HttpServletResponse resp)
            <span class="code-keyword">throws</span> ServletException {

        <span class="code-keyword">try</span> {
            resp.setContentType(<span class="code-quote">"text/plain"</span>);
            PrintWriter out = resp.getWriter();

            out.println(<span class="code-quote">"*** ApacheDS RootDSE ***\n"</span>);

            DirContext ctx = <span class="code-keyword">new</span> InitialDirContext(<span
class="code-keyword">this</span>.createEnv());

            SearchControls ctls = <span class="code-keyword">new</span> SearchControls();
            ctls.setReturningAttributes(<span class="code-keyword">new</span>
<span class="code-object">String</span>[] { <span class="code-quote">"*"</span>,
<span class="code-quote">"+"</span> });
            ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

            NamingEnumeration&lt;SearchResult&gt; result = ctx.search("",
                    <span class="code-quote">"(objectClass=*)"</span>, ctls);
            <span class="code-keyword">if</span> (result.hasMore()) {
                SearchResult entry = result.next();
                Attributes as = entry.getAttributes();

                NamingEnumeration&lt;<span class="code-object">String</span>&gt;
ids = as.getIDs();
                <span class="code-keyword">while</span> (ids.hasMore()) {
                    <span class="code-object">String</span> id = ids.next();
                    Attribute attr = as.get(id);
                    <span class="code-keyword">for</span> (<span class="code-object">int</span>
i = 0; i &lt; attr.size(); ++i) {
                        out.println(id + <span class="code-quote">": "</span>
+ attr.get(i));
                    }
                }
            }
            ctx.close();

            out.flush();
        } <span class="code-keyword">catch</span> (Exception e) {
            <span class="code-keyword">throw</span> <span class="code-keyword">new</span>
ServletException(e);
        }
    }

    /**
     * Creates an environment configuration <span class="code-keyword">for</span>
JNDI access.
     */
    <span class="code-keyword">protected</span> Hashtable&lt;<span class="code-object">Object</span>,
<span class="code-object">Object</span>&gt; createEnv() {

        <span class="code-comment">// Fetch directory servive from servlet context
</span>        ServletContext servletContext = <span class="code-keyword">this</span>.getServletContext();
        DirectoryService directoryService = (DirectoryService) servletContext
                .getAttribute(DirectoryService.JNDI_KEY);

        Hashtable&lt;<span class="code-object">Object</span>, <span class="code-object">Object</span>&gt;
env = <span class="code-keyword">new</span> Hashtable&lt;<span class="code-object">Object</span>,
<span class="code-object">Object</span>&gt;();
        env.put(DirectoryService.JNDI_KEY, directoryService);
        env.put(Context.PROVIDER_URL, "");
        env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class
                .getName());

        env.put(Context.SECURITY_PRINCIPAL, <span class="code-quote">"uid=admin,ou=system"</span>);
        env.put(Context.SECURITY_CREDENTIALS, <span class="code-quote">"secret"</span>);
        env.put(Context.SECURITY_AUTHENTICATION, <span class="code-quote">"simple"</span>);

        <span class="code-keyword">return</span> env;
    }
}

</pre>
</div></div>

<p>In order to make the servlet available to clients, it has to be declared in the deployment
descriptor <em>web.xml</em>, here are the additions (a servlet named <em>RootDseServlet</em>
for the class above, and a URL mapping)</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>web.xml, extended</b></div><div
class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;?xml version=<span class="code-quote">"1.0"</span>
encoding=<span class="code-quote">"UTF-8"</span>?&gt;</span>
&lt;!DOCTYPE web-app PUBLIC <span class="code-quote">"-//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN"</span>
<span class="code-quote">"http://java.sun.com/dtd/web-app_2_3.dtd"</span>&gt;
<span class="code-tag">&lt;web-app&gt;</span>

  ...
  <span class="code-tag">&lt;servlet&gt;</span>
    <span class="code-tag">&lt;servlet-name&gt;</span>RootDseServlet<span
class="code-tag">&lt;/servlet-name&gt;</span>
    <span class="code-tag">&lt;servlet-class&gt;</span>
      org.apache.directory.samples.embed.webapp.RootDseServlet
    <span class="code-tag">&lt;/servlet-class&gt;</span>
  <span class="code-tag">&lt;/servlet&gt;</span>

   <span class="code-tag">&lt;servlet-mapping&gt;</span>
     <span class="code-tag">&lt;servlet-name&gt;</span>RootDseServlet<span
class="code-tag">&lt;/servlet-name&gt;</span>
     <span class="code-tag">&lt;url-pattern&gt;</span>/RootDse<span
class="code-tag">&lt;/url-pattern&gt;</span>
   <span class="code-tag">&lt;/servlet-mapping&gt;</span>
<span class="code-tag">&lt;/web-app&gt;</span>
</pre>
</div></div>

<p>Redeploy the web application. If you point to your tomcat server with the appropriate
URL (<a href="http://localhost:8080/ApacheDS/RootDse" rel="nofollow">http://localhost:8080/ApacheDS/RootDse</a>),
you'll see the content of the Root DSE as depicted below: </p>

<p><img src="/confluence/download/attachments/55251/RootDseServletInBrowser.png"
align="absmiddle" border="0" /></p>



     </div>
     <div id="commentsSection" class="wiki-content pageSection">
       <div style="float: right;">
            <a href="http://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
       </div>

       <a href="http://cwiki.apache.org/confluence/display/DIRxSRVx11/4.3.+Embedding+ApacheDS+as+a+Web+Application">View
Online</a>
       |
       <a href="http://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=55251&revisedVersion=39&originalVersion=38">View
Change</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message