Inceptum/common/src/main/java/io/gitlab/jfronny/inceptum/common/Utils.java

83 lines
3.3 KiB
Java

package io.gitlab.jfronny.inceptum.common;
import io.gitlab.jfronny.commons.OSUtils;
import io.gitlab.jfronny.commons.io.JFiles;
import io.gitlab.jfronny.commons.logging.Logger;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Utils {
public static final int CACHE_SIZE = 128;
public static final Pattern NEW_LINE = Pattern.compile("[\r\n]+");
public static final Pattern VALID_FILENAME = Pattern.compile("[a-zA-Z0-9_\\-.][a-zA-Z0-9 _\\-.]*[a-zA-Z0-9_\\-.]");
public static final Logger LOGGER = Logger.forName("Inceptum");
private static ClassLoader SYSTEM_LOADER = ClassLoader.getSystemClassLoader();
public static void openWebBrowser(URI uri) {
try {
if (OSUtils.TYPE == OSUtils.Type.LINUX && OSUtils.executablePathContains("xdg-open")) {
Runtime.getRuntime().exec(new String[]{"xdg-open", uri.toString()});
} else if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
}
} catch (Exception e) {
Utils.LOGGER.error("Error opening web browser!", e);
}
}
public static void openFile(File file) {
try {
if (OSUtils.TYPE == OSUtils.Type.LINUX && OSUtils.executablePathContains("xdg-open")) {
Runtime.getRuntime().exec(new String[]{"xdg-open", file.getAbsoluteFile().toString()});
} else if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().open(file);
}
} catch (Exception e) {
Utils.LOGGER.error("Error opening file!", e);
}
}
public static FileSystem openZipFile(Path zip, boolean create) throws IOException, URISyntaxException {
return JFiles.openZipFile(zip, create, SYSTEM_LOADER);
}
@SuppressWarnings("unused") // Called through reflection from wrapper
public static void wrapperInit(ClassLoader loader) {
SYSTEM_LOADER = loader;
MetaHolder.setWrapperFlag();
}
/**
* Joins strings with the provided separator but removes separators from the start and end of the strings
* Example: join('/', "some/path/", "/some/subpath/", "example/") -> "some/path/some/subpath/example
*
* @param separator The separator to join with
* @param segments The strings to join
* @return The joined string
*/
public static String join(String separator, String... segments) {
return Arrays.stream(segments)
.map(s -> s.startsWith(separator) ? s.substring(separator.length()) : s)
.map(s -> s.endsWith(separator) ? s.substring(0, s.length() - separator.length()) : s)
.filter(s -> !s.isEmpty())
.collect(Collectors.joining(separator));
}
public static String getCurrentFlavor() {
return switch (OSUtils.TYPE) {
case WINDOWS -> "windows";
case MAC_OS -> "macos";
case LINUX -> "linux";
};
}
}