View Javadoc
1   /*
2    * Portions of this software was developed by employees of the National Institute
3    * of Standards and Technology (NIST), an agency of the Federal Government and is
4    * being made available as a public service. Pursuant to title 17 United States
5    * Code Section 105, works of NIST employees are not subject to copyright
6    * protection in the United States. This software may be subject to foreign
7    * copyright. Permission in the United States and in foreign countries, to the
8    * extent that NIST may hold copyright, to use, copy, modify, create derivative
9    * works, and distribute this software and its documentation without fee is hereby
10   * granted on a non-exclusive basis, provided that this notice and disclaimer
11   * of warranty appears in all copies.
12   *
13   * THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER
14   * EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY
15   * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
16   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM
17   * INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE
18   * SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE.  IN NO EVENT
19   * SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT,
20   * INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM,
21   * OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY,
22   * CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR
23   * PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT
24   * OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.
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") // intended
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", // readability
151         "PMD.CyclomaticComplexity", "PMD.CognitiveComplexity" // reasonable
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); // NOPMD readability
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); // NOPMD readability
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 }