View Javadoc

1   /***
2    * 
3    * Copyright 2004 Protique Ltd
4    * 
5    * Licensed under the Apache License, Version 2.0 (the "License"); 
6    * you may not use this file except in compliance with the License. 
7    * You may obtain a copy of the License at 
8    * 
9    * http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS, 
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
14   * See the License for the specific language governing permissions and 
15   * limitations under the License. 
16   * 
17   **/
18  package org.codehaus.activespace.query.groovy;
19  
20  import groovy.lang.Binding;
21  import groovy.lang.GroovyShell;
22  import org.codehaus.activespace.query.QueryContext;
23  import org.codehaus.activespace.query.QueryException;
24  import org.codehaus.activespace.query.QueryManager;
25  import org.codehaus.groovy.runtime.InvokerHelper;
26  
27  import java.util.List;
28  
29  /***
30   * An implementation of the QueryManager using <a href="http://groovy.codehaus.org/">Groovy</a>
31   *
32   * @version $Revision: 1.1 $
33   */
34  public class GroovyQueryManager implements QueryManager {
35  
36      public List select(String query, QueryContext context) throws QueryException {
37          Object answer = evaluate(query, context);
38          return InvokerHelper.asList(answer);
39      }
40  
41      public Object evaluate(String query, QueryContext context) throws QueryException {
42          GroovyShell shell = createShell(context);
43          try {
44              return shell.evaluate(query);
45          }
46          catch (Exception e) {
47              throw new QueryException("Failed to perform query '" + query + "' due to: " + e, e);
48          }
49      }
50  
51      protected GroovyShell createShell(final QueryContext context) {
52          GroovyShell shell = new GroovyShell(new Binding() {
53              public Object getProperty(String name) {
54                  return context.getValue(name);
55              }
56  
57              public Object getVariable(String name) {
58                  return context.getValue(name);
59              }
60          });
61          return shell;
62      }
63  }