Skip to content

Commit

Permalink
Initial commit for dynamic rules for PR
Browse files Browse the repository at this point in the history
  • Loading branch information
seaside1 committed Oct 4, 2023
1 parent 58b51c1 commit 51e3403
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
*/
public class JRuleCompiler {

private static final String ORG_OPENHAB_CORE = "org.openhab.core-";
private static final String ORG_OPENHAB_CORE_THING = "org.openhab.core.thing-";
private static final String JAVA_CLASS_PATH_PROPERTY = "java.class.path";
private static final String CLASSPATH_OPTION = "-classpath";
public static final String JAR_JRULE_NAME = "jrule.jar";
Expand Down Expand Up @@ -149,7 +151,8 @@ public void loadClass(ClassLoader classLoader, String className, boolean createI
final Object obj = loadedClass.getDeclaredConstructor().newInstance();
logDebug("Created instance: {} obj: {}", className, obj);
} catch (Exception x) {
logError("Could not create create instance using default constructor: {}: {}", className, x);
logError("Could not create create instance using default constructor: {}", className);
logger.error("Failed to load class", x);
}
}
}
Expand Down Expand Up @@ -241,11 +244,14 @@ public boolean compile(List<File> javaSourceFiles, String classPath) {
final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
final List<String> optionList = new ArrayList<>();
optionList.add(CLASSPATH_OPTION);
String openhabCoreJar = getOpenhabCoreJar().map(s -> s + File.pathSeparator).orElse("");
final String openhabCoreJar = getOpenhabCoreJar().map(s -> s + File.pathSeparator).orElse("");
logDebug("Openhab-Core Jar: {}", openhabCoreJar);
String cp = openhabCoreJar + System.getProperty(JAVA_CLASS_PATH_PROPERTY) + File.pathSeparator + classPath;
final String openhabCoreThingJar = getOpenhabCoreThingJar().map(s -> s + File.pathSeparator).orElse("");
logDebug("Openhab-Core-Thing Jar: {}", openhabCoreThingJar);
String cp = openhabCoreJar + System.getProperty(JAVA_CLASS_PATH_PROPERTY) + File.pathSeparator
+ openhabCoreThingJar + System.getProperty(JAVA_CLASS_PATH_PROPERTY) + File.pathSeparator + classPath;
optionList.add(cp);
logDebug("Compiling classes using classpath: {}", cp);
logDebug("1337Compiling classes using classpath: {}", cp);
javaSourceFiles.stream().filter(javaSourceFile -> javaSourceFile.exists() && javaSourceFile.canRead())
.forEach(javaSourceFile -> logDebug("Compiling java Source file: {}", javaSourceFile));

Expand Down Expand Up @@ -273,6 +279,14 @@ public boolean compile(List<File> javaSourceFiles, String classPath) {
}

private Optional<String> getOpenhabCoreJar() {
return getOpenHABJar(ORG_OPENHAB_CORE);
}

private Optional<String> getOpenhabCoreThingJar() {
return getOpenHABJar(ORG_OPENHAB_CORE_THING);
}

private Optional<String> getOpenHABJar(String jarPrefix) {
if (!System.getProperties().containsKey(PROPERTY_KARAF_HOME_URI)
&& !System.getProperties().containsKey(PROPERTY_KARAF_DEFAULT_REPOSITORY)) {
logWarn("required system properties does not exist [{}]",
Expand All @@ -284,9 +298,10 @@ private Optional<String> getOpenhabCoreJar() {
+ System.getProperty(PROPERTY_KARAF_DEFAULT_REPOSITORY);
logDebug("Openhab Jars path: {}", openhabJars);
Optional<String> coreJarPath;

try (Stream<Path> stream = Files.walk(Paths.get(openhabJars))) {
coreJarPath = stream.filter(path -> path.getFileName().toString().endsWith(JRuleConstants.JAR_FILE_TYPE))
.filter(path -> path.getFileName().toString().startsWith("org.openhab.core-"))
.filter(path -> path.getFileName().toString().startsWith(jarPrefix))
.map(path -> path.toFile().getAbsolutePath()).findFirst();
} catch (IOException e) {
logError(e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -96,7 +97,7 @@
*/
public class JRuleEngine implements PropertyChangeListener {
public static final String MDC_KEY_TIMER = "timer";
private static final String[] EMPTY_LOG_TAGS = new String[0];
public static final String[] EMPTY_LOG_TAGS = new String[0];
private static final int AWAIT_TERMINATION_THREAD_SECONDS = 2;
private List<JRuleExecutionContext> contextList = new CopyOnWriteArrayList<>();
private JRuleTimerExecutor timerExecutor = new JRuleTimerExecutor(this);
Expand Down Expand Up @@ -133,6 +134,24 @@ public void add(JRule jRule, boolean enableRule) {
.forEach(method -> this.add(method, jRule, enableRule));
}

public void addDynamicWhenReceivedCommand(Method method, JRule jRule, String ruleName, List<String> items) {
JRuleModuleEntry ruleModuleEntry = new JRuleModuleEntry(jRule, method, ruleName);
List<JRulePreconditionContext> emptyPreconditionContextList = new ArrayList<>(0);
for (String itemName : items) {
JRuleItemReceivedCommandExecutionContext context = new JRuleItemReceivedCommandExecutionContext(jRule,
ruleName, JRuleEngine.EMPTY_LOG_TAGS, method, itemName, JRuleMemberOf.None, Optional.empty(),
emptyPreconditionContextList, Optional.empty(), null, null);

addToContext(context, false);
ruleLoadingStatistics.addItemStateTrigger();
ruleModuleEntry.addJRuleWhenItemReceivedCommand(context);

logInfo("Adding Dynamic Rule Name: {} item: {}", ruleName, itemName);
}
ruleLoadingStatistics.addRuleClass();
ruleProvider.add(ruleModuleEntry);
}

private void add(Method method, JRule jRule, boolean enableRule) {
logDebug("Adding rule method: {}", method.getName());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,19 +136,22 @@ public JRuleHandler(JRuleConfig config, ItemRegistry itemRegistry, ThingRegistry
actionGenerator = new JRuleActionClassGenerator(config);
compiler = new JRuleCompiler(config);

JRuleEventHandler jRuleEventHandler = JRuleEventHandler.get();
final JRuleEventHandler jRuleEventHandler = JRuleEventHandler.get();
jRuleEventHandler.setEventPublisher(eventPublisher);
jRuleEventHandler.setItemRegistry(itemRegistry);
eventSubscriber.addPropertyChangeListener(this);
JRuleVoiceHandler jRuleVoiceHandler = JRuleVoiceHandler.get();
final JRuleVoiceHandler jRuleVoiceHandler = JRuleVoiceHandler.get();
jRuleVoiceHandler.setVoiceManager(voiceManager);
JRuleTransformationHandler jRuleTransformationHandler = JRuleTransformationHandler.get();
final JRuleTransformationHandler jRuleTransformationHandler = JRuleTransformationHandler.get();
jRuleTransformationHandler.setBundleContext(bundleContext);

JRuleThingHandler thingHandler = JRuleThingHandler.get();
final JRuleThingHandler thingHandler = JRuleThingHandler.get();
thingHandler.setThingManager(thingManager);
thingHandler.setThingRegistry(thingRegistry);

final JRuleItemHandler itemHandler = JRuleItemHandler.get();
itemHandler.setItemRegistry(itemRegistry);

logDebug("JRuleHandler()");
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Copyright (c) 2010-2023 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.automation.jrule.internal.handler;

import org.openhab.core.items.Item;
import org.openhab.core.items.ItemRegistry;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.StringType;

/**
* The {@link JRuleItemHandler} provides access to item Registry
*
* @author Joseph (Seaside) Hagberg - Initial contribution
*/
public class JRuleItemHandler {

private static volatile JRuleItemHandler instance = null;

private JRuleItemHandler() {
}

private ItemRegistry itemRegistry;

public void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}

public static JRuleItemHandler get() {
if (instance == null) {
synchronized (JRuleItemHandler.class) {
if (instance == null) {
instance = new JRuleItemHandler();
}
}
}
return instance;
}

public Item addToRegistry(Item item) {
return itemRegistry.add(item);
}

public boolean itemRegistryContainsItem(String itemName) {
return itemRegistry.get(itemName) != null;
}

public Item addNumberItem(String name, int value) {
final NumberItem numberItem = new NumberItem(name);
numberItem.setState(new DecimalType(value));
return itemRegistry.add(numberItem);
}

public Item addStringItem(String name, String value) {
final StringItem stringItem = new StringItem(name);
stringItem.setState(new StringType(value));
return itemRegistry.add(stringItem);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
*/
package org.openhab.automation.jrule.internal.handler;

import java.util.Collection;

import org.openhab.automation.jrule.things.JRuleThingStatus;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingManager;
Expand Down Expand Up @@ -61,7 +63,12 @@ public void enable(String thingUID) {
setEnabled(thingUID, true);
}

public Collection<Thing> getThings() {
return thingRegistry.getAll();
}

private void setEnabled(String thingUID, boolean enabled) {
thingRegistry.getAll().forEach(t -> t.getBridgeUID());
Thing thing = thingRegistry.get(new ThingUID(thingUID));
if (thing != null) {
thingManager.setEnabled(new ThingUID(thingUID), enabled);
Expand Down
10 changes: 8 additions & 2 deletions src/main/java/org/openhab/automation/jrule/rules/JRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ public class JRule {
public static final ThreadLocal<JRuleExecutionContext> JRULE_EXECUTION_CONTEXT = new ThreadLocal<>();

public JRule() {
// Add rules default disabled, let openHAB enable rules if not disabled in GUI
JRuleEngine.get().add(this, false);
this(true);
}

public JRule(boolean addToEngine) {
if (addToEngine) {
// Add rules default disabled, let openHAB enable rules if not disabled in GUI
JRuleEngine.get().add(this, false);
}
}

protected void say(String text) {
Expand Down

0 comments on commit 51e3403

Please sign in to comment.