Skip to content
This repository has been archived by the owner on May 26, 2020. It is now read-only.

Commit

Permalink
Add raml and json schema validation mojo
Browse files Browse the repository at this point in the history
  • Loading branch information
skiddykong committed May 3, 2016
1 parent 3bde04d commit 7add70d
Show file tree
Hide file tree
Showing 30 changed files with 870 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
*/
public class FileTreeScanner {

private static final Logger LOGGER = LoggerFactory.getLogger(FileTreeScanner.class);
private static final String CLASSPATH = "CLASSPATH";
private static final String RAML_PATTERN = "**/*.raml";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import static org.apache.maven.plugins.annotations.ResolutionScope.COMPILE_PLUS_RUNTIME;

@Mojo(name = "generate", requiresProject = true, threadSafe = false, requiresDependencyResolution = COMPILE_PLUS_RUNTIME, defaultPhase = LifecyclePhase.GENERATE_SOURCES)
@Mojo(name = "generate", requiresDependencyResolution = COMPILE_PLUS_RUNTIME, defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class GenerateMojo extends AbstractMojo {

private static final String DEFAULT_INCLUDE = "**/*.raml";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package uk.gov.justice.raml.validation.maven;

import com.google.common.collect.ImmutableList;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.raml.parser.rule.ValidationResult;
import uk.gov.justice.raml.io.FileTreeScannerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

@Mojo(name = "check-syntax")
public class RamlSyntaxCheckMojo extends AbstractMojo {

private static final String DEFAULT_INCLUDE = "**/*.raml";

@Parameter(defaultValue = "${project}")
private MavenProject project;

@Parameter(property = "sourceDirectory", defaultValue = "CLASSPATH")
private File sourceDirectory;

@Parameter(property = "includes.include")
private List<String> includes;

@Parameter(property = "excludes.exclude")
private List<String> excludes;

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

if (includes.isEmpty()) {
includes = ImmutableList.of(DEFAULT_INCLUDE);
}

Map<Path, ValidationResult> results = null;

try {
results = new RamlSyntaxValidator(new FileTreeScannerFactory())
.validateRamls(configuration());
} catch (IOException e) {
throw new MojoExecutionException("Files not loaded", e);
}


if (results.size() == 0) {
getLog().info("Raml and Json Schema Validation Complete");
}

if (results.size() != 0) {

String validationResultsPrint = printResults(results, sourceDirectory);

getLog().error(validationResultsPrint);

throw new MojoFailureException(results, "Raml & Json schema validation has failed", validationResultsPrint);
}
}

private String printResults(Map<Path, ValidationResult> results, File sourceDirectory) {

StringBuilder sb = new StringBuilder();

sb.append("\nThere are ");
sb.append(results.size());
sb.append(" validation errors: \n");

results.entrySet().stream()
.forEach(resultEntry -> {
sb.append("\nSyntax check has failed for ");
sb.append(sourceDirectory);
sb.append(resultEntry.getKey());
sb.append("\nError Level : ");
sb.append(resultEntry.getValue().getLevel());
sb.append(" Line : ");
sb.append(resultEntry.getValue().getLine());
sb.append(" Column : ");
sb.append(resultEntry.getValue().getStartColumn());
sb.append("\n");
sb.append(resultEntry.getValue().getMessage());
sb.append("\n");
});
return sb.toString();

}

private SyntaxValidatorConfig configuration() {

return new SyntaxValidatorConfig(sourceDirectory.toPath(),
includes,
excludes);

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package uk.gov.justice.raml.validation.maven;

import org.raml.parser.loader.FileResourceLoader;
import org.raml.parser.rule.ValidationResult;
import uk.gov.justice.raml.io.FileTreeScannerFactory;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.raml.parser.visitor.RamlValidationService.createDefault;

public class RamlSyntaxValidator {

private final FileTreeScannerFactory scannerFactory;

public RamlSyntaxValidator(final FileTreeScannerFactory scannerFactory) {

this.scannerFactory = scannerFactory;

}

public Map<Path, ValidationResult> validateRamls (SyntaxValidatorConfig config) throws IOException {

final String[] includes = config.getIncludes().toArray(new String[config.getIncludes().size()]);
final String[] excludes = config.getExcludes().toArray(new String[config.getExcludes().size()]);

final Collection<Path> paths = scannerFactory.create().find(config.getSourceDirectory(), includes, excludes);

Map<Path, ValidationResult> results = new HashMap<>();

for(Path path : paths) {

List<ValidationResult> tmpResults = validationResults(path, config);

for(ValidationResult result : tmpResults) {
if(result != null) {
results.put(path, result);
}
}
}
return results;
}

private List<ValidationResult> validationResults(Path path, SyntaxValidatorConfig config) {

return createDefault(new FileResourceLoader(config.getSourceDirectory().toFile())).validate(path.toFile().getName());

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package uk.gov.justice.raml.validation.maven;

import java.nio.file.Path;
import java.util.List;

public class SyntaxValidatorConfig {

private final Path sourceDirectory;

private final List<String> includes;

private final List<String> excludes;

public SyntaxValidatorConfig(final Path sourceDirectory,
final List<String> includes,
final List<String> excludes) {
this.sourceDirectory = sourceDirectory;
this.includes = includes;
this.excludes = excludes;
}

public Path getSourceDirectory() {
return sourceDirectory;
}

public List<String> getIncludes() {
return includes;
}

public List<String> getExcludes() {
return excludes;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
public class GenerateMojoTest extends BetterAbstractMojoTestCase {

@Override
protected void setUp() throws Exception {
public void setUp() throws Exception {
super.setUp();
DummyGeneratorCaptor.getInstance().init();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package uk.gov.justice.raml.validation.maven;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.raml.parser.rule.ValidationResult;
import uk.gov.justice.raml.jaxrs.maven.BetterAbstractMojoTestCase;
import uk.gov.justice.raml.jaxrs.maven.GenerateMojo;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.*;

public class RamlSyntaxValidatorMojoTest extends BetterAbstractMojoTestCase {

public void testShouldFindRamlsAndThrowMojoFailureException() throws Exception {

File pom = getTestFile("src/test/resources/validator/bad-schema/pom.xml");

RamlSyntaxCheckMojo mojo = (RamlSyntaxCheckMojo) lookupConfiguredMojo(pom, "check-syntax");

try {
mojo.execute();
fail("Raml and schema validation should have found errors");
} catch (MojoFailureException e) {
//test passed
}
}

public void testShouldFindMultipleRamlsAndThrowMojoFailureException() throws Exception {

File pom = getTestFile("src/test/resources/validator/multiple-ramls/pom.xml");

RamlSyntaxCheckMojo mojo = (RamlSyntaxCheckMojo) lookupConfiguredMojo(pom, "check-syntax");

try {
mojo.execute();
fail("Raml and schema validation should have found errors");
} catch (MojoFailureException e) {
//test passed
}
}

public void testShouldFindRamlButNoErrors() throws Exception {

File pom = getTestFile("src/test/resources/validator/good-raml/pom.xml");

RamlSyntaxCheckMojo mojo = (RamlSyntaxCheckMojo) lookupConfiguredMojo(pom, "check-syntax");

mojo.execute();

}

public void testShouldPassIfNoRamlFound() throws Exception {

File pom = getTestFile("src/test/resources/validator/no-raml/pom.xml");

RamlSyntaxCheckMojo mojo = (RamlSyntaxCheckMojo) lookupConfiguredMojo(pom, "check-syntax");

mojo.execute();
}
}

28 changes: 28 additions & 0 deletions raml-maven-plugin/src/test/resources/validator/bad-schema/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>uk.gov.justice.raml.test</groupId>
<artifactId>project-to-test</artifactId>
<version>1.0.0-SNAPSHOT</version>

<build>
<plugins>
<plugin>
<artifactId>raml-maven-plugin</artifactId>
<groupId>uk.gov.justice.maven</groupId>
<configuration>
<sourceDirectory>src/raml</sourceDirectory>
<!--<includes>-->
<!--<include>**/*.raml</include>-->
<!--</includes>-->
<!--<excludes>-->
<!--<exclude>**/external-ignore.raml</exclude>-->
<!--</excludes>-->
</configuration>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"cakeName": "Eton Mess",
"ingredients": [
{
"name": "custard",
"quantity": 2
},
{
"name": "egg",
"quantity": 6
},
{
"name": "sugar",
"quantity": 500
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"recipeId": "79d0c503-052f-4105-9b05-b49d9c4cf6a2"
}
Loading

0 comments on commit 7add70d

Please sign in to comment.