Skip to content

Commit

Permalink
Cleanup Java code
Browse files Browse the repository at this point in the history
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 spotbugs/sonar-findbugs#876.

Signed-off-by: Wouter Born <github@maindrain.net>
  • Loading branch information
wborn committed Jan 8, 2024
1 parent 4d550cb commit 8a6eae3
Show file tree
Hide file tree
Showing 45 changed files with 169 additions and 264 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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
*/
Expand All @@ -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
Expand Down Expand Up @@ -338,20 +338,15 @@ 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);
}

/**
* Process the color tags - labelcolor and valuecolor
*
* @param w
* The widget to process
* @param snippet
* @param originalSnippet
* The snippet to translate
* @return The updated snippet
*/
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public boolean canRender(Widget w) {
@Override
public EList<Widget> 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%",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public EList<Widget> 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()
? "<span %valuestyle% class=\"mdl-form__input-prefix\">" + prefix + "</span>"
Expand Down Expand Up @@ -181,8 +181,7 @@ public EList<Widget> 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)) {
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ public EList<Widget> 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Widget> children, String sitemap)
private void processChildren(StringBuilder sbPre, StringBuilder sbPost, EList<Widget> 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%", "");
Expand All @@ -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!");
Expand Down Expand Up @@ -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);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public boolean canRender(Widget w) {
@Override
public EList<Widget> 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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> 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 + "\"");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,7 @@ public Object getRrdSeries(QueryablePersistenceService persistenceService, Item
try {
List<String> 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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public List<String> getDesigns() {
// all designs
File designDir = ManagerSettings.getInstance().getDesignFolder();
File[] designs = designDir.listFiles();
List<String> res = new ArrayList<String>();
List<String> res = new ArrayList<>();
if (designs != null) {
Arrays.sort(designs);
for (File design : designs) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 8a6eae3

Please sign in to comment.