1 /*
2 * SPDX-FileCopyrightText: none
3 * SPDX-License-Identifier: CC0-1.0
4 */
5
6 package gov.nist.secauto.metaschema.cli.processor.command;
7
8 import gov.nist.secauto.metaschema.core.util.ObjectUtils;
9 import gov.nist.secauto.metaschema.core.util.UriUtils;
10
11 import java.net.URI;
12 import java.net.URISyntaxException;
13 import java.nio.file.Path;
14 import java.nio.file.Paths;
15
16 import edu.umd.cs.findbugs.annotations.NonNull;
17 import nl.talsmasoftware.lazy4j.Lazy;
18
19 /**
20 * A base class for terminal commands in the command processing hierarchy.
21 * Terminal commands represent leaf nodes that perform actual operations and
22 * cannot have child commands.
23 */
24 public abstract class AbstractTerminalCommand implements ICommand {
25 private static Lazy<Path> currentWorkingDirectory = Lazy.lazy(() -> Paths.get(System.getProperty("user.dir")));
26
27 /**
28 * A utility method that can be used to get the current working directory.
29 * <p>
30 * This method is thread-safe due to lazy initialization.
31 *
32 * @return the current working directory
33 */
34 @NonNull
35 protected static Path getCurrentWorkingDirectory() {
36 return ObjectUtils.notNull(currentWorkingDirectory.get());
37 }
38
39 /**
40 * A utility method that can be used to resolve a path against the current
41 * working directory.
42 * <p>
43 * If the path is already absolute, then the provided path is returned.
44 *
45 * @param path
46 * the path to resolve
47 *
48 * @return the resolved path
49 */
50 @NonNull
51 protected static Path resolveAgainstCWD(@NonNull Path path) {
52
53 return path.isAbsolute()
54 ? path
55 : ObjectUtils.notNull(getCurrentWorkingDirectory().resolve(path).normalize());
56 }
57
58 /**
59 * A utility method that can be used to resolve a URI against the URI for the
60 * current working directory.
61 * <p>
62 * If the URI is already absolute, then the provided URI is returned.
63 * <p>
64 * The path is normalized after resolution to remove any redundant name elements
65 * (like "." or "..").
66 *
67 *
68 * @param uri
69 * the uri to resolve
70 *
71 * @return the resolved URI
72 */
73 @NonNull
74 protected static URI resolveAgainstCWD(@NonNull URI uri) {
75 return uri.isAbsolute()
76 ? uri
77 : ObjectUtils.notNull(getCurrentWorkingDirectory().toUri().resolve(uri.normalize()));
78 }
79
80 /**
81 * A utility method that can be used to resolve a URI (as a string) against the
82 * URI for the current working directory.
83 *
84 * @param uri
85 * the uri to resolve
86 * @return the resolved URI
87 * @throws URISyntaxException
88 * if the provided URI is not a valid URI
89 */
90 @NonNull
91 protected static URI resolveAgainstCWD(@NonNull String uri) throws URISyntaxException {
92 return UriUtils.toUri(uri, ObjectUtils.notNull(getCurrentWorkingDirectory().toUri()));
93 }
94 }