<html>
<head>
<base href="https://cwiki.apache.org/confluence">
<link rel="stylesheet" href="/confluence/s/1810/9/1/_/styles/combined.css?spaceKey=DIRxSRVx11&forWysiwyg=true"
type="text/css">
</head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
<h2><a href="https://cwiki.apache.org/confluence/display/DIRxSRVx11/4.1.+Embedding+ApacheDS+into+an+application">4.1.
Embedding ApacheDS into an application</a></h2>
<h4>Page <b>edited</b> by <a href="https://cwiki.apache.org/confluence/display/~kayyagari">Kiran
Ayyagari</a>
</h4>
<br/>
<h4>Changes (2)</h4>
<div id="page-diffs">
<table class="diff" cellpadding="0" cellspacing="0">
<tr><td class="diff-snipped" >...<br></td></tr>
<tr><td class="diff-unchanged" >{tip:title=ApacheDS 1.5.7} <br>For
an example on how to embed the Apache Directory Server version 1.5.7 please look at the <br></td></tr>
<tr><td class="diff-deleted-lines" style="color:#999;background-color:#fdd;text-decoration:line-through;">code
present at [^http://svn.apache.org/repos/asf/directory/samples/trunk/embedded-sample] <br></td></tr>
<tr><td class="diff-added-lines" style="background-color: #dfd;">code
present at [Example For Embedding version 1.5.7|http://svn.apache.org/repos/asf/directory/samples/trunk/embedded-sample]
<br></td></tr>
<tr><td class="diff-unchanged" >{tip} <br> <br></td></tr>
<tr><td class="diff-snipped" >...<br></td></tr>
</table>
</div> <h4>Full Content</h4>
<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
width='33%' class='ScrollbarPrevName'> </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'> <a href="/confluence/display/DIRxSRVx11/4.2.+Using+ApacheDS+for+unit+tests">4.2.
Using ApacheDS for unit tests</a></td><td class='ScrollbarNextIcon'><a
href="/confluence/display/DIRxSRVx11/4.2.+Using+ApacheDS+for+unit+tests"><img border='0'
align='middle' src='/confluence/images/icons/forwd_16.gif' width='16' height='16'></a></td></tr></table></div>
<h1><a name="4.1.EmbeddingApacheDSintoanapplication-EmbeddingApacheDirectoryServerintoanapplication"></a>Embedding
Apache Directory Server into an 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>
<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.7</b><br
/>For an example on how to embed the Apache Directory Server version 1.5.7 please look
at the<br/>
code present at <a href="http://svn.apache.org/repos/asf/directory/samples/trunk/embedded-sample"
class="external-link" rel="nofollow">Example For Embedding version 1.5.7</a></td></tr></table></div>
<p>The idea is to use the server directly without having to communicate with a remote
server, eliminating all the network layer. This is one of the reason ADS has been developed
in Java: to allow such usage.</p>
<p>We will go through a very simple example step by step to show you how this can be
done.</p>
<h2><a name="4.1.EmbeddingApacheDSintoanapplication-Settinguptheenvironment"></a>Setting
up the environment</h2>
<p>We first need to define a base for our project. We use Maven (2.0.9 or above) to
build our project, so the structure we will use looks like this:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
.
|-- pom.xml
`-- src
`-- main
`-- java
`-- org
`-- apache
`-- directory
`-- EmbeddedADS.java
</pre>
</div></div>
<p>You could download both files here:<br/>
<a href="/confluence/download/attachments/102487/EmbeddedADS.java?version=1&modificationDate=1259453744000">EmbeddedADS.java</a><br/>
<a href="/confluence/download/attachments/102487/pom.xml?version=1&modificationDate=1259453733000">pom.xml</a></p>
<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>If you don't want to use Maven
you need to add the following dependencies to your classpath in order to compile and run this
sample.<br/>
* apacheds-all-1.5.5.jar<br/>
* slf4j-api-1.5.6.jar<br/>
* slf4j-log4j12-1.5.6.jar<br/>
* log4j-1.2.14.jar</td></tr></table></div>
<h2><a name="4.1.EmbeddingApacheDSintoanapplication-Creatingtheapplication"></a>Creating
the application</h2>
<p>So let's start with the code. It's quite simple: we define a class, add a main()
method, and initialize the server, before using it. In the code snippet below, we have removed
all the initialization part to keep only the main() method.</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">package</span> org.apache.directory;
/**
* A simple example exposing how to embed Apache Directory Server
* into an application.
*
* @author <a href=<span class="code-quote">"mailto:dev@directory.apache.org"</span>>Apache
Directory Project</a>
* @version $Rev$, $Date$
*/
<span class="code-keyword">public</span> class EmbeddedADS
{
/** The directory service */
<span class="code-keyword">private</span> DirectoryService service;
...
/**
* Creates a <span class="code-keyword">new</span> instance of EmbeddedADS.
It initializes the directory service.
*
* @<span class="code-keyword">throws</span> Exception If something went wrong
*/
<span class="code-keyword">public</span> EmbeddedADS() <span class="code-keyword">throws</span>
Exception
{
init();
}
/**
* Main class. We just <span class="code-keyword">do</span> a lookup on the
server to check that it's available.
*
* @param args Not used.
*/
<span class="code-keyword">public</span> <span class="code-keyword">static</span>
void main( <span class="code-object">String</span>[] args ) <span class="code-comment">//<span
class="code-keyword">throws</span> Exception
</span> {
<span class="code-keyword">try</span>
{
<span class="code-comment">// Create the server
</span> EmbeddedADS ads = <span class="code-keyword">new</span>
EmbeddedADS();
<span class="code-comment">// Read an entry
</span> Entry result = ads.service.getAdminSession().lookup( <span class="code-keyword">new</span>
LdapDN( <span class="code-quote">"dc=apache,dc=org"</span> ) );
<span class="code-comment">// And print it <span class="code-keyword">if</span>
available
</span> <span class="code-object">System</span>.out.println(
<span class="code-quote">"Found entry : "</span> + result );
}
<span class="code-keyword">catch</span> ( Exception e )
{
<span class="code-comment">// Ok, we have something wrong going on ...
</span> e.printStackTrace();
}
}
}
</pre>
</div></div>
<p>As you can see, we first initialize the server, and immediately do a lookup to check
that we can read an entry from it.</p>
<p>Let's focus on the initialization part now.</p>
<h2><a name="4.1.EmbeddingApacheDSintoanapplication-Initializingtheserver"></a>Initializing
the server</h2>
<p>This is done in the <b>init()</b> method. It will create the DirectoryService
global object (<b>service</b>), and create a partition in which we will store
the entries. </p>
<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>A partition is a storage point,
associated with a DN, root point for this partition. It's a bit like a mounting point on Unix.<br/>
We also need a context entry associated to this DN.</td></tr></table></div>
<p>Here, we will create the <b>apache</b> partition, associated with the
'dc=apache,dc=org' DN.</p>
<p>Here is the code for this method :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
...
/**
* Initialize the server. It creates the partition, adds the index, and
* injects the context entries <span class="code-keyword">for</span> the created
partitions.
*
* @<span class="code-keyword">throws</span> Exception <span class="code-keyword">if</span>
there were some problems <span class="code-keyword">while</span> initializing
the system
*/
<span class="code-keyword">private</span> void init() <span class="code-keyword">throws</span>
Exception
{
<span class="code-comment">// Initialize the LDAP service
</span> service = <span class="code-keyword">new</span> DefaultDirectoryService();
<span class="code-comment">// Disable the ChangeLog system
</span> service.getChangeLog().setEnabled( <span class="code-keyword">false</span>
);
<span class="code-comment">// Create a <span class="code-keyword">new</span>
partition named 'apache'.
</span> Partition apachePartition = addPartition( <span class="code-quote">"apache"</span>,
<span class="code-quote">"dc=apache,dc=org"</span> );
<span class="code-comment">// Index some attributes on the apache partition
</span> addIndex( apachePartition, <span class="code-quote">"objectClass"</span>,
<span class="code-quote">"ou"</span>, <span class="code-quote">"uid"</span>
);
<span class="code-comment">// And start the service
</span> service.startup();
<span class="code-comment">// Inject the apache root entry <span class="code-keyword">if</span>
it does not already exist
</span> <span class="code-keyword">if</span> ( !service.getAdminSession().exists(
apachePartition.getSuffixDn() ) )
{
LdapDN dnApache = <span class="code-keyword">new</span> LdapDN( <span
class="code-quote">"dc=Apache,dc=Org"</span> );
ServerEntry entryApache = service.newEntry( dnApache );
entryApache.add( <span class="code-quote">"objectClass"</span>, <span
class="code-quote">"top"</span>, <span class="code-quote">"domain"</span>,
<span class="code-quote">"extensibleObject"</span> );
entryApache.add( <span class="code-quote">"dc"</span>, <span class="code-quote">"Apache"</span>
);
service.getAdminSession().add( entryApache );
}
<span class="code-comment">// We are all done !
</span> }
...
</pre>
</div></div>
<p>We disabled the <b>ChangeLog</b> service because it's useless in our
case. As you can see, the steps to initialize the server are:</p>
<ul class="alternate" type="square">
<li>create a new DirectoryService instance</li>
<li>add a partition</li>
<li>add some index</li>
<li>start the service</li>
<li>add the context entry</li>
</ul>
<p>One important point: as the data are remanent, we have to check that the added context
entry does not exist already before adding it.</p>
<p>Some helper methods have been used : <b>addPartition</b> and <b>addIndex</b>.
Here they are :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
...
/**
* Add a <span class="code-keyword">new</span> partition to the server
*
* @param partitionId The partition Id
* @param partitionDn The partition DN
* @<span class="code-keyword">return</span> The newly added partition
* @<span class="code-keyword">throws</span> Exception If the partition can't
be added
*/
<span class="code-keyword">private</span> Partition addPartition( <span
class="code-object">String</span> partitionId, <span class="code-object">String</span>
partitionDn ) <span class="code-keyword">throws</span> Exception
{
<span class="code-comment">// Create a <span class="code-keyword">new</span>
partition named 'foo'.
</span> Partition partition = <span class="code-keyword">new</span>
JdbmPartition();
partition.setId( partitionId );
partition.setSuffix( partitionDn );
service.addPartition( partition );
<span class="code-keyword">return</span> partition;
}
/**
* Add a <span class="code-keyword">new</span> 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
*/
<span class="code-keyword">private</span> void addIndex( Partition partition,
<span class="code-object">String</span>... attrs )
{
<span class="code-comment">// Index some attributes on the apache partition
</span> HashSet<Index<?, ServerEntry>> indexedAttributes
= <span class="code-keyword">new</span> HashSet<Index<?, ServerEntry>>();
<span class="code-keyword">for</span> ( <span class="code-object">String</span>
attribute:attrs )
{
indexedAttributes.add( <span class="code-keyword">new</span> JdbmIndex<<span
class="code-object">String</span>,ServerEntry>( attribute ) );
}
((JdbmPartition)partition).setIndexedAttributes( indexedAttributes );
}
...
</pre>
</div></div>
<p>That's it! (the attached code will contain the needed imports)</p>
<h2><a name="4.1.EmbeddingApacheDSintoanapplication-Buildingthesample"></a>Building
the sample</h2>
<p>Using Maven this is easy:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
$ mvn clean compile
[INFO] Scanning <span class="code-keyword">for</span> projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building ApacheDS embedded sample
[INFO] task-segment: [clean, compile]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean {execution: <span class="code-keyword">default</span>-clean}]
[INFO] Deleting directory /tmp/EmbeddedADS/target
[INFO] [resources:resources {execution: <span class="code-keyword">default</span>-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build
is platform dependent!
[INFO] skip non existing resourceDirectory /tmp/EmbeddedADS/src/main/resources
[INFO] [compiler:compile {execution: <span class="code-keyword">default</span>-compile}]
[INFO] Compiling 1 source file to /tmp/EmbeddedADS/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Sat Nov 28 20:02:23 CET 2009
[INFO] Final Memory: 17M/76M
[INFO] ------------------------------------------------------------------------
</pre>
</div></div>
<p>The resulting jar can be found in the <b>target</b> directory. </p>
<h2><a name="4.1.EmbeddingApacheDSintoanapplication-Runningthesample"></a>Running
the sample</h2>
<p>Using Maven this is easy:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
$ mvn exec:java -Dexec.mainClass=org.apache.directory.EmbeddedADS
[INFO] Scanning <span class="code-keyword">for</span> projects...
[INFO] Searching repository <span class="code-keyword">for</span> plugin with
prefix: 'exec'.
[INFO] ------------------------------------------------------------------------
[INFO] Building ApacheDS embedded sample
[INFO] task-segment: [exec:java]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing exec:java
[INFO] No goals needed <span class="code-keyword">for</span> project - skipping
[INFO] [exec:java {execution: <span class="code-keyword">default</span>-cli}]
</pre>
</div></div>
<p>When the main method is run, you should obtain something like :</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
log4j:WARN No appenders could be found <span class="code-keyword">for</span> logger
(org.apache.directory.server.schema.registries.DefaultNormalizerRegistry).
log4j:WARN Please initialize the log4j system properly.
Found entry : ServerEntry
dn[n]: dc=Apache,dc=Org
objectClass: extensibleObject
objectClass: domain
objectClass: top
dc: Apache
</pre>
</div></div>
<p>That's it!</p>
</div>
<div id="commentsSection" class="wiki-content pageSection">
<div style="float: right;">
<a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
</div>
<a href="https://cwiki.apache.org/confluence/display/DIRxSRVx11/4.1.+Embedding+ApacheDS+into+an+application">View
Online</a>
|
<a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=102487&revisedVersion=8&originalVersion=7">View
Changes</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|