Skip to content

Commit

Permalink
Added experimental support for the OSCAL mapping model, which is curr…
Browse files Browse the repository at this point in the history
…ently under development.

Fixed CLI argument defects in the convert and schema generation sub-commands.
Fixed a defect causing some errors to not be reported.
Fixed PMD, spotbugs, and compile errors/warnings.
  • Loading branch information
david-waltermire committed Oct 27, 2022
1 parent 3478b86 commit fe0f911
Show file tree
Hide file tree
Showing 9 changed files with 71 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import gov.nist.secauto.oscal.tools.cli.core.commands.assessmentresults.AssessmentResultsCommand;
import gov.nist.secauto.oscal.tools.cli.core.commands.catalog.CatalogCommand;
import gov.nist.secauto.oscal.tools.cli.core.commands.componentdefinition.ComponentDefinitionCommand;
import gov.nist.secauto.oscal.tools.cli.core.commands.mappingcollection.MappingCollectionCommand;
import gov.nist.secauto.oscal.tools.cli.core.commands.metaschema.MetaschemaCommand;
import gov.nist.secauto.oscal.tools.cli.core.commands.poam.PlanOfActionsAndMilestonesCommand;
import gov.nist.secauto.oscal.tools.cli.core.commands.profile.ProfileCommand;
Expand All @@ -52,6 +53,7 @@ public CLI() {
cliProcessor.addCommandHandler(new ProfileCommand());
cliProcessor.addCommandHandler(new ComponentDefinitionCommand());
cliProcessor.addCommandHandler(new SystemSecurityPlanCommand());
cliProcessor.addCommandHandler(new MappingCollectionCommand());
cliProcessor.addCommandHandler(new AssessmentPlanCommand());
cliProcessor.addCommandHandler(new AssessmentResultsCommand());
cliProcessor.addCommandHandler(new PlanOfActionsAndMilestonesCommand());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,44 +129,45 @@ public void validateOptions(CLIProcessor processor, CommandContext context) thro
@Override
public ExitStatus executeCommand(CLIProcessor processor, CommandContext context) {

String toFormatText = context.getCmdLine().getOptionValue("to");
Format toFormat = Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));

List<String> extraArgs = context.getExtraArguments();

Path destination;
if (extraArgs.size() == 1) {
destination = null;
} else {
Path destination = null;
if (extraArgs.size() > 1) {
destination = Paths.get(extraArgs.get(1)).toAbsolutePath();
}

if (destination != null) {
if (Files.exists(destination)) {
if (!context.getCmdLine().hasOption("overwrite")) {
return ExitCode.FAIL.exitMessage("The provided destination '" + destination
+ "' already exists and the --overwrite option was not provided.");
return ExitCode.FAIL.exitMessage( // NOPMD readability
"The provided destination '" + destination
+ "' already exists and the --overwrite option was not provided.");
}
if (!Files.isWritable(destination)) {
return ExitCode.FAIL.exitMessage("The provided destination '" + destination + "' is not writable.");
return ExitCode.FAIL.exitMessage( // NOPMD readability
"The provided destination '" + destination + "' is not writable.");
}
} else {
Path parent = destination.getParent();
if (parent != null) {
try {
Files.createDirectories(parent);
} catch (IOException ex) {
return ExitCode.INVALID_TARGET.exit().withThrowable(ex);
return ExitCode.INVALID_TARGET.exit().withThrowable(ex); // NOPMD readability
}
}
}
}

Path source = Paths.get(extraArgs.get(0));

String toFormatText = context.getCmdLine().getOptionValue("to");
Format toFormat = Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));

