cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache CXF Documentation > JAX-RS Advanced Features
Date Thu, 12 Jul 2012 11:35:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/2042/9/1/_/styles/combined.css?spaceKey=CXF20DOC&amp;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/CXF20DOC/JAX-RS+Advanced+Features">JAX-RS Advanced Features</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~sergey_beryozkin">Sergey Beryozkin</a>
    </h4>
        <br/>
                         <h4>Changes (4)</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" >{code} <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">h2. Search Expressions in URI Path segments <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">By default, a FIQL expression is expected to be available in either &#39;_s&#39; or &#39;_search&#39; query. <br>For example, &quot;find all the books with an &#39;id&#39; property value less than 123&quot;: <br>{code:xml} <br>GET /books?_s=id=lt=123 <br>{code} <br></td></tr>
            <tr><td class="diff-unchanged" > <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">Starting from CXF 2.6.2, it is possible to work with FIQL expressions included in URI path segments, for example, the same query can be expressed <br>in a number of ways: <br> <br>{code:xml} <br> <br>GET /books/id=lt=123 <br>GET /books[id=lt=123] <br>GET /books(id=lt=123) <br>GET /books;id=lt=123 <br> <br>//etc, etc <br> <br>{code} <br> <br>Such expressions can be captured in the code using JAX-RS annotations: <br>{code:java} <br>@Path(&quot;search&quot;) <br>public class BooksResource { <br>   @Context <br>   private SearchContext context; <br> <br>   //GET /books[id=lt=123] <br>   @GET <br>   @Path(&quot;books[{search}]&quot;)  <br>   public List&lt;Book&gt; findSelectedBooks(@PathParam(&quot;search&quot;) String searchExpression) { <br>       return doFindSelectedBooks(searchExpression); <br>   } <br> <br>   //GET /books(id=lt=123) <br>   @GET <br>   @Path(&quot;books({search})&quot;)  <br>   public List&lt;Book&gt; findSelectedBooks(@PathParam(&quot;search&quot;) String searchExpression) { <br>       return doFindSelectedBooks(searchExpression); <br>   } <br> <br>   //GET /books/id=lt=123 <br>   @GET <br>   @Path(&quot;books/{search}&quot;)  <br>   public List&lt;Book&gt; findSelectedBooks(@PathParam(&quot;search&quot;) String searchExpression) { <br>       return doFindSelectedBooks(searchExpression); <br>   } <br> <br>   //GET /books;id=lt=123 <br>   @GET <br>   @Path(&quot;books;{search}&quot;)  <br>   public List&lt;Book&gt; findSelectedBooks(@PathParam(&quot;search&quot;) String searchExpression) { <br>       return doFindSelectedBooks(searchExpression); <br>   } <br> <br>   public List&lt;Book&gt; doFindSelectedBooks(String searchExpression) { <br>       SearchCondition&lt;Book&gt; sc = context.getCondition(searchExpression, Book.class); <br> <br>       // JPA2 enity manager is initialized earlier <br>       JPATypedQuery&lt;Book&gt; visitor = new JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class); <br>       sc.visit(visitor); <br> <br>       TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery(); <br>       return typedQuery.getResultList(); <br>   } <br> <br>} <br>{code}  <br> <br>Note that if you have an expression added to a URI path segment with a &quot;;&quot; character acting as a separator, example, &quot;/books;id=lt=123&quot;, <br>or if an expression itself includes &quot;;&quot;, example, &quot;/books[id=lt=123;id=gt=300]&quot; (&quot;find all the books with id less than 123 or greater than 300&quot;)  <br>then a boolean contextual property &quot;ignore.matrix.parameters&quot; has to be set to &quot;true&quot; for the runtime to avoid splitting the path segment into the path value and matrix parameters. <br> <br>h2. Queries involving multiple entities <br> <br>h3. Basic queries <br> <br>Consider the query like &quot;find the first chapters of all the books with &#39;id&#39; less than 123&quot;. <br>One easy way to manage such queries is to make FIQL and JAX-RS work together. For example:     <br> <br>@Path(&quot;search&quot;) <br>public class BooksResource { <br>   @Context <br>   private SearchContext context; <br> <br>   //GET /books[id=lt=123]/chapter/1 <br>   @GET <br>   @Path(&quot;books[{search}]/chapter/{id}&quot;)  <br>   public List&lt;Book&gt; findSelectedBooks(@PathParam(&quot;search&quot;) String searchExpression, <br>                                       @PathParam(&quot;id&quot;) int chapterIndex) { <br>       return doFindSelectedChapters(searchExpression, chapterIndex); <br>   } <br> <br>   public List&lt;Chapter&gt; doFindSelectedChapters(String searchExpression, int chapterIndex) { <br>       SearchCondition&lt;Book&gt; sc = context.getCondition(searchExpression, Book.class); <br> <br>       // JPA2 enity manager is initialized earlier <br>       JPATypedQuery&lt;Book&gt; visitor = new JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class); <br>       sc.visit(visitor); <br> <br>       TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery(); <br>       List&lt;Book&gt; books = typedQuery.getResultList(); <br> <br>       List&lt;Chapter&gt; chapters = new ArrayList&lt;Chapter&gt;(books.size); <br>       for (Book book : books) { <br>           chapters.add(book.getChapter(chapterIndex));  <br>       }    <br>       return chapters; <br>   } <br> <br>} <br>{code}  <br> <br>h3. Complex queries <br> <br>At the moment one needs to follow the example (not necessarily using JPA2) presented in the previous section to manage the complex queries  <br>such as &quot;find all the chapters with id less than 5 for all the books with id greater than 300&quot;, for example:  <br> <br> <br>@Path(&quot;search&quot;) <br>public class BooksResource { <br>   @Context <br>   private SearchContext context; <br> <br>   //GET /books(id=gt=300)/chapters(id=lt=5) <br>   @GET <br>   @Path(&quot;books({search1})/chapter/{search2}&quot;)  <br>   public List&lt;Book&gt; findSelectedBooks(@PathParam(&quot;search1&quot;) String bookExpression, <br>                                       @PathParam(&quot;search2&quot;) String chapterExpression) { <br>       return doFindSelectedBooks(bookExpression, chapterExpression); <br>   } <br> <br>   public List&lt;Chapter&gt; doFindSelectedChapters(String bookExpression, String chapterExpression) { <br>       // find the books first <br> <br>       SearchCondition&lt;Book&gt; bookCondition = context.getCondition(searchExpression, Book.class); <br> <br>       JPATypedQuery&lt;Book&gt; visitor = new JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class); <br>       bookCondition.visit(visitor); <br>       TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery(); <br>       List&lt;Book&gt; books = typedQuery.getResultList(); <br> <br>       // now get the chapters <br>       SearchCondition&lt;Chapter&gt; chapterCondition = context.getCondition(chapterExpression, Chapter.class); <br>       List&lt;Chapter&gt; chapters = new ArrayList&lt;Chapter&gt;(); <br>       for (Book book : books) { <br>           chapters.addAll(chapterCondition.findAll(book.getChapters());  <br>       }    <br>       return chapters; <br>   } <br> <br>} <br>{code}  <br> <br>The above code can be quite functional but not necessarilry optimal. Much depends on the actual relationship between the endities, whether the initial (JPA2) query eagerly loaded all the chapters for every given book, etc. Perhaps a JOIN-like query which will immediately return only the matching chapters will be more optimal. Support for capturing the expressions involving multiple entities and possibly converting them to JOIN statements will be investigated shortly. <br> <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h2. Building FIQL queries <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">h3. Alternative query languages <br> <br>At the moment FIQL is the only and default query language (capable of expressing simple and complex quieries) recognized by the Search module. <br>org.apache.cxf.jaxrs.ext.search.SearchConditionParser has been introduced to facilitate a support for the alternative query languages. More work in this area will be done in the future.  <br> <br></td></tr>
            <tr><td class="diff-unchanged" >h1. Oneway invocations <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <p><span style="font-size:2em;font-weight:bold">JAX-RS : Advanced Features</span></p>

