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 #4509

Added REST APIs:
- GET /inbox/{thingUID}/filesyntax to generate file syntax for the thing associated to the discovery result
- GET /items/filesyntax to generate file syntax for all items
- GET /items/{itemname}/filesyntax to generate file syntax for an item
- GET /things/filesyntax to generate file syntax for all things
- GET /things/{thingUID}/filesyntax to generate file syntax for a thing

All these APIs have a parameter named "format" to request a particular output format. Of course, a syntax generator should be available for this format.
Only "DSL" format is provided by this PR as this is currently our unique supported format for items and things in config files.
So this parameter is set to "DSL" by default.
In the future, new formats could be added and they will be automatically supported by these APIs.

The API GET /things/filesyntax has another parameter named "preferPresentationAsTree" allowing to choose between a flat display or a display as a tree.
Its default value is true for a display of things as tree.

Signed-off-by: Laurent Garnier <[email protected]>
  • Loading branch information
lolodomo committed Jan 25, 2025
1 parent ce37425 commit 2ce9669
Show file tree
Hide file tree
Showing 17 changed files with 1,255 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,60 @@ 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();
}

return Response.ok(generator.generateSyntax(List.of(simulateThing(result, thingType)), false)).build();
}

/*
* Create a thing from a discovery result without inserting it in the thing registry
*/
private Thing simulateThing(DiscoveryResult result, ThingType thingType) {
Map<String, Object> configParams = new HashMap<>();
List<ConfigDescriptionParameter> configDescriptionParameters = List.of();
URI descURI = thingType.getConfigDescriptionURI();
if (descURI != null) {
ConfigDescription desc = configDescRegistry.getConfigDescription(descURI);
if (desc != null) {
configDescriptionParameters = desc.getParameters();
}
}
for (ConfigDescriptionParameter param : configDescriptionParameters) {
Object value = result.getProperties().get(param.getName());
if (value != null) {
configParams.put(param.getName(), ConfigUtil.normalizeType(value, param));
}
}
Configuration config = new Configuration(configParams);
return ThingFactory.createThing(thingType, result.getThingUID(), config, result.getBridgeUID(),
configDescRegistry);
}
}
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,18 @@
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.semantics.SemanticTagRegistry;
import org.openhab.core.semantics.SemanticsPredicates;
import org.openhab.core.thing.link.ItemChannelLink;
import org.openhab.core.thing.link.ItemChannelLinkRegistry;
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 @@ -182,7 +188,9 @@ private static void respectForwarded(final UriBuilder uriBuilder, final @Context
private final MetadataRegistry metadataRegistry;
private final MetadataSelectorMatcher metadataSelectorMatcher;
private final SemanticTagRegistry semanticTagRegistry;
private final ItemChannelLinkRegistry itemChannelLinkRegistry;
private final TimeZoneProvider timeZoneProvider;
private final Map<String, ItemSyntaxGenerator> itemSyntaxGenerators = new ConcurrentHashMap<>();

private final RegistryChangedRunnableListener<Item> resetLastModifiedItemChangeListener = new RegistryChangedRunnableListener<>(
() -> lastModified = null);
Expand All @@ -202,6 +210,7 @@ public ItemResource(//
final @Reference MetadataRegistry metadataRegistry,
final @Reference MetadataSelectorMatcher metadataSelectorMatcher,
final @Reference SemanticTagRegistry semanticTagRegistry,
final @Reference ItemChannelLinkRegistry itemChannelLinkRegistry,
final @Reference TimeZoneProvider timeZoneProvider) {
this.dtoMapper = dtoMapper;
this.eventPublisher = eventPublisher;
Expand All @@ -212,6 +221,7 @@ public ItemResource(//
this.metadataRegistry = metadataRegistry;
this.metadataSelectorMatcher = metadataSelectorMatcher;
this.semanticTagRegistry = semanticTagRegistry;
this.itemChannelLinkRegistry = itemChannelLinkRegistry;
this.timeZoneProvider = timeZoneProvider;

this.itemRegistry.addRegistryChangeListener(resetLastModifiedItemChangeListener);
Expand All @@ -224,6 +234,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 +920,58 @@ 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()), itemChannelLinkRegistry.getAll(),
metadataRegistry.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();
}

Set<ItemChannelLink> channelLinks = itemChannelLinkRegistry.getLinks(itemname);
Set<Metadata> metadata = metadataRegistry.getAll().stream()
.filter(md -> md.getUID().getItemName().equals(itemname)).collect(Collectors.toSet());

return Response.ok(generator.generateSyntax(List.of(item), channelLinks, metadata)).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 +1077,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 2ce9669

Please sign in to comment.