1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package gov.nist.secauto.metaschema.cli.commands;
28
29 import gov.nist.secauto.metaschema.cli.processor.CLIProcessor.CallingContext;
30 import gov.nist.secauto.metaschema.cli.processor.ExitCode;
31 import gov.nist.secauto.metaschema.cli.processor.ExitStatus;
32 import gov.nist.secauto.metaschema.cli.processor.InvalidArgumentException;
33 import gov.nist.secauto.metaschema.cli.processor.OptionUtils;
34 import gov.nist.secauto.metaschema.cli.processor.command.AbstractCommandExecutor;
35 import gov.nist.secauto.metaschema.cli.processor.command.AbstractTerminalCommand;
36 import gov.nist.secauto.metaschema.cli.processor.command.DefaultExtraArgument;
37 import gov.nist.secauto.metaschema.cli.processor.command.ExtraArgument;
38 import gov.nist.secauto.metaschema.core.util.CustomCollectors;
39 import gov.nist.secauto.metaschema.core.util.ObjectUtils;
40 import gov.nist.secauto.metaschema.databind.IBindingContext;
41 import gov.nist.secauto.metaschema.databind.io.Format;
42 import gov.nist.secauto.metaschema.databind.io.IBoundLoader;
43
44 import org.apache.commons.cli.CommandLine;
45 import org.apache.commons.cli.Option;
46 import org.apache.logging.log4j.LogManager;
47 import org.apache.logging.log4j.Logger;
48
49 import java.io.IOException;
50 import java.nio.file.Files;
51 import java.nio.file.Path;
52 import java.nio.file.Paths;
53 import java.util.Collection;
54 import java.util.List;
55 import java.util.Locale;
56
57 import edu.umd.cs.findbugs.annotations.NonNull;
58
59 public abstract class AbstractConvertSubcommand
60 extends AbstractTerminalCommand {
61 private static final Logger LOGGER = LogManager.getLogger(AbstractConvertSubcommand.class);
62
63 @NonNull
64 private static final String COMMAND = "convert";
65 @NonNull
66 private static final List<ExtraArgument> EXTRA_ARGUMENTS = ObjectUtils.notNull(List.of(
67 new DefaultExtraArgument("source file", true),
68 new DefaultExtraArgument("destination file", false)));
69
70 @NonNull
71 private static final Option OVERWRITE_OPTION = ObjectUtils.notNull(
72 Option.builder()
73 .longOpt("overwrite")
74 .desc("overwrite the destination if it exists")
75 .build());
76 @NonNull
77 private static final Option TO_OPTION = ObjectUtils.notNull(
78 Option.builder()
79 .longOpt("to")
80 .required()
81 .hasArg().argName("FORMAT")
82 .desc("convert to format: xml, json, or yaml")
83 .build());
84
85 @Override
86 public String getName() {
87 return COMMAND;
88 }
89
90 @Override
91 public Collection<? extends Option> gatherOptions() {
92 return ObjectUtils.notNull(List.of(
93 OVERWRITE_OPTION,
94 TO_OPTION));
95 }
96
97 @Override
98 public List<ExtraArgument> getExtraArguments() {
99 return EXTRA_ARGUMENTS;
100 }
101
102 @SuppressWarnings("PMD.PreserveStackTrace")
103 @Override
104 public void validateOptions(CallingContext callingContext, CommandLine cmdLine) throws InvalidArgumentException {
105
106 try {
107 String toFormatText = cmdLine.getOptionValue(TO_OPTION);
108 Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
109 } catch (IllegalArgumentException ex) {
110 InvalidArgumentException newEx = new InvalidArgumentException(
111 String.format("Invalid '%s' argument. The format must be one of: %s.",
112 OptionUtils.toArgument(TO_OPTION),
113 Format.names().stream()
114 .collect(CustomCollectors.joiningWithOxfordComma("and"))));
115 newEx.setOption(TO_OPTION);
116 newEx.addSuppressed(ex);
117 throw newEx;
118 }
119
120 List<String> extraArgs = cmdLine.getArgList();
121 if (extraArgs.isEmpty() || extraArgs.size() > 2) {
122 throw new InvalidArgumentException("Illegal number of arguments.");
123 }
124
125 Path source = Paths.get(extraArgs.get(0));
126 if (!Files.exists(source)) {
127 throw new InvalidArgumentException("The provided source '" + source + "' does not exist.");
128 }
129 if (!Files.isReadable(source)) {
130 throw new InvalidArgumentException("The provided source '" + source + "' is not readable.");
131 }
132 }
133
134 protected abstract static class AbstractConversionCommandExecutor
135 extends AbstractCommandExecutor {
136
137 public AbstractConversionCommandExecutor(
138 @NonNull CallingContext callingContext,
139 @NonNull CommandLine commandLine) {
140 super(callingContext, commandLine);
141 }
142
143 @NonNull
144 protected abstract IBindingContext getBindingContext();
145
146 @NonNull
147 protected abstract Class<?> getLoadedClass();
148
149 @SuppressWarnings({
150 "PMD.OnlyOneReturn",
151 "PMD.CyclomaticComplexity", "PMD.CognitiveComplexity"
152 })
153 @Override
154 public ExitStatus execute() {
155 CommandLine cmdLine = getCommandLine();
156
157 List<String> extraArgs = cmdLine.getArgList();
158
159 Path destination = null;
160 if (extraArgs.size() > 1) {
161 destination = Paths.get(extraArgs.get(1)).toAbsolutePath();
162 }
163
164 if (destination != null) {
165 if (Files.exists(destination)) {
166 if (!cmdLine.hasOption(OVERWRITE_OPTION)) {
167 return ExitCode.INVALID_ARGUMENTS.exitMessage(
168 String.format("The provided destination '%s' already exists and the '%s' option was not provided.",
169 destination,
170 OptionUtils.toArgument(OVERWRITE_OPTION)));
171 }
172 if (!Files.isWritable(destination)) {
173 return ExitCode.IO_ERROR.exitMessage(
174 "The provided destination '" + destination + "' is not writable.");
175 }
176 } else {
177 Path parent = destination.getParent();
178 if (parent != null) {
179 try {
180 Files.createDirectories(parent);
181 } catch (IOException ex) {
182 return ExitCode.INVALID_TARGET.exit().withThrowable(ex);
183 }
184 }
185 }
186 }
187
188 Path source = Paths.get(extraArgs.get(0));
189 assert source != null;
190
191 String toFormatText = cmdLine.getOptionValue(TO_OPTION);
192 Format toFormat = Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
193
194 IBindingContext bindingContext = getBindingContext();
195 try {
196 IBoundLoader loader = bindingContext.newBoundLoader();
197 if (LOGGER.isInfoEnabled()) {
198 LOGGER.info("Converting '{}'.", source);
199 }
200
201 if (destination == null) {
202 loader.convert(source, ObjectUtils.notNull(System.out), toFormat, getLoadedClass());
203 } else {
204 loader.convert(source, destination, toFormat, getLoadedClass());
205 }
206 } catch (IOException | IllegalArgumentException ex) {
207 return ExitCode.PROCESSING_ERROR.exit().withThrowable(ex);
208 }
209 if (destination != null && LOGGER.isInfoEnabled()) {
210 LOGGER.info("Generated {} file: {}", toFormat.toString(), destination);
211 }
212 return ExitCode.OK.exit();
213 }
214
215 }
216 }