diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f68d1099657e34d4e7a68aadc730b3ecad84667d --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +### IntelliJ IDEA ### +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..13566b81b018ad684f3a35fee301741b2734c8f4 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000000000000000000000000000000000000..51dec71d1b5420d5abd7fcc58b43ed95e1979dac --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +TinyHost.iml \ No newline at end of file diff --git a/.idea/artifacts/TinyHost_jar.xml b/.idea/artifacts/TinyHost_jar.xml new file mode 100644 index 0000000000000000000000000000000000000000..398fbe9d08911371d678d32bd76f487bc5014211 --- /dev/null +++ b/.idea/artifacts/TinyHost_jar.xml @@ -0,0 +1,8 @@ +<component name="ArtifactManager"> + <artifact type="jar" name="TinyHost:jar"> + <output-path>$PROJECT_DIR$/out/artifacts/TinyHost_jar</output-path> + <root id="archive" name="TinyHost.jar"> + <element id="module-output" name="TinyHost" /> + </root> + </artifact> +</component> \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000000000000000000000000000000000000..6f29fee2f2b3b412625a792b92bcd1263e5b765a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK"> + <output url="file://$PROJECT_DIR$/out" /> + </component> +</project> \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000000000000000000000000000000000000..4b4943bdbd8e1977a02d937192141dcbc4b725b9 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="ProjectModuleManager"> + <modules> + <module fileurl="file://$PROJECT_DIR$/TinyHost.iml" filepath="$PROJECT_DIR$/TinyHost.iml" /> + </modules> + </component> +</project> \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000000000000000000000000000000000000..35eb1ddfbbc029bcab630581847471d7f238ec53 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project version="4"> + <component name="VcsDirectoryMappings"> + <mapping directory="" vcs="Git" /> + </component> +</project> \ No newline at end of file diff --git a/README.md b/README.md index cc1924d164b66e78af937e547ca6cbdda533525f..a4056c2d1f3c6795d07bf63de86be56d1e846849 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,45 @@ # TinyHost +## About +A small standalone http-server written in Java. +This server lets you host small webapps using only a single `.jar` file. +_TinyHost_ stores the content it is supposed to serve inside itself, making it easy to distribute and run anywhere. -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.informatik.uni-bremen.de/phaker/tinyhost.git -git branch -M main -git push -uf origin main +```shell +$ java -jar TinyHost.jar "host" "serve.jar" "pathToContent" ``` +This will make TinyHost create a copy of itself called `serve.jar`, +this copy will then be able to serve everything that was in the `pathToContent` directory. + +## Known Issues + +- At the moment TinyHost does not protect against tree walking attacks, however the impact of those should be small-ish, + since only content from within the `.jar`-File gets served +- When something goes wrong TinyHost might dump the stack trace to a html response +- There is no way of customizing MIME-TYPES of files. + TinyHost has a small list of MIME-TYPES that it uses to look them up, everything not on that list will be served as `text/plain`. + This list will expand in the future to be more complete + - This also means `.js`-Files will always be served as `application/javascript`. + Keep that in mind, if you want to serve e.g. javascript as `text/plain` for users to look at +- No logging whatsoever +- The Port to run on currently is asked via a popup window. + Terminating the server is also done via a GUI windows. +- Removing currently hosted material does not seem to work. + +## TODO +- [ ] Optional purely command line interface +- [ ] Selectively add/remove hosted files +- [ ] Dynamically generated page for `/`, if no `index.html` is present. +- [ ] Unified error pages + - Currently, all responses are individually hardcoded, it would be nice to have a template file, + for all errors to make it more unified. + - [ ] Make the style for those templates customizable. +- [ ] Remove `.gitkeep` from the `content` package somehow? + - Currently, a freshly built TinyHost only serves one file: `.gitkeep`. +- [ ] Plugin system for other Methods than `GET`? +- [ ] Protect against tree walking attacks + - This is minor but this server is only intended to serve the files in the `content` package. + Implementing this will also allow you to serve `.class` Files, since those are currently manually excluded. +- [ ] Clean up the code, it is a mess. -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.informatik.uni-bremen.de/phaker/tinyhost/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/TinyHost.iml b/TinyHost.iml new file mode 100644 index 0000000000000000000000000000000000000000..c90834f2d607afe55e6104d8aa2cdfffb713f688 --- /dev/null +++ b/TinyHost.iml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module type="JAVA_MODULE" version="4"> + <component name="NewModuleRootManager" inherit-compiler-output="true"> + <exclude-output /> + <content url="file://$MODULE_DIR$"> + <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> + </content> + <orderEntry type="inheritedJdk" /> + <orderEntry type="sourceFolder" forTests="false" /> + </component> +</module> \ No newline at end of file diff --git a/src/Either.java b/src/Either.java new file mode 100644 index 0000000000000000000000000000000000000000..b7de39d6bc3c617bfffbbb69ef5cf43dfe6c8be0 --- /dev/null +++ b/src/Either.java @@ -0,0 +1,74 @@ +import java.util.NoSuchElementException; +import java.util.Optional; + +@SuppressWarnings("unused") +public sealed interface Either<L, R> permits Either.Left, Either.Right { + + static <L, R extends Throwable> Either<L, R> of(java.util.function.Supplier<L> supplier) { + try { + return new Either.Left<>(supplier.get()); + } catch (Throwable t) { + try { + @SuppressWarnings("unchecked") + R exc = (R) t; + return new Right<>(exc); + } catch (ClassCastException e) { + try { + @SuppressWarnings("unchecked") + R exc = (R) t.getCause(); + return new Right<>(exc); + } catch (ClassCastException ignored) {} + throw t; + } + } + } + + default boolean isLeft() { + return (this instanceof Either.Left<L,R>); + } + default boolean isRight() { + return (this instanceof Either.Right<L,R>); + } + + default Optional<L> getLeft(){ + return switch (this) { + case Either.Left<L, R> left -> Optional.ofNullable(left.left); + case Either.Right<L, R> right -> Optional.empty(); + }; + } + + default Optional<R> getRight() { + return switch (this) { + case Either.Left<L, R> left -> Optional.empty(); + case Either.Right<L, R> right -> Optional.ofNullable(right.right); + }; + } + + default Either<R, L> flip() { + return switch (this) { + case Either.Left<L, R> left -> new Right<>(left.left); + case Either.Right<L, R> right -> new Left<>(right.right); + }; + } + + default <L2> Either<L2, R> andThen(java.util.function.Function<L, Either<L2, R>> nextFunc) { + return switch(this) { + case Either.Left<L, R> left -> nextFunc.apply(left.left); + case Either.Right<L, R> right -> new Either.Right<>(right.right); + }; + } + + default <R2> Either<L, R2> andThenErr(java.util.function.Function<R, Either<L, R2>> nextFunc) { + return switch(this) { + case Either.Left<L, R> left -> new Either.Left<>(left.left); + case Either.Right<L, R> right -> nextFunc.apply(right.right); + }; + } + + default L unwrap() throws NoSuchElementException { + return getLeft().orElseThrow(); + } + + record Left<L, R>(L left) implements Either<L, R> {} + record Right<L, R>(R right) implements Either<L, R> {} +} diff --git a/src/Main.java b/src/Main.java new file mode 100644 index 0000000000000000000000000000000000000000..a61e4395d6300e8cde9b0ec5c28e1f0c87a70d0c --- /dev/null +++ b/src/Main.java @@ -0,0 +1,255 @@ +//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or +// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. + +import java.awt.*; +import java.io.*; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +import javax.swing.*; + +public class Main { + + private static final String NAME = "TinyHost"; + private static final String VERSION = "0.5"; + + private static final Map<String,String> MIME_MAP = new HashMap<>(); + private static final String DEFAULT_MIME_TYPE = "text/plain"; + static { + MIME_MAP.put("appcache", "text/cache-manifest"); + MIME_MAP.put("css", "text/css"); + MIME_MAP.put("gif", "image/gif"); + MIME_MAP.put("html", "text/html"); + MIME_MAP.put("js", "application/javascript"); + MIME_MAP.put("json", "application/json"); + MIME_MAP.put("jpg", "image/jpeg"); + MIME_MAP.put("jpeg", "image/jpeg"); + MIME_MAP.put("mp4", "video/mp4"); + MIME_MAP.put("pdf", "application/pdf"); + MIME_MAP.put("png", "image/png"); + MIME_MAP.put("svg", "image/svg+xml"); + MIME_MAP.put("xlsm", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + MIME_MAP.put("xml", "application/xml"); + MIME_MAP.put("zip", "application/zip"); + MIME_MAP.put("md", "text/plain"); + MIME_MAP.put("txt", "text/plain"); + MIME_MAP.put("php", "text/plain"); + MIME_MAP.put("wasm", "application/wasm"); + } + + public static void main(String[] args) { + System.out.printf("Welcome to %s v%s%n", NAME, VERSION); + + if (args.length >= 2) { + final String param = args[1]; + final Path targetPath = new File(param).toPath(); + UI ui = UI.defaultImpl(); + switch (args[0].toLowerCase()) { + case "unhost" -> { + ReHost.unhost(targetPath, ui); + return; + } + case "host" -> { + Either<String, ArrayIndexOutOfBoundsException> content = Either.of(() -> args[2]); + switch (content) { + case Either.Left<String, ArrayIndexOutOfBoundsException> left -> + ReHost.host(new File(left.left()).toPath(), targetPath, ui); + + case Either.Right<String, ArrayIndexOutOfBoundsException> right -> + right.right().printStackTrace(System.out); + + } + return; + } + case "add" -> { + Either<String, ArrayIndexOutOfBoundsException> content = Either.of(() -> args[2]); + switch (content) { + case Either.Left<String, ArrayIndexOutOfBoundsException> left -> + ReHost.addHostedContent(new File(left.left()).toPath(), targetPath, ui); + + case Either.Right<String, ArrayIndexOutOfBoundsException> right -> + right.right().printStackTrace(System.out); + + } + return; + } + } + } + + + HttpServer server = null; + int port = -1; + do { + String portString = JOptionPane.showInputDialog("Bitte den Port angeben:", "8080"); + try { + port = Integer.parseInt(portString); + if (port <= 0) { + throw new IllegalArgumentException(); + } + server = HttpServer.create(new InetSocketAddress(port), 0); + } catch (Exception ignored) {} + } while (server == null); + + int finalPort = port; + Thread openBrowser = new Thread(() -> { + try { + Thread.sleep(1000); + } catch (Exception ignored) {} + openURL(String.format("http://localhost:%d/", finalPort)); + }); + openBrowser.start(); + + + Thread quitServer = new Thread(()-> { + Object[] options = {"Beenden"}; + int ignored = JOptionPane.showOptionDialog(null, + "Soll der Server beendet werden?", + "", + JOptionPane.DEFAULT_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, //do not use a custom Icon + options, //the titles of buttons + options[0]); //default button title + System.exit(0); + }); + + quitServer.start(); + + server.createContext("/", new MyHandler()); + server.setExecutor(null); // creates a default executor + + + server.start(); + + + } + + static class MyHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + System.out.println("Requested: " + t.getRequestURI()); + + + int code; + byte[] response; + String mimeType; + + if (t.getRequestMethod().equals("GET")) { + String uriString = t.getRequestURI().toString(); + if (uriString.equals("/")) { + uriString = "/index.html"; + } + + uriString = "/content" + uriString; + + if (uriString.endsWith(".class") || uriString.endsWith("MANIFEST.MF")) { + code = 404; + response = "Please don't request the Servers Code-Files. The Server does not like that :(".getBytes(); + mimeType = DEFAULT_MIME_TYPE; + } else { + try (InputStream in = getClass().getResourceAsStream(uriString)) { + code = 200; + + assert in != null; + response = in.readAllBytes(); + + mimeType = getMimeType(uriString); + System.out.println("Delivered: " + uriString); + } catch (Exception e) { + code = 404; + mimeType = "text/html"; + response = createErrorResponse(t, uriString, e).getBytes(); + } + } + } else { + code = 405; + response = "Please only use GET".getBytes(); + mimeType = DEFAULT_MIME_TYPE; + } + + t.getResponseHeaders().set("Content-Type", mimeType); + t.sendResponseHeaders(code, response.length); + + + OutputStream os = t.getResponseBody(); + os.write(response); + + os.close(); + } + } + + private static String createErrorResponse(HttpExchange t, String uriString, Exception e) { + StringBuilder builder = new StringBuilder(); + for (StackTraceElement line : e.getStackTrace()) { + builder.append("<li>").append(line).append("</li>"); + } + return String.format( + """ + <!DOCTYPE html> + <html> + <head> + <title>%s - 404</title> + <style> + body { + background-color: #252D28; + color: #ADADAD; + } + sub { + color: #FFA200; + } + code { + background-color: #1A1F1C; + } + </style> + </head> + <body> + Thank you for using <sub>%s</sub><br/> + <span>The server ran into a problem serving requested resource <code>%s</code> which should have been at <code>%s</code>.</span> + <ol>%s</ol> + </body> + </html> + """, NAME, NAME, t.getRequestURI(), uriString, builder); + + } + + public static void openURL(String url) { + if(Desktop.isDesktopSupported()){ + Desktop desktop = Desktop.getDesktop(); + try { + desktop.browse(new URI(url)); + } catch (IOException | URISyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }else{ + Runtime runtime = Runtime.getRuntime(); + try { + runtime.exec(new String[]{"xdg-open", url}); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + public static String getMimeType(String uri) { + Optional<String> extension = Optional.ofNullable(uri) + .filter(f -> f.contains(".")) + .map(f -> f.substring(uri.lastIndexOf(".") + 1)); + + String type = extension.flatMap(ext -> Optional.ofNullable(MIME_MAP.get(ext))).orElse(DEFAULT_MIME_TYPE); + + System.out.println("Type for >" + uri + "< is >" + type + "<"); + + return type; + } +} \ No newline at end of file diff --git a/src/ReHost.java b/src/ReHost.java new file mode 100644 index 0000000000000000000000000000000000000000..bc0e20429b5f32879f2ee596ad4760db5c348172 --- /dev/null +++ b/src/ReHost.java @@ -0,0 +1,147 @@ +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.*; +import java.util.HashMap; +import java.util.Map; + +/** + * This is a utility class, that manages the integration of content into hosts + * This class copies the jar-file this is in and either: + * - adds content to the currently hosted content + * - replaces the currently hosted content + * - removes the currently hosted content + * "Currently hosted" content refers to the content in this jar file. + * The modified content will then be inside a new copy of this server, + * as I have not found a way to modify a currently executed jar file. + */ +public final class ReHost { + private ReHost() { + throw new IllegalArgumentException("Utility class"); + } + + /** + * Creates a new copy of this jar file with its hosted content + * replaced by the content of the directory {@code contentToHost}. + * @param contentToHost The content the newly created server should host. + * @param targetFile The File location where the newly created Server should be placed. + * @param ui The User interface used to ask the user things, + * like "do you want to overwrite XY", if {@code targetFile} exists + * @throws IllegalArgumentException <ul><li>if either parameter is null,</li> + * <li>{@code contentToHost} does not exist</li> + * <li>{@code targetFile} exists and is a directory</li></ul> + */ + public static void host(Path contentToHost, Path targetFile, UI ui) { + unhost(targetFile, ui, false); + addHostedContent(contentToHost, targetFile, ui); + } + + public static void unhost(Path targetFile, UI ui) { + unhost(targetFile, ui, true); + } + + private static void unhost(Path targetFile, UI ignored, boolean createContentDir) { + Either<Path, IOException> temp = copySelf(targetFile); + switch (temp) { + case Either.Left<Path, IOException> left -> { + Path tempFile = left.unwrap(); + clearContents(tempFile, createContentDir); + try { + Files.move(tempFile, targetFile, StandardCopyOption.REPLACE_EXISTING); + System.out.println("Successfully copied " + tempFile + " to " + targetFile); + } catch (IOException e) { + e.printStackTrace(System.out); + } + } + case Either.Right<Path, IOException> right -> { + Exception e = right.right(); + e.printStackTrace(System.out); + } + } + } + + public static void addHostedContent(Path additionalContentToHost, Path targetFile, UI ignored) { + copySelf(targetFile); + copyContents(targetFile, additionalContentToHost); + } + + /* + * UTILITY METHODS: + */ + private static Either<Path, URISyntaxException> jarLocation() { + return Either.of(() -> { + try { + return new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toPath(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + } + + + private static Either<Path, IOException> copySelf(Path target) { + Either<Path, URISyntaxException> jarLocation = jarLocation(); + + return Either.of(() -> { + try { + return Files.copy(jarLocation.unwrap(), target, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + private static void clearContents(Path targetFile) { + clearContents(targetFile, true); + } + + private static void clearContents(Path targetFile, boolean createContentDir) { + Map<String, String> env = new HashMap<>(); + env.put("create", "false"); + + try (FileSystem fs = FileSystems.newFileSystem(targetFile, env)) { + Path target = fs.getPath("/content"); + + purgeDirectory(target); + + if (createContentDir) Files.createDirectory(target); + } catch (Exception e) { + e.printStackTrace(System.out); + System.exit(4); + } + } + + private static void purgeDirectory(Path dirPath) { + try (DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath)){ + for (Path path : stream) { + if (Files.isDirectory(path)) { + purgeDirectory(path); + } + Files.delete(path); + } + Files.delete(dirPath); + } catch (Exception e) { + e.printStackTrace(System.out); + } + } + + private static void copyContents(Path targetFile, Path contentDir) { + Map<String, String> env = new HashMap<>(); + env.put("create", "false"); + try (FileSystem fs = FileSystems.newFileSystem(targetFile, env)) { + Path target = fs.getPath("/content"); + + try (DirectoryStream<Path> stream = Files.newDirectoryStream(contentDir)) { + for (Path path : stream) { + Path name = path.getFileName(); + Path target2 = target.resolve(name.toString()); + Files.copy(path, target2, StandardCopyOption.REPLACE_EXISTING); + } + } + + } catch (Exception e) { + e.printStackTrace(System.out); + System.exit(4); + } + } +} diff --git a/src/UI.java b/src/UI.java new file mode 100644 index 0000000000000000000000000000000000000000..ee37a1a1d8c805be41e1e18591a3974e8a38a07c --- /dev/null +++ b/src/UI.java @@ -0,0 +1,14 @@ +public sealed interface UI permits UI.GUI, UI.TUI { + static UI defaultImpl() { + return new UI.GUI(); + } + + + final class GUI implements UI{ + + } + + final class TUI implements UI { + + } +} diff --git a/src/content/.gitkeep b/src/content/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391