diff --git a/src/main/java/mpo/dayon/assistant/control/ControlEngine.java b/src/main/java/mpo/dayon/assistant/control/ControlEngine.java index 3ed9159b..dadd4718 100644 --- a/src/main/java/mpo/dayon/assistant/control/ControlEngine.java +++ b/src/main/java/mpo/dayon/assistant/control/ControlEngine.java @@ -65,7 +65,7 @@ protected void execute() { }); } - private int getActingMouseButton(final int button) { + private static int getActingMouseButton(final int button) { if (MouseEvent.BUTTON1 == button) { return NetworkMouseControlMessage.BUTTON1; } @@ -91,7 +91,7 @@ protected void execute() { /** * Fix missing pair'd PRESSED event from RELEASED */ - private final HashMap pressedKeys = new HashMap<>(); + private final HashMap pressedKeys = new HashMap<>(4); /** * From AWT thread (!) diff --git a/src/main/java/mpo/dayon/assistant/gui/Assistant.java b/src/main/java/mpo/dayon/assistant/gui/Assistant.java index 151fc143..87495627 100644 --- a/src/main/java/mpo/dayon/assistant/gui/Assistant.java +++ b/src/main/java/mpo/dayon/assistant/gui/Assistant.java @@ -62,8 +62,6 @@ public class Assistant implements ClipboardOwner { private final NetworkAssistantEngine networkEngine; - private final ClipboardDispatcher clipboardDispatcher; - private BitCounter receivedBitCounter; private TileCounter receivedTileCounter; @@ -145,7 +143,6 @@ public Assistant(String tokenServerUrl, String language) { Log.warn("Could not set the [" + lnf + "] L&F!", ex); } initGui(); - clipboardDispatcher = new ClipboardDispatcher(); } private void initGui() { @@ -306,7 +303,7 @@ public void actionPerformed(ActionEvent ev) { } private void sendLocalClipboard() { - clipboardDispatcher.sendClipboard(networkEngine, frame, this); + ClipboardDispatcher.sendClipboard(networkEngine, frame, this); } /** @@ -411,7 +408,7 @@ private void updateCaptureConfiguration(CaptureEngineConfiguration newCaptureEng } } - private Gray8Bits toGrayLevel(int value) { + private static Gray8Bits toGrayLevel(int value) { return Gray8Bits.values()[6 - value]; } @@ -504,7 +501,7 @@ public void actionPerformed(ActionEvent ev) { return configure; } - private String validatePurgeValue(JTextField purgeSizeTf, int maxValue) { + private static String validatePurgeValue(JTextField purgeSizeTf, int maxValue) { final String purge = purgeSizeTf.getText(); if (purge.isEmpty()) { return translate("compression.cache.purge.msg1"); @@ -708,7 +705,7 @@ public boolean isUpnpEnabled() { synchronized (upnpEnabledLOCK) { while (upnpEnabled == null) { try { - upnpEnabledLOCK.wait(); + upnpEnabledLOCK.wait(5000); } catch (InterruptedException e) { Log.warn("Swallowed", e); Thread.currentThread().interrupt(); diff --git a/src/main/java/mpo/dayon/assistant/gui/AssistantConfiguration.java b/src/main/java/mpo/dayon/assistant/gui/AssistantConfiguration.java index 7c45d3ac..1290a6d1 100644 --- a/src/main/java/mpo/dayon/assistant/gui/AssistantConfiguration.java +++ b/src/main/java/mpo/dayon/assistant/gui/AssistantConfiguration.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } final AssistantConfiguration that = (AssistantConfiguration) o; - return language.equals(that.getLanguage()); + return language.equals(that.language); } @Override diff --git a/src/main/java/mpo/dayon/assistant/gui/AssistantFrame.java b/src/main/java/mpo/dayon/assistant/gui/AssistantFrame.java index a4918dc1..69949580 100644 --- a/src/main/java/mpo/dayon/assistant/gui/AssistantFrame.java +++ b/src/main/java/mpo/dayon/assistant/gui/AssistantFrame.java @@ -280,7 +280,7 @@ private JTabbedPane createTabbedPane() { return tabbedPane; } - private Component createTokenButton(Action tokenAction) { + private static Component createTokenButton(Action tokenAction) { String token = (String) tokenAction.getValue("token"); JButton button = createButton(tokenAction); if (token != null) { @@ -290,7 +290,7 @@ private Component createTokenButton(Action tokenAction) { return button; } - private StatusBar createStatusBar(ArrayList> counters) { + private static StatusBar createStatusBar(ArrayList> counters) { final StatusBar statusBar = new StatusBar(); final Component horizontalStrut = Box.createHorizontalStrut(10); statusBar.add(horizontalStrut); diff --git a/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngine.java b/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngine.java index 13bfd914..3243fe6b 100644 --- a/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngine.java +++ b/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngine.java @@ -93,7 +93,7 @@ public void cancel() { fireOnDisconnecting(); } - public void manageRouterPorts(int oldPort, int newPort) { + public static void manageRouterPorts(int oldPort, int newPort) { if (!UPnP.isUPnPAvailable()) { return; } diff --git a/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngineConfiguration.java b/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngineConfiguration.java index ca47fe91..3bdc8814 100644 --- a/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngineConfiguration.java +++ b/src/main/java/mpo/dayon/assistant/network/NetworkAssistantEngineConfiguration.java @@ -60,7 +60,7 @@ public boolean equals(Object o) { final NetworkAssistantEngineConfiguration that = (NetworkAssistantEngineConfiguration) o; - return port == that.getPort() && tokenServerUrl.equals(that.getTokenServerUrl()); + return port == that.port && tokenServerUrl.equals(that.tokenServerUrl); } @Override diff --git a/src/main/java/mpo/dayon/assistant/utils/NetworkUtilities.java b/src/main/java/mpo/dayon/assistant/utils/NetworkUtilities.java index b52ead55..7f4c2236 100644 --- a/src/main/java/mpo/dayon/assistant/utils/NetworkUtilities.java +++ b/src/main/java/mpo/dayon/assistant/utils/NetworkUtilities.java @@ -11,7 +11,7 @@ public interface NetworkUtilities { static List getInetAddresses() { - final List addresses = new ArrayList<>(); + final List addresses = new ArrayList<>(8); try { InetAddress loopback = null; diff --git a/src/main/java/mpo/dayon/assisted/gui/Assisted.java b/src/main/java/mpo/dayon/assisted/gui/Assisted.java index 9b9cc43c..67b4a0ac 100644 --- a/src/main/java/mpo/dayon/assisted/gui/Assisted.java +++ b/src/main/java/mpo/dayon/assisted/gui/Assisted.java @@ -20,6 +20,7 @@ import mpo.dayon.common.gui.common.ImageUtilities; import mpo.dayon.common.log.Log; import mpo.dayon.common.network.ClipboardDispatcher; +import mpo.dayon.common.network.NetworkEngine; import mpo.dayon.common.network.message.*; import javax.swing.*; @@ -55,8 +56,6 @@ public class Assisted implements Subscriber, ClipboardOwner { private NetworkAssistedEngine networkEngine; - private final ClipboardDispatcher clipboardDispatcher; - private boolean coldStart = true; private CaptureEngineConfiguration captureEngineConfiguration; @@ -84,7 +83,6 @@ public Assisted(String tokenServerUrl) { } catch (Exception ex) { Log.warn(format("Could not set the L&F [%s]", lnf), ex); } - clipboardDispatcher = new ClipboardDispatcher(); } /** @@ -171,14 +169,14 @@ private boolean requestConnectionSettings() { return ok; } - private String validateIpAddress(String ipAddress) { + private static String validateIpAddress(String ipAddress) { if (ipAddress.isEmpty()) { return translate("connection.settings.emptyIpAddress"); } return isValidIpAddressOrHostName(ipAddress.trim()) ? null : translate("connection.settings.invalidIpAddress"); } - private String validatePortNumber(String portNumber) { + private static String validatePortNumber(String portNumber) { if (portNumber.isEmpty()) { return translate("connection.settings.emptyPortNumber"); } @@ -316,7 +314,7 @@ private void stop(String serverName) { frame.onDisconnecting(); } - private NetworkAssistedEngineConfiguration extractConfiguration(String connectionParams) { + private static NetworkAssistedEngineConfiguration extractConfiguration(String connectionParams) { if (connectionParams != null) { int portStart = connectionParams.lastIndexOf('*'); if (portStart > 0) { @@ -395,13 +393,13 @@ private void onCompressorEngineConfigured(NetworkCompressorConfigurationMessage */ private void onClipboardRequested() { Log.info("Clipboard transfer request received"); - clipboardDispatcher.sendClipboard(networkEngine, frame, this); + ClipboardDispatcher.sendClipboard(networkEngine, frame, this); } private void onScreenshotRequested(){ Log.info("Screenshot request received"); try { - networkEngine.setClipboardContents(new Robot().createScreenCapture(ScreenUtilities.getSharedScreenSize()), this); + NetworkEngine.setClipboardContents(new Robot().createScreenCapture(ScreenUtilities.getSharedScreenSize()), this); } catch (AWTException e) { Log.error("Failed to capture screen", e); } diff --git a/src/main/java/mpo/dayon/assisted/utils/ScreenUtilities.java b/src/main/java/mpo/dayon/assisted/utils/ScreenUtilities.java index 7dc1bef5..4713091a 100644 --- a/src/main/java/mpo/dayon/assisted/utils/ScreenUtilities.java +++ b/src/main/java/mpo/dayon/assisted/utils/ScreenUtilities.java @@ -45,11 +45,13 @@ private ScreenUtilities() { } } - public static synchronized void setShareAllScreens(boolean doShareAllScreens) { - shareAllScreens = doShareAllScreens; - sharedScreenSize = doShareAllScreens ? COMBINED_SCREEN_SIZE : DEFAULT_SIZE; - rgb = new int[sharedScreenSize.height * sharedScreenSize.width]; - gray = new byte[rgb.length]; + public static void setShareAllScreens(boolean doShareAllScreens) { + synchronized (ScreenUtilities.class) { + shareAllScreens = doShareAllScreens; + sharedScreenSize = doShareAllScreens ? COMBINED_SCREEN_SIZE : DEFAULT_SIZE; + rgb = new int[sharedScreenSize.height * sharedScreenSize.width]; + gray = new byte[rgb.length]; + } } public static Rectangle getSharedScreenSize() { diff --git a/src/main/java/mpo/dayon/common/babylon/Babylon.java b/src/main/java/mpo/dayon/common/babylon/Babylon.java index a9d7896a..effb6ecd 100644 --- a/src/main/java/mpo/dayon/common/babylon/Babylon.java +++ b/src/main/java/mpo/dayon/common/babylon/Babylon.java @@ -16,25 +16,27 @@ public final class Babylon { private Babylon() { } - public static synchronized String translate(String tag, Object... arguments) { - final Locale locale = Locale.getDefault(); - final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE, locale); - String value; - try { - value = bundle.getString(tag); - if (value.trim().isEmpty()) { + public static String translate(String tag, Object... arguments) { + synchronized (Babylon.class) { + final Locale locale = Locale.getDefault(); + final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE, locale); + String value; + try { + value = bundle.getString(tag); + if (value.trim().isEmpty()) { + value = tag; + } + } catch (MissingResourceException ignored) { value = tag; } - } catch (MissingResourceException ignored) { - value = tag; - } - if (arguments != null && arguments.length > 0) { - value = formatValue(locale, value, tag, arguments); - } - if (value != null) { - return value.trim(); + if (arguments != null && arguments.length > 0) { + value = formatValue(locale, value, tag, arguments); + } + if (value != null) { + return value.trim(); + } + return null; } - return null; } @java.lang.SuppressWarnings("squid:S4973") diff --git a/src/main/java/mpo/dayon/common/capture/CaptureEngineConfiguration.java b/src/main/java/mpo/dayon/common/capture/CaptureEngineConfiguration.java index 4c52c46c..3c80c1b2 100644 --- a/src/main/java/mpo/dayon/common/capture/CaptureEngineConfiguration.java +++ b/src/main/java/mpo/dayon/common/capture/CaptureEngineConfiguration.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { final CaptureEngineConfiguration that = (CaptureEngineConfiguration) o; - return captureTick == that.getCaptureTick() && captureQuantization == that.getCaptureQuantization() && captureColors == that.captureColors; + return captureTick == that.captureTick && captureQuantization == that.captureQuantization && captureColors == that.captureColors; } @Override diff --git a/src/main/java/mpo/dayon/common/gui/common/BaseFrame.java b/src/main/java/mpo/dayon/common/gui/common/BaseFrame.java index d774d7d1..02794547 100644 --- a/src/main/java/mpo/dayon/common/gui/common/BaseFrame.java +++ b/src/main/java/mpo/dayon/common/gui/common/BaseFrame.java @@ -146,11 +146,11 @@ private void updateInputLocale() { } } - protected JButton createButton(Action action) { + protected static JButton createButton(Action action) { return createButton(action, true); } - protected JButton createButton(Action action, boolean visible) { + protected static JButton createButton(Action action, boolean visible) { final JButton button = new JButton(); addButtonProperties(action, button); button.setVisible(visible); @@ -161,7 +161,7 @@ protected JToggleButton createToggleButton(Action action) { return createToggleButton(action, true); } - protected JToggleButton createToggleButton(Action action, boolean visible) { + protected static JToggleButton createToggleButton(Action action, boolean visible) { final JToggleButton button = new JToggleButton(); addButtonProperties(action, button); button.setVisible(visible); @@ -174,7 +174,7 @@ protected JToggleButton createToggleButton(Action action, boolean visible, boole return button; } - private void addButtonProperties(Action action, AbstractButton button) { + private static void addButtonProperties(Action action, AbstractButton button) { button.setMargin(ZERO_INSETS); button.setHideActionText(true); button.setAction(action); @@ -401,7 +401,7 @@ private JPanel createPanel(JTextField addressTextField, JTextField portNumberTex return panel; } - private String toUpperFirst(String text) { + private static String toUpperFirst(String text) { return Pattern.compile("^.").matcher(text).replaceFirst(m -> m.group().toUpperCase()); } @@ -428,7 +428,7 @@ private String validateInputFields(JTextField addressTextField, JTextField portN return null; } - private void updateAssistedNetworkConfiguration(JTextField addressTextField, JTextField portNumberTextField, JCheckBox autoConnectCheckBox, String newTokenServerUrl) { + private static void updateAssistedNetworkConfiguration(JTextField addressTextField, JTextField portNumberTextField, JCheckBox autoConnectCheckBox, String newTokenServerUrl) { final NetworkAssistedEngineConfiguration newNetworkConfiguration = new NetworkAssistedEngineConfiguration( addressTextField.getText().trim(), Integer.parseInt(portNumberTextField.getText()), autoConnectCheckBox.isSelected(), newTokenServerUrl); @@ -437,19 +437,19 @@ private void updateAssistedNetworkConfiguration(JTextField addressTextField, JTe } } - private void updateAssistantNetworkConfiguration(JTextField portNumberTextField, String newTokenServerUrl, NetworkAssistantEngine networkEngine) { + private static void updateAssistantNetworkConfiguration(JTextField portNumberTextField, String newTokenServerUrl, NetworkAssistantEngine networkEngine) { final NetworkAssistantEngineConfiguration newNetworkConfiguration = new NetworkAssistantEngineConfiguration( Integer.parseInt(portNumberTextField.getText()), newTokenServerUrl); NetworkAssistantEngineConfiguration networkConfiguration = new NetworkAssistantEngineConfiguration(); if (!newNetworkConfiguration.equals(networkConfiguration)) { - networkEngine.manageRouterPorts(networkConfiguration.getPort(), newNetworkConfiguration.getPort()); + NetworkAssistantEngine.manageRouterPorts(networkConfiguration.getPort(), newNetworkConfiguration.getPort()); newNetworkConfiguration.persist(); networkEngine.reconfigure(newNetworkConfiguration); } } - private void updateSystemProperty(String newTokenServerUrl) { + private static void updateSystemProperty(String newTokenServerUrl) { if (newTokenServerUrl.isEmpty()) { System.clearProperty("dayon.custom.tokenServer"); return; @@ -457,7 +457,7 @@ private void updateSystemProperty(String newTokenServerUrl) { System.setProperty("dayon.custom.tokenServer", newTokenServerUrl); } - private GridBagConstraints createGridBagConstraints(int gridy) { + private static GridBagConstraints createGridBagConstraints(int gridy) { GridBagConstraints gc = new GridBagConstraints(); gc.fill = HORIZONTAL; gc.gridx = 0; @@ -465,7 +465,7 @@ private GridBagConstraints createGridBagConstraints(int gridy) { return gc; } - private boolean isActiveTokenServer(String tokenServer) { + private static boolean isActiveTokenServer(String tokenServer) { CompletableFuture future = CompletableFuture.supplyAsync(() -> { try { // HttpClient doesn't implement AutoCloseable nor close before Java 21! @@ -575,7 +575,7 @@ protected static JLabel getFingerprints() { return fingerprints; } - protected void clearFingerprints() { + protected static void clearFingerprints() { fingerprints.setText(null); fingerprints.setIcon(null); fingerprints.setCursor(null); diff --git a/src/main/java/mpo/dayon/common/gui/statusbar/StatusBar.java b/src/main/java/mpo/dayon/common/gui/statusbar/StatusBar.java index 7b48f443..983f7a4f 100644 --- a/src/main/java/mpo/dayon/common/gui/statusbar/StatusBar.java +++ b/src/main/java/mpo/dayon/common/gui/statusbar/StatusBar.java @@ -14,7 +14,7 @@ import static mpo.dayon.common.babylon.Babylon.translate; public class StatusBar extends JPanel { - + private static final int HEIGHT = 5; private final JLabel message = new JLabel(); private final JLabel sessionDuration = new JLabel("00:00:00"); @@ -30,7 +30,7 @@ public StatusBar() { } public void clearMessage() { - this.message.setText(null); + message.setText(null); } public void setMessage(String message) { @@ -51,48 +51,39 @@ public String getKeyboardLayout() { } private void addKeyboardLayout() { - final Dimension dimension = new Dimension(60, HEIGHT); - keyboardLayout.setHorizontalAlignment(CENTER); - keyboardLayout.setSize(dimension); - keyboardLayout.setPreferredSize(dimension); add(keyboardLayout); } public void addCounter(Counter counter, int width) { - final JLabel lbl = new JLabel(counter.getUid()); - final Dimension dimension = new Dimension(width, HEIGHT); - lbl.setHorizontalAlignment(CENTER); - lbl.setSize(dimension); - lbl.setPreferredSize(dimension); - lbl.setToolTipText(counter.getShortDescription()); - counter.addListener((counter1, value) -> lbl.setText(counter1.formatInstantValue(value))); - add(lbl); + JLabel label = createLabel(counter.getUid(), width); + label.setToolTipText(counter.getShortDescription()); + counter.addListener((counter1, value) -> label.setText(counter1.formatInstantValue(value))); + add(label); } public void addRamInfo() { - final JLabel lbl = new JLabel(); - final Dimension dimension = new Dimension(110, HEIGHT); - lbl.setHorizontalAlignment(CENTER); - lbl.setSize(dimension); - lbl.setPreferredSize(dimension); - BigBrother.get().registerRamInfo(new MemoryCounter(lbl)); - lbl.setToolTipText(translate("memory.info")); - add(lbl); + JLabel label = createLabel("", 110); + BigBrother.get().registerRamInfo(new MemoryCounter(label)); + label.setToolTipText(translate("memory.info")); + add(label); } public void addConnectionDuration() { - final Dimension dimension = new Dimension(65, HEIGHT); sessionDuration.setHorizontalAlignment(RIGHT); - sessionDuration.setSize(dimension); - sessionDuration.setPreferredSize(dimension); + sessionDuration.setPreferredSize(new Dimension(65, HEIGHT)); sessionDuration.setToolTipText(translate("session.duration")); add(sessionDuration); } public void addSeparator() { - final JToolBar.Separator separator = new JToolBar.Separator(); - separator.setOrientation(VERTICAL); - add(separator); + add(new JToolBar.Separator(new Dimension(5, HEIGHT))); + } + + private JLabel createLabel(String text, int width) { + JLabel label = new JLabel(text); + label.setHorizontalAlignment(CENTER); + label.setPreferredSize(new Dimension(width, HEIGHT)); + return label; } private static class MemoryCounter extends TimerTask { diff --git a/src/main/java/mpo/dayon/common/log/file/FileAppender.java b/src/main/java/mpo/dayon/common/log/file/FileAppender.java index 4ffb9fe5..3d5a54f8 100644 --- a/src/main/java/mpo/dayon/common/log/file/FileAppender.java +++ b/src/main/java/mpo/dayon/common/log/file/FileAppender.java @@ -35,27 +35,29 @@ public FileAppender(String filename) throws FileNotFoundException { setupFile(filename, true); } - @Override - public synchronized void append(LogLevel level, String message, Throwable error) { - try { - StringBuilder builder = new StringBuilder(); - builder.append(format(level, message)).append(System.lineSeparator()); - if (error != null) { - builder.append(getStackTrace(error)).append(System.lineSeparator()); - } - count += builder.length(); - if (count >= MAX_FILE_SIZE && count >= nextRolloverCount) { - rollOver(); - } - writer.write(builder.toString()); - writer.flush(); - } catch (RuntimeException ex) { - fallback.append(level, message, error); - fallback.append(LogLevel.WARN, "[FileAppender] error", ex); - } - } - - private String getStackTrace(Throwable error) { + @Override + public void append(LogLevel level, String message, Throwable error) { + synchronized (this) { + try { + StringBuilder builder = new StringBuilder(64); + builder.append(format(level, message)).append(System.lineSeparator()); + if (error != null) { + builder.append(getStackTrace(error)).append(System.lineSeparator()); + } + count += builder.length(); + if (count >= MAX_FILE_SIZE && count >= nextRolloverCount) { + rollOver(); + } + writer.write(builder.toString()); + writer.flush(); + } catch (RuntimeException ex) { + fallback.append(level, message, error); + fallback.append(LogLevel.WARN, "[FileAppender] error", ex); + } + } + } + + private static String getStackTrace(Throwable error) { final StringWriter out = new StringWriter(); final PrintWriter printer = new PrintWriter(out); error.printStackTrace(printer); @@ -67,7 +69,7 @@ private void setupFile(String filename, boolean append) throws FileNotFoundExcep final File file = new File(filename); count = file.length(); } - + @java.lang.SuppressWarnings("squid:S106") private void rollOver() { nextRolloverCount = count + MAX_FILE_SIZE; diff --git a/src/main/java/mpo/dayon/common/monitoring/BigBrother.java b/src/main/java/mpo/dayon/common/monitoring/BigBrother.java index 98429396..7e9a5314 100644 --- a/src/main/java/mpo/dayon/common/monitoring/BigBrother.java +++ b/src/main/java/mpo/dayon/common/monitoring/BigBrother.java @@ -27,7 +27,7 @@ public void registerCounter(final Counter counter, final long instantRatePeri } public void registerRamInfo(Runnable callback) { - scheduler.scheduleAtFixedRate(callback, 0, 1, TimeUnit.SECONDS); + scheduler.scheduleAtFixedRate(callback, 0, 1291, TimeUnit.MILLISECONDS); } public void shutdown() { diff --git a/src/main/java/mpo/dayon/common/monitoring/counter/AverageValueCounter.java b/src/main/java/mpo/dayon/common/monitoring/counter/AverageValueCounter.java index 892decb6..f5423c55 100644 --- a/src/main/java/mpo/dayon/common/monitoring/counter/AverageValueCounter.java +++ b/src/main/java/mpo/dayon/common/monitoring/counter/AverageValueCounter.java @@ -13,14 +13,12 @@ public void add(double value) { add(1.0, value); } - public void add(double weight, double value) { - synchronized (this) { - final double xvalue = weight * value; + public synchronized void add(double weight, double value) { + final double xvalue = weight * value; - instantWeight += weight; - instantValue += xvalue; - } - } + instantWeight += weight; + instantValue += xvalue; + } @Override public void computeAndResetInstantValue() { diff --git a/src/main/java/mpo/dayon/common/monitoring/counter/RateCounter.java b/src/main/java/mpo/dayon/common/monitoring/counter/RateCounter.java index cf5c1abd..79cc6f5c 100644 --- a/src/main/java/mpo/dayon/common/monitoring/counter/RateCounter.java +++ b/src/main/java/mpo/dayon/common/monitoring/counter/RateCounter.java @@ -15,11 +15,9 @@ public String formatInstantValue(Double value) { protected abstract String formatRate(Double rate); - public void add(double value) { - synchronized (this) { - instantValue += value; - } - } + public synchronized void add(double value) { + instantValue += value; + } @Override public void computeAndResetInstantValue() { diff --git a/src/main/java/mpo/dayon/common/network/ClipboardDispatcher.java b/src/main/java/mpo/dayon/common/network/ClipboardDispatcher.java index d8890f77..d3201962 100644 --- a/src/main/java/mpo/dayon/common/network/ClipboardDispatcher.java +++ b/src/main/java/mpo/dayon/common/network/ClipboardDispatcher.java @@ -15,7 +15,10 @@ public class ClipboardDispatcher { - public void sendClipboard(NetworkEngine networkEngine, BaseFrame frame, ClipboardOwner owner) { + private ClipboardDispatcher() { + } + + public static void sendClipboard(NetworkEngine networkEngine, BaseFrame frame, ClipboardOwner owner) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable content = clipboard.getContents(owner); diff --git a/src/main/java/mpo/dayon/common/network/NetworkEngine.java b/src/main/java/mpo/dayon/common/network/NetworkEngine.java index 324fde50..857c4499 100644 --- a/src/main/java/mpo/dayon/common/network/NetworkEngine.java +++ b/src/main/java/mpo/dayon/common/network/NetworkEngine.java @@ -80,23 +80,23 @@ public void sendClipboardFiles(List files, long size, String basePath) { } } - protected void setClipboardContents(String string, ClipboardOwner clipboardOwner) { + protected static void setClipboardContents(String string, ClipboardOwner clipboardOwner) { Log.debug(CLIPBOARD_DEBUG, () -> string); StringSelection stringSelection = new StringSelection(string); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, clipboardOwner); } - public void setClipboardContents(BufferedImage image, ClipboardOwner clipboardOwner) { + public static void setClipboardContents(BufferedImage image, ClipboardOwner clipboardOwner) { Log.debug(CLIPBOARD_DEBUG, () -> format("%dx%d", image.getWidth(), image.getHeight())); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new TransferableImage(image), clipboardOwner); } - private void setClipboardContents(List files, ClipboardOwner clipboardOwner) { + private static void setClipboardContents(List files, ClipboardOwner clipboardOwner) { Log.debug(CLIPBOARD_DEBUG, () -> String.valueOf(files)); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new TransferableFiles(files), clipboardOwner); } - private NetworkClipboardFilesHelper handleNetworkClipboardFilesHelper(NetworkClipboardFilesHelper filesHelper, ClipboardOwner clipboardOwner) { + private static NetworkClipboardFilesHelper handleNetworkClipboardFilesHelper(NetworkClipboardFilesHelper filesHelper, ClipboardOwner clipboardOwner) { if (filesHelper.isDone()) { setClipboardContents(filesHelper.getFiles(), clipboardOwner); return new NetworkClipboardFilesHelper(); diff --git a/src/main/java/mpo/dayon/common/network/message/NetworkMessage.java b/src/main/java/mpo/dayon/common/network/message/NetworkMessage.java index 966223f2..075d24ef 100644 --- a/src/main/java/mpo/dayon/common/network/message/NetworkMessage.java +++ b/src/main/java/mpo/dayon/common/network/message/NetworkMessage.java @@ -6,42 +6,34 @@ public abstract class NetworkMessage { private static final byte MAGIC_NUMBER = (byte) 170; - NetworkMessage() { - } + protected NetworkMessage() {} public abstract NetworkMessageType getType(); - - /** - * Take into account some extra-info sent over the network with the actual - * payload ... - */ public abstract int getWireSize(); - public abstract void marshall(ObjectOutputStream out) throws IOException; public static void marshallMagicNumber(ObjectOutputStream out) throws IOException { - out.writeByte(NetworkMessage.MAGIC_NUMBER); + out.writeByte(MAGIC_NUMBER); } public static void unmarshallMagicNumber(ObjectInputStream in) throws IOException { - if (NetworkMessage.MAGIC_NUMBER != in.readByte()) { + if (MAGIC_NUMBER != in.readByte()) { throw new IOException("Protocol error!"); } } - static > void marshallEnum(ObjectOutputStream out, Enum value) throws IOException { + public static > void marshallEnum(ObjectOutputStream out, Enum value) throws IOException { out.write(value.ordinal()); } public static > T unmarshallEnum(ObjectInputStream in, Class enumClass) throws IOException { - final byte ordinal = in.readByte(); - final T[] xenums = enumClass.getEnumConstants(); - return Arrays.stream(xenums) - .filter(xenum -> xenum.ordinal() == ordinal) + byte ordinal = in.readByte(); + return Arrays.stream(enumClass.getEnumConstants()) + .filter(x -> x.ordinal() == ordinal) .findFirst() - .orElseThrow(() -> new IllegalArgumentException("Unknown " + enumClass.getSimpleName() + " [" + ordinal + "] enum!")); + .orElseThrow(() -> new IllegalArgumentException("Unknown " + enumClass.getSimpleName() + " enum!")); } @Override public abstract String toString(); -} +} \ No newline at end of file diff --git a/src/main/java/mpo/dayon/common/security/CustomTrustManager.java b/src/main/java/mpo/dayon/common/security/CustomTrustManager.java index eccffa37..c6ef8ee5 100644 --- a/src/main/java/mpo/dayon/common/security/CustomTrustManager.java +++ b/src/main/java/mpo/dayon/common/security/CustomTrustManager.java @@ -19,9 +19,11 @@ import static java.lang.System.getProperty; public class CustomTrustManager implements X509TrustManager { + private static final X509Certificate[] ACCEPTED = {}; + @Override public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[]{}; + return ACCEPTED; } @Override diff --git a/src/main/java/mpo/dayon/common/squeeze/RegularRunLengthEncoder.java b/src/main/java/mpo/dayon/common/squeeze/RegularRunLengthEncoder.java index 6bfcc1cd..25736e08 100644 --- a/src/main/java/mpo/dayon/common/squeeze/RegularRunLengthEncoder.java +++ b/src/main/java/mpo/dayon/common/squeeze/RegularRunLengthEncoder.java @@ -39,7 +39,7 @@ public void runLengthEncode(MemByteBuffer out, MemByteBuffer capture) { } } - private void writeNonZero(MemByteBuffer out, int count) { + private static void writeNonZero(MemByteBuffer out, int count) { if (count > 0) { out.write(count); } diff --git a/src/main/java/mpo/dayon/common/squeeze/RegularTileCache.java b/src/main/java/mpo/dayon/common/squeeze/RegularTileCache.java index 99553d6f..9bce821a 100644 --- a/src/main/java/mpo/dayon/common/squeeze/RegularTileCache.java +++ b/src/main/java/mpo/dayon/common/squeeze/RegularTileCache.java @@ -14,24 +14,19 @@ public class RegularTileCache implements TileCache { private final Map tiles; private final int maxSize; private final int purgeSize; - private int hits; + private int hits = 0; public RegularTileCache(int maxSize, int purgeSize) { this.maxSize = maxSize; this.purgeSize = purgeSize; tiles = new LinkedHashMap<>(maxSize, 0.75f, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > maxSize; - } - @Override public CaptureTile get(Object key) { CaptureTile tile = super.get(key); if (tile != null) { ++hits; } - return tile; + return tile != null ? tile : CaptureTile.MISSING; } }; Log.info("Regular cache created [MAX:" + maxSize + "][PURGE:" + purgeSize + "]"); @@ -53,8 +48,7 @@ public void add(CaptureTile tile) { @Override public CaptureTile get(int cacheId) { - CaptureTile tile = tiles.get(cacheId); - return tile != null ? tile : CaptureTile.MISSING; + return tiles.get(cacheId); } @Override diff --git a/src/main/java/mpo/dayon/common/utils/SystemUtilities.java b/src/main/java/mpo/dayon/common/utils/SystemUtilities.java index e1765b38..ede8be9a 100644 --- a/src/main/java/mpo/dayon/common/utils/SystemUtilities.java +++ b/src/main/java/mpo/dayon/common/utils/SystemUtilities.java @@ -15,6 +15,7 @@ import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.util.*; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -28,6 +29,8 @@ public final class SystemUtilities { public static final String FLATPAK_BROWSER = "/app/bin/dayon.browser"; private static final String JAVA_VENDOR = "java.vendor"; public static final String DEFAULT_TOKEN_SERVER_URL = "https://fensterkitt.ch/dayon/"; + private static final Pattern FQ_HOSTNAME_REGEX = Pattern.compile("^([a-zA-Z\\d][a-zA-Z\\d\\-]{0,61}[a-zA-Z\\d]\\.)*[a-zA-Z]{2,}$"); + private static final Pattern IPV4_REGEX = Pattern.compile("(\\d{1,3})"); private SystemUtilities() { } @@ -69,7 +72,7 @@ private static void cleanDir(File folder) throws IOException { } public static List getSystemProperties() { - final List props = new ArrayList<>(); + final List props = new ArrayList<>(64); final List propNames = System.getProperties().keySet().stream().map(Object::toString).collect(Collectors.toList()); final int size = propNames.stream().max(Comparator.comparing(String::length)).orElse("").length(); final String format = "%" + size + "." + size + "s [%s]"; @@ -78,7 +81,7 @@ public static List getSystemProperties() { String propValue = getProperty(propName); // I want to display the actual content of the line separator... if (propName.equals("line.separator")) { - StringBuilder hex = new StringBuilder(); + StringBuilder hex = new StringBuilder(3); for (int idx = 0; idx < propValue.length(); idx++) { final int cc = propValue.charAt(idx); hex.append("\\").append(cc); @@ -188,15 +191,15 @@ private static boolean isValidIpV6(String serverName) { @java.lang.SuppressWarnings("squid:S5998") // matcher input is max 256 chars long private static boolean isValidHostname(String serverName) { return !isLookingLikeAnIpV4(serverName) && serverName.length() < 256 && - serverName.matches("^([a-zA-Z\\d][a-zA-Z\\d\\-]{0,61}[a-zA-Z\\d]\\.)*[a-zA-Z]{2,}$"); + FQ_HOSTNAME_REGEX.matcher(serverName).matches(); } public static boolean isValidUrl(String url) { try { new URI(url); if (url.startsWith("http://") || url.startsWith("https://")) { - if (url.lastIndexOf("/") > 7) { - return isValidIpAddressOrHostName(url.substring(url.indexOf("://") + 3, url.indexOf("/", url.indexOf("://") + 3))); + if (url.lastIndexOf('/') > 7) { + return isValidIpAddressOrHostName(url.substring(url.indexOf("://") + 3, url.indexOf('/', url.indexOf("://") + 3))); } else { return isValidIpAddressOrHostName(url.substring(url.indexOf("://") + 3)); } @@ -208,7 +211,7 @@ public static boolean isValidUrl(String url) { } private static boolean isLookingLikeAnIpV4(String serverName) { - return Arrays.stream(serverName.split("\\.")).allMatch(e -> e.matches("(\\d{1,3})")); + return Arrays.stream(serverName.split("\\.")).allMatch(e -> IPV4_REGEX.matcher(e).matches()); } public static boolean isValidToken(String token) throws NoSuchAlgorithmException { diff --git a/src/main/java/mpo/dayon/common/version/Version.java b/src/main/java/mpo/dayon/common/version/Version.java index e34e7dec..d5ce79dc 100644 --- a/src/main/java/mpo/dayon/common/version/Version.java +++ b/src/main/java/mpo/dayon/common/version/Version.java @@ -87,13 +87,13 @@ public String getLatestRelease() { } public static boolean isCompatibleVersion(int major, int minor, Version that) { - if (!isProd(major, minor) || !isProd(that.getMajor(), that.getMajor())) { + if (!isProd(major, minor) || !isProd(that.major, that.major)) { return true; } - if (that.getMajor() > 10 && (major > 10 || (major == 1 && minor == 10))) { + if (that.major > 10 && (major > 10 || (major == 1 && minor == 10))) { return true; } - return that.getMajor() == major && that.getMinor() == minor; + return that.major == major && that.minor == minor; } public static boolean isOutdatedVersion(int major, int otherMajor) {