Search in sources :

Example 1 with HueRuleEntry

use of org.openhab.io.hueemulation.internal.dto.HueRuleEntry in project openhab-addons by openhab.

the class Rules method postNewRule.

@SuppressWarnings({ "null" })
@POST
@Path("{username}/rules")
@Operation(summary = "Create a new rule", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public Response postNewRule(@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    HueRuleEntry newRuleData = cs.gson.fromJson(body, HueRuleEntry.class);
    if (newRuleData == null || newRuleData.name.isEmpty() || newRuleData.actions.isEmpty() || newRuleData.conditions.isEmpty()) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.INVALID_JSON, "Invalid request: No name or actions or conditons!");
    }
    String uid = UUID.randomUUID().toString();
    RuleBuilder builder = RuleBuilder.create(uid).withName(newRuleData.name);
    String description = newRuleData.description;
    if (description != null) {
        builder.withDescription(description);
    }
    try {
        builder.withActions(createActions(uid, newRuleData.actions, Collections.emptyList(), username));
        builder = createHueRuleConditions(newRuleData.conditions, builder, Collections.emptyList(), Collections.emptyList(), itemRegistry);
        ruleRegistry.add(builder.withTags(RULES_TAG).build());
    } catch (IllegalStateException e) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    return NetworkUtils.singleSuccess(cs.gson, uid, "id");
}
Also used : HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Operation(io.swagger.v3.oas.annotations.Operation)

Example 2 with HueRuleEntry

use of org.openhab.io.hueemulation.internal.dto.HueRuleEntry in project openhab-addons by openhab.

the class RulesTests method addGetRemoveRuleViaRest.

@SuppressWarnings("null")
@Test
public void addGetRemoveRuleViaRest() {
    // 1. Create
    String body = "{\"name\":\"test name\",\"description\":\"\",\"owner\":\"\",\"conditions\":[{\"address\":\"/lights/switch1/state/on\",\"operator\":\"dx\"}],\"actions\":[{\"address\":\"/lights/switch1/state\",\"method\":\"PUT\",\"body\":\"{\\u0027on\\u0027:true}\"}]}";
    Response response = commonSetup.client.target(commonSetup.basePath + "/testuser/rules").request().post(Entity.json(body));
    assertEquals(200, response.getStatus());
    assertThat(response.readEntity(String.class), containsString("success"));
    // 1.1 Check for entry
    Entry<String, HueRuleEntry> idAndEntry = cs.ds.rules.entrySet().stream().findAny().get();
    HueRuleEntry entry = idAndEntry.getValue();
    assertThat(entry.name, is("test name"));
    assertThat(entry.actions.get(0).address, is("/lights/switch1/state"));
    assertThat(entry.conditions.get(0).address, is("/lights/switch1/state/on"));
    // 1.2 Check for rule
    Rule rule = ruleRegistry.get(idAndEntry.getKey());
    assertThat(rule.getName(), is("test name"));
    assertThat(rule.getActions().get(0).getId(), is("-api-testuser-lights-switch1-state"));
    assertThat(rule.getActions().get(0).getTypeUID(), is("rules.HttpAction"));
    // 2. Get
    response = commonSetup.client.target(commonSetup.basePath + "/testuser/rules/" + idAndEntry.getKey()).request().get();
    assertEquals(200, response.getStatus());
    HueSceneEntry fromJson = new Gson().fromJson(response.readEntity(String.class), HueSceneEntry.class);
    assertThat(fromJson.name, is(idAndEntry.getValue().name));
    // 3. Remove
    response = commonSetup.client.target(commonSetup.basePath + "/testuser/rules/" + idAndEntry.getKey()).request().delete();
    assertEquals(200, response.getStatus());
    assertTrue(cs.ds.rules.isEmpty());
}
Also used : Response(javax.ws.rs.core.Response) HueSceneEntry(org.openhab.io.hueemulation.internal.dto.HueSceneEntry) Gson(com.google.gson.Gson) HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry) Rule(org.openhab.core.automation.Rule) Test(org.junit.jupiter.api.Test)

Example 3 with HueRuleEntry

use of org.openhab.io.hueemulation.internal.dto.HueRuleEntry in project openhab-addons by openhab.

