View Javadoc

1   /**
2    * Copyright 2010 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15  
16  package org.kuali.rice.krms.impl.repository.language;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.apache.velocity.exception.VelocityException;
20  import org.kuali.rice.krms.api.repository.language.NaturalLanguageTemplate;
21  import org.kuali.rice.krms.api.repository.language.NaturalLanguageTemplaterContract;
22  import org.kuali.rice.krms.api.repository.proposition.PropositionParameterType;
23  import org.kuali.rice.krms.api.repository.term.TermDefinitionContract;
24  import org.kuali.rice.krms.api.repository.type.KrmsTypeDefinitionContract;
25  import org.kuali.rice.krms.api.repository.type.KrmsTypeRepositoryService;
26  import org.kuali.rice.krms.impl.repository.KrmsTypeRepositoryServiceImpl;
27  import org.kuali.rice.krms.impl.repository.TermBoService;
28  import org.kuali.rice.krms.impl.repository.TermBoServiceImpl;
29  import org.kuali.student.common.util.VelocityTemplateEngine;
30  import org.kuali.student.r2.core.krms.naturallanguage.TermParameterTypes;
31  import org.kuali.student.r2.common.exceptions.DoesNotExistException;
32  import org.kuali.student.r2.common.exceptions.OperationFailedException;
33  import org.kuali.student.r2.core.krms.naturallanguage.Context;
34  import org.kuali.student.r2.core.krms.naturallanguage.ContextRegistry;
35  import org.slf4j.Logger;
36  import org.slf4j.LoggerFactory;
37  
38  import java.util.HashMap;
39  import java.util.List;
40  import java.util.Map;
41  
42  /**
43   * This class translates requirement components into a specific
44   * natural language. This class is not thread safe.
45   */
46  public class PropositionNaturalLanguageTemplater implements NaturalLanguageTemplaterContract {
47      /**
48       * SLF4J logging framework
49       */
50      private final static Logger logger = LoggerFactory.getLogger(PropositionNaturalLanguageTemplater.class);
51  
52      private ContextRegistry<Context> contextRegistry;
53  
54      private KrmsTypeRepositoryService krmsTypeRepositoryService = new KrmsTypeRepositoryServiceImpl();
55  
56      /**
57       * Relational operator token.
58       */
59      public final static String OPERATOR_TOKEN = "relationalOperator";
60      /**
61       * An integer value token.
62       */
63      public final static String CONSTANT_VALUE_TOKEN = "intValue";
64  
65      /**
66       * Velocity template engine.
67       */
68      private VelocityTemplateEngine templateEngine = new VelocityTemplateEngine();
69  
70  
71      /**
72       * Constructs a new proposition natural language templater.
73       */
74      public PropositionNaturalLanguageTemplater() {
75      }
76  
77  
78      /**
79       * Sets the template context registry.
80       *
81       * @param contextRegistry Template context registry
82       */
83      public void setContextRegistry(final ContextRegistry<Context> contextRegistry) {
84          this.contextRegistry = contextRegistry;
85      }
86  
87      public String translate(NaturalLanguageTemplate naturalLanguageTemplate, Map<String, Object> parametersMap) {
88  
89          if (naturalLanguageTemplate == null) {
90              return StringUtils.EMPTY;
91          }
92  
93          Map<String, Object> contextMap = null;
94          try {
95              contextMap = buildContextMap(naturalLanguageTemplate.getTypeId(), parametersMap);
96          } catch (Exception e) {
97              e.printStackTrace();  //TODO hand back to service.
98          }
99  
100         try {
101             String nl = this.templateEngine.evaluate(contextMap, naturalLanguageTemplate.getTemplate());
102             if (logger.isInfoEnabled()) {
103                 logger.info("nl=" + nl);
104             }
105             return nl;
106         } catch (VelocityException e) {
107             String msg = "Generating template for proposition failed: template='" + naturalLanguageTemplate.getTemplate() + "', contextMap=" + contextMap;
108             logger.error(msg, e);
109             //TODO hand back to service throw new Exception(msg);
110         }
111         return "Error";
112     }
113 
114     /**
115      * Builds a proposition type context map.
116      *
117      * @param typeId        the natural language template id
118      * @param parametersMap map containing the proposition parameter types and their values
119      * @throws java.lang.Exception Creating context map failed
120      */
121     private Map<String, Object> buildContextMap(String typeId, Map<String, Object> parametersMap) throws Exception {
122 
123         Map<String, Object> contextMap = new HashMap<String, Object>();
124         //Add proposition constant to contextMap.
125         if (parametersMap.containsKey(PropositionParameterType.CONSTANT.getCode())) {
126             contextMap.put(CONSTANT_VALUE_TOKEN, (String) parametersMap.get(PropositionParameterType.CONSTANT.getCode()));
127         }
128         //Add proposition operator to contextMap.
129         if (parametersMap.containsKey(PropositionParameterType.OPERATOR.getCode())) {
130             contextMap.put(OPERATOR_TOKEN, (String) parametersMap.get(PropositionParameterType.OPERATOR.getCode()));
131         }
132         //Access type service to retrieve type name.
133         KrmsTypeDefinitionContract type = getKrmsTypeRepositoryService().getTypeById(typeId);
134         List<Context> contextList = this.contextRegistry.get(type.getName());
135         if (contextList == null || contextList.isEmpty()) {
136             return contextMap;
137         }
138 
139         for (Context context : contextList) {
140             Map<String, Object> cm = context.createContextMap(parametersMap, new org.kuali.student.r2.common.dto.ContextInfo());  // KS contextInfo is not passed through here
141             contextMap.putAll(cm);
142         }
143 
144         if (logger.isInfoEnabled()) {
145             logger.info("contextMap=" + contextMap);
146         }
147         return contextMap;
148     }
149 
150 
151     private KrmsTypeRepositoryService getKrmsTypeRepositoryService() {
152         return krmsTypeRepositoryService;
153     }
154 
155     public void setKrmsTypeRepositoryService(KrmsTypeRepositoryService krmsTypeRepositoryService) {
156         this.krmsTypeRepositoryService = krmsTypeRepositoryService;
157     }
158 
159 }