Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Actions (openhab internal), rename old Actions to ThingActions #208

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/main/history/dependencies.xml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<features xmlns="http://karaf.apache.org/xmlns/features/v1.6.0" name="org.openhab.automation.jrule-4.2.0">
<features xmlns="http://karaf.apache.org/xmlns/features/v1.6.0" name="org.openhab.automation.jrule-4.2.1-SNAPSHOT">
<feature version="0.0.0">
<feature>openhab-runtime-base</feature>
<feature>wrap</feature>
<bundle>mvn:javax.el/javax.el-api/2.2.4</bundle>
<bundle>mvn:org.freemarker/freemarker/2.3.32</bundle>
<bundle>mvn:org.openhab.addons.bundles/org.openhab.automation.jrule/4.2.0</bundle>
<bundle>mvn:org.openhab.addons.bundles/org.openhab.automation.jrule/4.2.1-SNAPSHOT</bundle>
<bundle>wrap:mvn:javax.servlet/jsp-api/2.0</bundle>
<bundle>wrap:mvn:javax.servlet/servlet-api/2.4</bundle>
<bundle>wrap:mvn:org.lastnpe.eea/eea-all/2.2.1</bundle>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,46 +14,29 @@

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

import org.openhab.core.model.script.actions.Things;
import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.model.script.scoping.ActionClassLoader;