try {
performConvert(source, destination, toFormat);
} catch (IOException | BindingException | IllegalArgumentException ex) {
return ExitCode.FAIL.exit().withThrowable(ex);
return ExitCode.FAIL.exit().withThrowable(ex); // NOPMD readability
}
if (destination != null && LOGGER.isInfoEnabled()) {
LOGGER.info("Generated {} file: {}", toFormat.toString(), destination);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@

import gov.nist.secauto.oscal.tools.cli.framework.command.AbstractParentCommand;

public class AssessmentPlanCommand
public class MappingCollectionCommand
extends AbstractParentCommand {
private static final String COMMAND = "mapping-collection";

public AssessmentPlanCommand() {
public MappingCollectionCommand() {
super();
addCommandHandler(new ValidateSubcommand());
// addCommandHandler(new RenderSubcommand());
Expand All @@ -46,6 +46,6 @@ public String getName() {

@Override
public String getDescription() {
return "Perform an operation on an OSCAL Assessment Plan";
return "Perform an operation on an OSCAL mapping collection";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -142,31 +142,30 @@ public void validateOptions(CLIProcessor processor, CommandContext context)
@Override
public ExitStatus executeCommand(CLIProcessor cliProcessor, CommandContext context) {
List<String> extraArgs = context.getExtraArguments();
Path input = Paths.get(extraArgs.get(0));

Path destination;
if (extraArgs.size() == 1) {
destination = null;
} else {
Path destination = null;
if (extraArgs.size() > 1) {
destination = Paths.get(extraArgs.get(1)).toAbsolutePath();
}

if (destination != null) {
if (Files.exists(destination)) {
if (!context.getCmdLine().hasOption("overwrite")) {
return ExitCode.FAIL.exitMessage("The provided destination '" + destination
+ "' already exists and the --overwrite option was not provided.");
return ExitCode.FAIL.exitMessage( // NOPMD readability
"The provided destination '" + destination
+ "' already exists and the --overwrite option was not provided.");
}
if (!Files.isWritable(destination)) {
return ExitCode.FAIL.exitMessage("The provided destination '" + destination + "' is not writable.");
return ExitCode.FAIL.exitMessage( // NOPMD readability
"The provided destination '" + destination + "' is not writable.");
}
} else {
Path parent = destination.getParent();
if (parent != null) {
try {
Files.createDirectories(parent);
} catch (IOException ex) {
return ExitCode.INVALID_TARGET.exit().withThrowable(ex);
return ExitCode.INVALID_TARGET.exit().withThrowable(ex); // NOPMD readability
}
}
}
Expand All @@ -186,10 +185,11 @@ public ExitStatus executeCommand(CLIProcessor cliProcessor, CommandContext conte
}
}

Path input = Paths.get(extraArgs.get(0));
try {
performGeneration(input, destination, asFormat, configuration);
} catch (IOException | MetaschemaException ex) {
return ExitCode.FAIL.exit().withThrowable(ex);
return ExitCode.FAIL.exit().withThrowable(ex); // NOPMD readability
}
if (destination != null && LOGGER.isInfoEnabled()) {
LOGGER.info("Generated {} schema file: {}", asFormat.toString(), destination);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,6 @@

public class ResolveSubcommand
extends AbstractTerminalCommand {
@Override
public String getDescription() {
return "Resolve the specified OSCAL Profile";
}

private static final String COMMAND = "resolve";
private static final List<ExtraArgument> EXTRA_ARGUMENTS;
Expand All @@ -88,15 +84,19 @@ public String getName() {
return COMMAND;
}

@Override
public String getDescription() {
return "Resolve the specified OSCAL Profile";
}

@Override
public void gatherOptions(Options options) {
// options.addOption(Option.builder()
// .longOpt("as")
// .hasArg().argName("FORMAT")
// .desc("source format: xml, json, or yaml").build());
options.addOption(Option.builder()
.longOpt("as")
.hasArg().argName("FORMAT")
.desc("source format: xml, json, or yaml").build());
options.addOption(Option.builder("t")
.longOpt("to")
.required()
.hasArg().argName("FORMAT")
.desc("convert to format: xml, json, or yaml").build());
}
Expand All @@ -123,14 +123,16 @@ public void validateOptions(CLIProcessor processor, CommandContext context) thro
}
}

try {
String toFormatText = context.getCmdLine().getOptionValue("to");
Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
throw new InvalidArgumentException("Invalid '--to' argument. The format must be one of: "
+ Arrays.asList(Format.values()).stream()
.map(format -> format.name())
.collect(CustomCollectors.joiningWithOxfordComma("and")));
if (context.getCmdLine().hasOption("to")) {
try {
String toFormatText = context.getCmdLine().getOptionValue("to");
Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
throw new InvalidArgumentException("Invalid '--to' argument. The format must be one of: "
+ Arrays.asList(Format.values()).stream()
.map(format -> format.name())
.collect(CustomCollectors.joiningWithOxfordComma("and")));
}
}

List<String> extraArgs = context.getExtraArguments();
Expand Down Expand Up @@ -187,8 +189,13 @@ public ExitStatus executeCommand(CLIProcessor processor, CommandContext context)

source = source.toAbsolutePath();

String toFormatText = context.getCmdLine().getOptionValue("to");
Format toFormat = Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
Format toFormat;
if (context.getCmdLine().hasOption("to")) {
String toFormatText = context.getCmdLine().getOptionValue("to");
toFormat = Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
} else {
toFormat = asFormat;
}

Path destination;
if (extraArgs.size() == 1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,16 @@ public static Map<String, Object> parseYaml(Path target) throws IOException {
}
}

public static JSONObject yamlToJson(@NonNull Map<String, Object> map) throws JSONException {
/**
* Converts the provided YAML {@code map} into JSON.
*
* @param map
* the YAML map
* @return the JSON object
* @throws JSONException
* if an error occurred while building the JSON tree
*/
public static JSONObject yamlToJson(@NonNull Map<String, Object> map) {
return new JSONObject(map);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,9 @@ public void generateMessage(boolean withThrowable) {
}

if (logBuilder != null) {
Throwable throwable = null;
if (withThrowable) {
Throwable throwable = getThrowable();
throwable = getThrowable();
if (throwable != null) {
logBuilder.withThrowable(throwable);
}
Expand All @@ -103,7 +104,7 @@ public void generateMessage(boolean withThrowable) {
String message = getMessage();
if (message != null && !message.isEmpty()) {
logBuilder.log(message);
} else {
} else if (throwable != null) {
// log the throwable
logBuilder.log();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ private static void handleNoColor() {
}

public static void handleQuiet() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
LoggerContext ctx = (LoggerContext) LogManager.getContext(false); // NOPMD not closable here
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
Level oldLevel = loggerConfig.getLevel();
Expand Down Expand Up @@ -274,7 +274,7 @@ public void showHelp(

HelpFormatter formatter = new HelpFormatter();

AnsiPrintStream out = AnsiConsole.out();
AnsiPrintStream out = AnsiConsole.out(); // NOPMD not closable
int terminalWidth = Math.max(out.getTerminalWidth(), 40);

PrintWriter writer = new PrintWriter(out, true, StandardCharsets.UTF_8); // NOPMD - not owned
Expand Down
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@
<dependency.everit-json.version>1.14.1</dependency.everit-json.version>
<dependency.jetbrains-annotation.version>23.0.0</dependency.jetbrains-annotation.version>
<dependency.jline.version>3.21.0</dependency.jline.version>
<dependency.liboscal-java.version>1.0.4.2</dependency.liboscal-java.version>
<dependency.liboscal-java.version>1.0.4.3</dependency.liboscal-java.version>
<dependency.log4j2.version>2.18.0</dependency.log4j2.version>
<dependency.metaschema-framework.version>0.9.0</dependency.metaschema-framework.version>
<dependency.metaschema-framework.version>0.10.0</dependency.metaschema-framework.version>
<dependency.spotbugs-annotations.version>4.7.2</dependency.spotbugs-annotations.version>

<plugin.license.version>4.2.rc3</plugin.license.version>
Expand Down

0 comments on commit fe0f911

Please sign in to comment.