the class Rules method added.

@Override
public void added(Rule rule) {
    if (!rule.getTags().contains(RULES_TAG)) {
        return;
    }
    HueRuleEntry entry = new HueRuleEntry(rule.getName());
    String desc = rule.getDescription();
    if (desc != null) {
        entry.description = desc;
    }
    rule.getConditions().stream().filter(c -> c.getTypeUID().equals("hue.ruleCondition")).forEach(c -> {
        HueRuleEntry.Condition condition = c.getConfiguration().as(HueRuleEntry.Condition.class);
        // address with pattern "/sensors/2/state/buttonevent"
        String[] parts = condition.address.split("/");
        if (parts.length < 3) {
            return;
        }
        entry.conditions.add(condition);
    });
    rule.getActions().stream().filter(a -> a.getTypeUID().equals("rules.HttpAction")).forEach(a -> {
        HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName());
        if (command == null) {
            return;
        }
        // Remove the "/api/{user}" part
        String[] parts = command.address.split("/");
        command.address = "/" + String.join("/", Arrays.copyOfRange(parts, 3, parts.length));
        entry.actions.add(command);
    });
    cs.ds.rules.put(rule.getUID(), entry);
}
Also used : Arrays(java.util.Arrays) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse) Produces(javax.ws.rs.Produces) NetworkUtils(org.openhab.io.hueemulation.internal.NetworkUtils) Path(javax.ws.rs.Path) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) RegistryChangeListener(org.openhab.core.common.registry.RegistryChangeListener) ConfigStore(org.openhab.io.hueemulation.internal.ConfigStore) Trigger(org.openhab.core.automation.Trigger) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Configuration(org.openhab.core.config.core.Configuration) Map(java.util.Map) DELETE(javax.ws.rs.DELETE) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) Context(javax.ws.rs.core.Context) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) HueEmulationService(org.openhab.io.hueemulation.internal.HueEmulationService) Deactivate(org.osgi.service.component.annotations.Deactivate) Action(org.openhab.core.automation.Action) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Parameter(io.swagger.v3.oas.annotations.Parameter) List(java.util.List) Response(javax.ws.rs.core.Response) JaxrsApplicationSelect(org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect) Entry(java.util.Map.Entry) UriInfo(javax.ws.rs.core.UriInfo) HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) RuleRegistry(org.openhab.core.automation.RuleRegistry) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) ModuleBuilder(org.openhab.core.automation.util.ModuleBuilder) JaxrsWhiteboardConstants(org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants) Activate(org.osgi.service.component.annotations.Activate) JaxrsResource(org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource) HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry) Condition(org.openhab.core.automation.Condition) POST(javax.ws.rs.POST) Rule(org.openhab.core.automation.Rule) Item(org.openhab.core.items.Item) ItemRegistry(org.openhab.core.items.ItemRegistry) AbstractMap(java.util.AbstractMap) TreeMap(java.util.TreeMap) PUT(javax.ws.rs.PUT) RuleUtils(org.openhab.io.hueemulation.internal.RuleUtils) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry)

Example 4 with HueRuleEntry

use of org.openhab.io.hueemulation.internal.dto.HueRuleEntry in project openhab-addons by openhab.

the class Rules method modifyRuleApi.