<div>
<ul>
    <li><a href='#JAX-RSAdvancedFeatures-JMSSupport'>JMS Support</a></li>
<ul>
    <li><a href='#JAX-RSAdvancedFeatures-Endpoints'>Endpoints</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-Client'>Client</a></li>
</ul>
    <li><a href='#JAX-RSAdvancedFeatures-FIQLsearchqueries'>FIQL search queries</a></li>
<ul>
    <li><a href='#JAX-RSAdvancedFeatures-Introduction'>Introduction</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-DependenciesandConfiguration'>Dependencies and Configuration</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-ConsumingFIQLqueries'>Consuming FIQL queries</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-ConvertingFIQLqueries'>Converting FIQL queries</a></li>
<ul>
    <li><a href='#JAX-RSAdvancedFeatures-SQL'>SQL</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-JPA2.0'>JPA 2.0</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-Customvisitors'>Custom visitors</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-SearchBean'>SearchBean</a></li>
</ul>
    <li><a href='#JAX-RSAdvancedFeatures-SearchExpressionsinURIPathsegments'>Search Expressions in URI Path segments</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-Queriesinvolvingmultipleentities'>Queries involving multiple entities</a></li>
<ul>
    <li><a href='#JAX-RSAdvancedFeatures-Basicqueries'>Basic queries</a></li>
<ul>
    <li>Found <strong>10</strong> search result(s).</li>
    <li>Found <strong>10</strong> search result(s).</li>
</ul>
</ul>
    <li><a href='#JAX-RSAdvancedFeatures-BuildingFIQLqueries'>Building FIQL queries</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-Usingdatesinqueries'>Using dates in queries</a></li>
<ul>
    <li><a href='#JAX-RSAdvancedFeatures-Alternativequerylanguages'>Alternative query languages</a></li>
</ul>
</ul>
    <li><a href='#JAX-RSAdvancedFeatures-Onewayinvocations'>Oneway invocations</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-SupportforContinuations'>Support for Continuations</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-Serversidecaching'>Server-side caching</a></li>
    <li><a href='#JAX-RSAdvancedFeatures-RESTfulserviceswithoutannotations'>RESTful services without annotations</a></li>
</ul></div>

<h1><a name="JAX-RSAdvancedFeatures-JMSSupport"></a>JMS Support</h1>

<p>CXF has been designed such that multiple transports can be supported for a given endpoint. CXF JAX-RS endpoint and proxies can optionally <br/>
support the JMS transport. </p>

<h2><a name="JAX-RSAdvancedFeatures-Endpoints"></a>Endpoints</h2>

<p>If you would like your JAXRS endpoint be capable of serving not only HTTP but also JMS requests then you need to specify a JMS transportId, example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;jaxrs:server serviceName=<span class="code-quote">"s:BookService"</span> transportId=<span class="code-quote">"http://cxf.apache.org/transports/jms"</span> address=<span class="code-quote">"/"</span>&gt;</span>
 <span class="code-tag">&lt;jaxrs:serviceBeans&gt;</span>
   <span class="code-tag">&lt;bean class=<span class="code-quote">"org.apache.cxf.systest.jaxrs.JMSBookStore"</span>/&gt;</span>
 <span class="code-tag">&lt;/jaxrs:serviceBeans&gt;</span>
<span class="code-tag">&lt;/jaxrs:server&gt;</span>
</pre>
</div></div> 

<p>Additionally, JMS queue or topic <a href="http://cxf.apache.org/docs/using-the-jmsconfigfeature.html" class="external-link" rel="nofollow">configuration</a> needs to be done, for example, please see this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/jms_server_config.xml" class="external-link" rel="nofollow">beans.xml</a>. Please note how a serviceName attribute is used to specify a service QName for a jaxrs endpoint (default is {<a href="http://reverse.package.name" class="external-link" rel="nofollow">http://reverse.package.name</a>}ServiceClassName), this service name is <br/>
used to configure a jms destination.</p>

<p>Here is the actual <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSJmsTest.java" class="external-link" rel="nofollow">test</a>. </p>

<p>Here are JMS properties which can help with matching a required method on the JAXRS endpoint :</p>
<ul class="alternate" type="square">
	<li>"Content-Type" : default is "text/xml"</li>
	<li>"Accept" : default is "<b>/</b>"</li>
	<li>"OnewayMessage" : default is "false"</li>
	<li>"org.apache.cxf.message.Message.REQUEST_URI" : default is "/"</li>
	<li>"org.apache.cxf.message.Message.HTTP_REQUEST_METHOD" : default is "POST"</li>
</ul>


<p>If JMS messages are sent to topic destinations then one has to either set a "OnewayMessage" property or ensure that target JAXRS methods are annotated with org.apache.cxf.jaxrs.ext.Oneway. </p>

<p>As far as REQUEST_URI is concerned, it is initially matched against a jaxrs:server/@address. So if REQUEST_URI is not set or set to "/" then jaxrs:server/@address has to be set to "/". If REQUEST_URI is set to "/bar/foo" and<br/>
jaxrs:server/@address is set to "/bar" then it will be '/foo' which will be used to find a root resource class and its method.</p>

<p>By referencing a bean such as 'org.apache.cxf.systest.jaxrs.JMSBookStore' from multiple jaxrs endpoints you can ensure that both HTTP and JMS requests are handled by the same service bean. In such cases you may want to use a CXF JAXRS specific <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/ProtocolHeaders.java" class="external-link" rel="nofollow">ProtocolHeaders</a> context which will let you get either HTTP or JMS headers. </p>

<h2><a name="JAX-RSAdvancedFeatures-Client"></a>Client</h2>

<p>Starting from CXF 2.5.5 and CXF 2.6.2 it is possible to use the client proxies to invoke on JMS endpoints. All one needs to do is to provide a JMS endpoint address and then continue working with the proxy as usual. For example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// setup the the client
</span><span class="code-object">String</span> endpointAddressUrlEncoded = <span class="code-quote">"jms:jndi:dynamicQueues/test.jmstransport.text"</span>
             + <span class="code-quote">"?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory"</span>
             + <span class="code-quote">"&amp;replyToName=dynamicQueues/test.jmstransport.response"</span>
             + <span class="code-quote">"&amp;jndiURL=tcp:<span class="code-comment">//localhost:"</span> + JMS_PORT
</span>             + <span class="code-quote">"&amp;jndiConnectionFactoryName=ConnectionFactory"</span>;
               
JMSBookStore client = JAXRSClientFactory.create(endpointAddressUrlEncoded, JMSBookStore.class);
Book book = client.getBook(<span class="code-quote">"123"</span>);
assertEquals(<span class="code-quote">"Get a wrong response code."</span>, 200, WebClient.client(client).getResponse().getStatus());
assertEquals(<span class="code-quote">"Get a wrong book id."</span>, 123, book.getId());
</pre>
</div></div>

<p>The client runtime will set up the JMS properties described in the previous section according to JAX-RS and other annotations (such as org.apache.cxf.jaxrs.ext.Oneway) available in JMSBookStore resource class.</p>


<h1><a name="JAX-RSAdvancedFeatures-FIQLsearchqueries"></a>FIQL search queries</h1>

