Skip to content
Open
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 @@ -30,6 +30,7 @@
import gov.nist.secauto.metaschema.binding.io.Format;
import gov.nist.secauto.metaschema.binding.io.IBoundLoader;
import gov.nist.secauto.metaschema.binding.io.ISerializer;
import gov.nist.secauto.metaschema.binding.io.SerializationFeature;
import gov.nist.secauto.metaschema.cli.processor.CLIProcessor.CallingContext;
import gov.nist.secauto.metaschema.cli.processor.ExitCode;
import gov.nist.secauto.metaschema.cli.processor.ExitStatus;
Expand Down Expand Up @@ -99,11 +100,19 @@ public class ResolveSubcommand
.desc("overwrite the destination if it exists")
.build());
@NonNull
private static final Option PRETTY_PRINT_OPTION = ObjectUtils.notNull(
Option.builder()
.longOpt("pretty-print")
.desc("Enable pretty-printing of the output for better readability.")
.build());

@NonNull
private static final List<Option> OPTIONS = ObjectUtils.notNull(
List.of(
AS_OPTION,
TO_OPTION,
OVERWRITE_OPTION));
OVERWRITE_OPTION,
PRETTY_PRINT_OPTION));

@Override
public String getName() {
Expand Down Expand Up @@ -153,8 +162,8 @@ public void validateOptions(CallingContext callingContext, CommandLine cmdLine)
String toFormatText = cmdLine.getOptionValue(TO_OPTION);
Format.valueOf(toFormatText.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
InvalidArgumentException newEx
= new InvalidArgumentException("Invalid '--to' argument. The format must be one of: "
InvalidArgumentException newEx = new InvalidArgumentException(
"Invalid '--to' argument. The format must be one of: "
+ Arrays.asList(Format.values()).stream()
.map(format -> format.name())
.collect(CustomCollectors.joiningWithOxfordComma("and")));
Expand Down Expand Up @@ -197,6 +206,7 @@ protected ExitStatus executeCommand(
loader.disableFeature(DeserializationFeature.DESERIALIZE_VALIDATE_CONSTRAINTS);

Format asFormat;
boolean prettyPrint = cmdLine.hasOption(PRETTY_PRINT_OPTION);
// attempt to determine the format
if (cmdLine.hasOption(AS_OPTION)) {
try {
Expand Down Expand Up @@ -292,22 +302,51 @@ protected ExitStatus executeCommand(
.withThrowable(ex);
}

// DefaultConstraintValidator validator = new DefaultConstraintValidator(dynamicContext);
// DefaultConstraintValidator validator = new
// DefaultConstraintValidator(dynamicContext);
// ((IBoundXdmNodeItem)resolvedProfile).validate(validator);
// validator.finalizeValidation();

ISerializer<Catalog> serializer
= OscalBindingContext.instance().newSerializer(toFormat, Catalog.class);
ISerializer<Catalog> serializer = OscalBindingContext.instance().newSerializer(toFormat, Catalog.class);
try {
if (destination == null) {
serializer.serialize((Catalog) resolvedProfile.getValue(), ObjectUtils.notNull(System.out));
} else {
serializer.serialize((Catalog) resolvedProfile.getValue(), destination);
}
if (prettyPrint && destination != null) {

ExitStatus prettyPrintStatus = prettyPrintOutput(destination, toFormat);
if (prettyPrintStatus != null) {
return prettyPrintStatus;
}
}
} catch (IOException ex) {
return ExitCode.PROCESSING_ERROR.exit().withThrowable(ex);
}
}
return ExitCode.OK.exit();
}

ExitStatus prettyPrintOutput(Path destination, Format toFormat) {
File outputFile = destination.toFile();
try {
switch (toFormat) {
case JSON:
gov.nist.secauto.oscal.tools.cli.core.utils.PrettyPrinter.prettyPrintJson(outputFile);
break;
case YAML:
gov.nist.secauto.oscal.tools.cli.core.utils.PrettyPrinter.prettyPrintYaml(outputFile);
break;
case XML:
gov.nist.secauto.oscal.tools.cli.core.utils.PrettyPrinter.prettyPrintXml(outputFile);
break;
default:
// do nothing
}
} catch (Exception e) {
return ExitCode.PROCESSING_ERROR.exitMessage("Pretty-printing failed: " + e.getMessage()).withThrowable(e);
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Portions of this software was developed by employees of the National Institute
* of Standards and Technology (NIST), an agency of the Federal Government and is
* being made available as a public service. Pursuant to title 17 United States
* Code Section 105, works of NIST employees are not subject to copyright
* protection in the United States. This software may be subject to foreign
* copyright. Permission in the United States and in foreign countries, to the
* extent that NIST may hold copyright, to use, copy, modify, create derivative
* works, and distribute this software and its documentation without fee is hereby
* granted on a non-exclusive basis, provided that this notice and disclaimer
* of warranty appears in all copies.
*
* THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER
* EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY
* THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM
* INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE
* SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE. IN NO EVENT
* SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT,
* INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM,
* OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY,
* CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR
* PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT
* OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.
*/

package gov.nist.secauto.oscal.tools.cli.core.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import net.sf.saxon.TransformerFactoryImpl;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.file.Files;

public class PrettyPrinter {
public static void prettyPrintJson(File file) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(file, Object.class);
mapper.writerWithDefaultPrettyPrinter().writeValue(file, obj);
}

public static void prettyPrintYaml(File file) throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Object obj = mapper.readValue(file, Object.class);
mapper.writerWithDefaultPrettyPrinter().writeValue(file, obj);
}

public static void prettyPrintXml(File file) throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(file);

TransformerFactory transformerFactory = new TransformerFactoryImpl();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

try (OutputStream out = Files.newOutputStream(file.toPath())) {
transformer.transform(new DOMSource(doc), new StreamResult(out));
}
}
}
48 changes: 47 additions & 1 deletion src/test/java/gov/nist/secauto/oscal/tools/cli/core/CLITest.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import gov.nist.secauto.metaschema.binding.io.Format;
import gov.nist.secauto.metaschema.cli.processor.ExitCode;
Expand All @@ -39,13 +40,16 @@
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import java.nio.file.Files;

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

Expand Down Expand Up @@ -112,21 +116,63 @@ private static Stream<Arguments> providesValues() {
values
.add(Arguments.of(new String[] { cmd, "resolve", "--to=" + format.name().toLowerCase(), path.toString() },
ExitCode.OK, null));

// Pretty-print support test
String prettyPrintOutput = "target/resolved_pretty_print" + format.getDefaultExtension();
values.add(Arguments.of(new String[] {
cmd, "resolve",
"--to=" + format.name().toLowerCase(),
"--pretty-print",
path.toString(),
prettyPrintOutput,
"--overwrite"
}, ExitCode.OK, null));
}
}
}

return values.stream();
}

