Search in sources :

Example 36 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class ItemUpdater method receiveUpdate.

@Override
protected void receiveUpdate(ItemStateEvent updateEvent) {
    String itemName = updateEvent.getItemName();
    State newState = updateEvent.getItemState();
    try {
        GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
        boolean isAccepted = false;
        if (item.getAcceptedDataTypes().contains(newState.getClass())) {
            isAccepted = true;
        } else {
            // Look for class hierarchy
            for (Class<? extends State> state : item.getAcceptedDataTypes()) {
                try {
                    if (!state.isEnum() && state.newInstance().getClass().isAssignableFrom(newState.getClass())) {
                        isAccepted = true;
                        break;
                    }
                } catch (InstantiationException e) {
                    // Should never happen
                    logger.warn("InstantiationException on {}", e.getMessage());
                } catch (IllegalAccessException e) {
                    // Should never happen
                    logger.warn("IllegalAccessException on {}", e.getMessage());
                }
            }
        }
        if (isAccepted) {
            item.setState(newState);
        } else {
            logger.debug("Received update of a not accepted type ({}) for item {}", newState.getClass().getSimpleName(), itemName);
        }
    } catch (ItemNotFoundException e) {
        logger.debug("Received update for non-existing item: {}", e.getMessage());
    }
}
Also used : GenericItem(org.eclipse.smarthome.core.items.GenericItem) State(org.eclipse.smarthome.core.types.State) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 37 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class SendConsoleCommandExtension method execute.

@Override
public void execute(String[] args, Console console) {
    if (args.length > 0) {
        String itemName = args[0];
        try {
            Item item = this.itemRegistry.getItemByPattern(itemName);
            if (args.length > 1) {
                String commandName = args[1];
                Command command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandName);
                if (command != null) {
                    eventPublisher.post(ItemEventFactory.createCommandEvent(itemName, command));
                    console.println("Command has been sent successfully.");
                } else {
                    console.println("Error: Command '" + commandName + "' is not valid for item '" + itemName + "'");
                    console.println("Valid command types are:");
                    for (Class<? extends Command> acceptedType : item.getAcceptedCommandTypes()) {
                        console.print("  " + acceptedType.getSimpleName());
                        if (acceptedType.isEnum()) {
                            console.print(": ");
                            for (Object e : acceptedType.getEnumConstants()) {
                                console.print(e + " ");
                            }
                        }
                        console.println("");
                    }
                }
            } else {
                printUsage(console);
            }
        } catch (ItemNotFoundException e) {
            console.println("Error: Item '" + itemName + "' does not exist.");
        } catch (ItemNotUniqueException e) {
            console.print("Error: Multiple items match this pattern: ");
            for (Item item : e.getMatchingItems()) {
                console.print(item.getName() + " ");
            }
        }
    } else {
        printUsage(console);
    }
}
Also used : Item(org.eclipse.smarthome.core.items.Item) Command(org.eclipse.smarthome.core.types.Command) ItemNotUniqueException(org.eclipse.smarthome.core.items.ItemNotUniqueException) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 38 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class ItemResource method removeMember.

@DELETE
@RolesAllowed({ Role.ADMIN })
@Path("/{itemName: [a-zA-Z_0-9]*}/members/{memberItemName: [a-zA-Z_0-9]*}")
@ApiOperation(value = "Removes an existing member from a group item.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Item or member item not found or item is not of type group item."), @ApiResponse(code = 405, message = "Member item is not editable.") })
public Response removeMember(@PathParam("itemName") @ApiParam(value = "item name", required = true) String itemName, @PathParam("memberItemName") @ApiParam(value = "member item name", required = true) String memberItemName) {
    try {
        Item item = itemRegistry.getItem(itemName);
        if (!(item instanceof GroupItem)) {
            return Response.status(Status.NOT_FOUND).build();
        }
        GroupItem groupItem = (GroupItem) item;
        Item memberItem = itemRegistry.getItem(memberItemName);
        if (!(memberItem instanceof GenericItem)) {
            return Response.status(Status.NOT_FOUND).build();
        }
        if (managedItemProvider.get(memberItemName) == null) {
            return Response.status(Status.METHOD_NOT_ALLOWED).build();
        }
        GenericItem genericMemberItem = (GenericItem) memberItem;
        genericMemberItem.removeGroupName(groupItem.getName());
        managedItemProvider.update(genericMemberItem);
        return Response.ok(null, MediaType.TEXT_PLAIN).build();
    } catch (ItemNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}
Also used : ActiveItem(org.eclipse.smarthome.core.items.ActiveItem) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) RollershutterItem(org.eclipse.smarthome.core.library.items.RollershutterItem) GroupItem(org.eclipse.smarthome.core.items.GroupItem) GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) GenericItem(org.eclipse.smarthome.core.items.GenericItem) GroupItem(org.eclipse.smarthome.core.items.GroupItem) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) RolesAllowed(javax.annotation.security.RolesAllowed) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 39 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class PersistenceResource method putItemState.

