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.InvalidArgumentException;
031import gov.nist.secauto.metaschema.cli.processor.command.ICommandExecutor;
032import gov.nist.secauto.metaschema.core.configuration.DefaultConfiguration;
033import gov.nist.secauto.metaschema.core.configuration.IMutableConfiguration;
034import gov.nist.secauto.metaschema.core.model.IModule;
035import gov.nist.secauto.metaschema.core.model.MetaschemaException;
036import gov.nist.secauto.metaschema.core.model.constraint.IConstraintSet;
037import gov.nist.secauto.metaschema.core.model.util.JsonUtil;
038import gov.nist.secauto.metaschema.core.model.util.XmlUtil;
039import gov.nist.secauto.metaschema.core.model.xml.ModuleLoader;
040import gov.nist.secauto.metaschema.core.util.CollectionUtil;
041import gov.nist.secauto.metaschema.core.util.ObjectUtils;
042import gov.nist.secauto.metaschema.databind.IBindingContext;
043import gov.nist.secauto.metaschema.schemagen.ISchemaGenerator;
044import gov.nist.secauto.metaschema.schemagen.ISchemaGenerator.SchemaFormat;
045import gov.nist.secauto.metaschema.schemagen.SchemaGenerationFeature;
046
047import org.apache.commons.cli.CommandLine;
048import org.apache.commons.cli.Option;
049import org.json.JSONObject;
050
051import java.io.BufferedReader;
052import java.io.IOException;
053import java.nio.charset.StandardCharsets;
054import java.nio.file.Files;
055import java.nio.file.Path;
056import java.nio.file.Paths;
057import java.util.ArrayList;
058import java.util.Collection;
059import java.util.List;
060import java.util.Set;
061
062import javax.xml.transform.Source;
063
064import edu.umd.cs.findbugs.annotations.NonNull;
065
066public class ValidateContentUsingModuleCommand
067    extends AbstractValidateContentCommand {
068  @NonNull
069  private static final String COMMAND = "validate-content";
070
071  @Override
072  public String getName() {
073    return COMMAND;
074  }
075
076  @Override
077  public String getDescription() {
078    return "Verify that the provided resource is well-formed and valid to the provided Module-based model.";
079  }
080
081  @Override
082  public Collection<? extends Option> gatherOptions() {
083    Collection<? extends Option> orig = super.gatherOptions();
084
085    List<Option> retval = new ArrayList<>(orig.size() + 1);
086    retval.addAll(orig);
087    retval.add(MetaschemaCommandSupport.METASCHEMA_OPTION);
088
089    return CollectionUtil.unmodifiableCollection(retval);
090  }
091
092  @Override
093  public void validateOptions(CallingContext callingContext, CommandLine cmdLine) throws InvalidArgumentException {
094    super.validateOptions(callingContext, cmdLine);
095
096    String metaschemaName = cmdLine.getOptionValue(MetaschemaCommandSupport.METASCHEMA_OPTION);
097    Path metaschema = Paths.get(metaschemaName);
098    if (!Files.exists(metaschema)) {
099      throw new InvalidArgumentException("The provided module '" + metaschema + "' does not exist.");
100    }
101    if (!Files.isReadable(metaschema)) {
102      throw new InvalidArgumentException("The provided module '" + metaschema + "' is not readable.");
103    }
104  }
105
106  @Override
107  public ICommandExecutor newExecutor(CallingContext callingContext, CommandLine commandLine) {
108    return new OscalCommandExecutor(callingContext, commandLine);
109  }
110
111  private class OscalCommandExecutor
112      extends AbstractValidationCommandExecutor {
113
114    private Path tempDir;
115    private IModule module;
116
117    private OscalCommandExecutor(
118        @NonNull CallingContext callingContext,
119        @NonNull CommandLine commandLine) {
120      super(callingContext, commandLine);
121    }
122
123    private Path getTempDir() throws IOException {
124      if (tempDir == null) {
125        tempDir = Files.createTempDirectory("validation-");
126        tempDir.toFile().deleteOnExit();
127      }
128      return tempDir;
129    }
130
131    @NonNull
132    private IModule getModule(@NonNull Set<IConstraintSet> constraintSets)
133        throws MetaschemaException, IOException {
134      if (module == null) {
135        String moduleName = getCommandLine().getOptionValue(MetaschemaCommandSupport.METASCHEMA_OPTION);
136        Path modulePath = Paths.get(moduleName);
137        assert modulePath != null;
138
139        ModuleLoader loader = new ModuleLoader(constraintSets);
140        loader.allowEntityResolution();
141        module = loader.load(modulePath);
142      }
143      assert module != null;
144      return module;
145    }
146
147    @NonNull
148    private IModule getModule() {
149      // should be initialized already
150      return ObjectUtils.requireNonNull(module);
151    }
152
153    @Override
154    protected IBindingContext getBindingContext(@NonNull Set<IConstraintSet> constraintSets)
155        throws MetaschemaException, IOException {
156
157      return IBindingContext.instance().registerModule(getModule(constraintSets), getTempDir());
158    }
159
160    @Override
161    public List<Source> getXmlSchemas() throws IOException {
162      Path schemaFile = Files.createTempFile(getTempDir(), "schema-", ".json");
163      assert schemaFile != null;
164      IMutableConfiguration<SchemaGenerationFeature<?>> configuration = new DefaultConfiguration<>();
165      ISchemaGenerator.generateSchema(getModule(), schemaFile, SchemaFormat.XML, configuration);
166      return ObjectUtils.requireNonNull(List.of(
167          XmlUtil.getStreamSource(schemaFile.toUri().toURL())));
168    }
169
170    @Override
171    public JSONObject getJsonSchema() throws IOException {
172      Path schemaFile = Files.createTempFile(getTempDir(), "schema-", ".json");
173      assert schemaFile != null;
174      IMutableConfiguration<SchemaGenerationFeature<?>> configuration = new DefaultConfiguration<>();
175      ISchemaGenerator.generateSchema(getModule(), schemaFile, SchemaFormat.JSON, configuration);
176      try (BufferedReader reader = ObjectUtils.notNull(Files.newBufferedReader(schemaFile, StandardCharsets.UTF_8))) {
177        return JsonUtil.toJsonObject(reader);
178      }
179    }
180  }
181
182}