001/* 002 * Portions of this software was developed by employees of the National Institute 003 * of Standards and Technology (NIST), an agency of the Federal Government and is 004 * being made available as a public service. Pursuant to title 17 United States 005 * Code Section 105, works of NIST employees are not subject to copyright 006 * protection in the United States. This software may be subject to foreign 007 * copyright. Permission in the United States and in foreign countries, to the 008 * extent that NIST may hold copyright, to use, copy, modify, create derivative 009 * works, and distribute this software and its documentation without fee is hereby 010 * granted on a non-exclusive basis, provided that this notice and disclaimer 011 * of warranty appears in all copies. 012 * 013 * THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER 014 * EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY 015 * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF 016 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM 017 * INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE 018 * SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE. IN NO EVENT 019 * SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT, 020 * INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, 021 * OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY, 022 * CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR 023 * PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT 024 * OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER. 025 */ 026 027package gov.nist.secauto.metaschema.cli.commands; 028 029import gov.nist.secauto.metaschema.cli.processor.CLIProcessor.CallingContext; 030import gov.nist.secauto.metaschema.cli.processor.ExitCode; 031import gov.nist.secauto.metaschema.cli.processor.ExitStatus; 032import gov.nist.secauto.metaschema.cli.processor.InvalidArgumentException; 033import gov.nist.secauto.metaschema.cli.processor.OptionUtils; 034import gov.nist.secauto.metaschema.cli.processor.command.AbstractCommandExecutor; 035import gov.nist.secauto.metaschema.cli.processor.command.AbstractTerminalCommand; 036import gov.nist.secauto.metaschema.cli.processor.command.DefaultExtraArgument; 037import gov.nist.secauto.metaschema.cli.processor.command.ExtraArgument; 038import gov.nist.secauto.metaschema.core.util.CustomCollectors; 039import gov.nist.secauto.metaschema.core.util.ObjectUtils; 040import gov.nist.secauto.metaschema.databind.IBindingContext; 041import gov.nist.secauto.metaschema.databind.io.Format; 042import gov.nist.secauto.metaschema.databind.io.IBoundLoader; 043 044import org.apache.commons.cli.CommandLine; 045import org.apache.commons.cli.Option; 046import org.apache.logging.log4j.LogManager; 047import org.apache.logging.log4j.Logger; 048 049import java.io.IOException; 050import java.nio.file.Files; 051import java.nio.file.Path; 052import java.nio.file.Paths; 053import java.util.Collection; 054import java.util.List; 055import java.util.Locale; 056 057import edu.umd.cs.findbugs.annotations.NonNull; 058 059public abstract class AbstractConvertSubcommand 060 extends AbstractTerminalCommand { 061 private static final Logger LOGGER = LogManager.getLogger(AbstractConvertSubcommand.class); 062 063 @NonNull 064 private static final String COMMAND = "convert"; 065 @NonNull 066 private static final List<ExtraArgument> EXTRA_ARGUMENTS = ObjectUtils.notNull(List.of( 067 new DefaultExtraArgument("source file", true), 068 new DefaultExtraArgument("destination file", false))); 069 070 @NonNull 071 private static final Option OVERWRITE_OPTION = ObjectUtils.notNull( 072 Option.builder() 073 .longOpt("overwrite") 074 .desc("overwrite the destination if it exists") 075 .build()); 076 @NonNull 077 private static final Option TO_OPTION = ObjectUtils.notNull( 078 Option.builder() 079 .longOpt("to") 080 .required() 081 .hasArg().argName("FORMAT") 082 .desc("convert to format: xml, json, or yaml") 083 .build()); 084 085 @Override 086 public String getName() { 087 return COMMAND; 088 } 089 090 @Override 091 public Collection<? extends Option> gatherOptions() { 092 return ObjectUtils.notNull(List.of( 093 OVERWRITE_OPTION, 094 TO_OPTION)); 095 } 096 097 @Override 098 public List<ExtraArgument> getExtraArguments() { 099 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}