Loads the rule with the given text, and uses the engine to identify and
retrieve references to the input variables and output variables as required

@param rule is the rule in text
@param engine is the engine from which the rule is part of
4163
public void load(String rule, Engine engine) {
        deactivate();
        setEnabled(true);
        setText(rule);
        StringTokenizer tokenizer = new StringTokenizer(rule);
        String token;
        StringBuilder strAntecedent = new StringBuilder();
        StringBuilder strConsequent = new StringBuilder();
        double ruleWeight = 1.0;

        final byte S_NONE = 0, S_IF = 1, S_THEN = 2, S_WITH = 3, S_END = 4;
        byte state = S_NONE;
        try {
            while (tokenizer.hasMoreTokens()) {
                token = tokenizer.nextToken();
                int commentIndex = token.indexOf('#');
                if (commentIndex >= 0) {
                    token = token.substring(0, commentIndex);
                }
                switch (state) {
                    case S_NONE:
                        if (Rule.FL_IF.equals(token)) {
                            state = S_IF;
                        } else {
                            throw new RuntimeException(String.format(
                                    "[syntax error] expected keyword <%s>, but found <%s> in rule: %s", Rule.FL_IF, token, rule));
                        }
                        break;

                    case S_IF:
                        if (Rule.FL_THEN.equals(token)) {
                            state = S_THEN;
                        } else {
                            strAntecedent.append(token).append(" ");
                        }
                        break;
                    case S_THEN:
                        if (Rule.FL_WITH.equals(token)) {
                            state = S_WITH;
                        } else {
                            strConsequent.append(token).append(" ");
                        }
                        break;
                    case S_WITH:
                        try {
                            ruleWeight = Op.toDouble(token);
                            state = S_END;
                        } catch (NumberFormatException ex) {
                            throw ex;
                        }
                        break;

                    case S_END:
                        throw new RuntimeException(String.format(
                                "[syntax error] unexpected token <%s> at the end of rule", token));
                    default:
                        throw new RuntimeException(String.format(
                                "[syntax error] unexpected state <%s>", state));
                }
            }

            if (state == S_NONE) {
                throw new RuntimeException(String.format("[syntax error] %s rule: %s", (rule.isEmpty() ? "empty" : "ignored"), rule));
            } else if (state == S_IF) {
                throw new RuntimeException(String.format(
                        "[syntax error] keyword <%s> not found in rule: %s",
                        Rule.FL_THEN, rule));
            } else if (state == S_WITH) {
                throw new RuntimeException(String.format(
                        "[syntax error] expected a numeric value as the weight of the rule: %s",
                        rule));
            }
            getAntecedent().load(strAntecedent.toString(), engine);
            getConsequent().load(strConsequent.toString(), engine);
            setWeight(ruleWeight);
        } catch (RuntimeException ex) {
            unload();
            throw ex;
        }
    }
1225215
@Override
    public void activate(RuleBlock ruleBlock) {
        if (FuzzyLite.isDebugging()) {
            FuzzyLite.logger().log(Level.FINE, "Activation: {0} {1}",
                    new String[]{getClass().getName(), parameters()});
        }
        TNorm conjunction = ruleBlock.getConjunction();
        SNorm disjunction = ruleBlock.getDisjunction();
        TNorm implication = ruleBlock.getImplication();

        double sumActivationDegrees = 0.0;
        List<Rule> rulesToActivate = new ArrayList<Rule>(ruleBlock.getRules().size());
        for (Rule rule : ruleBlock.getRules()) {
            rule.deactivate();
            if (rule.isLoaded()) {
                double activationDegree = rule.activateWith(conjunction, disjunction);
                rulesToActivate.add(rule);
                sumActivationDegrees += activationDegree;
            }
        }
        for (Rule rule : rulesToActivate) {
            double activationDegree = rule.getActivationDegree() / sumActivationDegrees;
            rule.setActivationDegree(activationDegree);
            rule.trigger(implication);
        }
    }