@PUT
@Path("{username}/rules/{id}")
@Operation(summary = "Set rule attributes", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public // 
Response modifyRuleApi(// 
@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, @PathParam("id") @Parameter(description = "rule id") String id, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    final HueRuleEntry changeRequest = cs.gson.fromJson(body, HueRuleEntry.class);
    Rule rule = ruleRegistry.remove(id);
    if (rule == null) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Rule does not exist!");
    }
    RuleBuilder builder = RuleBuilder.create(rule);
    String temp;
    temp = changeRequest.name;
    if (!temp.isEmpty()) {
        builder.withName(changeRequest.name);
    }
    temp = changeRequest.description;
    if (!temp.isEmpty()) {
        builder.withDescription(temp);
    }
    try {
        if (!changeRequest.actions.isEmpty()) {
            builder.withActions(createActions(rule.getUID(), changeRequest.actions, rule.getActions(), username));
        }
        if (!changeRequest.conditions.isEmpty()) {
            builder = createHueRuleConditions(changeRequest.conditions, builder, rule.getTriggers(), rule.getConditions(), itemRegistry);
        }
        ruleRegistry.add(builder.build());
    } catch (IllegalStateException e) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    return NetworkUtils.successList(cs.gson, // 
    Arrays.asList(// 
    new HueSuccessGeneric(changeRequest.name, "/rules/" + id + "/name"), // 
    new HueSuccessGeneric(changeRequest.description, "/rules/" + id + "/description"), // 
    new HueSuccessGeneric(changeRequest.actions.toString(), "/rules/" + id + "/actions"), // 
    new HueSuccessGeneric(changeRequest.conditions.toString(), "/rules/" + id + "/conditions")));
}
Also used : HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry) Rule(org.openhab.core.automation.Rule) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) Path(javax.ws.rs.Path) Operation(io.swagger.v3.oas.annotations.Operation) PUT(javax.ws.rs.PUT)

Example 5 with HueRuleEntry

use of org.openhab.io.hueemulation.internal.dto.HueRuleEntry in project openhab-addons by openhab.

the class RulesTests method getAll.

@Test
public void getAll() {
    HueCommand command = new HueCommand("/api/testuser/lights/switch1/state", "PUT", "{'on':true}");
    HueRuleEntry.Condition condition = new HueRuleEntry.Condition("/lights/switch1/state/on", Operator.dx, null);
    Entry<Trigger, Condition> triggerCond = Rules.hueConditionToAutomation(command.address.replace("/", "-"), condition, itemRegistry);
    Rule rule = // 
    RuleBuilder.create("demo1").withName("test name").withTags(Rules.RULES_TAG).withActions(// 
    RuleUtils.createHttpAction(command, "command")).withTriggers(triggerCond.getKey()).withConditions(triggerCond.getValue()).build();
    ruleRegistry.add(rule);
    Response response = commonSetup.client.target(commonSetup.basePath + "/testuser/rules").request().get();
    Type type = new TypeToken<Map<String, HueRuleEntry>>() {
    }.getType();
    String body = response.readEntity(String.class);
    Map<String, HueRuleEntry> fromJson = new Gson().fromJson(body, type);
    HueRuleEntry entry = fromJson.get("demo1");
    assertThat(entry.name, is("test name"));
    assertThat(entry.actions.get(0).address, is("/lights/switch1/state"));
    assertThat(entry.conditions.get(0).address, is("/lights/switch1/state/on"));
}
Also used : Condition(org.openhab.core.automation.Condition) Gson(com.google.gson.Gson) HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) Response(javax.ws.rs.core.Response) OnOffType(org.openhab.core.library.types.OnOffType) Type(java.lang.reflect.Type) HSBType(org.openhab.core.library.types.HSBType) Trigger(org.openhab.core.automation.Trigger) HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry) Rule(org.openhab.core.automation.Rule) Map(java.util.Map) Test(org.junit.jupiter.api.Test)

Aggregations

HueRuleEntry (org.openhab.io.hueemulation.internal.dto.HueRuleEntry)7 Rule (org.openhab.core.automation.Rule)6 Response (javax.ws.rs.core.Response)4 Test (org.junit.jupiter.api.Test)4 Condition (org.openhab.core.automation.Condition)4 Trigger (org.openhab.core.automation.Trigger)4 HueCommand (org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand)4 Operation (io.swagger.v3.oas.annotations.Operation)3 Path (javax.ws.rs.Path)3 RuleBuilder (org.openhab.core.automation.util.RuleBuilder)3 Gson (com.google.gson.Gson)2 Map (java.util.Map)2 POST (javax.ws.rs.POST)2 PUT (javax.ws.rs.PUT)2 HueSuccessGeneric (org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric)2 Parameter (io.swagger.v3.oas.annotations.Parameter)1 ApiResponse (io.swagger.v3.oas.annotations.responses.ApiResponse)1 Type (java.lang.reflect.Type)1 AbstractMap (java.util.AbstractMap)1 ArrayList (java.util.ArrayList)1