Downloads Documentation Community Contribute Demo






Show Sidebar
Login | Register

Ticket #969: manual.diff

File manual.diff, 57.1 kB (added by nribeka, 9 months ago)

part of the diff for this ticket

  • metadata/api/hibernate/org/openmrs/logic/db/hibernate/TokenTag.hbm.xml

    old new  
     1<?xml version="1.0"?> 
     2<!DOCTYPE hibernate-mapping PUBLIC 
     3    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
     4    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > 
     5 
     6<hibernate-mapping package="org.openmrs"> 
     7 
     8        <class name="org.openmrs.logic.TokenTag" table="logic_token_tag" batch-size="25"> 
     9 
     10                <id name="tokenTagId" type="int" column="logic_token_tag_id"> 
     11                        <generator class="native" /> 
     12                </id> 
     13                 
     14                <property name="tag" type="java.lang.String" length="50" not-null="true" /> 
     15                <property name="description" type="java.lang.String" length="65535" not-null="true" /> 
     16 
     17 
     18 
     19                <!--  Metadata -->               
     20                <property name="dateCreated" type="java.util.Date" column="date_created" not-null="true"/> 
     21 
     22                <many-to-one name="creator" class="User" column="creator" not-null="true"/> 
     23                 
     24                <property name="voided" type="java.lang.Boolean" column="voided" 
     25                        length="1" not-null="true" /> 
     26                         
     27                <property name="dateVoided" type="java.util.Date" 
     28                        column="date_voided" length="19" /> 
     29                         
     30                <property name="voidReason" type="java.lang.String" 
     31                        column="void_reason" length="255" /> 
     32                         
     33                <many-to-one name="voidedBy" class="User" column="voided_by" /> 
     34                 
     35        </class> 
     36         
     37</hibernate-mapping> 
  • metadata/api/hibernate/org/openmrs/logic/db/hibernate/TokenDefinition.hbm.xml

    old new  
     1<?xml version="1.0"?> 
     2<!DOCTYPE hibernate-mapping PUBLIC 
     3    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
     4    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > 
     5 
     6<hibernate-mapping package="org.openmrs"> 
     7 
     8        <class name="org.openmrs.logic.TokenDefinition" table="logic_token_definition" lazy="false"> 
     9 
     10                <id name="tokenDefinitionId" type="int" column="logic_token_definition_id" unsaved-value="0"> 
     11                        <generator class="native" /> 
     12                </id> 
     13 
     14                <discriminator column="logic_token_definition_id" insert="false" /> 
     15                 
     16                <property name="token" type="java.lang.String" 
     17                        length="255" not-null="true"/> 
     18                         
     19                <property name="serializedRule" type="java.lang.String" column="serialized_rule"  
     20                        length="65535" not-null="true"/> 
     21 
     22                <set name="tags" lazy="true" table="logic_token_tag" cascade="save-update"> 
     23                        <key column="logic_token_definition_id" not-null="true"/> 
     24                        <one-to-many class="org.openmrs.logic.TokenTag"/> 
     25                </set>                   
     26        </class>         
     27</hibernate-mapping> 
  • metadata/api/hibernate/hibernate.cfg.xml

    old new  
    5858                <mapping resource="org/openmrs/api/db/hibernate/PatientState.hbm.xml" /> 
    5959                <mapping resource="org/openmrs/api/db/hibernate/Cohort.hbm.xml" /> 
    6060 
     61                <!-- Logic --> 
     62                <mapping resource="org/openmrs/logic/db/hibernate/TokenTag.hbm.xml" /> 
     63                <mapping resource="org/openmrs/logic/db/hibernate/TokenDefinition.hbm.xml" /> 
     64 
    6165                <!-- HL7 --> 
    6266                <mapping resource="org/openmrs/hl7/db/hibernate/HL7Source.hbm.xml" /> 
    6367                <mapping resource="org/openmrs/hl7/db/hibernate/HL7InQueue.hbm.xml" /> 
  • metadata/api/spring/applicationContext-service.xml

    old new  
    154154        </bean> 
    155155 
    156156        <!-- *************************** LOGIC SERVICE ************************* --> 
    157          
     157        <bean id="logicDAO" class="org.openmrs.logic.db.hibernate.HibernateLogicDAO"> 
     158                <property name="sessionFactory"><ref bean="sessionFactory"/></property>  
     159        </bean>  
    158160        <bean id="logicObsDAO" class="org.openmrs.logic.db.hibernate.HibernateLogicObsDAO"> 
    159161                <property name="sessionFactory"><ref bean="sessionFactory"/></property>  
    160162        </bean> 
     
    175177        </bean> 
    176178        <bean id="logicProgramDataSource" class="org.openmrs.logic.datasource.ProgramDataSource"> 
    177179        </bean> 
     180        <bean id="ruleFactoryTarget" class="org.openmrs.logic.RuleFactory"> 
     181                <property name="logicDAO"><ref bean="logicDAO"></ref></property> 
     182        </bean> 
    178183 
    179184        <!--  **************************  SCHEDULER SERVICE  *************************  --> 
    180185        <!--  
     
    312317                                <entry key="program"><ref bean="logicProgramDataSource" /></entry> 
    313318                        </map> 
    314319                </property> 
     320                <property name="ruleFactory"><ref bean="ruleFactory"/></property>        
    315321        </bean> 
    316322        <!-- /Logic Service and Logic Data Source setup --> 
    317323         
     
    622628                        <bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"/> 
    623629                </property> 
    624630        </bean> 
    625          
     631        <bean id="ruleFactory" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> 
     632                <property name="transactionManager"><ref local="transactionManager"/></property> 
     633                <property name="target"><ref local="ruleFactoryTarget"/></property> 
     634                <property name="preInterceptors"> 
     635                        <list> 
     636                                <ref local="authorizationInterceptor"/> 
     637                                <ref local="loggingInterceptor"/> 
     638                        </list> 
     639                </property> 
     640                <property name="transactionAttributeSource"> 
     641                        <bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource"/> 
     642                </property> 
     643        </bean> 
    626644        <bean id="messageSourceService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> 
    627645                <property name="transactionManager"><ref local="transactionManager"/></property> 
    628646                <property name="target"><ref local="messageSourceServiceTarget"/></property> 
  • src/api/org/openmrs/logic/RuleFactory.java

    old new  
    1313 */ 
    1414package org.openmrs.logic; 
    1515 
    16 import java.util.ArrayList; 
    1716import java.util.HashMap; 
    1817import java.util.HashSet; 
    19 import java.util.List; 
    2018import java.util.Map; 
    2119import java.util.Set; 
    2220 
    2321import org.apache.commons.logging.Log; 
    2422import org.apache.commons.logging.LogFactory; 
    25 import org.openmrs.Concept; 
    26 import org.openmrs.ConceptClass; 
    27 import org.openmrs.api.context.Context; 
    28 import org.openmrs.logic.datasource.ObsDataSource; 
     23import org.openmrs.logic.db.LogicDAO; 
    2924import org.openmrs.logic.result.Result.Datatype; 
    30 import org.openmrs.logic.rule.AgeRule; 
    31 import org.openmrs.logic.rule.HIVPositiveRule; 
    3225import org.openmrs.logic.rule.ReferenceRule; 
    3326import org.openmrs.logic.rule.RuleParameterInfo; 
    3427 
     
    4336 * @see org.openmrs.logic.datasource.LogicDataSource 
    4437 */ 
    4538public class RuleFactory { 
     39         
     40        // ***************** 
     41        // Private variables 
     42        // ***************** 
     43         
     44        /** Logger */ 
     45    protected final static Log log = LogFactory.getLog(RuleFactory.class); 
    4646 
    47     protected final Log log = LogFactory.getLog(getClass()); 
     47    /** Logic data access object. */ 
     48    private LogicDAO logicDao; 
     49     
     50    /** Used to serialize rules for persistence. */ 
     51    private RuleSerializer serializer = new RuleSerializer(); 
     52     
     53    /** Contains a registry of all registered rules and tokens. */ 
     54    private TokenRegistry tokenRegistry = null; 
    4855 
    49     /** 
    50      * Maps tokens to instances of rules.  Do not use this directly; 
    51      * instead, call getRuleMap() 
    52      */ 
    53     private Map<String, Rule> ruleMap = null; 
    54  
    55     /** 
    56      * Maps tokens to 1-n tags 
    57      */ 
     56    /** Maps tokens to 1-n tags */ 
    5857    private Map<String, Set<String>> tagsByToken = new HashMap<String, Set<String>>(); 
    5958 
    60     /** 
    61      * Maps tags to 1-n tokens (inverse of the tagsByToken, maintained for 
    62      * speedy lookups) 
    63      */ 
     59    /** Maps tags to 1-n tokens (inverse of the tagsByToken, maintained for speedy lookups) */ 
    6460    private Map<String, Set<String>> tokensByTag = new HashMap<String, Set<String>>(); 
    65  
     61     
     62        // ***************** 
     63        // Constructors 
     64        // ***************** 
     65     
     66    /** Default constructor */ 
     67    public RuleFactory() { } 
     68     
     69        // ***************** 
     70        // Instance methods 
     71        // ***************** 
     72     
    6673    /** 
    67      * Default constructor 
    68      */ 
    69     public RuleFactory() { 
    70     } 
    71  
    72     private synchronized Map<String, Rule> getRuleMap() { 
    73         if (ruleMap == null) { 
    74                 ruleMap = new HashMap<String, Rule>(); 
    75                 init(); 
    76         } 
    77         return ruleMap; 
    78     } 
    79     /** 
    80      *  
    81      * Internal initialization. Used as a hack to get some rules registered for 
    82      * testing as the logic service is being developed. This method should be 
    83      * replaced by external initialization steps to register concepts and other 
    84      * sources of rules 
    85      *  
    86      */ 
    87     public void init() { 
    88         // TODO: temporary cheat to get some stuff loaded 
    89         try { 
    90                 ObsDataSource obsdatasource = (ObsDataSource) Context.getLogicService().getLogicDataSource("obs"); 
    91             // TODO this is temporary; it should be read from persistent storage 
    92                 ArrayList<String> classes = new ArrayList<String>(); 
    93                 classes.add("Test"); 
    94                 classes.add("Finding"); 
    95                 classes.add("Question"); 
    96                  
    97                 for (String currClass : classes) { 
    98                                 ConceptClass cc = Context.getConceptService() 
    99                                                          .getConceptClassByName(currClass); 
    100                                 List<Concept> classConcepts = Context.getConceptService() 
    101                                                                     .getConceptsByClass(cc); 
    102                                 for (Concept c : classConcepts) { 
    103                                         String name = c.getBestName(Context.getLocale()).getName(); 
    104                                         obsdatasource.addKey(name); 
    105                                         ruleMap.put(name, new ReferenceRule("obs." + name)); 
    106                                 } 
    107                         } 
    108                     
    109             ruleMap.put("HIV POSITIVE", new HIVPositiveRule()); 
    110             ruleMap.put("GENDER", getRule("%%person.gender")); 
    111             ruleMap.put("BIRTHDATE", getRule("%%person.birthdate")); 
    112             ruleMap.put("BIRTHDATE ESTIMATED", getRule("%%person.birthdate estimated")); 
    113             ruleMap.put("DEAD", getRule("%%person.dead")); 
    114             ruleMap.put("DEATH DATE", getRule("%%person.death date")); 
    115             ruleMap.put("CAUSE OF DEATH", getRule("%%person.cause of death")); 
    116             ruleMap.put("AGE", new AgeRule()); 
    117         } catch (LogicException e) { 
    118             log.error("Error during RuleFactory initialization", e); 
    119         } 
    120     } 
    121  
    122     /** 
    123      *  
    12474     * Gets the rule registered under a given token 
    125      *  
    12675     * @param token token under which the rule was registered 
    12776     * @return the rule registered with the given token 
    12877     * @throws LogicException 
    12978     */ 
    13079    public Rule getRule(String token) throws LogicException { 
    131         if (token == null) 
     80        if (token == null) { 
    13281                throw new LogicException("Token cannot be null"); 
    133          
    134         if (token.startsWith("%%")) 
     82        } 
     83        if (token.startsWith("%%")) { 
    13584            return new ReferenceRule(token.substring(2)); 
    136  
    137         if (!getRuleMap().containsKey(token)) 
     85        } 
     86        if (!getTokenRegistry().containsToken(token)) { 
    13887            throw new LogicException("No token \"" + token + "\" registered"); 
    139  
    140         return getRuleMap().get(token); 
     88        } 
     89        return getTokenRegistry().getRule(token); 
    14190    } 
    14291 
    14392    /** 
    144      *  
    14593     * Returns all known tokens 
    146      *  
    14794     * @return all known tokens 
    14895     */ 
    14996    public Set<String> getTokens() { 
    150         return getRuleMap().keySet(); 
     97        return getTokenRegistry().getAllTokens(); 
    15198    } 
    15299 
    153100    /** 
    154      *  
    155101     * Returns tokens containing a particular string 
    156      *  
    157102     * @param token lookup string 
    158103     * @return all tokens that contain the lookup string 
    159104     */ 
     
    167112    } 
    168113 
    169114    /** 
    170      *  
    171115     * Registers a rule under the given token 
    172      *  
    173116     * @param token token under which to register the rule 
    174117     * @param rule the rule to be registered 
    175118     * @throws LogicException 
    176119     */ 
    177     public void addRule(String token, Rule rule) throws LogicException { 
    178         if (getRuleMap().containsKey(token)) 
    179             throw new LogicException("Duplicate token \"" + token + "\""); 
    180         getRuleMap().put(token, rule); 
     120    public Rule addRule(String token, Rule rule) throws LogicException { 
     121        if (getTokenRegistry().containsToken(token)) { 
     122            throw new DuplicateTokenException("Duplicate token \"" + token + "\""); 
     123        } 
     124        saveTokenDefinition(token, rule); 
     125        return rule; 
    181126    } 
    182127 
    183128    /** 
    184      *  
    185129     * Updates a rule that was previously registered 
    186      *  
    187130     * @param token token under which the rule was originally registered 
    188131     * @param rule new instance of the rule to replace the current version 
    189132     * @throws LogicException 
    190133     */ 
    191     public void updateRule(String token, Rule rule) throws LogicException { 
    192         //don't throw an error when updating the rule 
    193         getRuleMap().put(token, rule)
     134    public Rule updateRule(String token, Rule rule) throws LogicException { 
     135        saveTokenDefinition(token, rule); 
     136        return rule
    194137    } 
    195138 
    196139    /** 
    197      *  
    198140     * Unregister a rule 
    199      *  
    200141     * @param token token under which the rule was registered 
    201142     * @throws LogicException 
    202143     */ 
    203144    public void removeRule(String token) throws LogicException { 
    204         if (getRuleMap().containsKey(token)) 
    205             getRuleMap().remove(token); 
    206         else 
    207             throw new LogicException("Cannot delete missing token \"" + token 
    208                     + "\""); 
     145        if (!getTokenRegistry().containsToken(token)) { 
     146               throw new LogicException("Cannot delete missing token \"" + token + "\""); 
     147        } 
     148        logicDao.deleteTokenDefinition(token); 
     149        getTokenRegistry().removeRule(token); 
    209150    } 
    210151 
    211152    /** 
    212      *  
    213153     * Registers a rule and, at the same time, assigns 1-to-n tags to the rule 
    214154     *  
    215155     * @param token unique token under which the rule will be registered. This 
     
    220160     * @param rule the rule being registered 
    221161     * @throws LogicException 
    222162     */ 
    223     public void addRule(String token, String[] tags, Rule rule) 
    224             throws LogicException { 
    225         for (int i = 0; i < tags.length; i++) 
     163    public Rule addRule(String token, String[] tags, Rule rule) throws LogicException { 
     164        for (int i = 0; i < tags.length; i++) { 
    226165            addTokenTag(token, tags[i]); 
    227         addRule(token, rule); 
     166        } 
     167        return addRule(token, rule); 
    228168    } 
    229169 
    230170    /** 
    231      *  
    232171     * Adds a tag to a previously registered token 
    233172     *  
    234173     * @param token previous registered token 
     
    246185    } 
    247186 
    248187    /** 
    249      *  
    250188     * Returns all tags that match a given string 
    251189     *  
    252190     * @param partialTag any tags containing this string will be returned 
    253191     * @return 
    254192     */ 
    255193    public Set<String> findTags(String partialTag) { 
    256  
    257194        Set<String> resultTags = new HashSet<String>(); 
    258195        for (String tag : tokensByTag.keySet()) { 
    259196            if (tag.contains(partialTag)) 
    260197                resultTags.add(tag); 
    261198        } 
    262  
    263199        return resultTags; 
    264200    } 
    265201 
    266202    /** 
    267      *  
    268203     * Returns all tags attached to a given token 
    269204     *  
    270205     * @param token all tags attached to this token will be returned 
     
    275210    } 
    276211 
    277212    /** 
    278      *  
    279213     * Returns all tokens related to a given tag 
    280214     *  
    281215     * @param tag all tokens that have been tagged with the given tag will be returned 
     
    286220    } 
    287221 
    288222    /** 
    289      *  
    290223     * Removes a tag from a token  
    291224     *  
    292225     * @param token token that was previously tagged 
    293226     * @param tag the tag to be removed from the token 
    294227     */ 
    295228    public void removeTokenTag(String token, String tag) { 
    296         if (tagsByToken.containsKey(token) 
    297                 && tagsByToken.get(token).contains(tag)) 
     229        if (tagsByToken.containsKey(token) && tagsByToken.get(token).contains(tag)) { 
    298230            tagsByToken.get(token).remove(tag); 
    299         if (tokensByTag.containsKey(tag) 
    300                 && tokensByTag.get(tag).contains(token)) 
     231        } 
     232        if (tokensByTag.containsKey(tag) && tokensByTag.get(tag).contains(token)) { 
    301233            tokensByTag.get(tag).remove(token); 
     234        } 
    302235    } 
    303236 
    304237    /** 
    305      *  
    306238     * Returns the default data type for a rule associated with a given token.  While results 
    307239     * are loosely typed, a default data type can be helpful in managing rules within a user 
    308240     * interface or providing defaults 
     
    311243     * @return 
    312244     */ 
    313245    public Datatype getDefaultDatatype(String token) { 
    314         if (getRuleMap().containsKey(token)) 
    315             return getRuleMap().get(token).getDefaultDatatype(); 
    316         return null; 
     246        if (getTokenRegistry().containsToken(token)) { 
     247                return getTokenRegistry().getRule(token).getDefaultDatatype(); 
     248        } 
     249        return null; 
    317250    } 
    318251 
    319252    /** 
    320      *  
    321253     * Returns the expected parameters for a given rule 
    322254     *  
    323255     * @param token token under which the rule was registered 
    324256     * @return 
    325257     */ 
    326258    public Set<RuleParameterInfo> getParameterList(String token) { 
    327         if (getRuleMap().containsKey(token)) 
    328             return getRuleMap().get(token).getParameterList(); 
    329         return null; 
     259        if (getTokenRegistry().containsToken(token)) { 
     260                return getTokenRegistry().getRule(token).getParameterList(); 
     261        } 
     262        return null; 
    330263    } 
     264     
     265        // ***************** 
     266        // Protected helper methods 
     267        // ***************** 
    331268 
     269    /* Returns the TokenRegistry, populating it from the database if needed */ 
     270    protected synchronized TokenRegistry getTokenRegistry() { 
     271        if (tokenRegistry == null) { 
     272                log.info("Populating token registry..."); 
     273                tokenRegistry = TokenRegistry.getInstance(); 
     274                        for (TokenDefinition td : logicDao.getAllTokenDefinitions()) { 
     275                                Rule r = serializer.deserializeRule(td.getSerializedRule()); 
     276                                tokenRegistry.registerRule(td.getToken(), r); 
     277                                log.info("Added token: " + td.getToken() + " for Rule: " + r); 
     278                        } 
     279        } 
     280        return tokenRegistry; 
     281    } 
     282 
     283    /* Saves a TokenDefinition to the database and updates the TokenRegistry */ 
     284    protected TokenDefinition saveTokenDefinition(String token, Rule rule) throws LogicException { 
     285        TokenDefinition tokenDefinition = logicDao.getTokenDefinition(token); 
     286        if (tokenDefinition == null) { 
     287                tokenDefinition = new TokenDefinition(); 
     288                tokenDefinition.setToken(token); 
     289        } 
     290        tokenDefinition.setSerializedRule(serializer.serializeRule(rule)); 
     291        logicDao.saveTokenDefinition(tokenDefinition); 
     292        getTokenRegistry().registerRule(token, rule); 
     293        return tokenDefinition; 
     294    } 
     295     
     296        // ***************** 
     297        // Property access methods 
     298        // ***************** 
     299     
     300    /** 
     301     * Sets the logic dao. 
     302     * @param logicDao 
     303     */ 
     304    public void setLogicDAO(LogicDAO logicDao) {  
     305        this.logicDao = logicDao; 
     306    } 
    332307} 
  • src/api/org/openmrs/logic/RuleSerializer.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic; 
     15 
     16import org.openmrs.api.context.Context; 
     17import org.openmrs.logic.datasource.LogicDataSource; 
     18 
     19import com.thoughtworks.xstream.XStream; 
     20import com.thoughtworks.xstream.converters.SingleValueConverter; 
     21import com.thoughtworks.xstream.io.xml.DomDriver; 
     22 
     23/** 
     24 * Provides a standard mechanism for serializing / deserializing 
     25 * between Rules and String representations for Rule persistence 
     26 */ 
     27public class RuleSerializer { 
     28         
     29        /** Default Constructor */ 
     30        public RuleSerializer() { 
     31                xstream = new XStream(new DomDriver()); 
     32                xstream.registerConverter(dataSourceConverter); 
     33        } 
     34 
     35        /** 
     36         * Returns a String representation of the passed Rule instance 
     37         * @param r - The Rule to serialize 
     38         * @return - a String representation of the passed Rule instance 
     39         */ 
     40        public String serializeRule(Rule r) { 
     41                return xstream.toXML(r); 
     42        } 
     43         
     44        /** 
     45         * Returns a Rule instance represented by the passed String 
     46         * @param s - The String which represents a serialized Rule 
     47         * @return - a Rule instance represented by the passed String 
     48         */ 
     49        public Rule deserializeRule(String s) { 
     50                return (Rule) xstream.fromXML(s); 
     51        } 
     52         
     53        /* 
     54         * Private serialization mechanism used by this class. 
     55         * This is abstracted in the event our serialization 
     56         * strategy changes in the future. 
     57         */ 
     58        private XStream xstream; 
     59         
     60        /* 
     61         * Converter responsible for serializing a LogicDataSource by referring to it by name 
     62         */ 
     63        private SingleValueConverter dataSourceConverter = new SingleValueConverter() { 
     64                 
     65                @SuppressWarnings("unchecked") 
     66                public boolean canConvert(Class clazz) { 
     67                        return LogicDataSource.class.isAssignableFrom(clazz); 
     68                } 
     69                 
     70                public String toString(Object o) { 
     71                        LogicDataSource ds = (LogicDataSource)o; 
     72                        for (String dataSourceKey : Context.getLogicService().getLogicDataSources().keySet()) { 
     73                                LogicDataSource lds = Context.getLogicService().getLogicDataSources().get(dataSourceKey); 
     74                                if (ds.equals(lds)) { 
     75                                        return dataSourceKey; 
     76                                } 
     77                        } 
     78                        return null; 
     79                } 
     80                 
     81                public Object fromString(String dataSourceKey) { 
     82                        return Context.getLogicService().getLogicDataSources().get(dataSourceKey); 
     83                } 
     84        }; 
     85} 
  • src/api/org/openmrs/logic/db/LogicDAO.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic.db; 
     15 
     16import java.util.List; 
     17 
     18import org.openmrs.api.db.DAOException; 
     19import org.openmrs.logic.TokenDefinition; 
     20 
     21/** 
     22 * Logic-related database functions 
     23 */ 
     24public interface LogicDAO { 
     25         
     26        /** 
     27         * Saves the passed tokenDefinition to the database 
     28         *  
     29         * @param tokenDefinition, the TokenDefinition to be saved 
     30         * @throws DAOException 
     31         */ 
     32        public TokenDefinition saveTokenDefinition(TokenDefinition tokenDefinition) throws DAOException; 
     33 
     34        /** 
     35         * Purge the passed tokenDefinition from database. 
     36         *  
     37         * @param tokenDefinition, the TokenDefinition to be purged 
     38         */ 
     39        public void deleteTokenDefinition(TokenDefinition tokenDefinition) throws DAOException; 
     40         
     41        /** 
     42         * Purge the tokenDefinition matching the given token from database. 
     43         *  
     44         * @param token, the token to purge 
     45         */ 
     46        public void deleteTokenDefinition(String token) throws DAOException; 
     47 
     48        /** 
     49         * Get TokenDefinition for the passed Token 
     50         *  
     51         * @return TokenDefinition that matches the passed token 
     52         * @throws DAOException 
     53         */ 
     54    public TokenDefinition getTokenDefinition(String token) throws DAOException; 
     55         
     56        /** 
     57         * Get all TokenDefinitions 
     58         *  
     59         * @return List<TokenDefinition> containing all registered TokenDefinitions 
     60         * @throws DAOException 
     61         */ 
     62    public List<TokenDefinition> getAllTokenDefinitions() throws DAOException; 
     63     
     64} 
  • src/api/org/openmrs/logic/db/hibernate/HibernateLogicDAO.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic.db.hibernate; 
     15 
     16import java.util.List; 
     17 
     18import org.apache.commons.logging.Log; 
     19import org.apache.commons.logging.LogFactory; 
     20import org.hibernate.Criteria; 
     21import org.hibernate.SessionFactory; 
     22import org.hibernate.criterion.Expression; 
     23import org.hibernate.criterion.Order; 
     24import org.openmrs.api.db.DAOException; 
     25import org.openmrs.logic.TokenDefinition; 
     26import org.openmrs.logic.db.LogicDAO; 
     27import org.springframework.transaction.annotation.Transactional; 
     28 
     29/** 
     30 * Hibernate Implementation of Logic-related database functions 
     31 */ 
     32@Transactional 
     33public class HibernateLogicDAO implements LogicDAO { 
     34 
     35        protected final Log log = LogFactory.getLog(getClass()); 
     36 
     37        // ************** 
     38        // Properties 
     39        // ************** 
     40 
     41        protected SessionFactory sessionFactory; 
     42         
     43        // ************** 
     44        // Constructors 
     45        // ************** 
     46        public HibernateLogicDAO() {} 
     47         
     48        // ************** 
     49        // Instance methods 
     50        // ************** 
     51         
     52    /** 
     53     * @see org.openmrs.logic.db.LogicDAO#deleteTokenDefinition(TokenDefinition) 
     54     */ 
     55        public void deleteTokenDefinition(TokenDefinition tokenDefinition) throws DAOException { 
     56                sessionFactory.getCurrentSession().delete(tokenDefinition); 
     57    } 
     58         
     59    /** 
     60     * @see org.openmrs.logic.db.LogicDAO#deleteTokenDefinition(String) 
     61     */ 
     62        public void deleteTokenDefinition(String token) throws DAOException { 
     63                TokenDefinition td = getTokenDefinition(token); 
     64                if (td != null) { 
     65                        deleteTokenDefinition(td); 
     66                } 
     67    } 
     68 
     69    /** 
     70     * @see org.openmrs.logic.db.LogicDAO#saveTokenDefinition(TokenDefinition) 
     71     */ 
     72        public TokenDefinition saveTokenDefinition(TokenDefinition tokenDefinition) throws DAOException { 
     73                sessionFactory.getCurrentSession().saveOrUpdate(tokenDefinition); 
     74                return tokenDefinition; 
     75    } 
     76         
     77    /** 
     78     * @see org.openmrs.logic.db.LogicDAO#getTokenDefinition(String) 
     79     */ 
     80        public TokenDefinition getTokenDefinition(String token) throws DAOException { 
     81                Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TokenDefinition.class); 
     82                criteria.add(Expression.eq("token", token)); 
     83                return (TokenDefinition) criteria.uniqueResult(); 
     84        } 
     85         
     86    /** 
     87     * @see org.openmrs.logic.db.LogicDAO#getAllTokenDefinitions() 
     88     */ 
     89        @SuppressWarnings("unchecked") 
     90        public List<TokenDefinition> getAllTokenDefinitions() throws DAOException { 
     91                Criteria criteria = sessionFactory.getCurrentSession().createCriteria(TokenDefinition.class).addOrder(Order.asc("token")); 
     92                return criteria.list(); 
     93        } 
     94 
     95        // ************** 
     96        // Property methods 
     97        // ************** 
     98        /** 
     99         * Set session factory 
     100         * @param sessionFactory 
     101         */ 
     102        public void setSessionFactory(SessionFactory sessionFactory) { 
     103                this.sessionFactory = sessionFactory; 
     104        } 
     105         
     106} 
  • src/api/org/openmrs/logic/TokenRegistry.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic; 
     15 
     16import java.util.HashMap; 
     17import java.util.Map; 
     18import java.util.Set; 
     19 
     20/** 
     21 * Provides a standard mechanism for storing and accessing 
     22 * all registered tokens and the Rules that they represent 
     23 */ 
     24public class TokenRegistry { 
     25         
     26        // ***************** 
     27        // Static methods 
     28        // ***************** 
     29         
     30        /* The private static instance of the singleton token registry */ 
     31        private static TokenRegistry underlyingRegistry = null; 
     32         
     33        /** Returns the default, singleton access to the TokenRegistry */ 
     34        public synchronized static TokenRegistry getInstance() { 
     35                if (underlyingRegistry == null) { 
     36                        underlyingRegistry = new TokenRegistry(); 
     37                } 
     38                return underlyingRegistry; 
     39        } 
     40         
     41        /** 
     42         * Returns a normalized token for the passed String 
     43         * @param input - The input string to convert to a valid token 
     44         * @return - A valid token for the passed input string 
     45         */ 
     46        public static String convertToToken(String input) { 
     47                return (input == null ? null : input.toString().trim().toUpperCase()); 
     48        } 
     49         
     50        // ***************** 
     51        // Instance methods 
     52        // ***************** 
     53         
     54        /* The private instance of the underlying registry Map */ 
     55        private Map<String, Rule> underlyingMap = new HashMap<String, Rule>(); 
     56         
     57        /* The private synchronized accessor for the underlying registry Map */ 
     58        private synchronized Map<String, Rule> getUnderlyingMap() { 
     59                return underlyingMap; 
     60        } 
     61         
     62        /* Default constructor is made private to ensure access occurs through singleton */ 
     63        private TokenRegistry() {} 
     64         
     65        /** 
     66         * Returns true if the registry contains this token 
     67         * @param token - the token to lookup 
     68         * @return true if the registry contains this token 
     69         */ 
     70        public boolean containsToken(String token) { 
     71            return getUnderlyingMap().containsKey(convertToToken(token)); 
     72        } 
     73         
     74        /** 
     75         * Returns all registered tokens 
     76         */ 
     77        public Set<String> getAllTokens() { 
     78            return getUnderlyingMap().keySet(); 
     79        } 
     80         
     81        /** 
     82         * Returns the Rule that is registered with the passed token, 
     83         * or null if no Rule is registered. 
     84         * @param token - the token to lookup 
     85         * @return - the Rule that is registered to the passed token 
     86         */ 
     87        public Rule getRule(String token) { 
     88                return getUnderlyingMap().get(convertToToken(token)); 
     89        } 
     90         
     91        /** 
     92         * Registers the passed Rule with the passed token. 
     93         * This overwrites any previously registered Rule for the same token 
     94         * @param token - the token to register 
     95         * @param rule - the Rule to register 
     96         */ 
     97        public void registerRule(String token, Rule rule) { 
     98                getUnderlyingMap().put(convertToToken(token), rule); 
     99        } 
     100         
     101        /** 
     102         * Un-registers the Rule that is registered with the passed token 
     103         * @param token - the token to lookup 
     104         */ 
     105        public void removeRule(String token) { 
     106                getUnderlyingMap().remove(convertToToken(token)); 
     107        } 
     108         
     109        /** 
     110         * Throws an exception if cloning is attempted to ensure singleton is maintained 
     111         */ 
     112        public Object clone() throws CloneNotSupportedException { 
     113                throw new CloneNotSupportedException();  
     114        } 
     115} 
  • src/api/org/openmrs/logic/TokenTag.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic; 
     15 
     16import java.util.Date; 
     17 
     18import org.openmrs.User; 
     19 
     20/** 
     21 * TokenTag is a textual tag which can be applied to a logic token.  Tags 
     22 * allow us to categorize tokens together in logical groups, like Patient  
     23 * Demographics, Observations, Lab tests, etc. 
     24 *  
     25 */ 
     26public class TokenTag implements java.io.Serializable { 
     27 
     28        public static final long serialVersionUID = 33226787L; 
     29 
     30        // Fields 
     31        private Integer tokenTagId; 
     32        private String tag; 
     33        private String description; 
     34        private User creator; 
     35        private Date dateCreated; 
     36        private Boolean voided = false; 
     37        private User voidedBy; 
     38        private Date dateVoided; 
     39        private String voidReason; 
     40         
     41        // Constructors 
     42 
     43        /**  
     44         * Default constructor. 
     45         */ 
     46        public TokenTag() { } 
     47 
     48        /** 
     49         * Public constructor. Use factory methods to obtain 
     50         * copies of the desired tags.  
     51         *  
     52         * @param tag 
     53         * @param description 
     54         */ 
     55        public TokenTag(String tag, String description) { 
     56                setTag(tag); 
     57                setDescription(description); 
     58        } 
     59 
     60        public boolean equals(Object obj) { 
     61                if (!(obj instanceof TokenTag)) { 
     62                        return false; 
     63                } 
     64                TokenTag rhs = (TokenTag)obj; 
     65                 
     66                return (this.tokenTagId == rhs.tokenTagId); 
     67        } 
     68 
     69        public int hashCode() { 
     70                if (this.getTag() == null) 
     71                        return super.hashCode(); 
     72                int hash = 3; 
     73                hash = hash + 31 * this.getTag().hashCode(); 
     74                return hash; 
     75        } 
     76 
     77        // Property accessors 
     78 
     79         
     80 
     81        /** 
     82         * @return the token tag id 
     83         */ 
     84        public Integer getTokenTagId() { 
     85                return tokenTagId; 
     86        } 
     87 
     88        /** 
     89         * @param tokenTagId the token tag id to set 
     90         */ 
     91        public void setTokenTagId(Integer tokenTagId) { 
     92                this.tokenTagId = tokenTagId; 
     93        } 
     94         
     95        /** 
     96         * Returns the textual representation of this token tag. 
     97         *  
     98         * @return the textual representation of this token tag. 
     99         */ 
     100        public String getTag() { 
     101                return tag; 
     102        } 
     103 
     104        /** 
     105         * Sets the textual representation of this token tag. 
     106         *  
     107         * @param tag the textual representation 
     108         */ 
     109        public void setTag(String tag) { 
     110                this.tag = tag; 
     111        } 
     112 
     113        /** 
     114         * Returns the description of this tag. 
     115         *  
     116         * @return the description of this tag 
     117         */ 
     118        public String getDescription() { 
     119                return description; 
     120        } 
     121 
     122        /** 
     123         * Sets the description of this tag. 
     124         *  
     125         * @param description 
     126         */ 
     127        public void setDescription(String description) { 
     128                this.description = description; 
     129        } 
     130 
     131        /** 
     132         * @return Returns the creator. 
     133         */ 
     134        public User getCreator() { 
     135                return creator; 
     136        } 
     137 
     138        /** 
     139         * @param creator The creator to set. 
     140         */ 
     141        public void setCreator(User creator) { 
     142                this.creator = creator; 
     143        } 
     144 
     145        /** 
     146         * @return Returns the dateCreated. 
     147         */ 
     148        public Date getDateCreated() { 
     149                return dateCreated; 
     150        } 
     151 
     152        /** 
     153         * @param dateCreated The dateCreated to set. 
     154         */ 
     155        public void setDateCreated(Date dateCreated) { 
     156                this.dateCreated = dateCreated; 
     157        } 
     158 
     159        /** 
     160         * Returns whether the token tag has been voided. 
     161         *  
     162         * @return true if the token tag has been voided, false otherwise. 
     163         */ 
     164        public Boolean isVoided() { 
     165                return voided; 
     166        } 
     167 
     168        /** 
     169         * Returns whether the token tag has been voided. 
     170         *  
     171         * @return true if the token tag has been voided, false otherwise. 
     172         */ 
     173        public Boolean getVoided() { 
     174                return isVoided(); 
     175        } 
     176 
     177        /** 
     178         * Sets the voided status of the token tag. 
     179         *  
     180         * @param voided the voided status to set. 
     181         */ 
     182        public void setVoided(Boolean voided) { 
     183                this.voided = voided; 
     184        } 
     185 
     186        /** 
     187         * Returns the User who voided this token tag. 
     188         *  
     189         * @return the User who voided this token tag, or null if not set 
     190         */ 
     191        public User getVoidedBy() { 
     192                return voidedBy; 
     193        } 
     194 
     195        /** 
     196         * Sets the User who voided this token tag. 
     197         *  
     198         * @param voidedBy the user who voided this token tag. 
     199         */ 
     200        public void setVoidedBy(User voidedBy) { 
     201                this.voidedBy = voidedBy; 
     202        } 
     203 
     204        /** 
     205         * Returns the Date this token tag was voided. 
     206         *  
     207         * @return the Date this token tag was voided. 
     208         */ 
     209        public Date getDateVoided() { 
     210                return dateVoided; 
     211        } 
     212 
     213        /** 
     214         * Sets the Data this token tag was voided. 
     215         *  
     216         * @param dateVoided the date the token tag was voided. 
     217         */ 
     218        public void setDateVoided(Date dateVoided) { 
     219                this.dateVoided = dateVoided; 
     220        } 
     221 
     222        /** 
     223         * Returns the reason this token tag was voided. 
     224         *  
     225         * @return the reason this token tag was voided 
     226         */ 
     227        public String getVoidReason() { 
     228                return voidReason; 
     229        } 
     230 
     231        /** 
     232         * Sets the reason this token tag was voided. 
     233         *  
     234         * @param voidReason the reason this token tag was voided 
     235         */ 
     236        public void setVoidReason(String voidReason) { 
     237                this.voidReason = voidReason; 
     238        } 
     239 
     240        public String toString() { 
     241                return this.tag; 
     242        } 
     243 
     244 
     245 
     246} 
  • src/api/org/openmrs/logic/LogicService.java

    old new  
    9797         *  
    9898         * @param token the lookup key ("token") for this rule 
    9999         * @param rule new rule to be registered 
     100         * @return Rule - the Rule which has been added 
    100101         * @throws LogicException 
    101102         * @see org.openmrs.logic.Rule 
    102103         */ 
    103         public void addRule(String token, Rule rule) throws LogicException; 
     104        public Rule addRule(String token, Rule rule) throws LogicException; 
     105         
     106        /** 
     107         *  
     108         * Registers a new rule with the logic service. 
     109         *  
     110         * @param token the lookup key ("token") for this rule 
     111         * @param ruleClass the Rule class to register. 
     112         * @return Rule - the Rule which has been added 
     113         * @throws LogicException 
     114         * @see org.openmrs.logic.Rule 
     115         */ 
     116    public Rule addRule(String token, Class<? extends Rule> ruleClass) throws LogicException; 
    104117 
    105118        /** 
    106119         *  
     
    108121         * the given token 
    109122         *  
    110123         * @param token the unique lookup key ("token") for this rule 
    111          * @param tags words or phrases associated with this token (do not need to 
    112          *        be unique) 
     124         * @param tags words or phrases associated with this token (do not need to be unique) 
    113125         * @param rule new rule to be registered 
     126         * @return Rule - the Rule which has been added 
    114127         * @throws LogicException 
    115128         */ 
    116         public void addRule(String token, String[] tags, Rule rule) 
    117                 throws LogicException; 
     129        public Rule addRule(String token, String[] tags, Rule rule) throws LogicException; 
     130         
     131        /** 
     132         *  
     133         * Registers a new rule with the logic service, associating the tags with 
     134         * the given token 
     135         *  
     136         * @param token the unique lookup key ("token") for this rule 
     137         * @param tags words or phrases associated with this token (do not need to be unique) 
     138         * @param ruleClass the Rule class to register. 
     139         * @return Rule - the Rule which has been added 
     140         * @throws LogicException 
     141         */ 
     142        public Rule addRule(String token, String[] tags, Class<? extends Rule> ruleClass) throws LogicException; 
    118143 
    119144        /** 
    120145         *  
     
    376401         * @param name name of the logic data source to be unregistered 
    377402         */ 
    378403        public void removeLogicDataSource(String name); 
    379  
    380     public void loadRule(String tokenName,String ruleClassName) throws Exception; 
    381404     
    382405    public LogicCriteria parseString(String inStr); 
    383406Index: src/api/org/openmrs/logic/impl/LogicServiceImpl.java 
  • src/api/org/openmrs/logic/impl/LogicServiceImpl.java

    old new  
    6464    private RuleFactory ruleFactory; 
    6565     
    6666    private static Map<String, LogicDataSource> dataSources; 
    67  
     67     
    6868    /** 
    6969     * Default constructor. Creates a new RuleFactory (and populates it) 
    7070     */ 
    71     public LogicServiceImpl() { 
    72         ruleFactory = new RuleFactory(); 
    73     } 
    74  
     71    public LogicServiceImpl() {} 
     72     
    7573    /** 
    7674     * @see org.openmrs.logic.LogicService#getTokens() 
    7775     */ 
     
    8987    /** 
    9088     * @see org.openmrs.logic.LogicService#addRule(java.lang.String, org.openmrs.logic.Rule) 
    9189     */ 
    92     public void addRule(String token, Rule rule) throws LogicException { 
    93         ruleFactory.addRule(token, rule); 
     90    public Rule addRule(String token, Rule rule) throws LogicException { 
     91        return ruleFactory.addRule(token, rule); 
    9492    } 
     93     
     94    /** 
     95     * @see org.openmrs.logic.LogicService#addRule(java.lang.String, Class<org.openmrs.logic.Rule>) 
     96     */ 
     97    public Rule addRule(String token, Class<? extends Rule> ruleClass) throws LogicException { 
     98        Rule rule = null; 
     99            try { 
     100                rule = ruleClass.newInstance(); 
     101            } 
     102            catch (Exception e) { 
     103                throw new LogicException("Unable to instantiate Rule class: " + ruleClass, e); 
     104            } 
     105            return ruleFactory.addRule(token, rule); 
     106    } 
    95107 
    96108    /** 
    97109     * @see org.openmrs.logic.LogicService#getRule(java.lang.String) 
     
    211223    /** 
    212224     * @see org.openmrs.logic.LogicService#addRule(java.lang.String, java.lang.String[], org.openmrs.logic.rule.Rule) 
    213225     */ 
    214     public void addRule(String token, String[] tags, Rule rule) throws LogicException { 
    215         ruleFactory.addRule(token, tags, rule); 
     226    public Rule addRule(String token, String[] tags, Rule rule) throws LogicException { 
     227        return ruleFactory.addRule(token, tags, rule); 
    216228    } 
     229     
     230    /** 
     231     * @see org.openmrs.logic.LogicService#addRule(java.lang.String, java.lang.String[], Class<org.openmrs.logic.rule.Rule>) 
     232     */ 
     233    public Rule addRule(String token, String[] tags, Class<? extends Rule> ruleClass) throws LogicException { 
     234        Rule rule = null; 
     235            try { 
     236                rule = ruleClass.newInstance(); 
     237            } 
     238            catch (Exception e) { 
     239                throw new LogicException("Unable to instantiate Rule class: " + ruleClass, e); 
     240            } 
     241        return ruleFactory.addRule(token, tags, rule); 
     242    } 
    217243 
    218244    /** 
    219245     * @see org.openmrs.logic.LogicService#addTokenTag(java.lang.String, java.lang.String) 
     
    360386                        return null; 
    361387                    }    
    362388        } 
     389     
     390    /** 
     391     * Sets the RuleFactory 
     392     * @param ruleFactory 
     393     */ 
     394    public void setRuleFactory(RuleFactory ruleFactory) {  
     395        this.ruleFactory = ruleFactory; 
     396    } 
    363397} 
  • src/api/org/openmrs/logic/TokenDefinition.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic; 
     15 
     16import java.util.HashSet; 
     17import java.util.Set; 
     18 
     19/** 
     20 * Represents a unique reference to a Rule 
     21 */ 
     22public class TokenDefinition { 
     23         
     24        // ************** 
     25        // Properties 
     26        // ************** 
     27         
     28        private Integer tokenDefinitionId; 
     29        private String token; 
     30        private String serializedRule; 
     31        private Set<TokenTag> tags = new HashSet<TokenTag>(); 
     32         
     33         
     34        // ************** 
     35        // Constructors 
     36        // ************** 
     37         
     38        /** Default No-argument Constructor */ 
     39        public TokenDefinition() {} 
     40         
     41        /** 
     42         * Creates a new TokenDefinition with the passed token and ruleDefinition 
     43         * @param token 
     44         * @param ruleDefinition 
     45         */ 
     46        public TokenDefinition(String token, String serializedRule) { 
     47                setToken(token); 
     48                setSerializedRule(serializedRule); 
     49        } 
     50         
     51        // ************** 
     52        // Property Methods 
     53        // ************** 
     54         
     55        /** 
     56         * @return the tokenDefinitionId 
     57         */ 
     58        public Integer getTokenDefinitionId() { 
     59        return tokenDefinitionId; 
     60    } 
     61         
     62        /** 
     63         * @param the tokenDefinitionId to set. 
     64         */ 
     65        public void setTokenDefinitionId(Integer tokenDefinitionId) { 
     66        this.tokenDefinitionId = tokenDefinitionId; 
     67    } 
     68         
     69        /** 
     70         * @return the token 
     71         */ 
     72        public String getToken() { 
     73        return token; 
     74    } 
     75         
     76        /** 
     77         * @param the token to set 
     78         */ 
     79        public void setToken(String token) { 
     80        this.token = token; 
     81    } 
     82         
     83        /** 
     84         * @return the Serialized Rule that this token references 
     85         */ 
     86        public String getSerializedRule() { 
     87        return serializedRule; 
     88    } 
     89         
     90        /** 
     91         * @param the Serialized Rule that this token references 
     92         */ 
     93        public void setSerializedRule(String serializedRule) { 
     94        this.serializedRule = serializedRule; 
     95    } 
     96 
     97        /** 
     98     * @return the tags 
     99     */ 
     100    public Set<TokenTag> getTags() { 
     101        return tags; 
     102    } 
     103 
     104        /** 
     105     * @param tags the tags to set 
     106     */ 
     107    public void setTags(Set<TokenTag> tags) { 
     108        this.tags = tags; 
     109    }    
     110} 
  • src/api/org/openmrs/logic/DuplicateTokenException.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic; 
     15 
     16/** 
     17 *  
     18 * Logic-specific exception 
     19 *  
     20 */ 
     21public class DuplicateTokenException extends LogicException { 
     22 
     23    private static final long serialVersionUID = -2985522122680870005L; 
     24 
     25    public DuplicateTokenException() { 
     26        super(); 
     27    } 
     28 
     29    public DuplicateTokenException(String message) { 
     30        super(message); 
     31    } 
     32 
     33    public DuplicateTokenException(Throwable cause) { 
     34        super(cause); 
     35    } 
     36 
     37    public DuplicateTokenException(String message, Throwable cause) { 
     38        super(message, cause); 
     39    } 
     40 
     41} 
  • src/api/org/openmrs/logic/util/LogicUtil.java

    old new  
     1/** 
     2 * The contents of this file are subject to the OpenMRS Public License 
     3 * Version 1.0 (the "License"); you may not use this file except in 
     4 * compliance with the License. You may obtain a copy of the License at 
     5 * http://license.openmrs.org 
     6 * 
     7 * Software distributed under the License is distributed on an "AS IS" 
     8 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 
     9 * License for the specific language governing rights and limitations 
     10 * under the License. 
     11 * 
     12 * Copyright (C) OpenMRS, LLC.  All Rights Reserved. 
     13 */ 
     14package org.openmrs.logic.util; 
     15 
     16import java.util.HashSet; 
     17import java.util.Locale; 
     18import java.util.Map; 
     19import java.util.Properties; 
     20import java.util.Set; 
     21 
     22import org.apache.commons.logging.Log; 
     23import org.apache.commons.logging.LogFactory; 
     24import org.openmrs.Cohort; 
     25import org.openmrs.Concept; 
     26import org.openmrs.ConceptClass; 
     27import org.openmrs.ConceptName; 
     28import org.openmrs.api.context.Context; 
     29import org.openmrs.logic.DuplicateTokenException; 
     30import org.openmrs.logic.LogicCriteria; 
     31import org.openmrs.logic.LogicException; 
     32import org.openmrs.logic.LogicTransform; 
     33import org.openmrs.logic.Rule; 
     34import org.openmrs.logic.TokenRegistry; 
     35import org.openmrs.logic.datasource.LogicDataSource; 
     36import org.openmrs.logic.op.Operator; 
     37import org.openmrs.logic.result.EmptyResult; 
     38import org.openmrs.logic.result.Result; 
     39import org.openmrs.logic.rule.AgeRule; 
     40import org.openmrs.logic.rule.HIVPositiveRule; 
     41import org.openmrs.logic.rule.ReferenceRule; 
     42import org.openmrs.util.OpenmrsConstants; 
     43 
     44/** 
     45 *  
     46 */ 
     47public class LogicUtil { 
     48         
     49        private static final Log log = LogFactory.getLog(LogicUtil.class); 
     50 
     51        /** 
     52         * Programmatically applies aggregators like COUNT, AVERAGE, etc 
     53         *  
     54         * @param finalResult result map of patient id to result list 
     55         * @param criteria provides type of transform 
     56         */ 
     57        public static void applyAggregators(Map<Integer, Result> finalResult, 
     58                        LogicCriteria criteria,Cohort patients) { 
     59                Set<Integer> personIds = finalResult.keySet(); 
     60                LogicTransform transform = criteria.getExpression().getTransform(); 
     61                 
     62                // finalResult is empty so populate it with empty counts/averages 
     63                if (personIds.size() == 0) { 
     64 
     65                        for (Integer personId : patients.getMemberIds()) { 
     66                                if (transform != null 
     67                                        && (transform.getTransformOperator() == Operator.COUNT || transform.getTransformOperator() == Operator.AVERAGE)) { 
     68                                        Result newResult = new Result(); 
     69                                        newResult.setValueNumeric(0); 
     70                                        finalResult.put(personId, newResult); 
     71                                } 
     72                        } 
     73                        return; 
     74                } 
     75                 
     76                for (Integer personId : personIds) { 
     77                        // if this was a count, then return the actual count of results 
     78                        // instead of the objects 
     79                         
     80                        Result r = finalResult.get(personId); 
     81                        if (transform != null 
     82                                && transform.getTransformOperator() == Operator.COUNT) { 
     83                                Result newResult = new Result(); 
     84                                newResult.setValueNumeric(r.size()); 
     85                                finalResult.put(personId, newResult); 
     86                        } else if (transform != null 
     87                                && transform.getTransformOperator() == Operator.AVERAGE) { 
     88 
     89                                int count = 0; 
     90                                double sum = 0; 
     91                                for (Result currResult : r) { 
     92                                        if (!(currResult instanceof EmptyResult)) { 
     93                                                count++; 
     94                                                sum += currResult.toNumber(); 
     95                                        } 
     96                                } 
     97                                double average = 0; 
     98                                if (count > 0 && sum > 0) { 
     99                                        average = sum / count; 
     100                                } 
     101                                Result newResult = new Result(); 
     102                                newResult.setValueNumeric(average); 
     103                                finalResult.put(personId, newResult); 
     104                        } 
     105                } 
     106        } 
     107         
     108        /** 
     109         * Initialize global settings needed for the LogicService. 
     110         * @param p properties from runtime configuration 
     111         */ 
     112        public static void startup(Properties p) { 
     113                registerDefaultRules(); 
     114        } 
     115         
     116        /** 
     117         * Load default rules at startup, creating if necessary 
     118         */ 
     119        public static void registerDefaultRules() { 
     120                 
     121                try { 
     122                        // Ensure privileges and database session are present 
     123                        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPTS); 
     124                        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_CLASSES); 
     125                        Context.openSession(); 
     126                         
     127                        // Load previously persisted Rules from the database 
     128                        Set<String> alreadyRegisteredTokens = Context.getLogicService().getTokens(); 
     129         
     130                        // Register Tokens for all Concepts in specified classes or with specified ids 
     131                        LogicDataSource obsDataSource = Context.getLogicService().getLogicDataSource("obs"); 
     132                        Set<Concept> conceptsToRegister = new HashSet<Concept>(); 
     133                        String classProp = Context.getAdministrationService().getGlobalProperty("logic.autoRegisteredTokens.conceptClassNames"); 
     134                        log.debug("Auto-register concepts with class in: " + classProp); 
     135                        if (classProp != null) { 
     136                                for (String className : classProp.split(",")) { 
     137                                        ConceptClass cc = Context.getConceptService().getConceptClassByName(className); 
     138                                        conceptsToRegister.addAll(Context.getConceptService().getConceptsByClass(cc)); 
     139                                } 
     140                        } 
     141                        String idProp = Context.getAdministrationService().getGlobalProperty("logic.autoRegisteredTokens.conceptIds"); 
     142                        log.debug("Auto-register concepts with id: " + idProp); 
     143                        if (idProp != null) { 
     144                                for (String idStr : idProp.split(",")) { 
     145                                        Integer conceptId = Integer.parseInt(idStr); 
     146                                        conceptsToRegister.add(Context.getConceptService().getConcept(conceptId)); 
     147                                } 
     148                        } 
     149                        Locale conceptNameLocale = Locale.US; 
     150                        String localeProp = Context.getAdministrationService().getGlobalProperty("logic.defaultConceptNameLocale"); 
     151                        if (localeProp != null) { 
     152                                conceptNameLocale = new Locale(localeProp); 
     153                        } 
     154                        log.debug("Locale to use for token registration: " + localeProp); 
     155                         
     156                        for (Concept c : conceptsToRegister) { 
     157                                ConceptName conceptName = c.getPreferredName(conceptNameLocale); 
     158                                if (conceptName != null && obsDataSource.hasKey(conceptName.getName())) { 
     159                                        String token = TokenRegistry.convertToToken(conceptName.getName()); 
     160                                        if (!alreadyRegisteredTokens.contains(token)) { 
     161                                                Rule r = new ReferenceRule("obs." + conceptName.getName()); 
     162                                                registerRule(token, r); 
     163                                        } 
     164                                } 
     165                        } 
     166                 
     167                        // Register Tokens for all keys exposed by certain datasources 
     168                        registerAllDataSourceKeysAsRules("person", alreadyRegisteredTokens); 
     169                         
     170                        // Register tokens for additional Rule classes 
     171                        registerRule("HIV POSITIVE", HIVPositiveRule.class, alreadyRegisteredTokens); 
     172                        registerRule("AGE", AgeRule.class, alreadyRegisteredTokens); 
     173                } 
     174                catch (Throwable t) { 
     175                        log.error("An error occurred while registering default tokens: " + t); 
     176                        throw new LogicException(t); 
     177                } 
     178                finally { 
     179                        Context.closeSession(); 
     180                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPTS); 
     181                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPT_CLASSES); 
     182                } 
     183        } 
     184         
     185        private static void registerAllDataSourceKeysAsRules(String dataSourceName, Set<String> alreadyRegisteredTokens) { 
     186                LogicDataSource ds = Context.getLogicService().getLogicDataSource(dataSourceName); 
     187                for (String key : ds.getKeys()) { 
     188                        String token = TokenRegistry.convertToToken(key); 
     189                        if (!alreadyRegisteredTokens.contains(token)) { 
     190                                Rule r = new ReferenceRule(dataSourceName + "." + key); 
     191                                registerRule(key, r); 
     192                        } 
     193                } 
     194        } 
     195         
     196        private static void registerRule(String token, Class<? extends Rule> ruleClass, Set<String> alreadyRegisteredTokens) { 
     197                try { 
     198                        token = TokenRegistry.convertToToken(token); 
     199                        if (!alreadyRegisteredTokens.contains(token)) { 
     200                                Context.getLogicService().addRule(token, ruleClass); 
     201                        } 
     202                } 
     203                catch (DuplicateTokenException e) { 
     204                        log.debug("Rule with token <" + token.toUpperCase() + "> already in RuleMap.  Ignoring: " + ruleClass); 
     205                } 
     206        } 
     207         
     208        private static void registerRule(String token, Rule rule) { 
     209                try { 
     210                        log.debug("Trying to add rule with token: " + token); 
     211                        Context.getLogicService().addRule(token.toUpperCase(), rule); 
     212                } 
     213                catch (DuplicateTokenException e) { 
     214                        log.debug("Rule with token <" + token.toUpperCase() + "> already in RuleMap.  Ignoring: " + rule); 
     215                } 
     216        } 
     217} 
  • src/api/org/openmrs/api/context/Context.java

    old new  
    4949import org.openmrs.arden.ArdenService; 
    5050import org.openmrs.hl7.HL7Service; 
    5151import org.openmrs.logic.LogicService; 
     52import org.openmrs.logic.util.LogicUtil; 
    5253import org.openmrs.module.ModuleUtil; 
    5354import org.openmrs.notification.AlertService; 
    5455import org.openmrs.notification.MessageException; 
     
    627628                // data directory can be set from the runtime properties 
    628629                OpenmrsUtil.startup(props); 
    629630                 
     631                // Execute any necessary logic startup initialization 
     632                LogicUtil.startup(props); 
     633                 
    630634                // Loop over each module and startup each with these custom properties 
    631635                ModuleUtil.startup(props); 
    632636