private Response putItemState(String serviceId, String itemName, String value, String time) {
    // If serviceId is null, then use the default service
    PersistenceService service = null;
    String effectiveServiceId = serviceId != null ? serviceId : persistenceServiceRegistry.getDefaultId();
    service = persistenceServiceRegistry.get(effectiveServiceId);
    if (service == null) {
        logger.warn("Persistence service not found '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not found: " + effectiveServiceId);
    }
    Item item;
    try {
        if (itemRegistry == null) {
            logger.warn("Item registry not set.");
            return JSONResponse.createErrorResponse(Status.CONFLICT, "Item registry not set.");
        }
        item = itemRegistry.getItem(itemName);
    } catch (ItemNotFoundException e) {
        logger.warn("Item not found '{}'.", itemName);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Item not found: " + itemName);
    }
    // Try to parse a State from the input
    State state = TypeParser.parseState(item.getAcceptedDataTypes(), value);
    if (state == null) {
        // State could not be parsed
        logger.warn("Can't persist item {} with invalid state '{}'.", itemName, value);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "State could not be parsed: " + value);
    }
    ZonedDateTime dateTime = null;
    if (time != null && time.length() != 0) {
        dateTime = convertTime(time);
    }
    if (dateTime == null || dateTime.toEpochSecond() == 0) {
        logger.warn("Error with persistence store to {}. Time badly formatted {}.", itemName, time);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Time badly formatted.");
    }
    if (!(service instanceof ModifiablePersistenceService)) {
        logger.warn("Persistence service not modifiable '{}'.", effectiveServiceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not modifiable: " + effectiveServiceId);
    }
    ModifiablePersistenceService mService = (ModifiablePersistenceService) service;
    mService.store(item, Date.from(dateTime.toInstant()), state);
    return Response.status(Status.OK).build();
}
Also used : PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) ModifiablePersistenceService(org.eclipse.smarthome.core.persistence.ModifiablePersistenceService) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem) Item(org.eclipse.smarthome.core.items.Item) ZonedDateTime(java.time.ZonedDateTime) ModifiablePersistenceService(org.eclipse.smarthome.core.persistence.ModifiablePersistenceService) State(org.eclipse.smarthome.core.types.State) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Example 40 with ItemNotFoundException

use of org.eclipse.smarthome.core.items.ItemNotFoundException in project smarthome by eclipse.

the class SitemapResource method createWidgetBean.

