From 8a6eae39b99cfba240562c6c13ebabeeb9a73afd Mon Sep 17 00:00:00 2001 From: Wouter Born Date: Mon, 8 Jan 2024 19:06:26 +0100 Subject: [PATCH] Cleanup Java code This cleanup includes: * Fix deprecations * Fix JavaDocs * Remove redundant toString calls * Remove redundant semicolons * Simplify boolean expressions * Use diamond operator * Use enhanced for loops * Use instanceof pattern matching * Use isEmpty instead of 0 comparisons * Use lambdas * Use static inner classes * Use StandardCharsets Also adds the SA_LOCAL_SELF_COMPARISON suppression similar as used in other repositories for https://github.com/spotbugs/sonar-findbugs/issues/876. Signed-off-by: Wouter Born --- .../render/AbstractWidgetRenderer.java | 20 +++----- .../internal/render/ButtongridRenderer.java | 3 +- .../basic/internal/render/ImageRenderer.java | 2 +- .../basic/internal/render/InputRenderer.java | 12 ++--- .../internal/render/MapviewRenderer.java | 3 +- .../basic/internal/render/PageRenderer.java | 16 +++--- .../basic/internal/render/TextRenderer.java | 2 +- .../cometvisu/internal/ManagerSettings.java | 4 +- .../internal/StateBeanMessageBodyWriter.java | 6 +-- .../internal/backend/rest/ChartResource.java | 3 +- .../backend/rest/DataProviderResource.java | 2 +- .../backend/rest/EventBroadcaster.java | 1 - .../backend/rest/MultipartRequestMap.java | 2 +- .../internal/backend/rest/ReadResource.java | 8 +-- .../backend/sitemap/ConfigHelper.java | 50 +++++-------------- .../internal/backend/sitemap/VisuConfig.java | 34 +++++-------- .../internal/servlet/CometVisuApp.java | 20 +++----- .../internal/servlet/CometVisuServlet.java | 42 ++++++---------- .../internal/util/ClientInstaller.java | 13 ++--- .../ui/cometvisu/internal/util/FsUtil.java | 4 +- .../ui/cometvisu/internal/util/SseUtil.java | 12 ++--- .../java/org/openhab/ui/habot/card/Card.java | 26 +++++----- .../openhab/ui/habot/card/CardBuilder.java | 19 +++---- .../org/openhab/ui/habot/card/Component.java | 6 +-- .../ui/habot/card/internal/CardRegistry.java | 11 ++-- .../nlp/AbstractItemIntentInterpreter.java | 3 +- .../java/org/openhab/ui/habot/nlp/Intent.java | 4 +- .../internal/IntentDocumentSampleStream.java | 2 +- .../ui/habot/nlp/internal/IntentTrainer.java | 2 +- .../internal/NamedAttributesItemResolver.java | 2 +- .../nlp/internal/OpenNLPInterpreter.java | 31 +++++------- .../nlp/internal/SemanticsItemResolver.java | 11 ++-- .../skill/HistoryLastChangesSkill.java | 5 +- .../WebPushNotificationAction.java | 4 +- .../WebPushNotificationActionHandler.java | 4 +- .../internal/NotificationService.java | 4 +- .../internal/webpush/PushService.java | 2 +- .../internal/webpush/Subscription.java | 2 +- .../ui/habot/rest/internal/HABotResource.java | 4 +- .../ui/habot/test/AbstractTrainerTest.java | 9 ++-- .../CommunityWidgetGalleryProvider.java | 8 +-- .../community/DiscourseGalleryResponse.java | 6 +-- .../community/DiscourseTopicResponse.java | 4 +- pom.xml | 1 + .../spotbugs/suppressions.xml | 4 ++ 45 files changed, 169 insertions(+), 264 deletions(-) diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/AbstractWidgetRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/AbstractWidgetRenderer.java index 54cd782e0c..a143f75f4c 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/AbstractWidgetRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/AbstractWidgetRenderer.java @@ -13,7 +13,6 @@ package org.openhab.ui.basic.internal.render; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; @@ -35,6 +34,7 @@ import org.openhab.core.model.sitemap.sitemap.Widget; import org.openhab.core.types.State; import org.openhab.core.ui.items.ItemUIRegistry; +import org.openhab.core.util.ColorUtil; import org.openhab.ui.basic.internal.WebAppConfig; import org.openhab.ui.basic.render.RenderException; import org.openhab.ui.basic.render.WidgetRenderer; @@ -106,7 +106,7 @@ public ItemUIRegistry getItemUIRegistry() { /** * Replace some common values in the widget template * - * @param snippet snippet HTML code + * @param originalSnippet snippet HTML code * @param w corresponding widget * @return HTML code */ @@ -117,7 +117,7 @@ protected String preprocessSnippet(String originalSnippet, Widget w) { /** * Replace some common values in the widget template * - * @param snippet snippet HTML code + * @param originalSnippet snippet HTML code * @param w corresponding widget * @param ignoreStateForIcon true if state has to be ignored when requesting the icon * @return HTML code @@ -338,12 +338,7 @@ protected String escapeURL(@Nullable String string) { return ""; } - try { - return URLEncoder.encode(string, "UTF-8"); - } catch (UnsupportedEncodingException use) { - logger.warn("Cannot escape string '{}'. Returning unmodified string.", string); - return string; - } + return URLEncoder.encode(string, StandardCharsets.UTF_8); } /** @@ -351,7 +346,7 @@ protected String escapeURL(@Nullable String string) { * * @param w * The widget to process - * @param snippet + * @param originalSnippet * The snippet to translate * @return The updated snippet */ @@ -423,9 +418,8 @@ protected String processColor(Widget w, String originalSnippet) { } protected @Nullable String getRGBHexCodeFromItemState(@Nullable State itemState) { - if (itemState instanceof HSBType) { - HSBType hsbState = (HSBType) itemState; - return "#" + Integer.toHexString(hsbState.getRGB()).substring(2); + if (itemState instanceof HSBType hsbState) { + return "#" + Integer.toHexString(ColorUtil.hsbTosRgb(hsbState)).substring(2); } return null; } diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ButtongridRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ButtongridRenderer.java index efab75856a..8376a62f5e 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ButtongridRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ButtongridRenderer.java @@ -185,11 +185,10 @@ private String buildButton(String item, @Nullable String lab, String cmd, @Nulla throws RenderException { String button = getSnippet("button"); - String command = cmd; String label = lab == null ? cmd : lab; button = button.replace("%item%", item); - button = button.replace("%cmd%", escapeHtml(command)); + button = button.replace("%cmd%", escapeHtml(cmd)); String buttonClass = "buttongrid-button"; String style = ""; if (icon == null || !config.isIconsEnabled()) { diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ImageRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ImageRenderer.java index 462efdbfc6..51d60979a8 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ImageRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/ImageRenderer.java @@ -59,7 +59,7 @@ public boolean canRender(Widget w) { @Override public EList renderWidget(Widget w, StringBuilder sb, String sitemap) throws RenderException { Image image = (Image) w; - String snippet = (image.getChildren().size() > 0) ? getSnippet("image_link") : getSnippet("image"); + String snippet = (!image.getChildren().isEmpty()) ? getSnippet("image_link") : getSnippet("image"); boolean showHeaderRow = image.getLabel() != null; snippet = snippet.replace("%header_visibility_class%", diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/InputRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/InputRenderer.java index fff4dd2df1..453a409f4c 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/InputRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/InputRenderer.java @@ -134,7 +134,7 @@ public EList renderWidget(Widget w, StringBuilder sb, String sitemap) th State state = itemUIRegistry.getState(w); String prefix = getPrefix(w); - boolean hasUnit = item instanceof NumberItem ? (((NumberItem) item).getDimension() != null) : false; + boolean hasUnit = item instanceof NumberItem && (((NumberItem) item).getDimension() != null); String postfix = hasUnit ? "" : getPostfix(w); String prefixSnippet = !prefix.isBlank() ? "" + prefix + "" @@ -181,8 +181,7 @@ public EList renderWidget(Widget w, StringBuilder sb, String sitemap) th String unitSnippet = ""; String unit = ""; - if (item instanceof NumberItem) { - NumberItem numberItem = (NumberItem) item; + if (item instanceof NumberItem numberItem) { if (numberItem.getDimension() != null) { unit = getUnit(w, numberItem); if ("number".equals(inputHint)) { @@ -211,7 +210,7 @@ private String parseNumber(String value) { if (COMMA_SEPARATOR_PATTERN.matcher(newValue).find()) { newValue = newValue.replace("/\\./g", "").replace(",", "."); } - if (unitValue.length() > 0) { + if (!unitValue.isEmpty()) { newValue = newValue + " " + unitValue; } return newValue; @@ -230,8 +229,7 @@ private String getValue(Widget w, Item item) { value = "-"; } } - if (item instanceof NumberItem) { - NumberItem numberItem = (NumberItem) item; + if (item instanceof NumberItem numberItem) { if (numberItem.getDimension() != null) { String[] stateArray = value.split(" "); if (stateArray.length <= 1) { @@ -245,7 +243,7 @@ private String getValue(Widget w, Item item) { private String cleanValue(String value, Widget w, Item item) { String prefix = getPrefix(w); - boolean hasUnit = item instanceof NumberItem ? (((NumberItem) item).getDimension() != null) : false; + boolean hasUnit = item instanceof NumberItem && (((NumberItem) item).getDimension() != null); String postfix = hasUnit ? "" : getPostfix(w); String newValue = value.startsWith(prefix) ? value.substring(prefix.length()) : value; newValue = value.endsWith(postfix) ? newValue.substring(0, newValue.lastIndexOf(postfix)) : newValue; diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/MapviewRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/MapviewRenderer.java index 707bd54820..07b20d5531 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/MapviewRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/MapviewRenderer.java @@ -69,8 +69,7 @@ public EList renderWidget(Widget w, StringBuilder sb, String sitemap) th snippet = processColor(w, snippet); State state = itemUIRegistry.getState(mapview); - if (state instanceof PointType) { - PointType pointState = (PointType) state; + if (state instanceof PointType pointState) { double latitude = pointState.getLatitude().doubleValue(); double longitude = pointState.getLongitude().doubleValue(); snippet = snippet.replace("%url%", MAP_URL); diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/PageRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/PageRenderer.java index 19d85da26c..b32c249421 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/PageRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/PageRenderer.java @@ -136,12 +136,12 @@ public StringBuilder processPage(String id, String sitemap, String label, EList< return preChildren.append(postChildren); } - private void processChildren(StringBuilder sb_pre, StringBuilder sb_post, EList children, String sitemap) + private void processChildren(StringBuilder sbPre, StringBuilder sbPost, EList children, String sitemap) throws RenderException { // put a single frame around all children widgets, if there are no explicit frames if (!children.isEmpty()) { - EObject firstChild = children.get(0); - EObject parent = itemUIRegistry.getParent((Widget) firstChild); + Widget firstChild = children.get(0); + EObject parent = itemUIRegistry.getParent(firstChild); if (!(firstChild instanceof Frame || parent instanceof Frame || parent instanceof Sitemap)) { String frameSnippet = getSnippet("frame"); frameSnippet = frameSnippet.replace("%widget_id%", ""); @@ -150,8 +150,8 @@ private void processChildren(StringBuilder sb_pre, StringBuilder sb_post, EList< String[] parts = frameSnippet.split("%children%"); if (parts.length > 1) { - sb_pre.append(parts[0]); - sb_post.insert(0, parts[1]); + sbPre.append(parts[0]); + sbPost.insert(0, parts[1]); } if (parts.length > 2) { logger.error("Snippet 'frame' contains multiple %children% sections, but only one is allowed!"); @@ -185,10 +185,10 @@ private void processChildren(StringBuilder sb_pre, StringBuilder sb_post, EList< widgetType); } processChildren(newPre, newPost, nextChildren, sitemap); - sb_pre.append(newPre); - sb_pre.append(newPost); + sbPre.append(newPre); + sbPre.append(newPost); } else { - sb_pre.append(widgetSB); + sbPre.append(widgetSB); } } } diff --git a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/TextRenderer.java b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/TextRenderer.java index 269dabafce..e384344b6c 100644 --- a/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/TextRenderer.java +++ b/bundles/org.openhab.ui.basic/src/main/java/org/openhab/ui/basic/internal/render/TextRenderer.java @@ -52,7 +52,7 @@ public boolean canRender(Widget w) { @Override public EList renderWidget(Widget w, StringBuilder sb, String sitemap) throws RenderException { Text text = (Text) w; - String snippet = (text.getChildren().size() > 0) ? getSnippet("text_link") : getSnippet("text"); + String snippet = (!text.getChildren().isEmpty()) ? getSnippet("text_link") : getSnippet("text"); snippet = preprocessSnippet(snippet, w); snippet = snippet.replace("%id%", itemUIRegistry.getWidgetId(w)); diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/ManagerSettings.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/ManagerSettings.java index 6cdff42efb..ca1f50e6ae 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/ManagerSettings.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/ManagerSettings.java @@ -112,8 +112,8 @@ private void refreshMounts() { String[] parts = value.split(":"); String source = parts[0]; if (!source.contains("..") || (allowLookup && lookupMount.matcher(source).find())) { - boolean writeable = parts.length > 1 ? parts[1].contains("w") : false; - boolean showSubDirs = parts.length > 1 ? parts[1].contains("s") : false; + boolean writeable = parts.length > 1 && parts[1].contains("w"); + boolean showSubDirs = parts.length > 1 && parts[1].contains("s"); if (source.startsWith(File.separator)) { source = source.substring(1); } diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/StateBeanMessageBodyWriter.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/StateBeanMessageBodyWriter.java index 800b363301..82c31836ac 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/StateBeanMessageBodyWriter.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/StateBeanMessageBodyWriter.java @@ -70,14 +70,12 @@ public void writeTo(Object stateBean, Class type, Type genericType, Annotatio */ public String serialize(Object bean) { String msg = "{\"d\":{"; - if (bean instanceof StateBean) { - StateBean stateBean = (StateBean) bean; + if (bean instanceof StateBean stateBean) { msg += "\"" + stateBean.name + "\":\"" + stateBean.state + "\""; } else if (bean instanceof List) { List states = new ArrayList<>(); for (Object bo : (List) bean) { - if (bo instanceof StateBean) { - StateBean stateBean = (StateBean) bo; + if (bo instanceof StateBean stateBean) { states.add("\"" + stateBean.name + "\":\"" + stateBean.state + "\""); } } diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ChartResource.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ChartResource.java index ae7181537b..68271904dc 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ChartResource.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ChartResource.java @@ -252,8 +252,7 @@ public Object getRrdSeries(QueryablePersistenceService persistenceService, Item try { List itemNames = new ArrayList<>(); - if (item instanceof GroupItem) { - GroupItem groupItem = (GroupItem) item; + if (item instanceof GroupItem groupItem) { for (Item member : groupItem.getMembers()) { itemNames.add(member.getName()); } diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/DataProviderResource.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/DataProviderResource.java index 04880960e9..78968fdc85 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/DataProviderResource.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/DataProviderResource.java @@ -154,7 +154,7 @@ public List getDesigns() { // all designs File designDir = ManagerSettings.getInstance().getDesignFolder(); File[] designs = designDir.listFiles(); - List res = new ArrayList(); + List res = new ArrayList<>(); if (designs != null) { Arrays.sort(designs); for (File design : designs) { diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/EventBroadcaster.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/EventBroadcaster.java index 5dd53b6c2f..78918c1df8 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/EventBroadcaster.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/EventBroadcaster.java @@ -30,7 +30,6 @@ public interface EventBroadcaster { * Broadcasts an event described by the given parameters to all currently * listening clients. * - * @param item the item that should be broadcasted * @param eventObject bean that can be converted to a JSON object. */ void broadcastEvent(final Object eventObject); diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/MultipartRequestMap.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/MultipartRequestMap.java index ea9892fa7d..d83a0cb539 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/MultipartRequestMap.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/MultipartRequestMap.java @@ -89,7 +89,7 @@ private void processFilePart(Part part, String fileName) throws IOException { tempFile.deleteOnExit(); try (BufferedInputStream input = new BufferedInputStream(part.getInputStream(), 8192); - BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile), 8192);) { + BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile), 8192)) { byte[] buffer = new byte[8192]; for (int length = 0; ((length = input.read(buffer)) > 0);) { output.write(buffer, 0, length); diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ReadResource.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ReadResource.java index 73c292fe9e..039244fd71 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ReadResource.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/rest/ReadResource.java @@ -127,9 +127,6 @@ protected void removeItemFactory(ItemFactory itemFactory) { * Subscribes the connecting client to the stream of events filtered by the * given eventFilter. * - * @param eventFilter - * @return {@link EventOutput} object associated with the incoming - * connection. * @throws IOException * @throws InterruptedException */ @@ -238,7 +235,6 @@ public void unregisterItem(Item item) { * Broadcasts an event described by the given parameters to all currently * listening clients. * - * @param item the item which has changed * @param eventObject bean that can be converted to a JSON object. */ @Override @@ -248,9 +244,7 @@ public void broadcastEvent(final Object eventObject) { return; } - executorService.execute(() -> { - broadcaster.send(SseUtil.buildEvent(sse.newEventBuilder(), eventObject)); - }); + executorService.execute(() -> broadcaster.send(SseUtil.buildEvent(sse.newEventBuilder(), eventObject))); } @Override diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/ConfigHelper.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/ConfigHelper.java index c31fefcb16..f3059b198e 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/ConfigHelper.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/ConfigHelper.java @@ -429,13 +429,8 @@ public Label addLabel(Object element, String name, String iconName) { setter.invoke(element, label); return label; } - } catch (NoSuchMethodException | SecurityException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalAccessException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalArgumentException e) { - logger.error("{}", e.getMessage()); - } catch (InvocationTargetException e) { + } catch (NoSuchMethodException | SecurityException | InvocationTargetException | IllegalArgumentException + | IllegalAccessException e) { logger.error("{}", e.getMessage()); } return null; @@ -468,13 +463,8 @@ public Mapping addMapping(Object element, Mapping mapping) { Method setter = element.getClass().getMethod("setMapping", String.class); setter.invoke(element, mapping.getName()); return mapping; - } catch (NoSuchMethodException | SecurityException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalAccessException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalArgumentException e) { - logger.error("{}", e.getMessage()); - } catch (InvocationTargetException e) { + } catch (NoSuchMethodException | SecurityException | InvocationTargetException | IllegalArgumentException + | IllegalAccessException e) { logger.error("{}", e.getMessage()); } } @@ -628,11 +618,7 @@ private EList getMapping(Widget mapping = (EList) getter.invoke(widget); } catch (NoSuchMethodException | SecurityException e) { // do nothing, normal behaviour for item that have no mappingdefined - } catch (IllegalAccessException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalArgumentException e) { - logger.error("{}", e.getMessage()); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { logger.error("{}", e.getMessage()); } return mapping; @@ -641,7 +627,7 @@ private EList getMapping(Widget public Mapping addMapping(Object element, Widget widget) { Mapping mapping = null; EList smap = getMapping(widget); - if (smap != null && smap.size() > 0) { + if (smap != null && !smap.isEmpty()) { mapping = addMapping(element, String.valueOf(smap.hashCode()), smap); } @@ -944,13 +930,8 @@ public void addFormat(Object elem, String label) { format = m.group(2); method.invoke(elem, format); } - } catch (NoSuchMethodException | SecurityException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalAccessException e) { - logger.error("{}", e.getMessage()); - } catch (IllegalArgumentException e) { - logger.error("{}", e.getMessage()); - } catch (InvocationTargetException e) { + } catch (NoSuchMethodException | SecurityException | InvocationTargetException | IllegalArgumentException + | IllegalAccessException e) { logger.error("{}", e.getMessage()); } } @@ -973,10 +954,9 @@ public void cleanup(Object page, Pages pages) { List> childsToAdd = new ArrayList<>(); List> groupsToDelete = new ArrayList<>(); for (JAXBElement element : children) { - if (element.getValue() instanceof Page) { + if (element.getValue() instanceof Page p) { // check if this page only has invisible subpages and a pagejump // in the navbar => change the pagejump to the first subpage - Page p = (Page) element.getValue(); int visible = 0; Page firstChildPage = null; for (JAXBElement ge : p.getPageOrGroupOrNavbar()) { @@ -995,11 +975,9 @@ public void cleanup(Object page, Pages pages) { if (visible == 0 && firstChildPage != null) { // find the pagejumps (only on the root page) for (JAXBElement e : pages.getPage().getPageOrGroupOrNavbar()) { - if (e.getValue() instanceof Navbar) { - Navbar navbar = (Navbar) e.getValue(); + if (e.getValue() instanceof Navbar navbar) { for (JAXBElement ne : navbar.getPageOrGroupOrLine()) { - if (ne.getValue() instanceof Pagejump) { - Pagejump pj = (Pagejump) ne.getValue(); + if (ne.getValue() instanceof Pagejump pj) { if (pj.getTarget().equals(p.getName())) { pj.setTarget(firstChildPage.getName()); } @@ -1009,16 +987,14 @@ public void cleanup(Object page, Pages pages) { } } cleanup(element.getValue(), pages); - } else if (element.getValue() instanceof Group) { - Group group = (Group) element.getValue(); + } else if (element.getValue() instanceof Group group) { // check for visible elements int visible = 0; for (JAXBElement ge : group.getPageOrGroupOrLine()) { if (ge == null || ge.getValue() == null) { continue; } - if (ge.getValue() instanceof Page) { - Page p = (Page) ge.getValue(); + if (ge.getValue() instanceof Page p) { if (p.isVisible() == null || p.isVisible().booleanValue()) { visible++; } diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/VisuConfig.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/VisuConfig.java index 113bc987f5..b7ba998d67 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/VisuConfig.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/backend/sitemap/VisuConfig.java @@ -144,7 +144,7 @@ private String marshal(Pages bean, String xsdSchema) { classes[0] = bean.getClass(); JAXBContext jaxbContext = JAXBContext.newInstance(bean.getClass()); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - Schema schema = (xsdSchema == null || xsdSchema.trim().length() == 0) ? null + Schema schema = (xsdSchema == null || xsdSchema.trim().isEmpty()) ? null : schemaFactory.newSchema(new File(xsdSchema)); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setSchema(schema); @@ -153,9 +153,7 @@ private String marshal(Pages bean, String xsdSchema) { StringWriter sw = new StringWriter(); marshaller.marshal(bean, sw); res = sw.toString(); - } catch (JAXBException e) { - logger.error("{}", e.getMessage(), e); - } catch (SAXException e) { + } catch (JAXBException | SAXException e) { logger.error("{}", e.getMessage(), e); } return res; @@ -206,7 +204,7 @@ private void processWidget(Object rootPage, Widget widget, Pages pages, int leve if (widget instanceof LinkableWidget) { EList children = app.getItemUIRegistry().getChildren((LinkableWidget) widget); - if (children.size() == 0) { + if (children.isEmpty()) { processItemWidget(rootPage, widget, item, pages, level); } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Frame) { Group group = new Group(); @@ -220,8 +218,7 @@ private void processWidget(Object rootPage, Widget widget, Pages pages, int leve Page page = new Page(); page.setName(configHelper.getLabel(widget)); configHelper.addToRoot(rootPage, factory.createPagePage(page)); - if (widget instanceof org.openhab.core.model.sitemap.sitemap.Group) { - org.openhab.core.model.sitemap.sitemap.Group group = (org.openhab.core.model.sitemap.sitemap.Group) widget; + if (widget instanceof org.openhab.core.model.sitemap.sitemap.Group group) { // add Group item to the Navbar // logger.debug("page '{}' on level {}",page.getName(),level); NavbarPositionType position = (level <= 1) ? NavbarPositionType.TOP : NavbarPositionType.LEFT; @@ -247,17 +244,16 @@ private void processWidget(Object rootPage, Widget widget, Pages pages, int leve } private void processItemWidget(Object rootPage, Widget widget, Item item, Pages pages, int level) { - if (widget instanceof org.openhab.core.model.sitemap.sitemap.Switch) { + if (widget instanceof org.openhab.core.model.sitemap.sitemap.Switch switchWidget) { if (item == null) { return; } - org.openhab.core.model.sitemap.sitemap.Switch switchWidget = (org.openhab.core.model.sitemap.sitemap.Switch) widget; if (item instanceof RollershutterItem) { // in the demo-sitemap a rullershutter item is defined as // switch??? configHelper.addRollershutter(rootPage, item, switchWidget); - } else if (switchWidget.getMappings().size() > 0) { + } else if (!switchWidget.getMappings().isEmpty()) { // up to 5 mapping we can use a multitrigger if (switchWidget.getMappings().size() <= 4) { configHelper.mapToMultiTrigger(rootPage, item, switchWidget); @@ -315,11 +311,10 @@ private void processItemWidget(Object rootPage, Widget widget, Item item, Pages configHelper.addAddress(bean, item, Transform.DIMMER); configHelper.addLabel(bean, widget); configHelper.addToRoot(rootPage, factory.createPageSlide(bean)); - } else if (widget instanceof Setpoint) { + } else if (widget instanceof Setpoint setpoint) { if (item == null) { return; } - Setpoint setpoint = (Setpoint) widget; Slide bean = new Slide(); bean.setFormat("%d"); bean.setMin(setpoint.getMinValue()); @@ -330,11 +325,10 @@ private void processItemWidget(Object rootPage, Widget widget, Item item, Pages configHelper.addLabel(bean, widget); configHelper.addToRoot(rootPage, factory.createPageSlide(bean)); - } else if (widget instanceof Selection) { + } else if (widget instanceof Selection selection) { if (item == null) { return; } - Selection selection = (Selection) widget; // Map a Selection to a Group of triggers Group bean = new Group(); bean.setNowidget(true); @@ -356,8 +350,7 @@ private void processItemWidget(Object rootPage, Widget widget, Item item, Pages } configHelper.addToRoot(rootPage, factory.createPageGroup(bean)); - } else if (widget instanceof Webview) { - Webview webview = (Webview) widget; + } else if (widget instanceof Webview webview) { Web bean = new Web(); bean.setHeight(String.valueOf(webview.getHeight()) + "%"); bean.setWidth("100%"); @@ -367,8 +360,7 @@ private void processItemWidget(Object rootPage, Widget widget, Item item, Pages configHelper.addLabel(bean, widget); configHelper.addToRoot(rootPage, factory.createPageWeb(bean)); - } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Image) { - org.openhab.core.model.sitemap.sitemap.Image image = (org.openhab.core.model.sitemap.sitemap.Image) widget; + } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Image image) { Image bean = new Image(); bean.setSrc(image.getUrl()); bean.setRefresh(new BigDecimal(image.getRefresh())); @@ -376,22 +368,20 @@ private void processItemWidget(Object rootPage, Widget widget, Item item, Pages configHelper.addLabel(bean, widget); configHelper.addToRoot(rootPage, factory.createPageImage(bean)); - } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Video) { - org.openhab.core.model.sitemap.sitemap.Video video = (org.openhab.core.model.sitemap.sitemap.Video) widget; + } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Video video) { Video bean = new Video(); bean.setSrc(video.getUrl()); configHelper.addLabel(bean, widget); configHelper.addToRoot(rootPage, factory.createPageVideo(bean)); - } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Chart && item != null) { + } else if (widget instanceof org.openhab.core.model.sitemap.sitemap.Chart chart && item != null) { if (item == null) { return; } Plugin plugin = new Plugin(); plugin.setName("diagram"); configHelper.addPlugin(plugin); - org.openhab.core.model.sitemap.sitemap.Chart chart = (org.openhab.core.model.sitemap.sitemap.Chart) widget; Diagram bean = new Diagram(); bean.setSeries(configHelper.getCvChartPeriod(chart.getPeriod())); bean.setRefresh(new BigInteger(String.valueOf(chart.getRefresh()))); diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuApp.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuApp.java index 2c3b4f7e26..e5f9d3d83d 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuApp.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuApp.java @@ -196,11 +196,11 @@ private void readConfiguration(final Map properties) { Object propertyValue = properties.get(Config.COMETVISU_AUTODOWNLOAD_PROPERTY); // Value might be a string or a boolean - Boolean newValue = false; - if (propertyValue instanceof String) { - newValue = Boolean.valueOf((String) propertyValue); - } else if (propertyValue instanceof Boolean) { - newValue = (Boolean) propertyValue; + boolean newValue = false; + if (propertyValue instanceof String s) { + newValue = Boolean.parseBoolean(s); + } else if (propertyValue instanceof Boolean b) { + newValue = b; } boolean changed = Config.cometvisuAutoDownload != newValue; @@ -237,9 +237,7 @@ private void readConfiguration(final Map properties) { * Called by the SCR to activate the component with its configuration read * from CAS * - * @param bundleContext - * BundleContext of the Bundle that defines this component - * @param configuration + * @param configProps * Configuration properties for this component obtained from the * ConfigAdmin service */ @@ -272,9 +270,7 @@ private void registerServlet() { servlet = new CometVisuServlet(Config.cometvisuWebfolder, this); try { httpService.registerServlet(Config.cometvisuWebappAlias, servlet, servletParams, null); - } catch (ServletException e) { - logger.error("Error during servlet startup", e); - } catch (NamespaceException e) { + } catch (ServletException | NamespaceException e) { logger.error("Error during servlet startup", e); } } @@ -287,7 +283,7 @@ private void unregisterServlet() { * Called by the SCR when the configuration of a binding has been changed * through the ConfigAdmin service. * - * @param configuration + * @param configProps * Updated configuration properties */ @Modified diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuServlet.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuServlet.java index 4c7d93fcbd..aeeaacf23d 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuServlet.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/servlet/CometVisuServlet.java @@ -22,13 +22,12 @@ import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; @@ -188,21 +187,18 @@ protected File getRequestedFile(HttpServletRequest req) throws UnsupportedEncodi if (requestedFile.endsWith("/")) { requestedFile = requestedFile.substring(0, requestedFile.length() - 1); } - file = new File(userFileFolder, URLDecoder.decode(requestedFile, "UTF-8")); + file = new File(userFileFolder, URLDecoder.decode(requestedFile, StandardCharsets.UTF_8)); } // serve the file from the cometvisu src directory if (file == null || !file.exists() || file.isDirectory()) { - file = requestedFile != null ? new File(rootFolder, URLDecoder.decode(requestedFile, "UTF-8")) : rootFolder; + file = requestedFile != null + ? new File(rootFolder, URLDecoder.decode(requestedFile, StandardCharsets.UTF_8)) + : rootFolder; } if (file.isDirectory()) { // search for an index file - FilenameFilter filter = new FilenameFilter() { - @Override - public boolean accept(@Nullable File dir, @Nullable String name) { - return name != null && name.startsWith("index.") - && (name.endsWith(".php") || name.endsWith(".html")); - } - }; + FilenameFilter filter = (dir, name) -> name != null && name.startsWith("index.") + && (name.endsWith(".php") || name.endsWith(".html")); for (String dirFile : file.list(filter)) { // take the first one found file = new File(file, dirFile); @@ -363,14 +359,7 @@ private void processRssLogRequest(File file, HttpServletRequest request, HttpSer if ("rrd4j".equals(persistenceService.getId()) && FilterCriteria.Ordering.DESCENDING.equals(filter.getOrdering())) { // the RRD4j PersistenceService does not support descending ordering so we do it manually - Collections.sort(feed.entries, - new Comparator() { - @Override - public int compare(org.openhab.ui.cometvisu.internal.backend.model.rss.Entry o1, - org.openhab.ui.cometvisu.internal.backend.model.rss.Entry o2) { - return Long.compare(o2.publishedDate, o1.publishedDate); - } - }); + feed.entries.sort((o1, o2) -> Long.compare(o2.publishedDate, o1.publishedDate)); } logger.debug("querying {} item from {} to {} => {} results on service {}", filter.getItemName(), filter.getBeginDate(), filter.getEndDate(), i, persistenceService.getId()); @@ -447,7 +436,7 @@ private void processStaticRequest(@Nullable File file, HttpServletRequest reques // URL-decode the file name (might contain spaces and on) and // prepare // file object. - processFile = new File(rootFolder, URLDecoder.decode(requestedFile, "UTF-8")); + processFile = new File(rootFolder, URLDecoder.decode(requestedFile, StandardCharsets.UTF_8)); } else { processFile = file; } @@ -459,7 +448,7 @@ private void processStaticRequest(@Nullable File file, HttpServletRequest reques if (!processFile.exists()) { // show installation hints if the CometVisu-Clients main index.html is requested but cannot be found if (processFile.getParentFile().equals(rootFolder) - && (processFile.getName().equalsIgnoreCase("index.html") || processFile.getName().length() == 0)) { + && (processFile.getName().equalsIgnoreCase("index.html") || processFile.getName().isEmpty())) { // looking for CometVisu clients index.html file String path = null; File folder = processFile.isDirectory() ? processFile : processFile.getParentFile(); @@ -657,15 +646,14 @@ else if (!contentType.startsWith("image")) { if (ranges.isEmpty() || ranges.get(0).equals(full)) { // Return full file. - Range r = full; response.setContentType(contentType); - response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); + response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total); if (content) { - response.setHeader("HA", String.valueOf(r.length)); + response.setHeader("HA", String.valueOf(full.length)); // Copy full range. - copy(input, output, r.start, r.length); + copy(input, output, full.start, full.length); } } else if (ranges.size() == 1) { // Return single part of file. @@ -801,7 +789,7 @@ private static boolean matches(String matchHeader, String toMatch) { */ private static long sublong(String value, int beginIndex, int endIndex) { String substring = value.substring(beginIndex, endIndex); - return (substring.length() > 0) ? Long.parseLong(substring) : -1; + return (!substring.isEmpty()) ? Long.parseLong(substring) : -1; } /** @@ -863,7 +851,7 @@ private static void close(Closeable resource) { /** * This class represents a byte range. */ - protected class Range { + protected static class Range { long start; long end; long length; diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/ClientInstaller.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/ClientInstaller.java index 1c8e530eb4..89d0b36cca 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/ClientInstaller.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/ClientInstaller.java @@ -234,10 +234,9 @@ private Map getLatestRelease() { List> jsonResponse = new Gson().fromJson(response, ArrayList.class); // releases are ordered top-down, the latest release comes first - for (int i = 0; i < jsonResponse.size(); i++) { - var release = jsonResponse.get(i); - if (((boolean) release.getOrDefault("prerelease", true)) == false - && ((boolean) release.getOrDefault("draft", true)) == false) { + for (Map release : jsonResponse) { + if (!((boolean) release.getOrDefault("prerelease", true)) + && !((boolean) release.getOrDefault("draft", true))) { latestRelease = release; break; } @@ -259,8 +258,7 @@ public void downloadLatestRelease() { List> assets = (List>) latestRelease.get("assets"); Map releaseAsset = null; - for (Object assetObj : assets) { - Map asset = (Map) assetObj; + for (Map asset : assets) { String contentType = ((String) asset.getOrDefault("content_type", "")); String name = ((String) asset.getOrDefault("name", "")); if (contentType.equalsIgnoreCase("application/zip") @@ -313,8 +311,7 @@ private void extractFolder(String folderName, ZipFile zipFile, String destDir) { } new File(file.getParent()).mkdirs(); - try (InputStream is = zipFile.getInputStream(entry); - OutputStream os = new FileOutputStream(file);) { + try (InputStream is = zipFile.getInputStream(entry); OutputStream os = new FileOutputStream(file)) { for (int len; (len = is.read(BUFFER)) != -1;) { os.write(BUFFER, 0, len); } diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/FsUtil.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/FsUtil.java index 4e32c61320..022742bcc5 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/FsUtil.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/FsUtil.java @@ -233,7 +233,7 @@ public void saveFile(File file, String content, String hash) throws FileOperatio * @return A list of MointPoints that are mounted as directories in this path */ public ArrayList getMounts(Path path) { - ArrayList mounts = new ArrayList(); + ArrayList mounts = new ArrayList<>(); for (final MountPoint mount : ManagerSettings.getInstance().getMounts()) { if (mount.getAbsoluteTarget().startsWith(path)) { mounts.add(mount); @@ -248,7 +248,7 @@ public FsEntry getEntry(File file, boolean recursive, MountedFile mount) { entry.setName(file.getName()); entry.setHasChildren(file.isDirectory() && file.listFiles().length > 0); entry.setParentFolder(mount.getPath()); - entry.setWriteable(mount.isReadonlyMount() ? false : file.canWrite()); + entry.setWriteable(!mount.isReadonlyMount() && file.canWrite()); entry.setReadable(file.canRead()); entry.setMounted(false); entry.setInTrash(this.isInTrash(file)); diff --git a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/SseUtil.java b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/SseUtil.java index bc6b0a75c2..526aa39d3f 100644 --- a/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/SseUtil.java +++ b/bundles/org.openhab.ui.cometvisu/src/main/java/org/openhab/ui/cometvisu/internal/util/SseUtil.java @@ -31,12 +31,11 @@ public class SseUtil { /** - * Creates a new {@link OutboundEvent} object containing an + * Creates a new {@link OutboundSseEvent} object containing an * {@link StateBean} created for the given eventType, objectIdentifier, * eventObject. * - * @param eventType the event type for the event - * @param objectIdentifier the identifier for the main event object + * @param eventBuilder the builder used for building the event * @param eventObject the eventObject to be included * @return a new OutboundSseEvent */ @@ -51,12 +50,7 @@ public static OutboundSseEvent buildEvent(OutboundSseEvent.Builder eventBuilder, * Used to mark our current thread(request processing) that SSE blocking * should be enabled. */ - private static ThreadLocal blockingSseEnabled = new ThreadLocal<>() { - @Override - protected Boolean initialValue() { - return false; - } - }; + private static ThreadLocal blockingSseEnabled = ThreadLocal.withInitial(() -> false); /** * Returns true if the current thread is processing an SSE request that diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Card.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Card.java index 155709119d..d457c9464a 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Card.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Card.java @@ -41,10 +41,10 @@ public class Card extends Component implements Identifiable { @Nullable String subtitle; - Set objects = new HashSet(); - Set locations = new HashSet(); + Set objects = new HashSet<>(); + Set locations = new HashSet<>(); - Set tags = new HashSet(); + Set tags = new HashSet<>(); boolean bookmarked; boolean notReuseableInChat; @@ -213,7 +213,7 @@ public boolean isEphemeral() { * Specifies whether the card is ephemeral, meaning it is not saved permanently to the @link {@link CardRegistry} * and will be purged once a number of newer ephemeral cards are added * - * @return true if the card is ephemeral, false (default) otherwise + * @param ephemeral true if the card is ephemeral, false (default) otherwise */ public void setEphemeral(boolean ephemeral) { this.ephemeral = ephemeral; @@ -300,7 +300,7 @@ public void removeAllTags() { /** * Adds an object attribute to the card * - * @param tag the tag to add + * @param object the object to add */ public void addObjectAttribute(String object) { this.objects.add(object); @@ -309,7 +309,7 @@ public void addObjectAttribute(String object) { /** * Adds several object attributes to the card * - * @param tags the tags to add + * @param objects the objects to add */ public void addObjectAttributes(Collection objects) { this.objects.addAll(objects); @@ -318,7 +318,7 @@ public void addObjectAttributes(Collection objects) { /** * Adds several object attributes to the card * - * @param tags the tags to add + * @param objects the objects to add */ public void addObjectAttributes(String... objects) { this.objects.addAll(Arrays.asList(objects)); @@ -327,7 +327,7 @@ public void addObjectAttributes(String... objects) { /** * Removes an object attribute on a card * - * @param tag the tag to remove + * @param object the object to remove */ public void removeObjectAttribute(String object) { this.objects.remove(object); @@ -348,7 +348,7 @@ public boolean hasObjectAttribute(@Nullable String object) { /** * Adds an location attribute to the card * - * @param tag the tag to add + * @param location the location to add */ public void addLocationAttribute(String location) { this.locations.add(location); @@ -357,7 +357,7 @@ public void addLocationAttribute(String location) { /** * Adds several object attributes to the card * - * @param tags the tags to add + * @param locations the locations to add */ public void addLocationAttributes(Collection locations) { this.locations.addAll(locations); @@ -366,7 +366,7 @@ public void addLocationAttributes(Collection locations) { /** * Adds several object attributes to the card * - * @param tags the tags to add + * @param locations the locations to add */ public void addLocationAttributes(String... locations) { this.locations.addAll(Arrays.asList(locations)); @@ -375,7 +375,7 @@ public void addLocationAttributes(String... locations) { /** * Removes an object attribute on a card * - * @param tag the tag to remove + * @param location the location to remove */ public void removeLocationAttribute(String location) { this.locations.remove(location); @@ -384,7 +384,7 @@ public void removeLocationAttribute(String location) { /** * Returns whether the card has the specified location attribute * - * @param object + * @param location */ public boolean hasLocationAttribute(@Nullable String location) { if (this.locations == null || location == null || location.isEmpty()) { diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/CardBuilder.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/CardBuilder.java index 424a4ee159..1676cc64ea 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/CardBuilder.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/CardBuilder.java @@ -15,7 +15,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.IllegalFormatConversionException; -import java.util.Optional; +import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -34,7 +34,6 @@ import org.openhab.core.types.StateDescription; import org.openhab.ui.habot.card.internal.CardRegistry; import org.openhab.ui.habot.nlp.Intent; -import org.osgi.framework.FrameworkUtil; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Reference; @@ -76,7 +75,7 @@ public Card buildCard(Intent intent, Collection matchedItems) { String location = intent.getEntities().get("location"); Collection cardsInRegistry = this.cardRegistry.getCardMatchingAttributes(object, location).stream() - .filter(c -> !c.isNotReuseableInChat() && !c.isEphemeral()).collect(Collectors.toList()); + .filter(c -> !c.isNotReuseableInChat() && !c.isEphemeral()).toList(); if (!cardsInRegistry.isEmpty()) { // don't handle multiple cards, just return the first one Card existingCard = cardsInRegistry.iterator().next(); @@ -307,14 +306,13 @@ public Card buildChartCard(Intent intent, Collection matchedItems, String } } else { card.setTitle(intent.getEntities().entrySet().stream().filter(e -> !e.getKey().equals("period")) - .map(e -> e.getValue()).collect(Collectors.joining(", "))); + .map(Map.Entry::getValue).collect(Collectors.joining(", "))); } card.setSubtitle(period + " - " + matchingNonGroupItems.get().count() + " items"); // TODO: i18n } Component chart = new Component("HbChartImage"); - chart.addConfig("items", - matchingNonGroupItems.get().map(i -> i.getName()).collect(Collectors.toList()).toArray(new String[0])); + chart.addConfig("items", matchingNonGroupItems.get().map(Item::getName).toArray(String[]::new)); chart.addConfig("period", period); Component analyzeButton = new Component("HbAnalyzeActionButton"); @@ -336,11 +334,10 @@ public Card buildChartCard(Intent intent, Collection matchedItems, String * @return an optional group eligible for the card's title, or null if none was found */ private @Nullable GroupItem getMatchingGroup(Collection items) { - Optional groupItem = items.stream().filter(i -> i instanceof GroupItem) + return (GroupItem) items.stream().filter(GroupItem.class::isInstance) .filter(g -> items.stream().allMatch(i -> i.getName().equals(g.getName()) || ((GroupItem) g).getAllMembers().stream().anyMatch(i2 -> i2.getName().contains(i.getName())))) - .findFirst(); - return groupItem.isPresent() ? (GroupItem) groupItem.get() : null; + .findFirst().orElse(null); } private String formatState(Item item, State state) throws TransformationException { @@ -350,9 +347,7 @@ private String formatState(Item item, State state) throws TransformationExceptio if (stateDescription != null) { final String pattern = stateDescription.getPattern(); if (pattern != null) { - String transformedState = TransformationHelper.transform( - FrameworkUtil.getBundle(CardBuilder.class).getBundleContext(), pattern, - state.toString()); + String transformedState = TransformationHelper.transform(pattern, state.toString()); if (transformedState == null) { return state.toString(); } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Component.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Component.java index 84854cf893..d66112dcfe 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Component.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/Component.java @@ -46,7 +46,7 @@ public class Component { public Component(String componentName) { super(); this.component = componentName; - this.config = new HashMap(); + this.config = new HashMap<>(); } /** @@ -94,9 +94,9 @@ public Map> getSlots() { */ public List addSlot(String slotName) { if (slots == null) { - slots = new HashMap>(); + slots = new HashMap<>(); } - List newSlot = new ArrayList(); + List newSlot = new ArrayList<>(); this.slots.put(slotName, newSlot); return newSlot; diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/internal/CardRegistry.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/internal/CardRegistry.java index 97d4ff8183..3e5bbd1489 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/internal/CardRegistry.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/card/internal/CardRegistry.java @@ -66,7 +66,7 @@ public CardRegistry() { * @return matching cards */ public Collection getCardByTags(Set tags) { - List filteredCards = new ArrayList(); + List filteredCards = new ArrayList<>(); for (Card card : getAll()) { if (cardHasTags(card, tags)) { filteredCards.add(card); @@ -84,7 +84,7 @@ public Collection getCardByTags(Set tags) { * both are provided, matching cards have both. */ public Collection getCardMatchingAttributes(@Nullable String object, @Nullable String location) { - List filteredCards = new ArrayList(); + List filteredCards = new ArrayList<>(); for (Card card : getAll()) { if (cardMatchesAttributes(card, object, location)) { filteredCards.add(card); @@ -96,8 +96,7 @@ public Collection getCardMatchingAttributes(@Nullable String object, @Null @Override public Card add(Card element) { // Remove old ephemeral cards - List oldCards = getAll().stream().filter(card -> card.isEphemeral()).sorted(byTimestamp).skip(10) - .collect(Collectors.toList()); + List oldCards = getAll().stream().filter(Card::isEphemeral).sorted(byTimestamp).skip(10).toList(); for (Card card : oldCards) { logger.debug("Removing old ephemeral card {}", card.getUID()); @@ -116,10 +115,8 @@ public Card add(Card element) { */ public Collection getRecent(int skip, int count) { int limit = (count < 1) ? 10 : count; - List recentCards = getAll().stream().sorted(byTimestamp).skip(skip).limit(limit) - .collect(Collectors.toList()); - return recentCards; + return getAll().stream().sorted(byTimestamp).skip(skip).limit(limit).collect(Collectors.toList()); } /** diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/AbstractItemIntentInterpreter.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/AbstractItemIntentInterpreter.java index 1d5cc29486..ac5d6d6af4 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/AbstractItemIntentInterpreter.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/AbstractItemIntentInterpreter.java @@ -60,8 +60,7 @@ protected Set findItems(Intent intent) { // expand group items for (Item item : items.toArray(new Item[0])) { - if (item instanceof GroupItem) { - GroupItem gItem = (GroupItem) item; + if (item instanceof GroupItem gItem) { items.addAll(gItem.getMembers()); } } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/Intent.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/Intent.java index c0c80c29fb..f29f998463 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/Intent.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/Intent.java @@ -48,7 +48,7 @@ public Map getEntities() { /** * Sets the intent's entities * - * @param slots the map of entities + * @param entities the map of entities */ public void setEntities(Map entities) { this.entities = entities; @@ -66,6 +66,6 @@ public String toString() { */ public Intent(String name) { this.name = name; - this.entities = new HashMap(); + this.entities = new HashMap<>(); } } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentDocumentSampleStream.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentDocumentSampleStream.java index 4d275b19e6..460ed7c5a3 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentDocumentSampleStream.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentDocumentSampleStream.java @@ -44,7 +44,7 @@ public DocumentSample read() throws IOException { String[] tokens = WhitespaceTokenizer.INSTANCE.tokenize(sampleString); // remove entities - Vector vector = new Vector(tokens.length); + Vector vector = new Vector<>(tokens.length); // boolean skip = false; for (String token : tokens) { if (!token.startsWith("<")) { diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentTrainer.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentTrainer.java index 37e419f61a..dbc2ab926f 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentTrainer.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/IntentTrainer.java @@ -183,7 +183,7 @@ public Intent interpret(String query) { intent.getEntities().put(spans[i].getType(), names[i]); } - logger.debug("{}", intent.toString()); + logger.debug("{}", intent); return intent; } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/NamedAttributesItemResolver.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/NamedAttributesItemResolver.java index e0cf7c5e2f..517488b577 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/NamedAttributesItemResolver.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/NamedAttributesItemResolver.java @@ -132,7 +132,7 @@ public Stream getMatchingItems(String object, String location) { } return (object != null && location != null) ? objectMatch && locationMatch : objectMatch || locationMatch; - }).map(entry -> entry.getKey()); + }).map(Map.Entry::getKey); } private void updateItemNamedAttributes() { diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/OpenNLPInterpreter.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/OpenNLPInterpreter.java index 28b946f75f..5364545a13 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/OpenNLPInterpreter.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/OpenNLPInterpreter.java @@ -15,7 +15,7 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.Comparator; +import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -142,7 +142,7 @@ protected InputStream getNameSamples() throws UnsupportedLanguageException { StringBuilder nameSamplesDoc = new StringBuilder(); Map> itemAttributes = itemResolver.getAllItemNamedAttributes(); - Stream attributes = itemAttributes.values().stream().flatMap(a -> a.stream()); + Stream attributes = itemAttributes.values().stream().flatMap(Collection::stream); attributes.forEach(attribute -> { if (attribute.getType() == AttributeType.LOCATION) { @@ -168,20 +168,15 @@ public ChatReply reply(Locale locale, String text) throws InterpretationExceptio if (!locale.equals(currentLocale) || intentTrainer == null) { try { itemResolver.setLocale(locale); - intentTrainer = new IntentTrainer(locale.getLanguage(), - skills.values().stream().sorted(new Comparator<>() { - - @Override - public int compare(Skill o1, Skill o2) { - if (o1.getIntentId().equals("get-status")) { - return -1; - } - if (o2.getIntentId().equals("get-status")) { - return 1; - } - return o1.getIntentId().compareTo(o2.getIntentId()); - } - }).collect(Collectors.toList()), getNameSamples(), this.tokenizerId); + intentTrainer = new IntentTrainer(locale.getLanguage(), skills.values().stream().sorted((o1, o2) -> { + if (o1.getIntentId().equals("get-status")) { + return -1; + } + if (o2.getIntentId().equals("get-status")) { + return 1; + } + return o1.getIntentId().compareTo(o2.getIntentId()); + }).collect(Collectors.toList()), getNameSamples(), this.tokenizerId); this.intentTrainer = intentTrainer; currentLocale = locale; } catch (Exception e) { @@ -223,8 +218,8 @@ public int compare(Skill o1, Skill o2) { reply.setHint(intentInterpretation.getHint()); } if (intentInterpretation.getMatchedItems() != null) { - reply.setMatchedItems(intentInterpretation.getMatchedItems().stream().map(i -> i.getName()) - .collect(Collectors.toList()).toArray(new String[0])); + reply.setMatchedItems( + intentInterpretation.getMatchedItems().stream().map(Item::getName).toArray(String[]::new)); } if (intentInterpretation.getCard() != null) { reply.setCard(intentInterpretation.getCard()); diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/SemanticsItemResolver.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/SemanticsItemResolver.java index af0178b7b2..b51b13a34e 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/SemanticsItemResolver.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/SemanticsItemResolver.java @@ -71,13 +71,12 @@ public Stream getMatchingItems(String object, String location) { if (location != null) { items = semanticsService.getItemsInLocation(location, currentLocale).stream(); } else { - items = new HashSet(itemRegistry.getAll()).stream(); + items = new HashSet<>(itemRegistry.getAll()).stream(); } if (object != null) { List> semanticTagTypes = semanticsService.getByLabelOrSynonym(object, currentLocale); - if (!semanticTagTypes.isEmpty() - && semanticTagTypes.stream().noneMatch(t -> Location.class.isAssignableFrom(t))) { + if (!semanticTagTypes.isEmpty() && semanticTagTypes.stream().noneMatch(Location.class::isAssignableFrom)) { Predicate tagsPredicate = null; for (Class tag : semanticTagTypes) { Predicate tagPredicate = Property.class.isAssignableFrom(tag) @@ -102,14 +101,14 @@ public Map> getAllItemNamedAttributes() throws Uns throw new UnsupportedLanguageException(currentLocale); } - Map> attributes = new HashMap>(); + Map> attributes = new HashMap<>(); for (Item item : itemRegistry.getAll()) { Class semanticType = SemanticTags.getSemanticType(item); if (semanticType != null) { - Set itemAttributes = new HashSet(); + Set itemAttributes = new HashSet<>(); - attributes.put(item, new HashSet()); + attributes.put(item, new HashSet<>()); String attributeType = (Location.class.isAssignableFrom(semanticType)) ? "location" : "object"; // Add the item's label diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/skill/HistoryLastChangesSkill.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/skill/HistoryLastChangesSkill.java index 6260dcf0b4..446410cc3d 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/skill/HistoryLastChangesSkill.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/nlp/internal/skill/HistoryLastChangesSkill.java @@ -35,7 +35,6 @@ import org.openhab.ui.habot.nlp.IntentInterpretation; import org.openhab.ui.habot.nlp.ItemResolver; import org.openhab.ui.habot.nlp.Skill; -import org.osgi.framework.FrameworkUtil; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Reference; @@ -134,9 +133,7 @@ public String getIntentId() { final String pattern = stateDescription.getPattern(); if (pattern != null) { try { - String transformedState = TransformationHelper.transform( - FrameworkUtil.getBundle(HistoryLastChangesSkill.class).getBundleContext(), pattern, - state.toString()); + String transformedState = TransformationHelper.transform(pattern, state.toString()); if (transformedState != null && transformedState.equals(state.toString())) { return state.format(pattern); } else { diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationAction.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationAction.java index a2a68887de..679376ce8f 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationAction.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationAction.java @@ -85,10 +85,10 @@ public static void sendHABotNotificationWithTags(String message, List ta public static void sendHABotNotificationExt(String title, String message, String cardUID, List tags) { try { Gson gson = new Gson(); - HashMap payload = new HashMap(); + HashMap payload = new HashMap<>(); payload.put("title", title); payload.put("body", message); - HashMap data = new HashMap(); + HashMap data = new HashMap<>(); if (cardUID != null) { data.put("cardUID", cardUID); } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationActionHandler.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationActionHandler.java index 86a4599f33..b4981d3c9f 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationActionHandler.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/WebPushNotificationActionHandler.java @@ -71,10 +71,10 @@ public WebPushNotificationActionHandler(Action module, NotificationService notif try { Gson gson = new Gson(); - HashMap payload = new HashMap(); + HashMap payload = new HashMap<>(); payload.put("title", (title != null) ? title : "HABot"); payload.put("body", body); - HashMap data = new HashMap(); + HashMap data = new HashMap<>(); if (cardUID != null) { data.put("cardUID", cardUID); } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/NotificationService.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/NotificationService.java index a4a5f9d290..5144ac165f 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/NotificationService.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/NotificationService.java @@ -193,9 +193,7 @@ private void loadVAPIDKeys() { generateVAPIDKeyPair(); } catch (InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | IOException e1) { - RuntimeException ex = new RuntimeException("Cannot get the VAPID keypair for push notifications"); - ex.initCause(e1); - throw ex; + throw new RuntimeException("Cannot get the VAPID keypair for push notifications", e1); } } } diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/PushService.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/PushService.java index 625e867130..b1266ff66b 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/PushService.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/PushService.java @@ -154,7 +154,7 @@ public Future send(Notification notification) byte[] salt = encrypted.getSalt(); Invocation.Builder invocationBuilder = ClientBuilder.newClient().target(notification.getEndpoint()).request(); - MultivaluedMap headers = new MultivaluedHashMap(); + MultivaluedMap headers = new MultivaluedHashMap<>(); headers.add("TTL", String.valueOf(notification.getTTL())); if (notification.hasPayload()) { diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/Subscription.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/Subscription.java index 6533a8238c..02698492f3 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/Subscription.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/notification/internal/webpush/Subscription.java @@ -35,7 +35,7 @@ public Subscription(String endpoint, Keys keys) { this.keys = keys; } - public class Keys { + public static class Keys { public final String p256dh; public final String auth; diff --git a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/rest/internal/HABotResource.java b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/rest/internal/HABotResource.java index f02a25c109..31ea622490 100644 --- a/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/rest/internal/HABotResource.java +++ b/bundles/org.openhab.ui.habot/src/main/java/org/openhab/ui/habot/rest/internal/HABotResource.java @@ -170,8 +170,8 @@ public Response getAttributes() throws Exception { itemResolver.setLocale(locale); Map> attributesByItemName = new HashMap<>(); - itemResolver.getAllItemNamedAttributes().entrySet().stream() - .forEach(entry -> attributesByItemName.put(entry.getKey().getName(), entry.getValue())); + itemResolver.getAllItemNamedAttributes() + .forEach((key, value) -> attributesByItemName.put(key.getName(), value)); return Response.ok(attributesByItemName).build(); } diff --git a/bundles/org.openhab.ui.habot/src/test/java/org/openhab/ui/habot/test/AbstractTrainerTest.java b/bundles/org.openhab.ui.habot/src/test/java/org/openhab/ui/habot/test/AbstractTrainerTest.java index 5ea2f6908c..06fe7c7da4 100644 --- a/bundles/org.openhab.ui.habot/src/test/java/org/openhab/ui/habot/test/AbstractTrainerTest.java +++ b/bundles/org.openhab.ui.habot/src/test/java/org/openhab/ui/habot/test/AbstractTrainerTest.java @@ -13,7 +13,6 @@ package org.openhab.ui.habot.test; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; import java.io.InputStream; @@ -39,7 +38,7 @@ public class AbstractTrainerTest { protected IntentTrainer trainer = createUninitializedTrainer(); protected List skills = new ArrayList<>(); - public class Skills { + public static class Skills { public static final String GET_STATUS = "get-status"; public static final String ACTIVATE_OBJECT = "activate-object"; public static final String DEACTIVATE_OBJECT = "deactivate-object"; @@ -76,7 +75,7 @@ private IntentTrainer createUninitializedTrainer() { return trainerMock; } - public class MockSkill implements Skill { + public static class MockSkill implements Skill { private String intent; @@ -103,9 +102,9 @@ public String getIntentId() { protected Intent interpret(String query) { System.out.println("----"); System.out.println("\"" + query + "\""); - System.out.println(new TreeMap<>(trainer.getScoreMap(query)).descendingMap().toString()); + System.out.println(new TreeMap<>(trainer.getScoreMap(query)).descendingMap()); Intent intent = trainer.interpret(query); - System.out.println(intent.toString()); + System.out.println(intent); return intent; } diff --git a/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/CommunityWidgetGalleryProvider.java b/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/CommunityWidgetGalleryProvider.java index e166181df4..880904ae3b 100755 --- a/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/CommunityWidgetGalleryProvider.java +++ b/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/CommunityWidgetGalleryProvider.java @@ -51,7 +51,7 @@ public class CommunityWidgetGalleryProvider implements GalleryWidgetProvider { @Override public Stream getGalleryList() throws Exception { - List pages = new ArrayList(); + List pages = new ArrayList<>(); URL url = new URL(COMMUNITY_GALLERY_URL); int pageNb = 1; @@ -71,7 +71,7 @@ public Stream getGalleryList() throws Exception { } } - return pages.stream().flatMap(p -> Stream.of(p.topic_list.topics)).map(t -> convertTopicToWidgetsListItem(t)); + return pages.stream().flatMap(p -> Stream.of(p.topic_list.topics)).map(this::convertTopicToWidgetsListItem); } @Override @@ -118,7 +118,7 @@ public GalleryWidgetsItem getGalleryItem(String id) throws Exception { widget.contents = new String(widgetDownload.getInputStream().readAllBytes(), StandardCharsets.UTF_8); String cDisp = widgetDownload.getHeaderField("Content-Disposition"); - if (cDisp != null && cDisp.indexOf("=") != -1 && cDisp.indexOf(".widget.json") != -1) { + if (cDisp != null && cDisp.contains("=") && cDisp.contains(".widget.json")) { widget.id = cDisp.split("=")[1].replaceAll("\"", "").replaceAll("]", "") .replaceAll(".widget.json", ""); @@ -141,7 +141,7 @@ public GalleryWidgetsItem getGalleryItem(String id) throws Exception { /** * Transforms a Discourse topic to a {@link GalleryWidgetsListItem} * - * @param topic the topic + * @param t the topic * @return the list item */ private GalleryWidgetsListItem convertTopicToWidgetsListItem(Object t) { diff --git a/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseGalleryResponse.java b/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseGalleryResponse.java index 6d6fb042d0..2201cba78f 100755 --- a/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseGalleryResponse.java +++ b/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseGalleryResponse.java @@ -24,19 +24,19 @@ public class DiscourseGalleryResponse { public DiscourseUser[] users; public DiscourseTopicList topic_list; - public class DiscourseUser { + public static class DiscourseUser { public Integer id; public String username; public String avatar_template; } - public class DiscourseTopicList { + public static class DiscourseTopicList { public String more_topics_url; public Integer per_page; public DiscourseTopic[] topics; } - public class DiscourseTopic { + public static class DiscourseTopic { public Integer id; public String title; public String slug; diff --git a/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseTopicResponse.java b/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseTopicResponse.java index d21f1628a6..e0e573ac68 100755 --- a/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseTopicResponse.java +++ b/bundles/org.openhab.ui.habpanel/src/main/java/org/openhab/ui/habpanel/internal/gallery/community/DiscourseTopicResponse.java @@ -36,13 +36,13 @@ public class DiscourseTopicResponse { public DiscourseTopicDetails details; - public class DiscoursePostAuthor { + public static class DiscoursePostAuthor { public Integer id; public String username; public String avatar_template; } - public class DiscoursePostLink { + public static class DiscoursePostLink { public String url; public Boolean internal; public Integer clicks; diff --git a/pom.xml b/pom.xml index 213063eaf9..20ba7bd6e9 100644 --- a/pom.xml +++ b/pom.xml @@ -419,6 +419,7 @@ Import-Package: \\ ${basedirRoot}/tools/static-code-analysis/checkstyle/ruleset.properties ${basedirRoot}/tools/static-code-analysis/checkstyle/suppressions.xml + ${basedirRoot}/tools/static-code-analysis/spotbugs/suppressions.xml diff --git a/tools/static-code-analysis/spotbugs/suppressions.xml b/tools/static-code-analysis/spotbugs/suppressions.xml index bb11da72a0..a423a1d961 100644 --- a/tools/static-code-analysis/spotbugs/suppressions.xml +++ b/tools/static-code-analysis/spotbugs/suppressions.xml @@ -26,4 +26,8 @@ + + + +