360410
@SuppressWarnings("unchecked") // NOSONAR (Avoid Duplicate Literals)
    private void processEachRuleWithEachResultHandler(RI ruleInput) {
        // For each rule
        for (Rule<RI, RO> rule : rules) {
            // Validate the data and get the rule output
            Object ruleOutput = rule.validate(ruleInput);

            // Transform the rule output
            if (ruleOutputTransformers != null) {
                for (Transformer transformer : ruleOutputTransformers) {
                    ruleOutput = transformer.transform(ruleOutput);
                }
            }

            // Transform the transformed rule output to result handler input
            if (resultHandlerInputTransformers != null) {
                for (Transformer transformer : resultHandlerInputTransformers) {
                    ruleOutput = transformer.transform(ruleOutput);
                }
            }
            RHI resultHandlerInput = (RHI) ruleOutput;

            // Process the result handler input with the result handlers
            processResultHandlers(resultHandlerInput);
        }
    }
457162
private boolean loadMatchRules(String rulesUrl) {
	//load match rules from file
	try {
            //check for file URL 
            if (rulesUrl != null && rulesUrl.toLowerCase().startsWith("file:")) {
                return loadMatchRulesFromFile(rulesUrl);
            }
            
            //request match rules from remote URL 
    	    mCallbacks.printOutput("Loading match rules from: " + rulesUrl);
	    URL url = new URL(rulesUrl);
            IHttpService service = new HttpService(url);
            HttpRequest request = new HttpRequest(url);
            byte[] responseBytes = mCallbacks.makeHttpRequest(
                    service.getHost(), 
                    service.getPort(), 
                    HttpService.PROTOCOL_HTTPS.equalsIgnoreCase(service.getProtocol()), 
                    request.getBytes());
            
            //parse the response
            if (responseBytes == null) return false; //no response received from server 
            HttpResponse response = HttpResponse.parseMessage(responseBytes);
            
	    //read match rules from the response
            Reader is = new StringReader(response.getBody());
	    BufferedReader reader = new BufferedReader(is);
	    
            processMatchRules(reader);
                        
            return true;

	} catch (IOException e) {
	    scan.printStackTrace(e);
	} catch (Exception e) {
	    scan.printStackTrace(e);
        }
        
        return false;
    }
1027930
function ForCommand(value, engine) {
        var rule = new RegExp(
            stringFormat(
                /* jshint ignore:start */
                '^\\s*({0}[\\s\\S]+{1})\\s+as\\s+{0}([0-9a-z_]+){1}\\s*(,\\s*{0}([0-9a-z_]+){1})?\\s*$',
                /* jshint ignore:end */
                regexpLiteral(engine.options.variableOpen),
                regexpLiteral(engine.options.variableClose)
            ),
            'i'
        );


        var match = value.match(rule);
        if (!match) {
            throw new Error('Invalid ' + this.type + ' syntax: ' + value);
        }

        this.list = match[1];
        this.item = match[2];
        this.index = match[4];
        Command.call(this, value, engine);
        this.cloneProps = ['list', 'item', 'index'];
    }
926854
function Linter(ruleFilePath) {
    if (!ruleFilePath) logger.info("No rule file provided, using default rules");
    this.rules = loadRules(ruleFilePath);
    helper.initLineRulesRegexes(this.rules);
}
548287
private void trainRuleOnInstance(int ruleID, Instance instance) {
        //System.out.println("Processor:"+this.processorId+": Rule:"+ruleID+" -> Counter="+counter);
		Iterator<ActiveRule> ruleIterator= this.ruleSet.iterator();
		while (ruleIterator.hasNext()) {
			ActiveRule rule = ruleIterator.next();
			if (rule.getRuleNumberID() == ruleID) {
				// Check (again) for coverage
				if (rule.isCovering(instance) == true) {
					double error = rule.computeError(instance); //Use adaptive mode error
                    boolean changeDetected = ((RuleActiveRegressionNode)rule.getLearningNode()).updateChangeDetection(error);
                    if (changeDetected == true) {
                            ruleIterator.remove();
                            
                            this.sendRemoveRuleEvent(ruleID);
                    } else {
                    	rule.updateStatistics(instance);
                    	if (rule.getInstancesSeen()  % this.gracePeriod == 0.0) {
                    		if (rule.tryToExpand(this.splitConfidence, this.tieThreshold) ) {
                    			rule.split();
                    			
                    			// expanded: update Aggregator with new/updated predicate
                    			this.sendPredicate(rule.getRuleNumberID(), rule.getLastUpdatedRuleSplitNode(), 
        								(RuleActiveRegressionNode)rule.getLearningNode());
                    		}	
                    		
                    	}
                    	
                    }
				}
				
				return;
			}
		}
	}