<h2><a name="JAX-RSAdvancedFeatures-Introduction"></a>Introduction</h2>

<p>CXF JAXRS (since 2.3.0) lets users do the advanced search queries based on the <a href="http://tools.ietf.org/html/draft-nottingham-atompub-fiql-00" class="external-link" rel="nofollow">Feed Item Query Language</a>(FIQL). FIQL lets users express complex search expressions using an intuitive and URI friendly language.</p>

<p>For example, a query such as</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
?_search=name==CXF;version=ge=2.2
</pre>
</div></div>

<p>lets users to search for all the Apache projects with the name 'CXF' and the version greater or equals to '2.2'. The initial '=' separates the name of the query '_search' from the FIQL expression, while '==' and '=ge=' convey 'equals to' and 'greater or equals to' respectively.<br/>
An expression such as "name==CXF*" can be used to the partial equality checks (in this example: the name should start from "CXF").</p>

<p>More complex composite expressions can also be expressed easily enough.</p>

<p>Note that either '_search' or '_s' query has to be used to pass the FIQL expression.</p>

<h2><a name="JAX-RSAdvancedFeatures-DependenciesandConfiguration"></a>Dependencies and Configuration</h2>

<p>The following dependency is required starting from CXF 2.6.0:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
   <span class="code-tag">&lt;dependency&gt;</span>
      <span class="code-tag">&lt;groupId&gt;</span>org.apache.cxf<span class="code-tag">&lt;/groupId&gt;</span>
      <span class="code-tag">&lt;artifactId&gt;</span>cxf-rt-rs-extension-search<span class="code-tag">&lt;/artifactId&gt;</span>
      <span class="code-tag">&lt;version&gt;</span>2.5.0<span class="code-tag">&lt;/version&gt;</span>
   <span class="code-tag">&lt;/dependency&gt;</span>
</pre>
</div></div>

<p>Additionally, in CXF 2.6.0, <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/rs/extensions/search/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchContextProvider.java" class="external-link" rel="nofollow">SearchContextProvider</a> needs to be registered as jaxrs:provider. </p>

<h2><a name="JAX-RSAdvancedFeatures-ConsumingFIQLqueries"></a>Consuming FIQL queries</h2>

<p>To work with FIQL queries, a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/rs/extensions/search/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchContext.java" class="external-link" rel="nofollow">SearchContext</a> needs be injected into an application code and used to retrieve a <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/rs/extensions/search/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchCondition.java" class="external-link" rel="nofollow">SearchCondition</a> representing the current FIQL query. This SearchCondition can be used in a number of ways for finding the matching data.</p>

<p>For example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"books"</span>)
<span class="code-keyword">public</span> class Books {

<span class="code-keyword">private</span> Map&lt;<span class="code-object">Long</span>, Book&gt; books;
@Context
<span class="code-keyword">private</span> SearchContext context;

 @GET
 <span class="code-keyword">public</span> List&lt;Book&gt; getBook() {

   SearchCondition&lt;Book&gt; sc = searchContext.getCondition(Book.class);
   <span class="code-comment">// SearchCondition#isMet method can also be used to build a list of matching beans
</span>
   <span class="code-comment">// iterate over all the values in the books map and <span class="code-keyword">return</span> a collection of matching beans
</span>   List&lt;Book&gt; found = sc.findAll(books.values());
   <span class="code-keyword">return</span> found;
 }
}
</pre>
</div></div>

<p>Note that a searchContext.getCondition(Book.class) call may return an arbitrary complex SearchCondition, it can be a simple primitive<br/>
expression or a more complex one. The Book class needs to have a matching property per every name found in the FIQL expression, for example, given a 'name==b;id==123' expression, the Book class would need to have 'name' and 'id' properties available.</p>

<h2><a name="JAX-RSAdvancedFeatures-ConvertingFIQLqueries"></a>Converting FIQL queries</h2>

<p>SearchCondition can also be used to convert the search requirements (originally expressed in FIQL) into other query languages. <br/>
A custom <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/rs/extensions/search/src/main/java/org/apache/cxf/jaxrs/ext/search/SearchConditionVisitor.java" class="external-link" rel="nofollow">SearchConditionVisitor</a> implementation can be used to convert SearchCondition objects into custom expressions or typed objects. CXF ships visitors for converting expressions to SQL and JPA 2.0 CriteriaQuery or TypedQuery objects.</p>

<h3><a name="JAX-RSAdvancedFeatures-SQL"></a>SQL</h3>

<p>org.apache.cxf.jaxrs.ext.search.sql.SQLPrinterVisitor can be used for creating SQL expressions. For example: </p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// ?_s=<span class="code-quote">"name==ami*;level=gt=10"</span>
</span>SearchCondition&lt;Book&gt; sc = searchContext.getCondition(Book.class);
SQLPrinterVisitor&lt;Book&gt; visitor = <span class="code-keyword">new</span> SQLPrinterVisitor&lt;Book&gt;(<span class="code-quote">"table"</span>);
sc.visit(visitor);
assertEquals("SELECT * FROM table 
              WHERE 
              name LIKE 'ami%' 
              AND 
              level &gt; '10'",
              visitor.getResult());
</pre>
</div></div>

<p>Note that SQLPrinterVisitor can also be initialized with the names of columns and the field aliases map:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// ?_s=<span class="code-quote">"level=gt=10"</span>
</span>SearchCondition&lt;Book&gt; sc = searchContext.getCondition(Book.class);

Map&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt; fieldMap = <span class="code-keyword">new</span> HashMap&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt;();
fieldMap.put(<span class="code-quote">"level"</span>, <span class="code-quote">"LEVEL_FIELD"</span>);

SQLPrinterVisitor&lt;Book&gt; visitor = <span class="code-keyword">new</span> SQLPrinterVisitor&lt;Book&gt;(fieldMap, <span class="code-quote">"table"</span>, <span class="code-quote">"LEVEL_COLUMN"</span>);
sc.visit(visitor);
assertEquals("SELECT LEVEL_COLUMN FROM table 
              WHERE LEVEL_COLUMN &gt; '10'",
              visitor.getResult());
</pre>
</div></div>

<p>The fields map can help hide the names of the actual table columns/record fields from the Web frontend. Example, the users will know that the 'level' property is available while internally it will be converted to a LEVEL_COLUMN name.</p>

<h3><a name="JAX-RSAdvancedFeatures-JPA2.0"></a>JPA 2.0</h3>

<p>CXF 2.5.5 and CXF 2.6.2 introduces org.apache.cxf.jaxrs.ext.search.jpa.JPATypedQueryVisitor which can be used to produce javax.persistence.criteria.CriteriaQuery or javax.persistence.TypedQuery objects.</p>


<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">import</span> javax.persistence.EntityManager;
<span class="code-keyword">import</span> javax.persistence.TypedQuery;

<span class="code-comment">// init EntityManager as required
</span><span class="code-keyword">private</span> EntityManager entityManager;

<span class="code-comment">// ?_s=<span class="code-quote">"name==ami*;level=gt=10"</span>
</span>SearchCondition&lt;Book&gt; sc = searchContext.getCondition(Book.class);
JPATypedQuery&lt;Book&gt; visitor = <span class="code-keyword">new</span> JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class);
sc.visit(visitor);
TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery();
List&lt;Book&gt; books = typedQuery.getResultList();
<span class="code-comment">// or
</span><span class="code-comment">// CriteriaQuery&lt;Book&gt; criteriaQuery = visitor.getCriteriaQuery();</span>
</pre>
</div></div>

