Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code cleanup and Javadocs #106

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import gov.nist.secauto.metaschema.core.datatype.adapter.MetaschemaDataTypeProvider;
import gov.nist.secauto.metaschema.core.datatype.adapter.UuidAdapter;
import gov.nist.secauto.metaschema.core.metapath.item.function.IMapKey;
import gov.nist.secauto.metaschema.core.util.ObjectUtils;

import java.util.UUID;

Expand Down Expand Up @@ -38,7 +39,7 @@ public IMapKey asMapKey() {

@Override
public String asString() {
return asUuid().toString();
return ObjectUtils.notNull(asUuid().toString());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import static org.junit.jupiter.api.Assertions.assertEquals;

import gov.nist.secauto.metaschema.core.util.ObjectUtils;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
Expand All @@ -18,10 +20,10 @@

class IUuidItemTest {
private static Stream<Arguments> testCompare() { // NOPMD - false positive
UUID uuidRandom = UUID.randomUUID();
UUID uuid1 = UUID.fromString("4cfa2c52-9345-4012-8055-0bc9ac9b03fa");
UUID uuid2 = UUID.fromString("25a6d916-f179-4550-ad2b-7e7cd9df35d2");
String uuid2String = uuid2.toString();
UUID uuidRandom = ObjectUtils.notNull(UUID.randomUUID());
UUID uuid1 = ObjectUtils.notNull(UUID.fromString("4cfa2c52-9345-4012-8055-0bc9ac9b03fa"));
UUID uuid2 = ObjectUtils.notNull(UUID.fromString("25a6d916-f179-4550-ad2b-7e7cd9df35d2"));
String uuid2String = ObjectUtils.notNull(uuid2.toString());

return Stream.of(
Arguments.of(IUuidItem.valueOf(uuidRandom), IUuidItem.valueOf(uuidRandom), IIntegerItem.ZERO),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ interface ObjectWriter<T extends IFeatureComplexItemValueHandler> {

/**
* Perform a series of property write operations, starting first with this
* operation and followed bu the {@code after} operation.
* operation and followed by the {@code after} operation.
*
* @param after
* the secondary property write operation to perform
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,10 @@ public void writeItemField(IBoundObject item, IBoundInstanceModelGroupedField in
writeGroupedModelObject(
instance,
item,
((ObjectWriter<IBoundInstanceModelGroupedField>) this::writeDiscriminatorProperty)
.andThen(this::writeObjectProperties));
(parent, handler) -> {
writeDiscriminatorProperty(handler);
writeObjectProperties(parent, handler);
});
}

@Override
Expand All @@ -184,8 +186,10 @@ public void writeItemAssembly(IBoundObject item, IBoundInstanceModelGroupedAssem
writeGroupedModelObject(
instance,
item,
((ObjectWriter<IBoundInstanceModelGroupedAssembly>) this::writeDiscriminatorProperty)
.andThen(this::writeObjectProperties));
(parent, handler) -> {
writeDiscriminatorProperty(handler);
writeObjectProperties(parent, handler);
});
}

@Override
Expand Down Expand Up @@ -216,7 +220,6 @@ private void writeScalarItem(@NonNull Object item, @NonNull IFeatureScalarItemVa
}

private <T extends IBoundInstanceModelGroupedNamed> void writeDiscriminatorProperty(
@NonNull Object parentItem,
@NonNull T instance) throws IOException {

IBoundInstanceModelChoiceGroup choiceGroup = instance.getParentContainer();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public static Class<? extends IBoundObject> compileModule(@NonNull Path moduleFi
.loadClass(rootClassName)));
}

@NonNull
private static <T extends IBoundObject> T read(
@NonNull Format format,
@NonNull Path file,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ void testExistsWithVariable() throws IOException, URISyntaxException, Metaschema
}

@Test
@SuppressWarnings("unchecked")
void codegenTest() throws MetaschemaException, IOException {
List<IConstraintSet> constraints;
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class JsonParserTest
@Test
void testIssue308Regression() throws IOException, MetaschemaException {
ModuleLoader moduleLoader = new ModuleLoader();
IMetaschemaModule module
IMetaschemaModule<?> module
= moduleLoader.load(Paths.get("src/test/resources/metaschema/308-choice-regression/metaschema.xml"));

IBindingContext context = IBindingContext.instance();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.fasterxml.jackson.core.JsonParser;

import gov.nist.secauto.metaschema.core.model.IModule;
import gov.nist.secauto.metaschema.core.util.ObjectUtils;
import gov.nist.secauto.metaschema.databind.io.json.MetaschemaJsonReader;

import org.junit.jupiter.api.Test;
Expand All @@ -32,7 +33,9 @@ void testMinimalJsonParse() throws JsonParseException, IOException {
IBoundDefinitionModelAssembly classBinding = getRootAssemblyClassBinding();

try (JsonParser parser = newJsonParser(reader)) {
Object value = new MetaschemaJsonReader(parser).readObjectRoot(classBinding, classBinding.getRootJsonName());
Object value = new MetaschemaJsonReader(parser).readObjectRoot(
classBinding,
ObjectUtils.requireNonNull(classBinding.getRootJsonName()));
assertNotNull(value, "root was null");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,28 @@

@SuppressWarnings("PMD.ShortClassName")
public final class CLI {
/**
* The main command line entry point.
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
System.exit(runCli(args).getExitCode().getStatusCode());
}

/**
* Execute a command line.
*
* @param args
* the command line arguments
* @return the execution result
*/
@NonNull
public static ExitStatus runCli(String... args) {
System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");

Map<String, IVersionInfo> versions = ObjectUtils.notNull(
@SuppressWarnings("serial") Map<String, IVersionInfo> versions = ObjectUtils.notNull(
new LinkedHashMap<>() {
{
put(CLIProcessor.COMMAND_VERSION, new MetaschemaJavaVersion());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,25 @@ public void validateOptions(CallingContext callingContext, CommandLine cmdLine)
protected abstract static class AbstractConversionCommandExecutor
extends AbstractCommandExecutor {

public AbstractConversionCommandExecutor(
/**
* Construct a new command executor.
*
* @param callingContext
* the context of the command execution
* @param commandLine
* the parsed command line details
*/
protected AbstractConversionCommandExecutor(
@NonNull CallingContext callingContext,
@NonNull CommandLine commandLine) {
super(callingContext, commandLine);
}

/**
* Get the binding context to use for data processing.
*
* @return the context
*/
@NonNull
protected abstract IBindingContext getBindingContext();

Expand Down Expand Up @@ -161,9 +174,10 @@ public ExitStatus execute() {
}
}

String sourceName = extraArgs.get(0);
String sourceName = ObjectUtils.notNull(extraArgs.get(0));
URI cwd = ObjectUtils.notNull(Paths.get("").toAbsolutePath().toUri());

URI source;
URI cwd = Paths.get("").toAbsolutePath().toUri();
try {
source = UriUtils.toUri(sourceName, cwd);
} catch (URISyntaxException ex) {
Expand Down Expand Up @@ -206,6 +220,22 @@ public ExitStatus execute() {
return ExitCode.OK.exit();
}

/**
* Called to perform a content conversion.
*
* @param source
* the resource to convert
* @param toFormat
* the format to convert to
* @param writer
* the writer to use to write converted content
* @param loader
* the Metaschema loader to use to load the content to convert
* @throws FileNotFoundException
* if the requested resource was not found
* @throws IOException
* if there was an error reading or writing content
*/
protected abstract void handleConversion(
@NonNull URI source,
@NonNull Format toFormat,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,31 @@ protected abstract class AbstractValidationCommandExecutor
extends AbstractCommandExecutor
implements ISchemaValidationProvider {

/**
* Construct a new command executor.
*
* @param callingContext
* the context of the command execution
* @param commandLine
* the parsed command line details
*/
public AbstractValidationCommandExecutor(
@NonNull CallingContext callingContext,
@NonNull CommandLine commandLine) {
super(callingContext, commandLine);
}

/**
* Get the binding context to use for data processing.
*
* @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
*/
@NonNull
protected abstract IBindingContext getBindingContext(@NonNull Set<IConstraintSet> constraintSets)
throws MetaschemaException, IOException;
Expand Down Expand Up @@ -267,7 +286,7 @@ public ExitStatus execute() {
}

if (cmdLine.hasOption(SARIF_OUTPUT_FILE_OPTION) && LOGGER.isInfoEnabled()) {
Path sarifFile = Paths.get(cmdLine.getOptionValue(SARIF_OUTPUT_FILE_OPTION));
Path sarifFile = ObjectUtils.notNull(Paths.get(cmdLine.getOptionValue(SARIF_OUTPUT_FILE_OPTION)));

IVersionInfo version
= getCallingContext().getCLIProcessor().getVersionInfos().get(CLIProcessor.COMMAND_VERSION);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,15 @@ public ICommandExecutor newExecutor(CallingContext callingContext, CommandLine c
return ICommandExecutor.using(callingContext, cmdLine, this::executeCommand);
}

/**
* Called to execute the schema generation.
*
* @param callingContext
* the context information for the execution
* @param cmdLine
* the parsed command line details
* @return the execution result
*/
@SuppressWarnings({
"PMD.OnlyOneReturn", // readability
"unused"
Expand Down Expand Up @@ -188,12 +197,12 @@ protected ExitStatus executeCommand(
}
}

URI input;
String inputName = extraArgs.get(0);
URI cwd = Paths.get("").toAbsolutePath().toUri();
String inputName = ObjectUtils.notNull(extraArgs.get(0));
URI cwd = ObjectUtils.notNull(Paths.get("").toAbsolutePath().toUri());

URI input;
try {
input = UriUtils.toUri(extraArgs.get(0), cwd);
input = UriUtils.toUri(inputName, cwd);
} catch (URISyntaxException ex) {
return ExitCode.IO_ERROR.exitMessage(
String.format("Unable to load '%s' as it is not a valid file or URI.", inputName)).withThrowable(ex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,20 @@ private OscalCommandExecutor(
super(callingContext, commandLine);
}

@NonNull
private Path getTempDir() throws IOException {
if (tempDir == null) {
tempDir = Files.createTempDirectory("validation-");
tempDir.toFile().deleteOnExit();
}
assert tempDir != null;
return tempDir;
}

@NonNull
private IModule getModule(@NonNull Set<IConstraintSet> constraintSets)
throws MetaschemaException, IOException {
URI cwd = Paths.get("").toAbsolutePath().toUri();
URI cwd = ObjectUtils.notNull(Paths.get("").toAbsolutePath().toUri());

if (module == null) {
try {
Expand Down Expand Up @@ -135,7 +137,7 @@ public List<Source> getXmlSchemas(@NonNull URL targetResource) throws IOExceptio
IMutableConfiguration<SchemaGenerationFeature<?>> configuration = new DefaultConfiguration<>();
ISchemaGenerator.generateSchema(getModule(), schemaFile, SchemaFormat.XML, configuration);
return ObjectUtils.requireNonNull(List.of(
XmlUtil.getStreamSource(schemaFile.toUri().toURL())));
XmlUtil.getStreamSource(ObjectUtils.notNull(schemaFile.toUri().toURL()))));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
import gov.nist.secauto.metaschema.schemagen.SchemaGenerationFeature;

import org.apache.commons.cli.CommandLine;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;

import java.io.BufferedReader;
Expand All @@ -47,7 +45,6 @@

public class ValidateModuleCommand
extends AbstractValidateContentCommand {
private static final Logger LOGGER = LogManager.getLogger(ValidateModuleCommand.class);
@NonNull
private static final String COMMAND = "validate";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,17 @@ public ICommandExecutor newExecutor(CallingContext callingContext, CommandLine c
return ICommandExecutor.using(callingContext, cmdLine, this::executeCommand);
}

/**
* Execute the list functions command.
*
* @param callingContext
* the context of the command execution
* @param cmdLine
* the parsed command line details
* @return the execution result
*/
@SuppressWarnings({
"PMD.OnlyOneReturn", // readability
"unused"
"PMD.OnlyOneReturn" // readability
})
protected ExitStatus executeCommand(
@NonNull CallingContext callingContext,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ public class MetapathCommand
extends AbstractParentCommand {
private static final String COMMAND = "metapath";

/**
* Constructor for a new Metapath command.
*/
public MetapathCommand() {
super(true);
addCommandHandler(new ListFunctionsSubcommand());
Expand Down
Loading