private WidgetDTO createWidgetBean(String sitemapName, Widget widget, boolean drillDown, URI uri, String widgetId, Locale locale) {
    // Test visibility
    if (itemUIRegistry.getVisiblity(widget) == false) {
        return null;
    }
    WidgetDTO bean = new WidgetDTO();
    if (widget.getItem() != null) {
        try {
            Item item = itemUIRegistry.getItem(widget.getItem());
            String widgetTypeName = widget.eClass().getInstanceTypeName().substring(widget.eClass().getInstanceTypeName().lastIndexOf(".") + 1);
            boolean isMapview = "mapview".equalsIgnoreCase(widgetTypeName);
            Predicate<Item> itemFilter = (i -> i.getType().equals(CoreItemFactory.LOCATION));
            bean.item = EnrichedItemDTOMapper.map(item, isMapview, itemFilter, UriBuilder.fromUri(uri).build(), locale);
            bean.state = itemUIRegistry.getState(widget).toFullString();
            // In case the widget state is identical to the item state, its value is set to null.
            if (bean.state != null && bean.state.equals(bean.item.state)) {
                bean.state = null;
            }
        } catch (ItemNotFoundException e) {
            logger.debug("{}", e.getMessage());
        }
    }
    bean.widgetId = widgetId;
    bean.icon = itemUIRegistry.getCategory(widget);
    bean.labelcolor = itemUIRegistry.getLabelColor(widget);
    bean.valuecolor = itemUIRegistry.getValueColor(widget);
    bean.label = itemUIRegistry.getLabel(widget);
    bean.type = widget.eClass().getName();
    if (widget instanceof LinkableWidget) {
        LinkableWidget linkableWidget = (LinkableWidget) widget;
        EList<Widget> children = itemUIRegistry.getChildren(linkableWidget);
        if (widget instanceof Frame) {
            for (Widget child : children) {
                String wID = itemUIRegistry.getWidgetId(child);
                WidgetDTO subWidget = createWidgetBean(sitemapName, child, drillDown, uri, wID, locale);
                if (subWidget != null) {
                    bean.widgets.add(subWidget);
                }
            }
        } else if (children.size() > 0) {
            String pageName = itemUIRegistry.getWidgetId(linkableWidget);
            bean.linkedPage = createPageBean(sitemapName, itemUIRegistry.getLabel(widget), itemUIRegistry.getCategory(widget), pageName, drillDown ? children : null, drillDown, isLeaf(children), uri, locale, false);
        }
    }
    if (widget instanceof Switch) {
        Switch switchWidget = (Switch) widget;
        for (Mapping mapping : switchWidget.getMappings()) {
            MappingDTO mappingBean = new MappingDTO();
            mappingBean.command = mapping.getCmd();
            mappingBean.label = mapping.getLabel();
            bean.mappings.add(mappingBean);
        }
    }
    if (widget instanceof Selection) {
        Selection selectionWidget = (Selection) widget;
        for (Mapping mapping : selectionWidget.getMappings()) {
            MappingDTO mappingBean = new MappingDTO();
            mappingBean.command = mapping.getCmd();
            mappingBean.label = mapping.getLabel();
            bean.mappings.add(mappingBean);
        }
    }
    if (widget instanceof Slider) {
        Slider sliderWidget = (Slider) widget;
        bean.sendFrequency = sliderWidget.getFrequency();
        bean.switchSupport = sliderWidget.isSwitchEnabled();
    }
    if (widget instanceof List) {
        List listWidget = (List) widget;
        bean.separator = listWidget.getSeparator();
    }
    if (widget instanceof Image) {
        bean.url = buildProxyUrl(sitemapName, widget, uri);
        Image imageWidget = (Image) widget;
        if (imageWidget.getRefresh() > 0) {
            bean.refresh = imageWidget.getRefresh();
        }
    }
    if (widget instanceof Video) {
        Video videoWidget = (Video) widget;
        if (videoWidget.getEncoding() != null) {
            bean.encoding = videoWidget.getEncoding();
        }
        if (videoWidget.getEncoding() != null && videoWidget.getEncoding().toLowerCase().contains("hls")) {
            bean.url = videoWidget.getUrl();
        } else {
            bean.url = buildProxyUrl(sitemapName, videoWidget, uri);
        }
    }
    if (widget instanceof Webview) {
        Webview webViewWidget = (Webview) widget;
        bean.url = webViewWidget.getUrl();
        bean.height = webViewWidget.getHeight();
    }
    if (widget instanceof Mapview) {
        Mapview mapViewWidget = (Mapview) widget;
        bean.height = mapViewWidget.getHeight();
    }
    if (widget instanceof Chart) {
        Chart chartWidget = (Chart) widget;
        bean.service = chartWidget.getService();
        bean.period = chartWidget.getPeriod();
        bean.legend = chartWidget.getLegend();
        if (chartWidget.getRefresh() > 0) {
            bean.refresh = chartWidget.getRefresh();
        }
    }
    if (widget instanceof Setpoint) {
        Setpoint setpointWidget = (Setpoint) widget;
        bean.minValue = setpointWidget.getMinValue();
        bean.maxValue = setpointWidget.getMaxValue();
        bean.step = setpointWidget.getStep();
    }
    return bean;
}
Also used : Frame(org.eclipse.smarthome.model.sitemap.Frame) Slider(org.eclipse.smarthome.model.sitemap.Slider) Selection(org.eclipse.smarthome.model.sitemap.Selection) Mapview(org.eclipse.smarthome.model.sitemap.Mapview) Widget(org.eclipse.smarthome.model.sitemap.Widget) LinkableWidget(org.eclipse.smarthome.model.sitemap.LinkableWidget) Setpoint(org.eclipse.smarthome.model.sitemap.Setpoint) Mapping(org.eclipse.smarthome.model.sitemap.Mapping) Webview(org.eclipse.smarthome.model.sitemap.Webview) Image(org.eclipse.smarthome.model.sitemap.Image) LinkableWidget(org.eclipse.smarthome.model.sitemap.LinkableWidget) GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) Switch(org.eclipse.smarthome.model.sitemap.Switch) Video(org.eclipse.smarthome.model.sitemap.Video) List(org.eclipse.smarthome.model.sitemap.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) EList(org.eclipse.emf.common.util.EList) Chart(org.eclipse.smarthome.model.sitemap.Chart) ItemNotFoundException(org.eclipse.smarthome.core.items.ItemNotFoundException)

Aggregations

ItemNotFoundException (org.eclipse.smarthome.core.items.ItemNotFoundException)41 Item (org.eclipse.smarthome.core.items.Item)36 GroupItem (org.eclipse.smarthome.core.items.GroupItem)22 GenericItem (org.eclipse.smarthome.core.items.GenericItem)17 State (org.eclipse.smarthome.core.types.State)15 NumberItem (org.eclipse.smarthome.core.library.items.NumberItem)8 RollershutterItem (org.eclipse.smarthome.core.library.items.RollershutterItem)8 SwitchItem (org.eclipse.smarthome.core.library.items.SwitchItem)8 Command (org.eclipse.smarthome.core.types.Command)7 ItemNotUniqueException (org.eclipse.smarthome.core.items.ItemNotUniqueException)5 QuantityType (org.eclipse.smarthome.core.library.types.QuantityType)5 Mapping (org.eclipse.smarthome.model.sitemap.Mapping)5 Date (java.util.Date)4 CallItem (org.eclipse.smarthome.core.library.items.CallItem)4 DateTimeItem (org.eclipse.smarthome.core.library.items.DateTimeItem)4 StringItem (org.eclipse.smarthome.core.library.items.StringItem)4 Widget (org.eclipse.smarthome.model.sitemap.Widget)4 ColorItem (org.eclipse.smarthome.core.library.items.ColorItem)3 ContactItem (org.eclipse.smarthome.core.library.items.ContactItem)3 DimmerItem (org.eclipse.smarthome.core.library.items.DimmerItem)3