<p>org.apache.cxf.jaxrs.ext.search.jpa.JPALanguageVisitor for converting FIQL expressions into JPQL expressions have also been introduced.</p>

<h3><a name="JAX-RSAdvancedFeatures-Customvisitors"></a>Custom visitors</h3>

<p>Here is a possible code template to follow when a custom visitor needs to be written:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class CustomVisitor&lt;T&gt; impements SearchConditionVisitor&lt;T&gt; {

<span class="code-keyword">private</span> StringBuilder sb = <span class="code-keyword">new</span> StringBuilder();

<span class="code-keyword">public</span> void visit(SearchCondition&lt;T&gt; sc) {
        
        <span class="code-keyword">if</span> (sb == <span class="code-keyword">null</span>) {
            sb = <span class="code-keyword">new</span> StringBuilder();
            <span class="code-comment">// start the expression as needed
</span>        }
        
        PrimitiveStatement statement = sc.getStatement();
        <span class="code-keyword">if</span> (statement != <span class="code-keyword">null</span>) {
                <span class="code-comment">// ex a &gt; b
</span>                <span class="code-comment">// use statement.getValue()
</span>                <span class="code-comment">// use statement.getConditionType()
</span>                <span class="code-comment">// use statement.getProperty();
</span>                
        } <span class="code-keyword">else</span> {
            <span class="code-keyword">for</span> (SearchCondition&lt;T&gt; condition : sc.getSearchConditions()) {
                <span class="code-comment">// pre-process
</span>                condition.accept(<span class="code-keyword">this</span>);
                <span class="code-comment">// post-process
</span>            }
        }
    }

    <span class="code-keyword">public</span> <span class="code-object">String</span> getResult() {
        <span class="code-comment">// convert the internal state into <span class="code-object">String</span>
</span>    }
}
</pre>
</div></div>

<p>If needed you can access a FIQL query directly and delegate it further to your own custom FIQL handler:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

