<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ ModeShape (http://www.modeshape.org)
  ~
  ~ See the COPYRIGHT.txt file distributed with this work for information
  ~ regarding copyright ownership.  Some portions may be licensed
  ~ to Red Hat, Inc. under one or more contributor license agreements.
  ~ See the AUTHORS.txt file in the distribution for a full listing of 
  ~ individual contributors.
  ~
  ~ ModeShape is free software. Unless otherwise indicated, all code in ModeShape
  ~ is licensed to you under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  ~
  ~ ModeShape is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd	" [
<!ENTITY % CustomDTD SYSTEM "../custom.dtd">
%CustomDTD;
]>
<chapter id="using_modeshape">
	<title>Using ModeShape</title>
	<para>Using ModeShape within your application is actually quite straightforward.  Simply configure ModeShape with one or more
		repositories and the sources where the content for those repositories should be accessed and stored.  Then, your application
		just uses the <ulink url="&JSR283;">JCR 2.0 API</ulink> to connect to and use those repositories.
	</para>
	<para>
		Before we dive into how to configure ModeShape, let's start by looking at how your application will find and use the
		JCR repositories.
	</para>
	<sect1 id="repository_factory">
		<title>JCR's RepositoryFactory</title>
		<para>
			The latest version of the JCR 2.0 API specification (<ulink url="&JSR283;">JSR-283</ulink>) defines a &RepositoryFactory;
			interface that when coupled with the <ulink url="&Java;java/util/ServiceLoader.html">Java Standard Edition Service Loader mechanism</ulink>
			lets your application find JCR &Repository; instances using only the JCR API and Java interfaces, without using any implementation-specific
			interfaces.
		</para>
		<para>
			ModeShape supports and recommends using this approach, which looks like this:
		</para>
    <programlisting language="JAVA" role="JAVA"><![CDATA[
Properties parameters = new Properties();
parameters.load(...)   // typically loaded from property file or set programmatically
Repository repository;

for (RepositoryFactory factory : ServiceLoader.load(RepositoryFactory.class)) {
    repository = factory.getRepository(parameters);
    if (repository != null) break;
}]]></programlisting>
		<para>
			This code looks for all &RepositoryFactory; implementations on the classpath (assuming those implementations properly defined the service provider
			within their JARs), and will ask each to create a repository given the supplied parameters. The first factory that understands
			these parameters will return a &Repository; instance, while other factories will return null. The key, then, for defining which
			JCR &Repository; implementation your application uses are the parameters passed to the <code>getRepository(Map)</code> method.
			Simply load these from a properties file, and your application is set.
		</para>
		<note>
			<para>
				This &RepositoryFactory; approach is new to JCR 2.0. With JCR 1.0, your application likely used specific classes from the
				implementation to instantiate a &Repository; implementation.
			</para>
		</note>
		<para>
			Once you've gotten hold of a &Repository; instance, you can use it to create &Session;s. 
			JCR sessions are lightweight, so creating them is very fast. But they are <emphasis>not</emphasis> thread safe,
			so they shouldn't be used concurrently by multiple threads. Therefore, the JCR specification recommends
			applications create sessions to read, query or change repository content, and then quickly close the sessions:
    </para>			
   	<programlisting language="JAVA" role="JAVA"><![CDATA[Repository repository = // found earlier
Credentials credentials = ...; // JCR credentials
String workspaceName = ...; // The name of the workspace in the JCR repository
Session session = null;
try {
	// Obtain a JCR Session using simple authentication (or anonymous if configured)
	session = repo.login(credentials,workspaceName);
	
	// Use the JCR Session to read, query, or change repository content
	
	// Save any changes that were made ...
	session.save();
} catch (RepositoryException ex) {
	// Handle the error
} finally {
	if (session != null) session.logout();
}]]></programlisting>
		<para>
			JCR sessions are stateful, meaning they cache any information that is accessed to provide a single consistent
			view of the content, including any transient changes that haven't yet been saved. Thus, in applications with
			many concurrent sessions changing content, the cached data of a longer-lived session can become inconsistent
			with the stored content, and must be manually refreshed using the &Session;'s <code>refresh()</code> method.
			It is for this reason that the JCR specification recommends using short-lived sessions.
		</para>
		<para>
			Observing the repository for changes, however, will require registering listeners with a session, and will
			only receive events while that session is alive. Therefore, observation requires a longer-lived session.
			But the recommendation is that these longer-lived sessions are used only to register your application's listeners,
			and not used to read or update content.
		</para>
		<para>
			These are the basics of writing an application that uses JCR. Next, we'll start looking at the specifics
			of ModeShape, starting with those &RepositoryFactory; properties.
		</para>
		<sect2 id="modeshape_repository_factory_properties">
			<title>ModeShape's RepositoryFactory Properties</title>
		  <para>
				ModeShape's &RepositoryFactory; implementation looks for a single property named "<code>org.modeshape.jcr.URL</code>".
				The value of this property is most often a URL pointing to a ModeShape configuration file, which is
				on the local file system at an absolute path:
		  </para>
	    <programlisting><![CDATA[ file://path/to/configFile.xml?repositoryName=MyRepository ]]></programlisting>
	    <para>
		    or a path relative to the running application:
		  </para>
	    <programlisting><![CDATA[ file:configFile.xml?repositoryName=MyRepository ]]></programlisting>
	    <para>
		    The configuration file can even be accessed from a web service (e.g., a web server, WebDAV, or version control system) using any resolvable
		    URL, such as:
		  </para>
	    <programlisting><![CDATA[ http://www.example.com/path/to/configFile.xml?repositoryName=MyRepository ]]></programlisting>
	    <para>
				This works great for self-contained applications, because ModeShape will create a new repository engine
				that runs embedded in the application.
				However, applications running in platforms (such as servlet containers or Java application servers) will likely
				prefer that ModeShape runs as a <link linkend="modeshape_in_web_applications">central service in the platform</link>
				that can be shared by multiple applications. In these cases, the ModeShape engine will already be running and 
				registered in JNDI, so the application will use a URL that points to this JNDI location:
		  </para>
	    <programlisting><![CDATA[ jndi:name/in/jndi?repositoryName=MyRepository ]]></programlisting>
			<para>
				Here's an example of a property file containing the single ModeShape property for &RepositoryFactory;:
			</para>
	    <programlisting><![CDATA[# This URL use the repository named 'MyRepository' defined in the 'modeshape-configuration.xml' file
# located in the current directory. Use a different URL as needed.
#
org.modeshape.jcr.URL = file:modeshape-configuration.xml?repositoryName=MyRepository
]]></programlisting>
			<para>
				In the <link linkend="jcr_configuration">next section</link>, we'll take an introductory look at what these configuration files look.
			</para>
		</sect2>
	</sect1>
	<sect1 id="jcr_configuration">
		<title>ModeShape Configuration Files</title>
		<para>
			The previous section showed how easy it was to obtain a &Repository; and &Session; using the standard JCR API. 
			This section provides an introduction to ModeShape configuration files, although you will likely want to look at 
			the &ReferenceGuide; for more detail.
		</para>
		<para>
			Each configuration file defines the components that are used to create the repository:
			<itemizedlist>
				<listitem>
					<para><emphasis role="strong"><code>Repository sources</code></emphasis> are the POJO objects that each describe a particular
					location where content is stored.  Each repository source object is an instance of a ModeShape connector, and is configured
					with the properties that particular source.  ModeShape's &RepositorySource; classes are analogous to JDBC's &DataSource; classes -
					they are implemented by specific connectors (aka, "drivers") for specific kinds of repository sources (aka, "databases").
					Similarly, a &RepositorySource; instance is analogous to a &DataSource; instance, with bean properties for each configurable
					parameter.  Therefore, each repository source definition must supply the name of the &RepositorySource; class, any
					bean properties, and, optionally, the classpath that should be used to load the class. </para>
				</listitem>
				<listitem>
					<para><emphasis role="strong"><code>Repositories</code></emphasis> define the JCR repositories that are available.  Each
					repository has a unique name that is used to obtain the &Repository; instance,
					but each repository definition also can include the predefined namespaces (other than those automatically defined by
					ModeShape), various options, and the node types that are to be available in the repository without explicit registration
					through the JCR API.</para>
				</listitem>
				<listitem>
					<para><emphasis role="strong"><code>Sequencers</code></emphasis> define the particular sequencers that are available for use.
					Each sequencer definition provides the path expressions governing which nodes in the repository should be sequenced when those nodes change,
					and where the resulting output generated by the sequencer should be placed.  The definition also must state the name of 
					the sequencer class, any bean properties and, optionally, the classpath that should be used to load the class.</para>
				</listitem>
				<listitem>
					<para><emphasis role="strong"><code>MIME type detectors</code></emphasis> define the particular MIME type detector(s) that should
					be made available.  A MIME type detector does exactly what the name implies: it attempts to determine the MIME type given a
					"filename" and contents.  ModeShape automatically uses a detector that uses the file extension to identify the MIME type,
					but also provides an implementation that uses an external library to identify the MIME type based upon the contents.
					The definition must state the name of the detector class, any bean properties and, optionally, the classpath that should 
					be used to load the class.</para>
				</listitem>
			</itemizedlist>
		</para>
		<sect2 id="creating_a_configuration_file">
			<title>Example configuration file</title>
			<para>
				Here is the configuration file that is used in the repository example, though it has been simplified a bit and most comments 
				have been removed for clarity):
			</para>
    	<programlisting language="XML" role="XML"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:mode="http://www.modeshape.org/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0">
	  <!-- 
	  Define the JCR repositories 
	  -->
	  <mode:repositories>
	      <!-- 
	      Define a JCR repository that accesses the 'Cars' source directly.
	      -->
	      <mode:repository jcr:name="car repository" mode:source="Cars">
	          <mode:options jcr:primaryType="mode:options">
                <systemSourceName jcr:primaryType="mode:option" mode:value="system@Cars"/>
	              <jaasLoginConfigName jcr:primaryType="mode:option" mode:value="modeshape-jcr"/>
	              <!--
	              As a convenience, ModeShape defaults to granting guest users full access.  
	              In a production system, you would want to limit this access by uncommenting one of the 
	              options below:
	              
	              for no access:
	              <anonymousUserRoles jcr:PrimaryType="mode:option" mode:value="" />
	              
	              for read-only acces:
	              <anonymousUserRoles jcr:PrimaryType="mode:option" mode:value="readonly" /> 
	              -->
	          </mode:options>
	      </mode:repository>
	  </mode:repositories>
    <!-- 
    Define the sources for the content.  These sources are directly accessible using the ModeShape-specific 
    Graph API.
    -->
    <mode:sources jcr:primaryType="nt:unstructured">
        <mode:source jcr:name="Cars" 
                    mode:classname="org.modeshape.graph.connector.inmemory.InMemoryRepositorySource" 
                    mode:retryLimit="3" mode:defaultWorkspaceName="workspace1">
            <predefinedWorkspaceNames>system</predefinedWorkspaceNames>
        </mode:source>
    </mode:sources>
    <!-- 
    Define the clustering configuration. This is an optional section; leave it out when
    running in a non-clustered (single-process) mode.
    -->
    <mode:clustering clusterName="modeshape-cluster" configuration="jgroups-modeshape.xml" />
    <!-- 
    Define the sequencers. This is an optional section. 
    -->
    <mode:sequencers>
        <mode:sequencer jcr:name="Image Sequencer" 
                       mode:classname="org.modeshape.sequencer.image.ImageMetadataSequencer">
            <mode:description>Image metadata sequencer</mode:description>        
            <mode:pathExpression>/foo/source => /foo/target</mode:pathExpression>
            <mode:pathExpression>/bar/source => /bar/target</mode:pathExpression>
        </mode:sequencer>
    </mode:sequencers>
    <!--
	  Define how ModeShape will determine the MIME type of files. This is an optional section;
	  if you do not specify a MIME type detector, ModeShape will use a built-in one that is based
	  filename extensions for most commonly-used files.
    -->
    <mode:mimeTypeDetectors>
        <mode:mimeTypeDetector jcr:name="Detector" 
                 mode:description="Standard extension-based MIME type detector"/>
    </mode:mimeTypeDetectors>
</configuration>]]></programlisting>
		</sect2>
	</sect1>
	<sect1 id="modeshape_in_web_applications">
		<title>Using ModeShape in Web Applications</title>
		<para>
			Sometimes your applications can simply define a configuration file and use the &RepositoryFactory; to access its
			repositories. This is very straightforward, and this is useful for many simple applications because the application
			will then own the ModeShape instance(s).
		</para>
		<para>
			Web applications are a different story. Often, you would rather your web application not contain the code that initializes
			the JCR repository, but instead configure ModeShape as a central, shared service that all of your web applications
			can simply reference and use.
		</para>
		<para>
			Unfortunately, there's no common way to deploy ModeShape into the various web or application servers, since they all have
			slightly different deployment and configuration techniques. The remainder of this section will talk about
			how to deploy ModeShape to two popular open source servers, the 
			<link linkend="deloying_modeshape_to_jbossas">JBoss Application Server</link> and 
			<link linkend="deloying_modeshape_to_tomcat">Apache Tomcat</link>.
		</para>
		<sect2 id="deloying_modeshape_to_jbossas">
			<title>Deploying ModeShape to JBoss AS</title>
			<para>
				The <ulink url="http://jboss.org/jbossas">JBoss Application Server</ulink> (or JBoss AS) is a very popular
				open source Java application server, with an extremely healthy and active community. 
				ModeShape offers a way to deploy ModeShape into JBoss AS as as a central, shared service
				that can be monitored and administered using the embedded console.
			</para>
			<para>
				ModeShape provides a downloadable ZIP file that can be unzipped into any JBoss AS profile. When you do this,
				that profile will contain all the files necessary for ModeShape to run when the server is started.
				The default configuration is for a single, in-memory repository with two users. However,
				other than basic playing, you will want to edit the configuration files to define a more robust,
				persistent and secure configuration.
			</para>
			<para>
				This JBoss AS distribution ZIP file contains several components:
				<itemizedlist>
					<listitem>
						<para>
							JAR files for the JCR 2.0 API and ModeShape's small extensions to the JCR API on the global classpath
							(that is, in the "<code>lib/</code>" directory).
							These APIs are available to all deployed applications, services and components. The JCR API contains
							the "<code>javax.jcr</code>" packages and has no other dependencies. ModeShape's extensions
							define interfaces in the "<code>org.modeshape.jcr.api</code>" packages; these extend a few of the standard
							JCR API interfaces and add several methods to make them more useful.
						</para>
					</listitem>
					<listitem>
						<para>The ModeShape Service, represented as an exploded JAR file in the "<code>deploy</code>" directory.
							This is where the &JcrEngine; is running, though any application (or other JBoss service)
							can access its JCR Repository instances using the standard &RepositoryFactory; approach described 
							<link linkend="repository_factory">earlier</link> by using a URL such as:
						</para>
				    <programlisting> jndi:jcr/local?repositoryName=&defaultJBossASRepository;</programlisting>
						<para>
							By default, there is a single in-memory repository named "&defaultJBossASRepository;", but this 
							can be changed by simply editing the "<code>deploy/modeshape-services.jar/managedConfigRepository.xml</code>" 
							configuration file. All of ModeShape's standard sequencers and connectors (and JARs for their dependencies)
							are included, meaning they can be configured for use without worrying about adding JARs to the classpath.
							Feel free to remove any of the JARs are not needed for your custom configuration.
						</para>
					</listitem>
					<listitem>
						<para>A pair of JAAS properties files, located in the "<code>conf/props/</code>" directory, that come
							out of the box with an "admin" user (with password "admin") that has full read, write, and
							administration privileges, and a "guest" user (with password "guest") that has only
							read and write privileges. Simply edit these files to change users, passwords, and roles,
							or to configure JAAS differently.
						</para>
					</listitem>
					<listitem>
						<para>The ModeShape RESTful API, represented as an exploded WAR file in the "<code>deploy</code>" directory.
							This allows remote applications to interact with ModeShape to access and manipulate repository content
							using a RESTful API that uses JSON in the requests and responses. All ModeShape repositories
							can be accessed, and authentication is done using the ModeShape JAAS configuration.
						</para>
					</listitem>
					<listitem>
						<para>The ModeShape WebDAV API, represented as an exploded WAR file in the "<code>deploy</code>" directory.
							This web application allows external clients to access and manipulate the content in the 
							ModeShape repositories using the standard WebDAV protocol. For example, you can mount
							a repository (or parts of it) as a network drive on most operating systems, and then upload
							or download files and folders using standard OS operations and graphical tools. All ModeShape repositories
							can be accessed, and authentication is done using the ModeShape JAAS configuration.
						</para>
					</listitem>
					<listitem>
						<para>A plugin for the embedded JBoss AS console, represented as a WAR file in the "deploy" directory.
							This plugin also works with <ulink url="http://support.rhq-project.org/display/RHQ/Home">RHQ</ulink>
							administration, monitoring, alerting, operational
							control and configuration system. <emphasis role="strong">This feature is currently incomplete,
							but is undergoing active development.</emphasis>
						</para>
					</listitem>
					<listitem>
						<para>
							A JDBC driver for querying the repositories through JDBC. This driver is on the global
							classpath so it can be used in any deployed component. A single JDBC DataSource is
							also configured in the "<code>deploy/modeshape-services.jar/modeshape-jdbc-ds.xml</code>" 
							file to use the single default in-memory repository available out of the box. Simply edit
							this file to add or change the DataSource definitions.
						</para>
					</listitem>
				</itemizedlist>
				Here are the contents of this file:
			</para>
<programlisting>
conf/
conf/props/
conf/props/modeshape-roles.properties  
conf/props/modeshape-users.properties  
lib/
lib/jcr-2.0.jar         
lib/modeshape-jcr-api-&versionNumber;.jar  
lib/modeshape-jdbc-&versionNumber;.jar  
deploy/
deploy/modeshape-jboss-beans.xml  
deploy/modeshape-services.jar/
deploy/modeshape-services.jar/META-INF/
deploy/modeshape-services.jar/aperture-1.1.0.Beta1.jar 
deploy/modeshape-services.jar/joda-time-1.6.jar  
deploy/modeshape-services.jar/lucene-analyzers-3.0.2.jar  
deploy/modeshape-services.jar/lucene-core-3.0.2.jar  
deploy/modeshape-services.jar/lucene-regex-3.0.2.jar  
deploy/modeshape-services.jar/lucene-snowball-3.0.2.jar  
deploy/modeshape-services.jar/lucene-misc-3.0.2.jar  
deploy/modeshape-services.jar/poi-3.6.jar  
deploy/modeshape-services.jar/poi-scratchpad-3.6.jar  
deploy/modeshape-services.jar/managedConfigRepository.xml  
deploy/modeshape-services.jar/rdf2go.api-4.6.2.jar
deploy/modeshape-services.jar/META-INF/jboss-beans.xml  
deploy/modeshape-services.jar/modeshape-cnd-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-common-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-filesystem-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-infinispan-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-jbosscache-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-jcr-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-jdbc-metadata-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-store-jpa-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-connector-svn-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-graph-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-jbossas-service-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-jcr-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-jdbc-ds.xml  
deploy/modeshape-services.jar/modeshape-mimetype-detector-aperture-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-repository-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-search-lucene-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-classfile-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-cnd-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-ddl-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-java-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-jbpm-jpdl-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-msoffice-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-teiid-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-text-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-xml-&versionNumber;.jar  
deploy/modeshape-services.jar/modeshape-sequencer-zip-&versionNumber;.jar  
deploy/modeshape-rest.war/
deploy/modeshape-rest.war/META-INF/
deploy/modeshape-rest.war/WEB-INF/
deploy/modeshape-rest.war/WEB-INF/lib/
deploy/modeshape-rest.war/META-INF/MANIFEST.MF  
deploy/modeshape-rest.war/WEB-INF/jboss-web.xml  
deploy/modeshape-rest.war/WEB-INF/lib/jaxrs-api-1.2.1.GA.jar  
deploy/modeshape-rest.war/WEB-INF/lib/jettison-1.1.jar  
deploy/modeshape-rest.war/WEB-INF/lib/modeshape-jcr-&versionNumber;.jar  
deploy/modeshape-rest.war/WEB-INF/lib/modeshape-web-jcr-&versionNumber;.jar  
deploy/modeshape-rest.war/WEB-INF/lib/modeshape-web-jcr-rest-&versionNumber;.jar  
deploy/modeshape-rest.war/WEB-INF/lib/resteasy-jaxb-provider-1.2.1.GA.jar  
deploy/modeshape-rest.war/WEB-INF/lib/resteasy-jaxrs-1.2.1.GA.jar  
deploy/modeshape-rest.war/WEB-INF/lib/resteasy-jettison-provider-1.2.1.GA.jar  
deploy/modeshape-rest.war/WEB-INF/lib/scannotation-1.0.2.jar  
deploy/modeshape-rest.war/WEB-INF/web.xml  
deploy/modeshape-webdav.war/
deploy/modeshape-webdav.war/WEB-INF/
deploy/modeshape-webdav.war/WEB-INF/lib/
deploy/modeshape-webdav.war/WEB-INF/jboss-web.xml  
deploy/modeshape-webdav.war/WEB-INF/lib/aperture-1.1.0.Beta1.jar  
deploy/modeshape-webdav.war/WEB-INF/lib/modeshape-jcr-&versionNumber;.jar  
deploy/modeshape-webdav.war/WEB-INF/lib/modeshape-mimetype-detector-aperture-&versionNumber;.jar  
deploy/modeshape-webdav.war/WEB-INF/lib/modeshape-web-jcr-&versionNumber;.jar  
deploy/modeshape-webdav.war/WEB-INF/lib/modeshape-web-jcr-webdav-&versionNumber;.jar  
deploy/modeshape-webdav.war/WEB-INF/lib/webdav-servlet-2.0.1.jar  
deploy/modeshape-webdav.war/WEB-INF/web.xml  
deploy/admin-console.war/
deploy/admin-console.war/plugins/
deploy/admin-console.war/plugins/modeshape-jbossas-console-&versionNumber;.jar  
</programlisting>
    <para>
	    Your web application or JBoss service can use one of the JCR &Repository; instances running inside the ModeShape service
	    by simply using the &RepositoryFactory; technique described <link linkend="repository_factory">earlier</link>, with a
	    URL such as:
		</para>
    <programlisting> jndi:jcr/local?repositoryName=&defaultJBossASRepository;</programlisting>
    <para>
	    Be sure to use the correct repository name.
	  </para>
	  <para>
		  Since the JCR API JAR is on the global classpath, your web application can use the JCR API without
		  having to include the JAR file in your application's WAR file. In fact, your application will likely
		  get ClassCastExceptions if it does include the JCR API in its WAR file.
		  Plus, if needed, your application can use ModeShape's "<code>org.modeshape.jcr.api</code>" extensions to the JCR API
		  (again, on the global classpath), and should not need or use any of the classes or interfaces in the ModeShape implementation.
	  </para>
    </sect2>
		<sect2 id="deloying_modeshape_to_tomcat">
			<title>Deploying ModeShape to Tomcat</title>
			<para>
				Each kind of web server or application server is different, but all servlet containers do provide a way of configuring
				objects and placing them into JNDI.  ModeShape provides a &JndiRepositoryFactory; class that implements &ObjectFactory;
				and that can be used in the server's configuration. The &JndiRepositoryFactory; requires two properties:
				<itemizedlist>
					<listitem>
						<para>
							<emphasis role="strong"><code>configFile</code></emphasis> is the path to the 
							<link linkend="loading_from_file">configuration file</link> resource, which must be available on the classpath
						</para>
					</listitem>
					<listitem>
						<para>
							<emphasis role="strong"><code>repositoryName</code></emphasis> is the name of a JCR repository that exists
							in the JCR configuration and that will be made available by this JNDI entry
						</para>
					</listitem>
				</itemizedlist>
			</para>
			<para>
				Here's an example of a fragment of the <code>conf/context.xml</code> for Tomcat:
			</para>
<programlisting language="XML" role="XML"><![CDATA[<Resource name="jcr/local" 
          auth="Container"
          type="javax.jcr.Repository"
          factory="org.modeshape.jcr.JndiRepositoryFactory"
          configFile="/resource/path/to/configuration.xml"
          repositoryName="Test Repository Source" />]]></programlisting>
			<para>
				Note that it is possible to have multiple <code>Resource</code> entries. The &JndiRepositoryFactory; ensures
				that only one &JcrEngine; is instantiated, but that a &Repository; instance is registered for each entry.
			</para>
			<para>
				Before the server can start, however, all of the ModeShape jars need to be placed on the classpath for the server.
				JAAS also needs to be configured, and this can be done using the application server's configuration or in your
				web application if you're using a simple servlet container. For more details, see the &ReferenceGuide;.
			</para>
			<note>
				<para>
					The ModeShape community has solicited input on how we can make it easier to consume and use ModeShape in applications
					that do not use Maven. Check out the <ulink url="http://community.jboss.org/thread/146589">discussion thread</ulink>,
					and please add any suggestions or opinions!
				</para>
			</note>
			<para>
				Then, your web application needs to reference the <code>Resource</code> and state its requirements in its 
				<code>web.xml</code>:
			</para>
<programlisting language="XML" role="XML"><![CDATA[<resource-env-ref>
   <description>Repository</description>
   <resource-env-ref-name>jcr/local</resource-env-ref-name>
   <resource-env-ref-type>javax.jcr.Repository</resource-env-ref-type>
</resource-env-ref>]]></programlisting>
			<para>
				Note that the value of <code>resource-env-ref-name</code> matches the value of the name attribute on the 
				<code>&lt;Resource></code> tag in the <code>context.xml</code> described above.  This is a must.
			</para>
			<para>
				At this point, your web application can perform the lookup of the &Repository; object by using JNDI directly
				(or the more standard &RepositoryFactory; technique shown earlier), create and use a &Session;,
				and then close the &Session;.  Here's an example of a JSP page that does this:
			</para>
<programlisting language="JAVA" role="JAVA"><![CDATA[
<%@ page import="javax.naming.*, javax.jcr.*, org.jboss.security.config.IDTrustConfiguration" %>
<%!

static {
	// Initialize IDTrust
	IDTrustConfiguration idtrustConfig = new IDTrustConfiguration();
	try {
	    idtrustConfig.config("security/jaas.conf.xml");
	} catch (Exception ex) {
	    throw new IllegalStateException(ex);
	}
}
%>
<%
Session sess = null;
try {
	InitialContext initCtx = new InitialContext();
	Context envCtx = (Context) initCtx.lookup("java:comp/env");
	Repository repo = (Repository) envCtx.lookup("jcr/local");
	sess = repo.login(new SimpleCredentials("readwrite", "readwrite".toCharArray()));

	// Do something interesting with the Session ...
	out.println(sess.getRootNode().getPrimaryNodeType().getName());
} catch (Exception ex) {
	ex.printStackTrace();
} finally {
	if (sess != null) sess.logout();
}
%>
]]></programlisting>			
			<para>
				Since this uses a servlet container, there is no JAAS implementation configured, so note the 
				loading of IDTrust to create the JAAS realm.  (To make this work in Tomcat, the security
				folder that contains the <code>jaas.conf.xml</code>, <code>users.properties</code>, and
				<code>roles.properties</code> needs to be moved into the <code>%CATALINA_HOME%</code> directory.)
			</para>
			<note>
				<para>
				If you deploy your application to JBoss AS or EAP and deploy 
				<link linkend="deploying-modeshape-to-jbossas">ModeShape as a service</link>, your application
				doesn't have to do anything with JAAS, since that's provided by the platform.
			  </para>
			</note>
		</sect2>
	</sect1>
	<sect1 id="modeshape_classpath">
		<title>Setting the Classpath</title>
		<para>
			Deploying ModeShape as a service in <link linkend="deploying-modeshape-to-jbossas">JBoss AS</link>
			is all set up with the correct classpaths and configurations. In other deployments, you'll have
			to ensure that all of the ModeShape JARs are available on the appropriate classpath. 
			This section describes two different scenarios for doing this: Maven-based, and using
			JARs with the traditional classpath.
		</para>
		<sect2 id="using_modeshape_via_maven">
			<title>Building against ModeShape via Maven</title>
			<para>
				By far the easiest way to use ModeShape is to use Maven, because with just a few lines of code, Maven will automatically 
				pull all the JARs and source for all of the ModeShape libraries as well as everything those libraries need. 
				All of ModeShape's artifacts for each release are published in the new <ulink url="&JBossMaven;">JBoss Maven repository</ulink> 
				under the "<ulink url="&ModeShapeMaven;">org.modeshape</ulink>" group ID.
			</para>
			<sect3 id="using_jboss_maven_repository">
				<title>Using the JBoss Maven repository</title>
				<para>
					The JBoss Maven repository not only contains all of the artifacts for ModeShape and other open source projects
					hosted at <ulink url="http://www.jboss.org">JBoss.org</ulink>, but it also 
					<ulink url="&JBossMavenDoc;">proxies quite a few other repositories</ulink> that contain many other third-party
					libraries.
				</para>
				<para>
				  So if you're using Maven (or Ivy), first make sure your project knows about this new JBoss Maven repository.
					One way to do this is to add the following to your project POM (you'll still likely want to use other Maven repositories 
					for third-party artifacts):
				</para>
<programlisting language="XML" role="XML"><![CDATA[<repositories>
  <repository>
    <id>jboss</id>
    <url>http://repository.jboss.org/nexus/content/groups/public/</url>
  </repository>
</repositories>
]]></programlisting>
				<para>
					Or, you can add this information to your <code>~/.m2/settings.xml</code> file. For more information,
					see the <ulink url="&JBossMavenUsing;">JBoss wiki page</ulink>.
				</para>
			</sect3>
			<sect3 id="adding_modeshape_dependencies">
				<title>Add dependency to ModeShape</title>
				<para>
					Then, simply modify your project's POM by adding dependencies on the ModeShape JCR library:
			  </para>
<programlisting language="XML" role="XML"><![CDATA[<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-jcr</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
]]></programlisting>
				<para>
					This adds only the minimal libraries required to use ModeShape. If your application is going
					to use clustering, you'll need to also depend upon the clustering module:
				</para>
<programlisting language="XML" role="XML"><![CDATA[<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-clustering</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
]]></programlisting>
				<para>
					You also need to add dependencies for 
					each of the connectors and sequencers you want to use. Here is the list of available sequencers:
				</para>
<programlisting language="XML" role="XML"><![CDATA[<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-cnd</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-ddl</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshapce</groupId>
  <artifactId>modeshape-sequencer-images</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-classfile</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-java</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-mp3</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-msoffice</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-xml</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-xsd</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-wsdl</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-sramp</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-teiid</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-text</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-sequencer-zip</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
]]></programlisting>
			<para>
				Here is the list of available connectors:
			</para>
<programlisting language="XML" role="XML"><![CDATA[<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-filesystem</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-infinispan</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-jcr</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-jbosscache</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-jdbc-metadata</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-store-jpa</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.modeshape</groupId>
  <artifactId>modeshape-connector-svn</artifactId>
  <version>2.9-SNAPSHOT</version>
</dependency>]]></programlisting>
	      <para>
		      The sequencer and connector libraries you choose, plus every third-party library they need, will be pulled in automatically 
		      by Maven into your project.
		    </para>
			</sect3>
		</sect2>
			<sect2 id="adding_logging_dependencies">
				<title>Add dependencies for logging</title>
				<para>
					ModeShape is designed to use the same logging framework as your application, and it uses SLF4J to accomplish this. 
					In other words, ModeShape depends upon the SLF4J API library, but requires you to provide provide a logging implementation 
					as well as the appropriate SLF4J binding JAR.
				</para>
				<para>
					For example, if your application is using <ulink url="&Log4J;">Log4J</ulink>, your application will already have a dependency 
					for it, and so ModeShape log messages will be sent to the same logging system used in your application, you need to add a 
					dependency to the SLF4J-to-Log4J binding JAR:
				</para>
<programlisting language="XML" role="XML"><![CDATA[<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.6.1</version>
</dependency>
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.16</version>
</dependency>
]]></programlisting>
        <para>
	        Of course, SLF4J works with other logging frameworks, too. Some logging implementations (such as <ulink url="&LogBack;">LogBack</ulink>) 
	        implement the SLF4J API natively, meaning they require no binding JAR. For details on the options and how to configure them, see the 
	        <ulink url="&SLF4JManual;">SLF4J manual</ulink>.
        </para>
		</sect2>
		<sect2 id="using_modeshape_via_jars">
			<title>Building against ModeShape via JARs</title>
			<para>
				If your application doesn't use Maven, you'll need to obtain the ModeShape JARs and place them onto your application's classpath. 
				ModeShape provides a <ulink url="&SingleDownload;">single download</ulink> with all of the JARs for all ModeShape components 
				and all dependencies. This file contains the following:
				<itemizedlist>
	        <listitem>
	          <para>
	            <emphasis role="strong"><code>modeshape-jcr-&versionNumber;-jar-with-dependencies.jar</code></emphasis> contains all of the
	 						classes (except those under <code>javax.jcr</code>) necessary to run the core ModeShape JCR repository engine using
							the in-memory connector and the federating connector;
	          </para>
	        </listitem>
	        <listitem>
	          <para>
	            one <emphasis role="strong"><code>modeshape-connector-&lt;type>-&versionNumber;-jar-with-dependencies.jar</code></emphasis> 
							for each type of connector, each containing all of the classes necessary for that connector, designed to be added to the classpath
							after the <code>modeshape-jcr-&versionNumber;-jar-with-dependencies.jar</code> file;
	          </para>
	        </listitem>
	        <listitem>
	          <para>
	            one <emphasis role="strong"><code>modeshape-sequencer-&lt;type>-&versionNumber;-jar-with-dependencies.jar</code></emphasis> 
							for each type of connector, each containing all of the classes necessary for that sequencer, designed to be added to the classpath
							after the <code>modeshape-jcr-&versionNumber;-jar-with-dependencies.jar</code> file;
	          </para>
	        </listitem>
	        <listitem>
	          <para>
	            <emphasis role="strong"><code>modeshape-mimetype-detector-aperture-&versionNumber;-jar-with-dependencies.jar</code></emphasis> 
							containing all of the classes necessary for detecting the MIME type of files based upon
							their name and/or content, designed to be added to the classpath
							after the <code>modeshape-jcr-&versionNumber;-jar-with-dependencies.jar</code> file;
	          </para>
	        </listitem>
	        <listitem>
	          <para>
	            <emphasis role="strong"><code>modeshape-jpa-ddl-gen-&versionNumber;-jar-with-dependencies.jar</code></emphasis> 
							contains all of the classes required to run the DDL generation utility as a standalone application.
	          </para>
	        </listitem>
	      </itemizedlist>
				Note that the core engine is required in all configurations. The <code>jcr-2.0.jar</code> file is not included and must be provided by you. 
				And, as mentioned in the <link linkend="adding_logging_dependencies">previous section</link>, ModeShape uses SLF4J for logging and you must provide 
				a logging implementation as well as the appropriate SLF4J binding JAR.
			</para>
		</sect2>
	</sect1>
	<sect1 id="using_modeshape_whats_next">
		<title>What's next</title>
		<para>
			This chapter outline how you configure ModeShape, how you then access a <code>javax.jcr.Repository</code> instance,
			and use the standard JCR API to interact with the repository. The
			<link linkend="downloading_and_building">next chapter </link> walks you through downloading
			and building the ModeShape examples, while <link linkend="sequencer_example">Chapter 5</link>
			and <link linkend="repository_example">Chapter 6</link> shows how to run the examples.
		</para>
	</sect1>
</chapter>
