Skip to content

Commit

Permalink
Refactored code to reduce warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
david-waltermire committed Nov 2, 2024
1 parent 9c7c850 commit 359f822
Show file tree
Hide file tree
Showing 20 changed files with 425 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,7 @@ public static void handleQuiet() {
}

protected void showVersion() {
@SuppressWarnings("resource")
PrintStream out = AnsiConsole.out(); // NOPMD - not owner
@SuppressWarnings("resource") PrintStream out = AnsiConsole.out(); // NOPMD - not owner
getVersionInfos().values().stream().forEach(info -> {
out.println(ansi()
.bold().a(info.getName()).boldOff()
Expand Down Expand Up @@ -253,8 +252,7 @@ public class CallingContext {

@SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "Use of final fields")
public CallingContext(@NonNull List<String> args) {
@SuppressWarnings("PMD.LooseCoupling")
LinkedList<ICommand> calledCommands = new LinkedList<>();
@SuppressWarnings("PMD.LooseCoupling") LinkedList<ICommand> calledCommands = new LinkedList<>();
List<Option> options = new LinkedList<>(OPTIONS);
List<String> extraArgs = new LinkedList<>();

Expand Down Expand Up @@ -632,8 +630,7 @@ public void showHelp() {
AnsiPrintStream out = AnsiConsole.out();
int terminalWidth = Math.max(out.getTerminalWidth(), 40);

@SuppressWarnings("resource")
PrintWriter writer = new PrintWriter( // NOPMD not owned
@SuppressWarnings("resource") PrintWriter writer = new PrintWriter( // NOPMD not owned
out,
true,
StandardCharsets.UTF_8);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,9 @@ private void addConstraintValidationFinding(@NonNull ConstraintValidationFinding
results.add(new ConstraintResult(finding));
}

public void write(@NonNull Path outputFile) throws IOException {
public void write(
@NonNull Path outputFile,
@NonNull IBindingContext bindingContext) throws IOException {

URI output = ObjectUtils.notNull(outputFile.toUri());

Expand Down Expand Up @@ -246,7 +248,6 @@ public void write(@NonNull Path outputFile) throws IOException {
run.setTool(tool);
}

IBindingContext bindingContext = IBindingContext.newInstance();
bindingContext.registerModule(SarifModule.class);
bindingContext.newSerializer(Format.JSON, Sarif.class)
.disableFeature(SerializationFeature.SERIALIZE_ROOT)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import gov.nist.secauto.metaschema.core.model.validation.IValidationFinding;
import gov.nist.secauto.metaschema.core.util.IVersionInfo;
import gov.nist.secauto.metaschema.core.util.ObjectUtils;
import gov.nist.secauto.metaschema.databind.IBindingContext;

import org.jmock.Expectations;
import org.jmock.junit5.JUnit5Mockery;
Expand Down Expand Up @@ -110,7 +111,7 @@ void testValid() throws IOException {

// no need to cleanup this file, since it is created in the target directory
Path sarifFile = ObjectUtils.requireNonNull(Paths.get("target/test.sarif"));
handler.write(sarifFile);
handler.write(sarifFile, IBindingContext.newInstance());

Path sarifSchema = Paths.get("modules/sarif/sarif-schema-2.1.0.json");

Expand Down
3 changes: 1 addition & 2 deletions metaschema-cli/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@

<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>consolecaptor</artifactId>
<version>1.0.3</version>
<artifactId>logcaptor</artifactId>
<scope>test</scope>
</dependency>
<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@

import edu.umd.cs.findbugs.annotations.NonNull;

/**
* The main entry point for the CLI application.
*/
@SuppressWarnings("PMD.ShortClassName")
public final class CLI {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import gov.nist.secauto.metaschema.cli.processor.command.CommandExecutionException;
import gov.nist.secauto.metaschema.cli.processor.command.DefaultExtraArgument;
import gov.nist.secauto.metaschema.cli.processor.command.ExtraArgument;
import gov.nist.secauto.metaschema.core.model.MetaschemaException;
import gov.nist.secauto.metaschema.core.util.AutoCloser;
import gov.nist.secauto.metaschema.core.util.ObjectUtils;
import gov.nist.secauto.metaschema.databind.IBindingContext;
Expand All @@ -39,7 +38,7 @@
import edu.umd.cs.findbugs.annotations.NonNull;

/**
* Used by implementing classes to declare a content conversion command.
* Used by implementing classes to provide a content conversion command.
*/
public abstract class AbstractConvertSubcommand
extends AbstractTerminalCommand {
Expand Down Expand Up @@ -94,11 +93,8 @@ protected AbstractConversionCommandExecutor(
* Get the binding context to use for data processing.
*
* @return the context
* @throws MetaschemaException
* if a Metaschema error occurred
* @throws IOException
* if an error occurred while reading data
* @throws CommandExecutionException
* if an error occurred getting the binding context
*/
@NonNull
protected abstract IBindingContext getBindingContext() throws CommandExecutionException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import gov.nist.secauto.metaschema.core.configuration.IMutableConfiguration;
import gov.nist.secauto.metaschema.core.metapath.MetapathException;
import gov.nist.secauto.metaschema.core.model.IModule;
import gov.nist.secauto.metaschema.core.model.MetaschemaException;
import gov.nist.secauto.metaschema.core.model.constraint.IConstraintSet;
import gov.nist.secauto.metaschema.core.model.constraint.ValidationFeature;
import gov.nist.secauto.metaschema.core.model.validation.AggregateValidationResult;
Expand Down Expand Up @@ -47,7 +46,11 @@
import java.util.Set;

import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;

/**
* Used by implementing classes to provide a content validation command.
*/
public abstract class AbstractValidateContentCommand
extends AbstractTerminalCommand {
private static final Logger LOGGER = LogManager.getLogger(AbstractValidateContentCommand.class);
Expand Down Expand Up @@ -113,6 +116,9 @@ public List<ExtraArgument> getExtraArguments() {
return EXTRA_ARGUMENTS;
}

/**
* Drives the validation execution.
*/
protected abstract class AbstractValidationCommandExecutor
extends AbstractCommandExecutor {

Expand All @@ -136,27 +142,59 @@ public AbstractValidationCommandExecutor(
* @param constraintSets
* the constraints to configure in the resulting binding context
* @return the context
* @throws MetaschemaException
* if a Metaschema error occurred
* @throws IOException
* if an error occurred while reading data
* @throws CommandExecutionException
* if a error occurred while getting the binding context
*/
@NonNull
protected abstract IBindingContext getBindingContext(@NonNull Set<IConstraintSet> constraintSets)
throws CommandExecutionException;

/**
* Get the module to use for validation.
* <p>
* This module is used to generate schemas and as a source of built-in
* constraints.
*
* @param commandLine
* the provided command line argument information
* @param bindingContext
* the context used to access Metaschema module information based on
* Java class bindings
* @return the loaded Metaschema module
* @throws CommandExecutionException
* if an error occurred while loading the module
*/
@NonNull
protected abstract IModule getModule(
@NonNull CommandLine commandLine,
@NonNull IBindingContext bindingContext)
throws CommandExecutionException;

/**
* Get the schema validation implementation requested based on the provided
* command line arguments.
* <p>
* It is typical for this call to result in the dynamic generation of a schema
* to use for validation.
*
* @param module
* the Metaschema module to generate the schema from
* @param commandLine
* the provided command line argument information
* @param bindingContext
* the context used to access Metaschema module information based on
* Java class bindings
* @return the provider
*/
@NonNull
protected abstract ISchemaValidationProvider getSchemaValidationProvider(
@NonNull IModule module,
@NonNull CommandLine commandLine,
@NonNull IBindingContext bindingContext);

/**
* Execute the validation operation.
*/
@SuppressWarnings("PMD.OnlyOneReturn") // readability
@Override
public void execute() throws CommandExecutionException {
Expand All @@ -168,40 +206,63 @@ public void execute() throws CommandExecutionException {
CONSTRAINTS_OPTION,
currentWorkingDirectory);

IBindingContext bindingContext = getBindingContext(constraintSets);
IBoundLoader loader = bindingContext.newBoundLoader();

List<String> extraArgs = cmdLine.getArgList();

URI source = MetaschemaCommands.handleSource(
ObjectUtils.requireNonNull(extraArgs.get(0)),
currentWorkingDirectory);

IBindingContext bindingContext = getBindingContext(constraintSets);
IBoundLoader loader = bindingContext.newBoundLoader();
Format asFormat = MetaschemaCommands.determineSourceFormat(
cmdLine,
MetaschemaCommands.AS_FORMAT_OPTION,
loader,
source);

if (LOGGER.isInfoEnabled()) {
LOGGER.info("Validating '{}' as {}.", source, asFormat.name());
IValidationResult validationResult = validate(source, asFormat, cmdLine, bindingContext);
handleOutput(source, validationResult, cmdLine, bindingContext);

if (validationResult == null || validationResult.isPassing()) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("The file '{}' is valid.", source);
}
} else if (LOGGER.isErrorEnabled()) {
LOGGER.error("The file '{}' is invalid.", source);
}

IMutableConfiguration<ValidationFeature<?>> configuration = new DefaultConfiguration<>();
if (cmdLine.hasOption(SARIF_OUTPUT_FILE_OPTION) && cmdLine.hasOption(SARIF_INCLUDE_PASS_OPTION)) {
configuration.enableFeature(ValidationFeature.VALIDATE_GENERATE_PASS_FINDINGS);
if (validationResult != null && !validationResult.isPassing()) {
throw new CommandExecutionException(ExitCode.FAIL);
}
}

@SuppressWarnings("PMD.CyclomaticComplexity")
@Nullable
private IValidationResult validate(
@NonNull URI source,
@NonNull Format asFormat,
@NonNull CommandLine commandLine,
@NonNull IBindingContext bindingContext) throws CommandExecutionException {

if (LOGGER.isInfoEnabled()) {
LOGGER.info("Validating '{}' as {}.", source, asFormat.name());
}

IValidationResult validationResult = null;
try {
IModule module = bindingContext.registerModule(getModule(getCommandLine(), bindingContext));
if (!cmdLine.hasOption(NO_SCHEMA_VALIDATION_OPTION)) {
IModule module = bindingContext.registerModule(getModule(commandLine, bindingContext));
if (!commandLine.hasOption(NO_SCHEMA_VALIDATION_OPTION)) {
// perform schema validation
validationResult = getSchemaValidationProvider(module, getCommandLine(), bindingContext)
validationResult = getSchemaValidationProvider(module, commandLine, bindingContext)
.validateWithSchema(source, asFormat, bindingContext);
}

if (!cmdLine.hasOption(NO_CONSTRAINT_VALIDATION_OPTION)) {
if (!commandLine.hasOption(NO_CONSTRAINT_VALIDATION_OPTION)) {
IMutableConfiguration<ValidationFeature<?>> configuration = new DefaultConfiguration<>();
if (commandLine.hasOption(SARIF_OUTPUT_FILE_OPTION) && commandLine.hasOption(SARIF_INCLUDE_PASS_OPTION)) {
configuration.enableFeature(ValidationFeature.VALIDATE_GENERATE_PASS_FINDINGS);
}

// perform constraint validation
IValidationResult constraintValidationResult = bindingContext.validateWithConstraints(source, configuration);
validationResult = validationResult == null
Expand All @@ -223,9 +284,16 @@ public void execute() throws CommandExecutionException {
} catch (MetapathException ex) {
throw new CommandExecutionException(ExitCode.PROCESSING_ERROR, ex.getLocalizedMessage(), ex);
}
return validationResult;
}

if (cmdLine.hasOption(SARIF_OUTPUT_FILE_OPTION) && LOGGER.isInfoEnabled()) {
Path sarifFile = ObjectUtils.notNull(Paths.get(cmdLine.getOptionValue(SARIF_OUTPUT_FILE_OPTION)));
private void handleOutput(
@NonNull URI source,
@Nullable IValidationResult validationResult,
@NonNull CommandLine commandLine,
@NonNull IBindingContext bindingContext) throws CommandExecutionException {
if (commandLine.hasOption(SARIF_OUTPUT_FILE_OPTION) && LOGGER.isInfoEnabled()) {
Path sarifFile = ObjectUtils.notNull(Paths.get(commandLine.getOptionValue(SARIF_OUTPUT_FILE_OPTION)));

IVersionInfo version
= getCallingContext().getCLIProcessor().getVersionInfos().get(CLIProcessor.COMMAND_VERSION);
Expand All @@ -235,7 +303,7 @@ public void execute() throws CommandExecutionException {
if (validationResult != null) {
sarifHandler.addFindings(validationResult.getFindings());
}
sarifHandler.write(sarifFile);
sarifHandler.write(sarifFile, bindingContext);
} catch (IOException ex) {
throw new CommandExecutionException(ExitCode.IO_ERROR, ex.getLocalizedMessage(), ex);
}
Expand All @@ -244,17 +312,6 @@ public void execute() throws CommandExecutionException {
LoggingValidationHandler.instance().handleResults(validationResult);
}

if (validationResult == null || validationResult.isPassing()) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("The file '{}' is valid.", source);
}
} else if (LOGGER.isErrorEnabled()) {
LOGGER.error("The file '{}' is invalid.", source);
}

if (validationResult != null && !validationResult.isPassing()) {
throw new CommandExecutionException(ExitCode.FAIL);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@

import edu.umd.cs.findbugs.annotations.NonNull;

/**
* This command implementation supports the conversion of a content instance
* between supported formats based on a provided Metaschema module.
*/
public class ConvertContentUsingModuleCommand
extends AbstractConvertSubcommand {
@NonNull
Expand Down Expand Up @@ -80,7 +84,7 @@ private CommandExecutor(
protected IBindingContext getBindingContext() throws CommandExecutionException {
IBindingContext retval = MetaschemaCommands.newBindingContextWithDynamicCompilation();

IModule module = MetaschemaCommands.handleModule(
IModule module = MetaschemaCommands.loadModule(
getCommandLine(),
MetaschemaCommands.METASCHEMA_REQUIRED_OPTION,
ObjectUtils.notNull(getCurrentWorkingDirectory().toUri()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
* This command implementation supports generation of a diagram depicting the
* objects and relationships within a provided Metaschema module.
*/
public class GenerateDiagramCommand
extends AbstractTerminalCommand {
private static final Logger LOGGER = LogManager.getLogger(GenerateDiagramCommand.class);
Expand Down Expand Up @@ -87,7 +91,8 @@ public ICommandExecutor newExecutor(CallingContext callingContext, CommandLine c
* information about the calling context
* @param cmdLine
* the parsed command line details
* @return the execution result
* @throws CommandExecutionException
* if an error occurred while executing the command
*/
@SuppressWarnings({
"PMD.OnlyOneReturn", // readability
Expand Down Expand Up @@ -119,7 +124,7 @@ protected void executeCommand(
ex.getLocalizedMessage()),
ex);
}
IModule module = MetaschemaCommands.handleModule(moduleUri, bindingContext);
IModule module = MetaschemaCommands.loadModule(moduleUri, bindingContext);

if (destination == null) {
Writer stringWriter = new StringWriter();
Expand Down
Loading

0 comments on commit 359f822

Please sign in to comment.