@Path(<span class="code-quote">"/search"</span>)
<span class="code-keyword">public</span> class SearchEngine {
    @Context
    <span class="code-keyword">private</span> UriInfo ui;

    @GET
    <span class="code-keyword">public</span> List&lt;Book&gt; findBooks() {
        MultivaluedMap&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt; params = ui.getQueryParameters();
        <span class="code-object">String</span> fiqlQuery = params.getFirst(<span class="code-quote">"_s"</span>);
        <span class="code-comment">// delegate to your own custom handler 
</span>
        <span class="code-comment">// note that the original search expression can also be retrieved 
</span>        <span class="code-comment">// using a SearchContext.getSearchExpression() method
</span>}

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

<h3><a name="JAX-RSAdvancedFeatures-SearchBean"></a>SearchBean</h3>

<p>org.apache.cxf.jaxrs.ext.search.SearchBean is a utility bean class which can simplify analyzing the captured FIQL expressions and converting them to the other language expressions, in cases where having to update the bean class such as Book.class with all the properties thatmay need to be supported is not practical. For example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// ?_s=<span class="code-quote">"level=gt=10"</span>
</span>SearchCondition&lt;SearchBean&gt; sc = searchContext.getCondition(SearchBean.class);

Map\&lt;, <span class="code-object">String</span>\&gt; fieldMap = <span class="code-keyword">new</span> HashMap\&lt;<span class="code-object">String</span>, <span class="code-object">String</span>\&gt;();
fieldMap.put(<span class="code-quote">"level"</span>, <span class="code-quote">"LEVEL_FIELD"</span>);

SQLPrinterVisitor&lt;SearchBean&gt; visitor = <span class="code-keyword">new</span> SQLPrinterVisitor&lt;SearchBean&gt;(fieldMap, <span class="code-quote">"table"</span>, <span class="code-quote">"LEVEL_COLUMN"</span>);
sc.visit(visitor);
assertEquals("SELECT LEVEL_COLUMN FROM table 
              WHERE LEVEL_COLUMN &gt; '10'",
              visitor.getResult());
</pre>
</div></div>

<h2><a name="JAX-RSAdvancedFeatures-SearchExpressionsinURIPathsegments"></a>Search Expressions in URI Path segments</h2>

<p>By default, a FIQL expression is expected to be available in either '_s' or '_search' query.<br/>
For example, "find all the books with an 'id' property value less than 123":</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
GET /books?_s=id=lt=123
</pre>
</div></div>

<p>Starting from CXF 2.6.2, it is possible to work with FIQL expressions included in URI path segments, for example, the same query can be expressed<br/>
in a number of ways:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">

GET /books/id=lt=123
GET /books[id=lt=123]
GET /books(id=lt=123)
GET /books;id=lt=123

//etc, etc

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

<p>Such expressions can be captured in the code using JAX-RS annotations:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
@Path(<span class="code-quote">"search"</span>)
<span class="code-keyword">public</span> class BooksResource {
   @Context
   <span class="code-keyword">private</span> SearchContext context;

   <span class="code-comment">//GET /books[id=lt=123]
</span>   @GET
   @Path(<span class="code-quote">"books[{search}]"</span>) 
   <span class="code-keyword">public</span> List&lt;Book&gt; findSelectedBooks(@PathParam(<span class="code-quote">"search"</span>) <span class="code-object">String</span> searchExpression) {
       <span class="code-keyword">return</span> doFindSelectedBooks(searchExpression);
   }

   <span class="code-comment">//GET /books(id=lt=123)
</span>   @GET
   @Path(<span class="code-quote">"books({search})"</span>) 
   <span class="code-keyword">public</span> List&lt;Book&gt; findSelectedBooks(@PathParam(<span class="code-quote">"search"</span>) <span class="code-object">String</span> searchExpression) {
       <span class="code-keyword">return</span> doFindSelectedBooks(searchExpression);
   }

   <span class="code-comment">//GET /books/id=lt=123
</span>   @GET
   @Path(<span class="code-quote">"books/{search}"</span>) 
   <span class="code-keyword">public</span> List&lt;Book&gt; findSelectedBooks(@PathParam(<span class="code-quote">"search"</span>) <span class="code-object">String</span> searchExpression) {
       <span class="code-keyword">return</span> doFindSelectedBooks(searchExpression);
   }

   <span class="code-comment">//GET /books;id=lt=123
</span>   @GET
   @Path(<span class="code-quote">"books;{search}"</span>) 
   <span class="code-keyword">public</span> List&lt;Book&gt; findSelectedBooks(@PathParam(<span class="code-quote">"search"</span>) <span class="code-object">String</span> searchExpression) {
       <span class="code-keyword">return</span> doFindSelectedBooks(searchExpression);
   }

   <span class="code-keyword">public</span> List&lt;Book&gt; doFindSelectedBooks(<span class="code-object">String</span> searchExpression) {
       SearchCondition&lt;Book&gt; sc = context.getCondition(searchExpression, Book.class);
   
       <span class="code-comment">// JPA2 enity manager is initialized earlier
</span>       JPATypedQuery&lt;Book&gt; visitor = <span class="code-keyword">new</span> JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class);
       sc.visit(visitor);
   
       TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery();
       <span class="code-keyword">return</span> typedQuery.getResultList();
   }

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

<p>Note that if you have an expression added to a URI path segment with a ";" character acting as a separator, example, "/books;id=lt=123",<br/>
or if an expression itself includes ";", example, "/books<span class="error">&#91;id=lt=123;id=gt=300&#93;</span>" ("find all the books with id less than 123 or greater than 300") <br/>
then a boolean contextual property "ignore.matrix.parameters" has to be set to "true" for the runtime to avoid splitting the path segment into the path value and matrix parameters.</p>

<h2><a name="JAX-RSAdvancedFeatures-Queriesinvolvingmultipleentities"></a>Queries involving multiple entities</h2>

<h3><a name="JAX-RSAdvancedFeatures-Basicqueries"></a>Basic queries</h3>

<p>Consider the query like "find the first chapters of all the books with 'id' less than 123".<br/>
One easy way to manage such queries is to make FIQL and JAX-RS work together. For example:    </p>

<p>@Path("search")<br/>
public class BooksResource {<br/>
   @Context<br/>
   private SearchContext context;</p>

<p>   //GET /books<a href="/confluence/pages/createpage.action?spaceKey=CXF20DOC&amp;title=id%3Dlt%3D123&amp;linkCreation=true&amp;fromPageId=24190907" class="createlink">id=lt=123</a>/chapter/1<br/>
   @GET<br/>
   @Path("books<a href="/confluence/pages/createpage.action?spaceKey=CXF20DOC&amp;title=<div class="searchMacro">
    <h4 class="resultSummary">
                    Found <strong>10</strong> search result(s).
	 
        </h4>

    					<div class="result">
            
			
	            
<span class="icon icon-file-unknown" title=File>File</span>    
			<a href="/confluence/download/attachments/35979/logo_jprofiler01.gif?version=1">logo_jprofiler01.gif</a>
	
			<span class="smalltext">
			(<a href="/confluence/display/ACTIVEMQ">Apache ActiveMQ</a>
			&gt; <a href="/confluence/display/ACTIVEMQ/Navigation">Navigation</a>)
		</span>
	    
    <br />
    <span class="smalltext">
                                    Image -
                        2 kB -
        
        

                    - <a href="/confluence/download/attachments/35979/logo_jprofiler01.gif?version=1">Download</a>
            - <a href="/confluence/pages/viewpageattachments.action?pageId=35979&highlight=logo_jprofiler01.gif#Navigation-attachment-logo_jprofiler01.gif">Attachments</a>
            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/CAMEL/Camel+2.11.0+Release">Camel 2.11.0 Release</a>
	
			<span class="smalltext">(<a href="/confluence/display/CAMEL">Apache Camel</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	            <span class="icon icon-user" title=User profile>User profile:</span>
    
			<a href="/confluence/display/~neeraj1988">neeraj tiwari</a>
	
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/CAMEL/Camel+Maven+Plugin">Camel Maven Plugin</a>
	
			<span class="smalltext">(<a href="/confluence/display/CAMEL">Apache Camel</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/GIRAPH/Install+and+test+Giraph+0.20+on+CDH3u1">Install and test Giraph 0.20 on CDH3u1</a>
	
			<span class="smalltext">(<a href="/confluence/display/GIRAPH">Apache Giraph (Incubating)</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+3.5">AOO 3.5</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+3.5+Release+Planning">AOO 3.5 Release Planning</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+3.5+Release+Notes">AOO 3.5 Release Notes</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+4.0+Release+Planning">AOO 4.0 Release Planning</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/Releases">Releases</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
            </div>
&amp;linkCreation=true&amp;fromPageId=24190907" class="createlink"><div class="searchMacro">
    <h4 class="resultSummary">
                    Found <strong>10</strong> search result(s).
	 
        </h4>

    					<div class="result">
            
			
	            
<span class="icon icon-file-unknown" title=File>File</span>    
			<a href="/confluence/download/attachments/35979/logo_jprofiler01.gif?version=1">logo_jprofiler01.gif</a>
	
			<span class="smalltext">
			(<a href="/confluence/display/ACTIVEMQ">Apache ActiveMQ</a>
			&gt; <a href="/confluence/display/ACTIVEMQ/Navigation">Navigation</a>)
		</span>
	    
    <br />
    <span class="smalltext">
                                    Image -
                        2 kB -
        
        

                    - <a href="/confluence/download/attachments/35979/logo_jprofiler01.gif?version=1">Download</a>
            - <a href="/confluence/pages/viewpageattachments.action?pageId=35979&highlight=logo_jprofiler01.gif#Navigation-attachment-logo_jprofiler01.gif">Attachments</a>
            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/CAMEL/Camel+2.11.0+Release">Camel 2.11.0 Release</a>
	
			<span class="smalltext">(<a href="/confluence/display/CAMEL">Apache Camel</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	            <span class="icon icon-user" title=User profile>User profile:</span>
    
			<a href="/confluence/display/~neeraj1988">neeraj tiwari</a>
	
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/CAMEL/Camel+Maven+Plugin">Camel Maven Plugin</a>
	
			<span class="smalltext">(<a href="/confluence/display/CAMEL">Apache Camel</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/GIRAPH/Install+and+test+Giraph+0.20+on+CDH3u1">Install and test Giraph 0.20 on CDH3u1</a>
	
			<span class="smalltext">(<a href="/confluence/display/GIRAPH">Apache Giraph (Incubating)</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+3.5">AOO 3.5</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+3.5+Release+Planning">AOO 3.5 Release Planning</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+3.5+Release+Notes">AOO 3.5 Release Notes</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/AOO+4.0+Release+Planning">AOO 4.0 Release Planning</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
        			<div class="result">
            
			
	                <span class="icon icon-page" title=Page>Page:</span>
        
			<a href="/confluence/display/OOOUSERS/Releases">Releases</a>
	
			<span class="smalltext">(<a href="/confluence/display/OOOUSERS">Apache OpenOffice Community</a>)</span>
	    
    <br />
    <span class="smalltext">
        
        Jul 12, 2012

            </span>

	
            </div>
            </div>
</a>/chapter/</p>
<div class="error"><span class="error">Unknown macro: {id}</span> <p>") <br/>
   public List&lt;Book&gt; findSelectedBooks(@PathParam("search") String searchExpression,<br/>
                                       @PathParam("id") int chapterIndex) </p>
<div class="error"><span class="error">Unknown macro: {
       return doFindSelectedChapters(searchExpression, chapterIndex);
   }</span> </div>

<p>   public List&lt;Chapter&gt; doFindSelectedChapters(String searchExpression, int chapterIndex) {<br/>
       SearchCondition&lt;Book&gt; sc = context.getCondition(searchExpression, Book.class);</p>

<p>       // JPA2 enity manager is initialized earlier<br/>
       JPATypedQuery&lt;Book&gt; visitor = new JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class);<br/>
       sc.visit(visitor);</p>

<p>       TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery();<br/>
       List&lt;Book&gt; books = typedQuery.getResultList();</p>

<p>       List&lt;Chapter&gt; chapters = new ArrayList&lt;Chapter&gt;(books.size);<br/>
       for (Book book : books) </p>
<div class="error"><span class="error">Unknown macro: {
           chapters.add(book.getChapter(chapterIndex)); 
       }</span> </div>
<p>   <br/>
       return chapters;<br/>
   }</p>

<p>}</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java"> 

h3. Complex queries

At the moment one needs to follow the example (not necessarily using JPA2) presented in the previous section to manage the complex queries 
such as <span class="code-quote">"find all the chapters with id less than 5 <span class="code-keyword">for</span> all the books with id greater than 300"</span>, <span class="code-keyword">for</span> example: 


@Path(<span class="code-quote">"search"</span>)
<span class="code-keyword">public</span> class BooksResource {
   @Context
   <span class="code-keyword">private</span> SearchContext context;

   <span class="code-comment">//GET /books(id=gt=300)/chapters(id=lt=5)
</span>   @GET
   @Path(<span class="code-quote">"books({search1})/chapter/{search2}"</span>) 
   <span class="code-keyword">public</span> List&lt;Book&gt; findSelectedBooks(@PathParam(<span class="code-quote">"search1"</span>) <span class="code-object">String</span> bookExpression,
                                       @PathParam(<span class="code-quote">"search2"</span>) <span class="code-object">String</span> chapterExpression) {
       <span class="code-keyword">return</span> doFindSelectedBooks(bookExpression, chapterExpression);
   }

   <span class="code-keyword">public</span> List&lt;Chapter&gt; doFindSelectedChapters(<span class="code-object">String</span> bookExpression, <span class="code-object">String</span> chapterExpression) {
       <span class="code-comment">// find the books first
</span>       
       SearchCondition&lt;Book&gt; bookCondition = context.getCondition(searchExpression, Book.class);
   
       JPATypedQuery&lt;Book&gt; visitor = <span class="code-keyword">new</span> JPATypedQueryVisitor&lt;Book&gt;(entityManager, Book.class);
       bookCondition.visit(visitor);
       TypedQuery&lt;Book&gt; typedQuery = visitor.getQuery();
       List&lt;Book&gt; books = typedQuery.getResultList();

       <span class="code-comment">// now get the chapters
</span>       SearchCondition&lt;Chapter&gt; chapterCondition = context.getCondition(chapterExpression, Chapter.class);
       List&lt;Chapter&gt; chapters = <span class="code-keyword">new</span> ArrayList&lt;Chapter&gt;();
       <span class="code-keyword">for</span> (Book book : books) {
           chapters.addAll(chapterCondition.findAll(book.getChapters()); 
       }   
       <span class="code-keyword">return</span> chapters;
   }

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

<p>The above code can be quite functional but not necessarilry optimal. Much depends on the actual relationship between the endities, whether the initial (JPA2) query eagerly loaded all the chapters for every given book, etc. Perhaps a JOIN-like query which will immediately return only the matching chapters will be more optimal. Support for capturing the expressions involving multiple entities and possibly converting them to JOIN statements will be investigated shortly.</p>


<h2><a name="JAX-RSAdvancedFeatures-BuildingFIQLqueries"></a>Building FIQL queries</h2>

<p>CXF 2.4.0 introduces <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/java/org/apache/cxf/jaxrs/ext/search/client/SearchConditionBuilder.java" class="external-link" rel="nofollow">SearchConditionBuilder</a> which makes it simpler to build FIQL queries. SearchConditionBuilder is an abstract class that returns a FIQL builder by default:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
SearchConditionBuilder b = SearchConditionBuilder.instance();
<span class="code-object">String</span> fiqlQuery = b.is(<span class="code-quote">"id"</span>).greaterThan(123).query();

WebClient wc = WebClient.create(<span class="code-quote">"http:<span class="code-comment">//books.com/search"</span>);
</span>wc.query(<span class="code-quote">"_s"</span>, fiqlQuery);
<span class="code-comment">// find all the books with id greater than 123 
</span>Collection books = wc.getCollection(Book.class);
</pre>
</div></div>

<p>Here is an example of building more complex queries:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-comment">// OR condition
</span><span class="code-object">String</span> ret = b.is(<span class="code-quote">"foo"</span>).greaterThan(20).or().is(<span class="code-quote">"foo"</span>).lessThan(10).query();
assertEquals(<span class="code-quote">"foo=gt=20,foo=lt=10"</span>, ret);

<span class="code-comment">// AND condition
</span><span class="code-object">String</span> ret = b.is(<span class="code-quote">"foo"</span>).greaterThan(20).and().is(<span class="code-quote">"bar"</span>).equalTo(<span class="code-quote">"plonk"</span>).query();
assertEquals(<span class="code-quote">"foo=gt=20;bar==plonk"</span>, ret);

<span class="code-comment">// Complex condition
</span><span class="code-object">String</span> ret = b.is(<span class="code-quote">"foo"</span>).equalTo(123.4).or().and(
            b.is(<span class="code-quote">"bar"</span>).equalTo(<span class="code-quote">"asadf*"</span>), 
            b.is(<span class="code-quote">"baz"</span>).lessThan(20)).query();
assertEquals(<span class="code-quote">"foo==123.4,(bar==asadf*;baz=lt=20.0)"</span>, ret);
</pre>
</div></div>

<h2><a name="JAX-RSAdvancedFeatures-Usingdatesinqueries"></a>Using dates in queries</h2>

<p>By default, the date values have to have the following <a href="http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html" class="external-link" rel="nofollow">format</a>: "yyyy-MM-dd'T'HH:mm:ss.SSSZ", for example:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
?_search=time=le=2010-03-11T18:00:00.000+00:00
</pre>
</div></div> 

<p>A simpler date format can be supported. Use "search.date-format" and "search.timezone.support" contextual properies, ex, "search.date-format"="yyyy-MM-dd'T'HH:mm:ss" and "search.timezone.support"="false" will let users avoid specifying milliseconds and timezones:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
?_search=time=le=2010-03-11T18:00:00
</pre>
</div></div>

<p>At the moment, for custom date formats be recognized by SearchConditionBuilder, FIQLSearchConditionBuilder has to be created explicitly:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
Map&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt; props = <span class="code-keyword">new</span> HashMap&lt;<span class="code-object">String</span>, <span class="code-object">String</span>&gt;();
props.put(<span class="code-quote">"search.date-format"</span>, <span class="code-quote">"yyyy-MM-dd'T'HH:mm:ss"</span>);
props.put(<span class="code-quote">"search.timezone.support"</span>, <span class="code-quote">"<span class="code-keyword">false</span>"</span>);

Date d = df.parse(<span class="code-quote">"2011-03-01 12:34:00"</span>);
        
FiqlSearchConditionBuilder bCustom = <span class="code-keyword">new</span> FiqlSearchConditionBuilder(props);
        
<span class="code-object">String</span> ret = bCustom.is(<span class="code-quote">"foo"</span>).equalTo(d).query();
assertEquals(<span class="code-quote">"foo==2011-03-01T12:34:00"</span>, ret);
</pre>
</div></div>

<h3><a name="JAX-RSAdvancedFeatures-Alternativequerylanguages"></a>Alternative query languages</h3>

<p>At the moment FIQL is the only and default query language (capable of expressing simple and complex quieries) recognized by the Search module.<br/>
org.apache.cxf.jaxrs.ext.search.SearchConditionParser has been introduced to facilitate a support for the alternative query languages. More work in this area will be done in the future. </p>

<h1><a name="JAX-RSAdvancedFeatures-Onewayinvocations"></a>Oneway invocations</h1>

<p>Resource methods with an org.apache.cxf.jaxrs.ext.Oneway annotation will be invoked oneway with the original request returning 202 HTTP status. HTTP or JMS clients can also add a "OnewayRequest" header if adding Oneway annotations is not an option.</p>

<h1><a name="JAX-RSAdvancedFeatures-SupportforContinuations"></a>Support for Continuations </h1>

<p>Please see <a href="http://sberyozkin.blogspot.com/2008/12/continuations-in-cxf.html" class="external-link" rel="nofollow">this blog entry</a> describing how JAXRS (and indeed) JAXWS services can rely on the CXF Continuations API. </p>

<p>Please see the <a href="/confluence/pages/createpage.action?spaceKey=CXF20DOC&amp;title=CXF+Continuations&amp;linkCreation=true&amp;fromPageId=24190907" class="createlink">CXF Continuations</a> page for more information.</p>

<h1><a name="JAX-RSAdvancedFeatures-Serversidecaching"></a>Server-side caching</h1>

<p><a href="http://ehcache.org/documentation/web_caching.html" class="external-link" rel="nofollow">Ehcache-Web</a> and other similar frameworks can be used to provide an advanced support for<br/>
the server-side caching.</p>

<p>For example, the only thing you need to do to interpose Ehcache-Web on top of CXF JAX-RS endpoints is to add the following declarations to the web.xml, assuming the name of the war is 'ehcache-cxf':</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
<span class="code-tag">&lt;context-param&gt;</span>
        <span class="code-tag">&lt;param-name&gt;</span>webAppRootKey<span class="code-tag">&lt;/param-name&gt;</span>
        <span class="code-tag">&lt;param-value&gt;</span>ehcache-cxf<span class="code-tag">&lt;/param-value&gt;</span>
    <span class="code-tag">&lt;/context-param&gt;</span>
<span class="code-tag">&lt;filter&gt;</span>
        <span class="code-tag">&lt;filter-name&gt;</span>SimplePageCachingFilter<span class="code-tag">&lt;/filter-name&gt;</span>
        <span class="code-tag">&lt;filter-class&gt;</span>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter<span class="code-tag">&lt;/filter-class&gt;</span>
        <span class="code-tag">&lt;init-param&gt;</span>
            <span class="code-tag">&lt;param-name&gt;</span>varyHeader<span class="code-tag">&lt;/param-name&gt;</span>
            <span class="code-tag">&lt;param-value&gt;</span>true<span class="code-tag">&lt;/param-value&gt;</span>
        <span class="code-tag">&lt;/init-param&gt;</span>
    <span class="code-tag">&lt;/filter&gt;</span>
    
    <span class="code-tag">&lt;filter-mapping&gt;</span>
        <span class="code-tag">&lt;filter-name&gt;</span>SimplePageCachingFilter<span class="code-tag">&lt;/filter-name&gt;</span>
        <span class="code-tag">&lt;url-pattern&gt;</span>/*<span class="code-tag">&lt;/url-pattern&gt;</span>
    <span class="code-tag">&lt;/filter-mapping&gt;</span>
</pre>
</div></div> 

<p>Please see the <a href="http://ehcache.org/documentation/web_caching.html" class="external-link" rel="nofollow">Ehcache-Web</a> page for more information on how to configure it, here is one example:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml">
&lt;ehcache <span class="code-keyword">xmlns:xsi</span>=<span class="code-quote">"http://www.w3.org/2001/XMLSchema-instance"</span>
    xsi:noNamespaceSchemaLocation=<span class="code-quote">"../../main/config/ehcache.xsd"</span>
    updateCheck=<span class="code-quote">"false"</span>
    monitoring=<span class="code-quote">"autodetect"</span>
    dynamicConfig=<span class="code-quote">"true"</span>&gt;
	
	&lt;defaultCache
		maxElementsInMemory=<span class="code-quote">"10"</span>
		eternal=<span class="code-quote">"false"</span>
		timeToIdleSeconds=<span class="code-quote">"5"</span>
		timeToLiveSeconds=<span class="code-quote">"10"</span>
		overflowToDisk=<span class="code-quote">"true"</span> /&gt;
	
    &lt;cache name=<span class="code-quote">"SimplePageCachingFilter"</span>
		maxElementsInMemory=<span class="code-quote">"100"</span>
		eternal=<span class="code-quote">"false"</span>
		overflowToDisk=<span class="code-quote">"false"</span>
		timeToIdleSeconds=<span class="code-quote">"5"</span>
		timeToLiveSeconds=<span class="code-quote">"10"</span>
        memoryStoreEvictionPolicy=<span class="code-quote">"LFU"</span> /&gt;
<span class="code-tag">&lt;/ehcache&gt;</span>
</pre>
</div></div>

<p>This configuration has to be saved in ehcache-web.xml file and available as a class-path resource starting from the root.</p>

<h1><a name="JAX-RSAdvancedFeatures-RESTfulserviceswithoutannotations"></a>RESTful services without annotations </h1>

<p>One of the latest CXF JAX-RS extensions allows users to provide external models with the information which the runtime typically gets from JAX-RS annotations like @Path, @PathParam, @Consumes, @Produces, etc.<br/>
There might be a number of cases when it can be advantageous to describe how a given resource can be exposed as a RESTful service without actually modifying this resource. For example, when new dynamic interface implementations are registered, when no source code can be modified, when the cost of future updates (for ex, modifying the value of @Path annotations) is considered to be expensive, etc.</p>

<p>User model schema type is described in the <a href="http://svn.apache.org/repos/asf/cxf/trunk/rt/frontend/jaxrs/src/main/resources/schemas/jaxrs.xsd" class="external-link" rel="nofollow">jaxrs.xsd</a>. </p>

<p>The top-level 'model' element can have 'resource' children elements. A 'resource' element describes a resource class which can be either a root resource class or a sub-resource one and it can have attributes describing 'path', 'produces' and 'consumes' values and it has a 'name' attribute which identifies a fully-qualified resource class. <br/>
A 'resource' element can have a number of 'operation' elements pointing to resource methods (with its 'name' attribute) and can have 'path', 'produces', 'consumes' and 'verb' (HTTP method) values. An 'operation' element which has no 'verb' attribute is treated as a sub-resource locator - a corresponding resource class has to be available in the model with its 'name' attribute matching the return type's name of this operation.<br/>
Every operation can have a number of 'param' elements. A 'param' element should have its 'name' attribute matching a corresponding parameter name in the class resource method. Its 'type' can have the following values : 'PATH', 'QUERY', 'CONTEXT', 'HEADER', 'MATRIX', 'COOKIE', 'FORM' or 'REQUEST_BODY'. Parameters corresponding to response types do not have to be described. It can also have 'defaultValue' and 'encoded' values being set.</p>

<p>Starting from CXF 2.3.2-SNAPSHOT a "oneway" attribute can also be applied to individual operations.</p>

<p>Here is an example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-xml"></pre>
</div></div>
<p>&lt;model xmlns="http://cxf.apache.org/jaxrs"&gt;<br/>
  &lt;resource name="org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations" path="bookstore"<br/>
    produces="application/json" consumes="application/json"&gt;<br/>
    &lt;operation name="getBook" verb="GET" path="/books/</p></div>
<p>" produces="application/xml"&gt;<br/>
       &lt;param name="id" type="PATH"/&gt;<br/>
    &lt;/operation&gt;<br/>
    &lt;operation name="getBookChapter" path="/books/</p>
<div class="error"><span class="error">Unknown macro: {id}</span> </div>
<p>/chapter"&gt;<br/>
       &lt;param name="id" type="PATH"/&gt;<br/>
    &lt;/operation&gt;<br/>
    &lt;operation name="updateBook" verb="PUT"&gt;<br/>
       &lt;param name="book" type="REQUEST_BODY"/&gt;<br/>
    &lt;/operation&gt;<br/>
  &lt;/resource&gt;<br/>
  &lt;resource name="org.apache.cxf.systest.jaxrs.ChapterNoAnnotations"&gt;<br/>
    &lt;operation name="getItself" verb="GET"/&gt;<br/>
    &lt;operation name="updateChapter" verb="PUT" consumes="application/xml"&gt;<br/>
        &lt;param name="content" type="REQUEST_BODY"/&gt;<br/>
    &lt;/operation&gt;<br/>
  &lt;/resource&gt;<br/>
&lt;/model&gt;</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">

This model describes two resources, BookStoreNoAnnotations and ChapterNoAnnotations. The BookStoreNoAnnotations resource has three resource operations, 'getBook', 'getBookChapter' and 'updateBook'. Note that the 'getBookChapter' operation element (described in the model) has no 'verb' attribute so runtime will identify it as a subresource locator.
The runtime will introspect the [org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/BookStoreNoAnnotations.java] class and check the <span class="code-keyword">return</span> types <span class="code-keyword">for</span> both 'getBook' and 'getBookChapter' methods.  BookStoreNoAnnotations.getBookChapter() method's <span class="code-keyword">return</span> type is [org.apache.cxf.systest.jaxrs.ChapterNoAnnotations|http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/ChapterNoAnnotations.java] so the model will be checked <span class="code-keyword">if</span> it contains the resource element with the 'name' attribute equal to 'org.apache.cxf.systest.jaxrs.ChapterNoAnnotations'. After <span class="code-keyword">this</span> resource has been found, the  ChapterNoAnnotations class is recognized as a sub-resource and then its 'getItself' method is checked.  
</span>
Additionally the BookStoreNoAnnotations resource declares that all its resource methods produce 'application/json' mediaTypes, <span class="code-keyword">while</span> its 'getBook' method overrides its with its own 'produces' value. BookStoreNoAnnotations resource also has a 'consumes' attribute which requires all of the resource methods (such as 'updateBook') to consume <span class="code-quote">"application/json"</span> formats. The ChapterNoAnnotations 'updateChapter' resource operation requires 'application/xml' formats.

You can use a comma-seperated list of media type values <span class="code-keyword">if</span> needed, <span class="code-keyword">for</span> example, produces(<span class="code-quote">"application/xml;charset=utf-8,application/json"</span>) or consumes(<span class="code-quote">"application/xml;charset=utf-8,application/json"</span>).

Please also see <span class="code-keyword">this</span> [model file|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/resources/resources2.xml] <span class="code-keyword">for</span> an example. Providing <span class="code-keyword">this</span> file will let all implementations of the <span class="code-keyword">interface</span> described in <span class="code-keyword">this</span> model instance be exposed as RESTful services supported by the JAX-RS runtime. 
</span>
h2. Configuration 

A user model can be referenced in a number of ways. It can be embedded in a jaxrs:server endpoint definition or linked to through a jaxrs:server modelRef attribute as a classpath resource. 

Please see <span class="code-keyword">this</span> [bean|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs/WEB-INF/beans.xml] Spring configuration file, look at jaxrs server beans with 'bookservice6' and 'bookservice7' names.
</span>
Note that when registering a model from Spring you <span class="code-keyword">do</span> not need to declare a jaxrs server serviceBeans section - the runtime will instantiate the beans itself. If you <span class="code-keyword">do</span> need to inject certain properties into your service bean from Spring then you <span class="code-keyword">do</span> need to declare a service bean too. In <span class="code-keyword">this</span> <span class="code-keyword">case</span> <span class="code-keyword">this</span> bean will be instantiated twice - once by the runtime during the model introspection and once by Spring, however in the end it will be the bean created by Spring that will be used, the one created by the runtime will be removed.
You can avoid <span class="code-keyword">this</span> <span class="code-object">double</span> instantiation by having your model describing the interfaces which the actual root resource beans will implement. In <span class="code-keyword">this</span> <span class="code-keyword">case</span> only Spring will create a bean and the runtime will apply the model description to <span class="code-keyword">this</span> injected bean. Note that <span class="code-keyword">if</span> Spring proxifies your bean (<span class="code-keyword">for</span> example by applying transaction aspects to it) then the model does have to describe an <span class="code-keyword">interface</span> <span class="code-keyword">for</span> a match between the model and the injected bean proxy to succeed.

Please have a look at [<span class="code-keyword">this</span> Spring bean|http:<span class="code-comment">//svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_proxy/WEB-INF/beans.xml]. The jaxrs endpoint with id 'bookservice2' will have BookStoreWithNoAnnotations created twice but it will be the Spring created BookStoreWithNoAnnotations bean that will serve as a resource class instance. The jaxrs endpoint with id 'bookservice3' will have BookStoreWithNoAnnotationsImpl class instantiated only by Spring, with the model describing BookStoreWithNoAnnotationsInterface only that <span class="code-keyword">this</span> class <span class="code-keyword">implements</span>.
</span>

You can also register a model programmatically, <span class="code-keyword">for</span> example :

{code:java}
JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
            sf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9080/"</span>);
</span><span class="code-object">String</span> modelRef = <span class="code-quote">"classpath:/org/apache/cxf/systest/jaxrs/resources/resources2.xml"</span>;
sf.setModelRef(modelRef);

<span class="code-comment">// or <span class="code-keyword">if</span> you have <span class="code-keyword">interface</span> classes described in the model already loaded, ex : OSGI
</span><span class="code-comment">// sf.setModelRefWithServiceClass(modelRef, BookStoreNoAnnotationsInterface.class);
</span>
<span class="code-comment">// register an actual bean only <span class="code-keyword">if</span> the model describes interfaces
</span>sf.setServiceBeans(<span class="code-keyword">new</span> BookStoreNoAnnotationsImpl());
</pre>
</div></div>

<p>Please also see <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/JAXRSClientServerUserResourceTest.java" class="external-link" rel="nofollow">this system test</a> for the example of how model beans like UserResource can be created and registered programmatically.</p>

<p>Similarly, you can register a user model on the client side, either from jaxrs:client or programmatically, example :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
JAXRSClientFactoryBean cf = <span class="code-keyword">new</span> JAXRSClientFactoryBean();
cf.setAddress(<span class="code-quote">"http:<span class="code-comment">//localhost:9080/"</span>);
</span><span class="code-object">String</span> modelRef = <span class="code-quote">"classpath:/org/apache/cxf/systest/jaxrs/resources/resources2.xml"</span>;
sf.setModelRef(modelRef);
BookStoreNoAnnotations proxy = cf.create(BookStoreNoAnnotations.class);
</pre>
</div></div>

<p>At the moment it is only possible to register a user model with CXFNonSpringJAXRSServlet using the latest 2.2.3-SNAPSHOT like the way it is done in this <a href="http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_non_spring/WEB-INF/web.xml" class="external-link" rel="nofollow">web.xml</a>. See CXFServlet3 and CXFServlet4 servlet declarations. Note that CXFServlet4 registers a model containing interfaces so it also registers a BookStoreNoAnnotationsImpl service class.</p>

<p>The workaround is to create a custom servlet :</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
<span class="code-keyword">public</span> class JAXRSUserModelServlet <span class="code-keyword">extends</span> CXFNonSpringJaxrsServlet  {

@Override
<span class="code-keyword">public</span> void loadBus(ServletConfig servletConfig) <span class="code-keyword">throws</span> ServletException {

<span class="code-keyword">super</span>.loadBus(servletConfig);

JAXRSServerFactoryBean sf = <span class="code-keyword">new</span> JAXRSServerFactoryBean();
<span class="code-object">String</span> address = servletConfig.getInitParameter(SERVICE_ADDRESS_PARAM); <span class="code-comment">//jaxrs.address
</span><span class="code-keyword">if</span> (address == <span class="code-keyword">null</span>) {
address = <span class="code-quote">"/"</span>;
}
sf.setAddress(address);

<span class="code-comment">// modelRef needs to start from 'classpath:', ex 'classpath:/WEB-INF/models/model1.xml
</span><span class="code-object">String</span> modelRef = servletConfig.getInitParameter(<span class="code-quote">"user.model"</span>);
sf.setModelRef(modelRef);
sf.create();
}
</pre>
</div></div>
    </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/CXF20DOC/JAX-RS+Advanced+Features">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=24190907&revisedVersion=16&originalVersion=15">View Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS+Advanced+Features?showComments=true&amp;showCommentArea=true#addcomment">Add Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message