/**
* The {@link JRuleAbstractAction}
*
* @author Robert Delbrück - Initial contribution
*/
public abstract class JRuleAbstractAction {
private final ThingActions thingActions;
private final String scope;
private final String thingUID;

protected JRuleAbstractAction(String scope, String thingUID) {
this.scope = scope;
this.thingUID = thingUID;
thingActions = Objects.requireNonNull(Things.getActions(scope, thingUID),
String.format("action for '%s' with uid '%s' could not be found", scope, thingUID));
}

protected Object invokeMethod(String methodName, Class<?>[] classes, Object... args) {
protected Object invokeMethod(String clazzName, String methodName, Class<?>[] classes, Object... args) {
try {
Method method = thingActions.getClass().getDeclaredMethod(methodName, classes);
return method.invoke(thingActions, args);
ActionClassLoader cl = new ActionClassLoader(JRuleAbstractAction.class.getClassLoader());
Class<?> clazz = Class.forName(clazzName, true, cl);
Method method = clazz.getDeclaredMethod(methodName, classes);
return method.invoke(null, args);
} catch (NoSuchMethodException e) {
throw new RuntimeException("method not found", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("error invoking method", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("cannot access method", e);
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot found class", e);
}
}

public String getThingUID() {
return thingUID;
}

public String getScope() {
return scope;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* 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.actions;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

import org.openhab.core.model.script.actions.Things;
import org.openhab.core.model.script.scoping.ActionClassLoader;
import org.openhab.core.thing.binding.ThingActions;

/**
* The {@link JRuleAbstractThingAction}
*
* @author Robert Delbrück - Initial contribution
*/
public abstract class JRuleAbstractThingAction {
private final ThingActions thingActions;
private final String scope;
private final String thingUID;

protected JRuleAbstractThingAction(String scope, String thingUID) {
this.scope = scope;
this.thingUID = thingUID;
thingActions = Objects.requireNonNull(Things.getActions(scope, thingUID),
String.format("action for '%s' with uid '%s' could not be found", scope, thingUID));
}

protected Object invokeMethod(String methodName, Class<?>[] classes, Object... args) {
try {
ActionClassLoader cl = new ActionClassLoader(JRuleAbstractThingAction.class.getClassLoader());
Class<?> clazz = Class.forName(thingActions.getClass().getName(), true, cl);
Method method = clazz.getDeclaredMethod(methodName, classes);
return method.invoke(thingActions, args);
} catch (NoSuchMethodException e) {
throw new RuntimeException("method not found", e);
} catch (InvocationTargetException e) {
throw new RuntimeException("error invoking method", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("cannot access method", e);
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot found class", e);
}
}

public String getThingUID() {
return thingUID;
}

public String getScope() {
return scope;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,7 @@

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.lang3.ClassUtils;
Expand All @@ -32,11 +24,8 @@
import org.openhab.automation.jrule.internal.JRuleConstants;
import org.openhab.automation.jrule.internal.JRuleLog;
import org.openhab.automation.jrule.internal.generator.JRuleAbstractClassGenerator;
import org.openhab.core.automation.annotation.ActionInput;
import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.model.script.engine.action.ActionDoc;
import org.openhab.core.model.script.engine.action.ActionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -59,16 +48,16 @@ public JRuleActionClassGenerator(JRuleConfig jRuleConfig) {
super(jRuleConfig);
}

public boolean generateActionSource(Thing thing) {
public boolean generateActionSource(ActionService actionService) {
try {
Map<String, Object> processingModel = new HashMap<>();

Map<String, Object> actionModel = createActionModel(thing);
Map<String, Object> actionModel = createActionModel(actionService);
processingModel.put("action", actionModel);

File targetSourceFile = new File(new StringBuilder().append(jRuleConfig.getActionsDirectory())
.append(File.separator).append(jRuleConfig.getGeneratedItemPrefix())
.append(getActionFriendlyName(thing.getUID().toString())).append(JRuleConstants.JAVA_FILE_TYPE)
.append(actionService.getActionClass().getSimpleName()).append(JRuleConstants.JAVA_FILE_TYPE)
.toString());

try (FileWriter fileWriter = new FileWriter(targetSourceFile)) {
Expand All @@ -83,19 +72,19 @@ public boolean generateActionSource(Thing thing) {

} catch (Exception e) {
JRuleLog.error(logger, LOG_NAME_CLASS_GENERATOR,
"Internal error when generating java source for action {}: {}", thing.getUID().toString(),
"Internal error when generating java source for action {}: {}", actionService.getActionClass(),
ExceptionUtils.getStackTrace(e));

}

return false;
}

public boolean generateActionsSource(Collection<Thing> things) {
public boolean generateActionsSource(Collection<ActionService> actionServices) {
try {
List<Map<String, Object>> model = things.stream()
.sorted(Comparator.comparing(e -> getActionFriendlyName(e.getUID().toString())))
.map(this::createActionsModel).collect(Collectors.toList());
List<Map<String, Object>> model = actionServices.stream()
.sorted(Comparator.comparing(e -> e.getActionClass().getSimpleName())).map(this::createActionsModel)
.collect(Collectors.toList());
Map<String, Object> processingModel = new HashMap<>();
processingModel.put("actions", model);
processingModel.put("packageName", jRuleConfig.getGeneratedActionPackage());
Expand All @@ -120,89 +109,81 @@ public boolean generateActionsSource(Collection<Thing> things) {
return false;
}

private Map<String, Object> createActionsModel(Thing thing) {
private Map<String, Object> createActionsModel(ActionService actionService) {
Map<String, Object> freemarkerModel = new HashMap<>();
freemarkerModel.put("id", thing.getUID().toString());
freemarkerModel.put("scope", thing.getUID().getBindingId());
freemarkerModel.put("name", StringUtils.uncapitalize(getActionFriendlyName(thing.getUID().toString())));
freemarkerModel.put("name",
StringUtils.uncapitalize(StringUtils.uncapitalize(actionService.getActionClass().getSimpleName())));
freemarkerModel.put("package", jRuleConfig.getGeneratedActionPackage());
freemarkerModel.put("class",
jRuleConfig.getGeneratedItemPrefix() + getActionFriendlyName(thing.getUID().toString()));
freemarkerModel.put("label", thing.getLabel());
jRuleConfig.getGeneratedItemPrefix() + actionService.getActionClass().getSimpleName());
freemarkerModel.put("actionClass", actionService.getActionClass().getSimpleName());
freemarkerModel.put("label", actionService.getActionClass());
freemarkerModel.put("templateName", "Actions");
freemarkerModel.put("parentClass", "JRuleAbstractAction");
return freemarkerModel;
}

private Map<String, Object> createActionModel(Thing thing) {
private Map<String, Object> createActionModel(ActionService actionService) {
Map<String, Object> freemarkerModel = new HashMap<>();
freemarkerModel.put("id", thing.getUID().toString());
freemarkerModel.put("name", getActionFriendlyName(thing.getUID().toString()));
freemarkerModel.put("id", actionService.getActionClass());
freemarkerModel.put("name", actionService.getActionClass().getSimpleName());
freemarkerModel.put("package", jRuleConfig.getGeneratedActionPackage());
freemarkerModel.put("class",
jRuleConfig.getGeneratedItemPrefix() + getActionFriendlyName(thing.getUID().toString()));
freemarkerModel.put("label", thing.getLabel());
jRuleConfig.getGeneratedItemPrefix() + actionService.getActionClass().getSimpleName());
freemarkerModel.put("actionClass", actionService.getActionClass().getSimpleName());
freemarkerModel.put("actionClassFqn", actionService.getActionClass().getName());
freemarkerModel.put("label", actionService.getActionClass());
freemarkerModel.put("templateName", "Action");
freemarkerModel.put("parentClass", "JRuleAbstractAction");

List<Object> methodList = new ArrayList<>();
freemarkerModel.put("methods", methodList);

if (thing.getHandler() != null) {
Class<? extends ThingHandlerService> thingActionsClass = thing.getHandler().getServices().stream()
.filter(ThingActions.class::isAssignableFrom).findFirst()
.orElseThrow(() -> new IllegalStateException("should not occur here"));

freemarkerModel.put("type", thingActionsClass.getTypeName());
Set<String> imports = new TreeSet<>();
freemarkerModel.put("imports", imports);

Arrays.stream(thingActionsClass.getDeclaredMethods())
.filter(method -> method.getAnnotation(RuleAction.class) != null).collect(Collectors.toSet())

.forEach(method -> {
Map<Object, Object> methodMap = new HashMap<>();
methodMap.put("name", method.getName());

Class<?> returnType = replaceTypeIfNecessary(method.getReturnType());

methodMap.put("returnType", returnType.getTypeName());
methodMap.put("import", !returnType.isPrimitive());
methodMap.put("hasReturnType", !returnType.getTypeName().equalsIgnoreCase("void"));
if (!returnType.isPrimitive() && !returnType.getTypeName().equalsIgnoreCase("void")) {
imports.add(returnType.getTypeName());
}

List<Object> args = new ArrayList<>();
methodMap.put("args", args);
Arrays.stream(method.getParameters()).forEach(parameter -> {
if (parameter.getAnnotation(ActionInput.class) != null) {
Map<Object, Object> arg = new HashMap<>();
Class<?> parameterType = replaceTypeIfNecessary(parameter.getType());
arg.put("type", parameterType.getTypeName());
arg.put("reflectionType", ClassUtils.primitiveToWrapper(parameter.getType())
.getTypeName().replaceFirst("java.lang.", ""));
arg.put("name", parameter.getAnnotation(ActionInput.class).name());
args.add(arg);
}
});
methodList.add(methodMap);
Class<?> actionsClass = actionService.getActionClass();

freemarkerModel.put("type", actionsClass.getTypeName());
Set<String> imports = new TreeSet<>();
// imports.add(actionService.getActionClass().getName());
freemarkerModel.put("imports", imports);

Arrays.stream(actionsClass.getDeclaredMethods()).filter(method -> method.getAnnotation(ActionDoc.class) != null)
.collect(Collectors.toSet())

.forEach(method -> {
Map<Object, Object> methodMap = new HashMap<>();
methodMap.put("name", method.getName());

Class<?> returnType = replaceTypeIfNecessary(method.getReturnType());

methodMap.put("returnType", returnType.getTypeName());
methodMap.put("import", !returnType.isPrimitive());
methodMap.put("hasReturnType", !returnType.getTypeName().equalsIgnoreCase("void"));
if (!returnType.isPrimitive() && !returnType.getTypeName().equalsIgnoreCase("void")) {
imports.add(returnType.getTypeName());
}

List<Object> args = new ArrayList<>();
methodMap.put("args", args);
Arrays.stream(method.getParameters()).forEach(parameter -> {
Map<Object, Object> arg = new HashMap<>();
Class<?> parameterType = replaceTypeIfNecessary(parameter.getType());
arg.put("type", parameterType.getTypeName());
arg.put("reflectionType", ClassUtils.primitiveToWrapper(parameter.getType()).getTypeName()
.replaceFirst("java.lang.", ""));
arg.put("name", parameter.getName());
args.add(arg);
});
}
methodList.add(methodMap);
});
return freemarkerModel;
}

private Class<?> replaceTypeIfNecessary(Class<?> type) {
if (type.isPrimitive() || "org.openhab.core.library.types".equals(type.getPackageName())
|| "org.openhab.core.items".equals(type.getPackageName())
|| "org.openhab.core.types".equals(type.getPackageName())
|| type.getPackageName().startsWith("java.")) {
return type;
} else {
return Object.class;
}
}

public static String getActionFriendlyName(String thingUid) {
return Arrays.stream(thingUid.split("[:\\-]")).map(StringUtils::capitalize).collect(Collectors.joining(""));
}
}
Loading
Loading