Skip to content

[CQ] Cleanup in the singleton utils package #8160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions flutter-idea/src/io/flutter/jxbrowser/JxBrowserManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,19 +87,17 @@ else if (Objects.equals(info.getMajorVersion(), "2020")) {
public static final String ANALYTICS_CATEGORY = "jxbrowser";
private static InstallationFailedReason latestFailureReason;
private final JxBrowserUtils jxBrowserUtils;
private final FileUtils fileUtils;

@VisibleForTesting
protected JxBrowserManager(@NotNull JxBrowserUtils jxBrowserUtils, @NotNull FileUtils fileUtils) {
protected JxBrowserManager(@NotNull JxBrowserUtils jxBrowserUtils) {
this.jxBrowserUtils = jxBrowserUtils;
this.fileUtils = fileUtils;
}

@NotNull
public static JxBrowserManager getInstance() {
if (manager == null) {
//noinspection ConstantConditions
manager = new JxBrowserManager(new JxBrowserUtils(), FileUtils.getInstance());
manager = new JxBrowserManager(new JxBrowserUtils());
}
return manager;
}
Expand Down Expand Up @@ -229,7 +227,7 @@ public void setUp(@NotNull String projectName) {

LOG.info(projectName + ": Installing JxBrowser");

final boolean directoryExists = fileUtils.makeDirectory(DOWNLOAD_PATH);
final boolean directoryExists = FileUtils.makeDirectory(DOWNLOAD_PATH);
if (!directoryExists) {
LOG.info(projectName + ": Unable to create directory for JxBrowser files");
setStatusFailed(new InstallationFailedReason(FailureType.DIRECTORY_CREATION_FAILED));
Expand All @@ -251,7 +249,7 @@ public void setUp(@NotNull String projectName) {
boolean allDownloaded = true;
for (String fileName : fileNames) {
assert fileName != null;
if (!fileUtils.fileExists(getFilePath(fileName))) {
if (!FileUtils.fileExists(getFilePath(fileName))) {
allDownloaded = false;
break;
}
Expand All @@ -268,7 +266,7 @@ public void setUp(@NotNull String projectName) {
for (String fileName : fileNames) {
assert fileName != null;
final String filePath = getFilePath(fileName);
if (!fileUtils.deleteFile(filePath)) {
if (!FileUtils.deleteFile(filePath)) {
LOG.info(projectName + ": Existing file could not be deleted - " + filePath);
}
}
Expand Down Expand Up @@ -350,7 +348,7 @@ private void loadClasses(@NotNull String[] fileNames) {
paths.add(Paths.get(getFilePath(fileName)));
}
//noinspection ConstantConditions
fileUtils.loadPaths(this.getClass().getClassLoader(), paths);
FileUtils.loadPaths(this.getClass().getClassLoader(), paths);
}
catch (Exception ex) {
LOG.info("Failed to load JxBrowser file", ex);
Expand Down
14 changes: 11 additions & 3 deletions flutter-idea/src/io/flutter/utils/AsyncUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,21 @@
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;

import org.jetbrains.annotations.NotNull;

public class AsyncUtils {

private AsyncUtils() {
throw new AssertionError("No instances.");
}

/**
* Helper to get the value of a future on the UI thread.
* <p>
* The action will never be called if the future is cancelled.
*/
public static <T> void whenCompleteUiThread(CompletableFuture<T> future, BiConsumer<? super T, ? super Throwable> action) {
public static <T> void whenCompleteUiThread(@NotNull CompletableFuture<T> future,
@NotNull BiConsumer<? super T, ? super Throwable> action) {
future.whenCompleteAsync(
(T value, Throwable throwable) -> {
// Exceptions due to the Future being cancelled need to be treated
Expand All @@ -39,7 +47,7 @@ public static <T> void whenCompleteUiThread(CompletableFuture<T> future, BiConsu
);
}

public static void invokeLater(Runnable runnable) {
public static void invokeLater(@NotNull Runnable runnable) {
final Application app = ApplicationManager.getApplication();
if (app == null || app.isUnitTestMode()) {
// This case existing to support unit testing.
Expand All @@ -50,7 +58,7 @@ public static void invokeLater(Runnable runnable) {
}
}

public static void invokeAndWait(Runnable runnable) throws ProcessCanceledException {
public static void invokeAndWait(@NotNull Runnable runnable) throws ProcessCanceledException {
final Application app = ApplicationManager.getApplication();
if (app == null || app.isUnitTestMode()) {
try {
Expand Down
2 changes: 2 additions & 0 deletions flutter-idea/src/io/flutter/utils/CollectionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
import java.util.stream.Stream;

public class CollectionUtils {

private CollectionUtils() {
throw new AssertionError("No instances.");
}

public static <T> boolean anyMatch(@NotNull T[] in, @NotNull final Predicate<T> predicate) {
Expand Down
7 changes: 6 additions & 1 deletion flutter-idea/src/io/flutter/utils/ElementIO.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
* Utilities for reading and writing IntelliJ run configurations to and from the disk.
*/
public class ElementIO {

private ElementIO() {
throw new AssertionError("No instances.");
}

public static void addOption(@NotNull Element element, @NotNull String name, @Nullable String value) {
if (value == null) return;

Expand All @@ -25,7 +30,7 @@ public static void addOption(@NotNull Element element, @NotNull String name, @Nu
element.addContent(child);
}

public static Map<String, String> readOptions(Element element) {
public static Map<String, String> readOptions(@NotNull Element element) {
final Map<String, String> result = new HashMap<>();
for (Element child : element.getChildren()) {
if ("option".equals(child.getName())) {
Expand Down
39 changes: 17 additions & 22 deletions flutter-idea/src/io/flutter/utils/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,68 +5,63 @@
*/
package io.flutter.utils;

import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.lang.UrlClassLoader;
import com.jetbrains.lang.dart.DartFileType;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.nio.file.Path;
import java.util.List;

public class FileUtils {
private static FileUtils fileUtils;
import org.jetbrains.annotations.NotNull;

public static FileUtils getInstance() {
if (fileUtils == null) {
fileUtils = new FileUtils();
}
return fileUtils;
public class FileUtils {

private FileUtils() {
throw new AssertionError("No instances.");
}

/**
* Makes a directory at the provided path.
*
* @param path path of the directory to be created.
* @return true if the directory already existed, or if it was successfully created; false if the directory could not be created.
*/
public boolean makeDirectory(String path) {
public static boolean makeDirectory(@NotNull String path) {
final File directory = new File(path);
if (!directory.exists()) {
return directory.mkdirs();
}
return true;
}

public boolean fileExists(String path) {
public static boolean fileExists(@NotNull String path) {
final File file = new File(path);
return file.exists();
}

/**
* Deletes a file at the provided path.
*
* @param path path of the file to be deleted.
* @return true if the file does not exist, or if it was successfully deleted; false if the file could not be deleted.
*/
public boolean deleteFile(String path) {
public static boolean deleteFile(@NotNull String path) {
final File file = new File(path);
if (file.exists()) {
return file.delete();
}
return true;
}

/**
* Loads a list of file paths with a class loader.
*
* <p>
* This is only available for versions 211.4961.30 and later.
* @param classLoader classloader that can be used as a UrlClassLoader to load the files.
* @param paths list of file paths to load.
*
* @param classLoader classloader that can be used as an UrlClassLoader to load the files.
* @param paths list of file paths to load.
*/
public void loadPaths(ClassLoader classLoader, List<Path> paths) {
final UrlClassLoader urlClassLoader = (UrlClassLoader) classLoader;
public static void loadPaths(@NotNull ClassLoader classLoader, @NotNull List<Path> paths) {
final UrlClassLoader urlClassLoader = (UrlClassLoader)classLoader;
urlClassLoader.addFiles(paths);
}

public static boolean isDartFile(@NotNull VirtualFile file) {
return file.getFileType().equals(DartFileType.INSTANCE);
}
}
1 change: 1 addition & 0 deletions flutter-idea/src/io/flutter/utils/FlutterModuleUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public class FlutterModuleUtils {
public static final String DEPRECATED_FLUTTER_MODULE_TYPE_ID = "WEB_MODULE";

private FlutterModuleUtils() {
throw new AssertionError("No instances.");
}

/**
Expand Down
2 changes: 2 additions & 0 deletions flutter-idea/src/io/flutter/utils/JsonUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package io.flutter.utils;

import com.google.gson.*;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
Expand All @@ -18,6 +19,7 @@
public class JsonUtils {

private JsonUtils() {
throw new AssertionError("No instances.");
}

@Nullable
Expand Down
4 changes: 4 additions & 0 deletions flutter-idea/src/io/flutter/utils/OpenApiUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@

public class OpenApiUtils {

private OpenApiUtils() {
throw new AssertionError("No instances.");
}

public static @NotNull VirtualFile @NotNull [] getContentRoots(@NotNull Module module) {
var moduleRootManager = ModuleRootManager.getInstance(module);
return moduleRootManager == null ? VirtualFile.EMPTY_ARRAY : moduleRootManager.getContentRoots();
Expand Down
9 changes: 7 additions & 2 deletions flutter-idea/src/io/flutter/utils/SystemUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,26 @@
import com.intellij.execution.util.ExecUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.concurrency.AppExecutorUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.concurrent.CompletableFuture;

public class SystemUtils {

private SystemUtils() {
throw new AssertionError("No instances.");
}

/**
* Locate a given command-line tool given its name.
* <p>
* This is used to locate binaries that are not pre-installed. If it is necessary to find pre-installed
* binaries it will require more work, especially on Windows.
*/
@Nullable
public static String which(String toolName) {
public static String which(@NotNull String toolName) {
final File gitExecutableFromPath =
PathEnvironmentVariableUtil.findInPath(SystemInfo.isWindows ? toolName + ".exe" : toolName, getPath(), null);
if (gitExecutableFromPath != null) {
Expand All @@ -45,7 +50,7 @@ private static String getPath() {
* <p>
* This is a non-blocking equivalient to {@link ExecUtil#execAndGetOutput(GeneralCommandLine)}.
*/
public static CompletableFuture<ProcessOutput> execAndGetOutput(GeneralCommandLine cmd) {
public static CompletableFuture<ProcessOutput> execAndGetOutput(@NotNull GeneralCommandLine cmd) {
final CompletableFuture<ProcessOutput> future = new CompletableFuture<>();

AppExecutorUtil.getAppExecutorService().submit(() -> {
Expand Down
5 changes: 5 additions & 0 deletions flutter-idea/src/io/flutter/utils/UIUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
import org.jetbrains.annotations.NotNull;

public class UIUtils {

private UIUtils() {
throw new AssertionError("No instances.");
}

/**
* All editor notifications in the Flutter plugin should get and set the background color from this method, which will ensure if any are
* changed, they are all changed.
Expand Down
34 changes: 20 additions & 14 deletions flutter-idea/src/io/flutter/utils/UrlUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,25 @@
import java.net.URL;

public class UrlUtils {
public static String generateHtmlFragmentWithHrefTags(String input) {
StringBuilder builder = new StringBuilder();
for (String token : input.split(" ")) {
if (!builder.isEmpty()) {
builder.append(" ");
}
try {
URL url = new URL(token);
builder.append("<a href=\"").append(url).append("\">").append(url).append("</a>");
} catch(MalformedURLException e) {
builder.append(token);
}
}
return builder.toString();

private UrlUtils() {
throw new AssertionError("No instances.");
}

public static String generateHtmlFragmentWithHrefTags(String input) {
StringBuilder builder = new StringBuilder();
for (String token : input.split(" ")) {
if (!builder.isEmpty()) {
builder.append(" ");
}
try {
URL url = new URL(token);
builder.append("<a href=\"").append(url).append("\">").append(url).append("</a>");
}
catch (MalformedURLException e) {
builder.append(token);
}
}
return builder.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public void testSetUpIfKeyNotFound() throws FileNotFoundException {
when(mockUtils.getJxBrowserKey()).thenThrow(new FileNotFoundException("Key not found"));

// If the directory for JxBrowser files cannot be created, the installation should fail.
final JxBrowserManager manager = new JxBrowserManager(mockUtils, mock(FileUtils.class));
final JxBrowserManager manager = new JxBrowserManager(mockUtils);

manager.setUp(projectName);
Assert.assertEquals(JxBrowserStatus.INSTALLATION_FAILED, manager.getStatus());
Expand All @@ -49,7 +49,7 @@ public void testSetUpIfDirectoryFails() throws FileNotFoundException {
when(mockFileUtils.makeDirectory(DOWNLOAD_PATH)).thenReturn(false);

// If the directory for JxBrowser files cannot be created, the installation should fail.
final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockFileUtils);
final JxBrowserManager manager = new JxBrowserManager(mockUtils);

manager.setUp(projectName);
Assert.assertEquals(JxBrowserStatus.INSTALLATION_FAILED, manager.getStatus());
Expand All @@ -65,7 +65,7 @@ public void testSetUpIfPlatformFileNotFound() throws FileNotFoundException {
when(mockFileUtils.makeDirectory(DOWNLOAD_PATH)).thenReturn(true);

// If the system platform is not found among JxBrowser files, then the installation should fail.
final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockFileUtils);
final JxBrowserManager manager = new JxBrowserManager(mockUtils);

manager.setUp(projectName);
Assert.assertEquals(JxBrowserStatus.INSTALLATION_FAILED, manager.getStatus());
Expand All @@ -84,7 +84,7 @@ public void testSetUpIfAllFilesExist() throws FileNotFoundException {
when(mockFileUtils.fileExists(anyString())).thenReturn(true);

// If all of the files are already downloaded, we should load the existing files.
final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockFileUtils);
final JxBrowserManager manager = new JxBrowserManager(mockUtils);

manager.setUp(projectName);
final String[] expectedFileNames = {PLATFORM_FILE_NAME, API_FILE_NAME, SWING_FILE_NAME};
Expand All @@ -108,7 +108,7 @@ public void testSetUpIfFilesMissing() throws FileNotFoundException {
when(mockFileUtils.deleteFile(anyString())).thenReturn(true);

// If any of our required files do not exist, we want to delete any existing files and start a download of all of the required files.
final JxBrowserManager manager = new JxBrowserManager(mockUtils, mockFileUtils);
final JxBrowserManager manager = new JxBrowserManager(mockUtils);
final JxBrowserManager spy = spy(manager);
final String[] expectedFileNames = {PLATFORM_FILE_NAME, API_FILE_NAME, SWING_FILE_NAME};
doNothing().when(spy).downloadJxBrowser(expectedFileNames);
Expand Down
Loading