private void assertPrettyPrintedOutput(Path outputPath, Format format) throws IOException {
String content = Files.readString(outputPath, StandardCharsets.UTF_8);
assertAll(
() -> assertTrue(content != null && !content.isBlank()),
() -> {
// Naive pretty-print assertion: check for line breaks and indentation
long lineCount = content.lines().count();
boolean hasIndentedLines = content.lines().anyMatch(line -> line.startsWith(" ") || line.startsWith(" "));

assertTrue(lineCount > 5, "Expected multiple lines for pretty-printed output");
assertTrue(hasIndentedLines, "Expected indented lines in pretty-printed output");
});
}

@ParameterizedTest
@MethodSource("providesValues")
void testAllSubCommands(@NonNull String[] args, @NonNull ExitCode expectedExitCode,
Class<? extends Throwable> expectedThrownClass) {
Class<? extends Throwable> expectedThrownClass) throws IOException {
if (expectedThrownClass == null) {
evaluateResult(CLI.runCli(args), expectedExitCode);
} else {
evaluateResult(CLI.runCli(args), expectedExitCode, expectedThrownClass);
}

// Check pretty-print output content if applicable
if (expectedExitCode == ExitCode.OK
&& List.of(args).contains("--pretty-print")
&& args.length >= 6) { // Ensure output path exists in args
String outputPathStr
= args[args.length - 2].endsWith("--overwrite") ? args[args.length - 3] : args[args.length - 2];
Path outputPath = Paths.get(outputPathStr);
String formatStr = Arrays.stream(args)
.filter(arg -> arg.startsWith("--to="))
.findFirst()
.map(arg -> arg.substring("--to=".length()))
.orElse("json");
Format format = Format.valueOf(formatStr.toUpperCase());
assertPrettyPrintedOutput(outputPath, format);
}

}
}
Loading