Skip to content

Commit

Permalink
[REST] New REST APIs to generate DSL syntax for items and things
Browse files Browse the repository at this point in the history
Related to openhab#4509

Signed-off-by: Laurent Garnier <[email protected]>
  • Loading branch information
lolodomo committed Jan 23, 2025
1 parent ce37425 commit 3f50ec9
Show file tree
Hide file tree
Showing 17 changed files with 1,211 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
*/
package org.openhab.core.io.rest.core.internal.discovery;

import static org.openhab.core.config.discovery.inbox.InboxPredicates.forThingUID;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

import javax.annotation.security.RolesAllowed;
Expand All @@ -33,6 +40,11 @@
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.auth.Role;
import org.openhab.core.config.core.ConfigDescription;
import org.openhab.core.config.core.ConfigDescriptionParameter;
import org.openhab.core.config.core.ConfigDescriptionRegistry;
import org.openhab.core.config.core.ConfigUtil;
import org.openhab.core.config.core.Configuration;
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultFlag;
import org.openhab.core.config.discovery.dto.DiscoveryResultDTO;
Expand All @@ -44,9 +56,15 @@
import org.openhab.core.io.rest.Stream2JSONInputStream;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingFactory;
import org.openhab.core.thing.syntaxgenerator.ThingSyntaxGenerator;
import org.openhab.core.thing.type.ThingType;
import org.openhab.core.thing.type.ThingTypeRegistry;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JSONRequired;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect;
Expand Down Expand Up @@ -96,10 +114,25 @@ public class InboxResource implements RESTResource {
public static final String PATH_INBOX = "inbox";

private final Inbox inbox;
private final ThingTypeRegistry thingTypeRegistry;
private final ConfigDescriptionRegistry configDescRegistry;
private final Map<String, ThingSyntaxGenerator> thingSyntaxGenerators = new ConcurrentHashMap<>();

@Activate
public InboxResource(final @Reference Inbox inbox) {
public InboxResource(final @Reference Inbox inbox, final @Reference ThingTypeRegistry thingTypeRegistry,
final @Reference ConfigDescriptionRegistry configDescRegistry) {
this.inbox = inbox;
this.thingTypeRegistry = thingTypeRegistry;
this.configDescRegistry = configDescRegistry;
}

@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE)
protected void addThingSyntaxGenerator(ThingSyntaxGenerator thingSyntaxGenerator) {
thingSyntaxGenerators.put(thingSyntaxGenerator.getFormat(), thingSyntaxGenerator);
}

protected void removeThingSyntaxGenerator(ThingSyntaxGenerator thingSyntaxGenerator) {
thingSyntaxGenerators.remove(thingSyntaxGenerator.getFormat());
}

@POST
Expand Down Expand Up @@ -182,4 +215,61 @@ public Response unignore(@PathParam("thingUID") @Parameter(description = "thingU
inbox.setFlag(new ThingUID(thingUID), DiscoveryResultFlag.NEW);
return Response.ok(null, MediaType.TEXT_PLAIN).build();
}

@GET
@Path("/{thingUID}/filesyntax")
@Produces(MediaType.TEXT_PLAIN)
@Operation(operationId = "generateSyntaxForDiscoveryResult", summary = "Generate file syntax for the thing associated to the discovery result.", responses = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class))),
@ApiResponse(responseCode = "400", description = "Unsupported syntax format."),
@ApiResponse(responseCode = "404", description = "Discovery result not found in the inbox or thing type not found.") })
public Response generateSyntaxForDiscoveryResult(
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @Parameter(description = "language") @Nullable String language,
@PathParam("thingUID") @Parameter(description = "thingUID") String thingUID,
@DefaultValue("DSL") @QueryParam("format") @Parameter(description = "syntax format") String format) {
ThingSyntaxGenerator generator = thingSyntaxGenerators.get(format);
if (generator == null) {
String message = "No syntax available for format " + format + "!";
return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
}

List<DiscoveryResult> results = inbox.getAll().stream().filter(forThingUID(new ThingUID(thingUID))).toList();
if (results.isEmpty()) {
String message = "Discovery result for thing with UID " + thingUID + " not found in the inbox!";
return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}
DiscoveryResult result = results.get(0);
ThingType thingType = thingTypeRegistry.getThingType(result.getThingTypeUID());
if (thingType == null) {
String message = "Thing type with UID " + result.getThingTypeUID() + " does not exist!";
return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}
Configuration config = buildThingConfiguration(thingType, result.getProperties());
Thing thing = ThingFactory.createThing(thingType, result.getThingUID(), config, result.getBridgeUID(),
configDescRegistry);

return Response.ok(generator.generateSyntax(List.of(thing), false)).build();
}

private Configuration buildThingConfiguration(ThingType thingType, Map<String, Object> properties) {
Map<String, Object> configParams = new HashMap<>();
for (ConfigDescriptionParameter param : getConfigDescriptionParameters(thingType)) {
Object value = properties.get(param.getName());
if (value != null) {
configParams.put(param.getName(), ConfigUtil.normalizeType(value, param));
}
}
return new Configuration(configParams);
}