1335863
protected RuleSet readRules(MavenProject rootModule) throws MojoExecutionException {
        List<RuleSource> sources = new ArrayList<>();
        PluginRepository pluginRepository = pluginRepositoryProvider.getPluginRepository();
        if (rulesUrl != null) {
            getLog().debug("Retrieving rules from URL " + rulesUrl.toString());
            sources.add(new UrlRuleSource(rulesUrl));
        } else {
            // read rules from rules directory
            addRuleFiles(sources, ProjectResolver.getRulesDirectory(rootModule, rulesDirectory));
            if (rulesDirectories != null) {
                for (String directory : rulesDirectories) {
                    addRuleFiles(sources, ProjectResolver.getRulesDirectory(rootModule, directory));
                }
            }
            List<RuleSource> ruleSources = pluginRepository.getRulePluginRepository().getRuleSources();
            sources.addAll(ruleSources);
        }
        Collection<RuleParserPlugin> ruleParserPlugins;
        try {
            ruleParserPlugins = pluginRepository.getRuleParserPluginRepository().getRuleParserPlugins(getRuleConfiguration());
        } catch (RuleException e) {
            throw new MojoExecutionException("Cannot get rules rule source reader plugins.", e);        }
        try {
            RuleParser ruleParser = new RuleParser(ruleParserPlugins);
            return ruleParser.parse(sources);
        } catch (RuleException e) {
            throw new MojoExecutionException("Cannot read rules.", e);
        }
    }
275833
public void initialize(final JsMessagingEngine engine) {

        final String methodName = "initialize";
        if (TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName, engine);
        }

        final Set listeners;

        _messagingEngine = engine;

        synchronized (MESSAGING_ENGINES) {

            // Do we already have a set of initialized MEs on this bus?
            Set messagingEngines = (Set) MESSAGING_ENGINES.get(engine
                    .getBusName());

            // If not, create a new set and add it to the map
            if (messagingEngines == null) {

                messagingEngines = new HashSet();
                MESSAGING_ENGINES.put(engine.getBusName(), messagingEngines);

            }

            // Add the initializing ME to the set
            messagingEngines.add(engine);

            // Get listeners to notify
            listeners = getListeners(_messagingEngine.getBusName());

        }

        // Notify listeners
        for (final Iterator iterator = listeners.iterator(); iterator.hasNext();) {

            final SibRaMessagingEngineListener listener = (SibRaMessagingEngineListener) iterator
                    .next();
            listener.messagingEngineInitializing(_messagingEngine);

        }

        if (TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }
713587
public void addRule(final RuleBuildContext context) {
        final RuleImpl rule = context.getRule();
        final RuleDescr ruleDescr = context.getRuleDescr();

        RuleClassBuilder classBuilder = context.getDialect().getRuleClassBuilder();

        String ruleClass = classBuilder.buildRule(context);
        // return if there is no ruleclass name;
        if (ruleClass == null) {
            return;
        }

        // The compilation result is for the entire rule, so difficult to associate with any descr
        addClassCompileTask(this.pkg.getName() + "." + ruleDescr.getClassName(),
                            ruleDescr,
                            ruleClass,
                            this.src,
                            new RuleErrorHandler(ruleDescr,
                                                 rule,
                                                 "Rule Compilation error"));

        JavaDialectRuntimeData data = (JavaDialectRuntimeData) this.pkg.getDialectRuntimeRegistry().getDialectData(ID);

        for (Map.Entry<String, String> invokers : context.getInvokers().entrySet()) {
            final String className = invokers.getKey();

            // Check if an invoker - returnvalue, predicate, eval or consequence has been associated
            // If so we add it to the PackageCompilationData as it will get wired up on compilation
            final Object invoker = context.getInvokerLookup(className);
            if (invoker instanceof Wireable) {
                data.putInvoker(className, (Wireable)invoker);
            }
            final String text = invokers.getValue();

            final BaseDescr descr = context.getDescrLookup(className);
            addClassCompileTask(className,
                                descr,
                                text,
                                this.src,
                                new RuleInvokerErrorHandler(descr,
                                                            rule,
                                                            "Unable to generate rule invoker."));
        }

        // setup the line mappins for this rule
        final String name = this.pkg.getName() + "." + StringUtils.ucFirst(ruleDescr.getClassName());
        final LineMappings mapping = new LineMappings(name);
        mapping.setStartLine(ruleDescr.getConsequenceLine());
        mapping.setOffset(ruleDescr.getConsequenceOffset());

        this.pkg.getDialectRuntimeRegistry().getLineMappings().put(name,
                                                                   mapping);
    }
832058
public void setEngine(final ActionEngine engine) {
	if (!Objects.equals(this.engine, engine)) { // Only if changed
	    synchronized (contexts) {
		contexts.clear();
	    }
	}
	this.engine = engine;
    }
237554
public void setRules(List rules) {
        Assert.notNull(rules);
        if (logger.isDebugEnabled()) {
            logger.debug("Configuring rules in source...");
        }
        getRuleContext(DEFAULT_CONTEXT_ID).clear();
        for (Iterator i = rules.iterator(); i.hasNext();) {
            addRules((Rules) i.next());
        }
    }
29209
@SuppressWarnings("unchecked") // NOSONAR (Avoid Duplicate Literals)
    private void processEachDataProviderWithEachRule() {
        // For each data provider
        for (DataProvider<DPO> dataProvider : dataProviders) {
            // Get the data provider output
            Object transformedOutput = dataProvider.getData();

            // Transform the data provider output
            if (dataProviderOutputTransformers != null) {
                for (Transformer transformer : dataProviderOutputTransformers) {
                    transformedOutput = transformer.transform(transformedOutput);
                }
            }

            // Transform the transformed data provider output to rule input
            if (ruleInputTransformers != null) {
                for (Transformer transformer : ruleInputTransformers) {
                    transformedOutput = transformer.transform(transformedOutput);
                }
            }
            RI ruleInput = (RI) transformedOutput;

            // Process the rule input with the rules
            processRules(ruleInput);
        }
    }
674792
public static void enhanceRuleMetadata(RuleProvider provider, Rule rule)
    {
        if (rule instanceof Context)
        {
            Context context = (Context) rule;
            if (!context.containsKey(RuleMetadataType.ORIGIN))
                context.put(RuleMetadataType.ORIGIN, provider.getMetadata().getOrigin());
            if (!context.containsKey(RuleMetadataType.RULE_PROVIDER))
                context.put(RuleMetadataType.RULE_PROVIDER, provider);
            if (!context.containsKey(RuleMetadataType.TAGS))
                context.put(RuleMetadataType.TAGS, provider.getMetadata().getTags());
        }
    }
341760
public static synchronized void registerEngine(RenderEngine engine) {
    if (null == availableEngines) {
      availableEngines = new HashMap();
    }
    availableEngines.put(engine.getName(), engine);
  }
376855
@Override
    public final void prepare(Engine engine) throws InitializationException {
        if (isEnabled()) {
            prepareAnalyzer(engine);
        } else {
            LOGGER.debug("{} has been disabled", getName());
        }
    }
310545
public synchronized void addRule(final RuleImpl rule) throws InvalidPatternException {
        final List<TerminalNode> terminals = this.ruleBuilder.addRule( rule,
                                                                       this.kBase );

        BaseNode[] nodes = terminals.toArray( new BaseNode[terminals.size()] );
        this.rules.put( rule.getFullyQualifiedName(), nodes );
        if (rule.isQuery()) {
            this.queries.put( rule.getName(), nodes );
        }
    }