private List<ConfigDescriptionParameter> getConfigDescriptionParameters(ThingType thingType) {
URI descURI = thingType.getConfigDescriptionURI();
if (descURI != null) {
ConfigDescription desc = configDescRegistry.getConfigDescription(descURI);
if (desc != null) {
return desc.getParameters();
}
}
return List.of();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -89,13 +90,16 @@
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.semantics.SemanticTagRegistry;
import org.openhab.core.semantics.SemanticsPredicates;
import org.openhab.core.thing.syntaxgenerator.ItemSyntaxGenerator;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.TypeParser;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JSONRequired;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect;
Expand Down Expand Up @@ -183,6 +187,7 @@ private static void respectForwarded(final UriBuilder uriBuilder, final @Context
private final MetadataSelectorMatcher metadataSelectorMatcher;
private final SemanticTagRegistry semanticTagRegistry;
private final TimeZoneProvider timeZoneProvider;
private final Map<String, ItemSyntaxGenerator> itemSyntaxGenerators = new ConcurrentHashMap<>();

private final RegistryChangedRunnableListener<Item> resetLastModifiedItemChangeListener = new RegistryChangedRunnableListener<>(
() -> lastModified = null);
Expand Down Expand Up @@ -224,6 +229,15 @@ void deactivate() {
this.metadataRegistry.removeRegistryChangeListener(resetLastModifiedMetadataChangeListener);
}

@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE)
protected void addItemSyntaxGenerator(ItemSyntaxGenerator itemSyntaxGenerator) {
itemSyntaxGenerators.put(itemSyntaxGenerator.getFormat(), itemSyntaxGenerator);
}

protected void removeItemSyntaxGenerator(ItemSyntaxGenerator itemSyntaxGenerator) {
itemSyntaxGenerators.remove(itemSyntaxGenerator.getFormat());
}

private UriBuilder uriBuilder(final UriInfo uriInfo, final HttpHeaders httpHeaders) {
final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder().path(PATH_ITEMS).path("{itemName}");
respectForwarded(uriBuilder, httpHeaders);
Expand Down Expand Up @@ -901,6 +915,53 @@ public Response getSemanticItem(final @Context UriInfo uriInfo, final @Context H
return JSONResponse.createResponse(Status.OK, dto, null);
}

@GET
@RolesAllowed({ Role.ADMIN })
@Path("/filesyntax")
@Produces(MediaType.TEXT_PLAIN)
@Operation(operationId = "generateSyntaxForAllItems", summary = "Generate file syntax for all items.", security = {
@SecurityRequirement(name = "oauth2", scopes = { "admin" }) }, responses = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class))),
@ApiResponse(responseCode = "400", description = "Unsupported syntax format.") })
public Response generateSyntaxForAllItems(
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @Parameter(description = "language") @Nullable String language,
@DefaultValue("DSL") @QueryParam("format") @Parameter(description = "syntax format") String format) {
ItemSyntaxGenerator generator = itemSyntaxGenerators.get(format);
if (generator == null) {
String message = "No syntax available for format " + format + "!";
return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
}
return Response.ok(generator.generateSyntax(sortItems(itemRegistry.getAll()))).build();
}

@GET
@RolesAllowed({ Role.ADMIN })
@Path("/{itemname: [a-zA-Z_0-9]+}/filesyntax")
@Produces(MediaType.TEXT_PLAIN)
@Operation(operationId = "generateSyntaxForItem", summary = "Generate file syntax for an item.", security = {
@SecurityRequirement(name = "oauth2", scopes = { "admin" }) }, responses = {
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class))),
@ApiResponse(responseCode = "400", description = "Unsupported syntax format."),
@ApiResponse(responseCode = "404", description = "Item not found.") })
public Response generateSyntaxForItem(
@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @Parameter(description = "language") @Nullable String language,
@PathParam("itemname") @Parameter(description = "item name") String itemname,
@DefaultValue("DSL") @QueryParam("format") @Parameter(description = "syntax format") String format) {
ItemSyntaxGenerator generator = itemSyntaxGenerators.get(format);
if (generator == null) {
String message = "No syntax available for format " + format + "!";
return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
}

Item item = getItem(itemname);
if (item == null) {
String message = "Item " + itemname + " does not exist!";
return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}

return Response.ok(generator.generateSyntax(List.of(item))).build();
}

private JsonObject buildStatusObject(String itemName, String status, @Nullable String message) {
JsonObject jo = new JsonObject();
jo.addProperty("name", itemName);
Expand Down Expand Up @@ -1006,4 +1067,48 @@ private void addMetadata(EnrichedItemDTO dto, Set<String> namespaces, @Nullable
private boolean isEditable(String itemName) {
return managedItemProvider.get(itemName) != null;
}

private List<Item> sortItems(Collection<Item> items) {
return items.stream().sorted((item1, item2) -> {
if (item1.getName().equals(item2.getName())) {
return 0;
} else if (isAncestorGroupOf(item1, item2)) {
return -1;
} else if (isAncestorGroupOf(item2, item1)) {
return 1;
} else if (item1 instanceof GroupItem && !(item2 instanceof GroupItem)) {
return -1;
} else if (item2 instanceof GroupItem && !(item1 instanceof GroupItem)) {
return 1;
} else {
return item1.getName().compareTo(item2.getName());
}
}).collect(Collectors.toList());
}

private boolean isAncestorGroupOf(Item item1, Item item2) {
if (!item1.getName().equals(item2.getName()) && item1 instanceof GroupItem group) {
if (item2 instanceof GroupItem) {
List<Item> items = new ArrayList<>();
fillGroupTree(items, group);
return items.contains(item2);
} else {
return group.getAllMembers().contains(item2);
}
}
return false;
}

private void fillGroupTree(List<Item> items, Item item) {
if (!items.contains(item)) {
items.add(item);
if (item instanceof GroupItem group) {
for (Item member : group.getMembers()) {
if (member instanceof GroupItem groupMember) {
fillGroupTree(items, groupMember);
}
}
}
}
}
}
Loading

0 comments on commit 3f50ec9

Please sign in to comment.