Search in sources :

Example 11 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class NodePathResolveTestRunner method runChild.

/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 */
@Override
protected void runChild(NodePathResolveTestCase child, RunNotifier notifier) {
    Description description = this.describeChild(child);
    Statement statement = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            String testCP = "fixtures/paths/" + child.getTest();
            URL testUrl = Thread.currentThread().getContextClassLoader().getResource(testCP);
            Assert.assertNotNull(testUrl);
            // Read the test source
            String original = loadResource(testUrl);
            Assert.assertNotNull(original);
            // Parse into a Json object
            Object originalParsed = mapper.readTree(original);
            // Parse into a data model
            Document doc = Library.readDocument(originalParsed);
            Assert.assertNotNull(doc);
            // Parse the test path
            NodePath np = new NodePath(child.getPath());
            // Resolve the path to a node in the source
            Node resolvedNode = np.resolve(doc);
            Assert.assertNotNull(resolvedNode);
            // Compare source path to node path (test generating a node path from a node)
            NodePath createdPath = Library.createNodePath(resolvedNode);
            String expectedPath = child.getPath();
            String actualPath = createdPath.toString();
            Assert.assertEquals(expectedPath, actualPath);
            // Verify that the resolved node is what we expected it to be
            Object actualObj = Library.writeNode(resolvedNode);
            String actual = mapper.writeValueAsString(actualObj);
            String expectedCP = "fixtures/paths/" + child.getTest() + ".expected.json";
            URL expectedUrl = Thread.currentThread().getContextClassLoader().getResource(expectedCP);
            Assert.assertNotNull(testUrl);
            String expected = loadResource(expectedUrl);
            assertJsonEquals(expected, actual);
        }
    };
    runLeaf(statement, description, notifier);
}
Also used : Description(org.junit.runner.Description) Statement(org.junit.runners.model.Statement) Node(io.apicurio.datamodels.core.models.Node) Document(io.apicurio.datamodels.core.models.Document) URL(java.net.URL) NodePath(io.apicurio.datamodels.core.models.NodePath)

Example 12 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class ValidationTestRunner method runChild.

/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 */
@Override
protected void runChild(ValidationTestCase child, RunNotifier notifier) {
    Description description = this.describeChild(child);
    Statement statement = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            String testCP = "fixtures/validation/" + child.getTest();
            URL testUrl = Thread.currentThread().getContextClassLoader().getResource(testCP);
            Assert.assertNotNull("Could not load test resource: " + testCP, testUrl);
            // Read the test source
            String original = loadResource(testUrl);
            Assert.assertNotNull(original);
            // Parse into a Json object
            Object originalParsed = mapper.readTree(original);
            // Parse into a data model
            Document doc = Library.readDocument(originalParsed);
            // Validate the document
            IValidationSeverityRegistry severityRegistry = null;
            if (child.getSeverity() != null) {
                final ValidationProblemSeverity severity = ValidationProblemSeverity.valueOf(child.getSeverity());
                severityRegistry = new IValidationSeverityRegistry() {

                    @Override
                    public ValidationProblemSeverity lookupSeverity(ValidationRuleMetaData rule) {
                        return severity;
                    }
                };
            }
            List<ValidationProblem> problems = Library.validateDocument(doc, severityRegistry, Collections.emptyList()).get();
            // Now compare with expected
            String actual = formatProblems(problems);
            String expectedCP = testCP + ".expected";
            URL expectedUrl = Thread.currentThread().getContextClassLoader().getResource(expectedCP);
            Assert.assertNotNull("Could not load test resource: " + expectedCP, expectedUrl);
            String expected = loadResource(expectedUrl);
            Assert.assertEquals(normalize(expected), normalize(actual));
        }
    };
    runLeaf(statement, description, notifier);
}
Also used : Description(org.junit.runner.Description) Statement(org.junit.runners.model.Statement) ValidationProblem(io.apicurio.datamodels.core.models.ValidationProblem) Document(io.apicurio.datamodels.core.models.Document) URL(java.net.URL) ValidationProblemSeverity(io.apicurio.datamodels.core.models.ValidationProblemSeverity)

Example 13 with Document

use of io.apicurio.datamodels.core.models.Document in project syndesis by syndesisio.

the class OpenApiCustomizer method generateOpenAPIRestDSL.

@SuppressWarnings("PMD.SignatureDeclareThrowsException")
private SourceSpec generateOpenAPIRestDSL(OpenApi openApi) throws Exception {
    final byte[] openApiBytes = openApi.getDocument();
    final Document openApiDoc = Library.readDocumentFromJSONString(new String(openApiBytes, UTF_8));
    if (!(openApiDoc instanceof OasDocument)) {
        throw new IllegalArgumentException(String.format("Unsupported OpenAPI document type: %s - %s", openApiDoc.getClass(), openApiDoc.getDocumentType()));
    }
    final String camelRestDsl = RestDslXmlGenerator.toXml((OasDocument) openApiDoc).generate(new DefaultCamelContext());
    final String content = configuration.getCamelk().isCompression() ? CamelKSupport.compress(camelRestDsl) : camelRestDsl;
    return new SourceSpec.Builder().dataSpec(new DataSpec.Builder().compression(configuration.getCamelk().isCompression()).content(content).name("openapi-routes").build()).language("xml").build();
}
Also used : OasDocument(io.apicurio.datamodels.openapi.models.OasDocument) SourceSpec(io.syndesis.server.controller.integration.camelk.crd.SourceSpec) DataSpec(io.syndesis.server.controller.integration.camelk.crd.DataSpec) Document(io.apicurio.datamodels.core.models.Document) OasDocument(io.apicurio.datamodels.openapi.models.OasDocument) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext)

Example 14 with Document

use of io.apicurio.datamodels.core.models.Document in project syndesis by syndesisio.

the class ProjectGenerator method addRestDefinition.

private void addRestDefinition(TarArchiveOutputStream tos, Integration integration) throws IOException {
    // assuming that we have a single swagger definition for the moment
    Optional<ResourceIdentifier> rid = integration.getResources().stream().filter(Kind.OpenApi::sameAs).findFirst();
    if (!rid.isPresent()) {
        return;
    }
    final ResourceIdentifier openApiResource = rid.get();
    final Optional<String> maybeOpenApiResourceId = openApiResource.getId();
    if (!maybeOpenApiResourceId.isPresent()) {
        return;
    }
    final String openApiResourceId = maybeOpenApiResourceId.get();
    Optional<OpenApi> res = resourceManager.loadOpenApiDefinition(openApiResourceId);
    if (!res.isPresent()) {
        return;
    }
    final byte[] openApiBytes = res.get().getDocument();
    final Document openApiDoc = Library.readDocumentFromJSONString(new String(openApiBytes, StandardCharsets.UTF_8));
    if (!(openApiDoc instanceof OasDocument)) {
        throw new IllegalArgumentException(String.format("Unsupported OpenAPI document type: %s - %s", openApiDoc.getClass(), openApiDoc.getDocumentType()));
    }
    final StringBuilder code = new StringBuilder();
    RestDslGenerator.toAppendable((OasDocument) openApiDoc).withClassName("RestRoute").withPackageName("io.syndesis.example").withoutSourceCodeTimestamps().generate(code);
    addTarEntry(tos, "src/main/java/io/syndesis/example/RestRoute.java", code.toString().getBytes(StandardCharsets.UTF_8));
    addTarEntry(tos, "src/main/java/io/syndesis/example/RestRouteConfiguration.java", ProjectGeneratorHelper.generate(integration, restRoutesMustache));
    addTarEntry(tos, "src/main/resources/openapi.json", openApiBytes);
}
Also used : OasDocument(io.apicurio.datamodels.openapi.models.OasDocument) ResourceIdentifier(io.syndesis.common.model.ResourceIdentifier) Kind(io.syndesis.common.model.Kind) StepKind(io.syndesis.common.model.integration.StepKind) Document(io.apicurio.datamodels.core.models.Document) OasDocument(io.apicurio.datamodels.openapi.models.OasDocument) OpenApi(io.syndesis.common.model.openapi.OpenApi)

Example 15 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-registry by Apicurio.

the class OpenApiOrAsyncApiContentExtractor method extract.

@Override
public ExtractedMetaData extract(ContentHandle content) {
    try {
        Document openApi = Library.readDocumentFromJSONString(content.content());
        MetaDataVisitor viz = new MetaDataVisitor();
        Library.visitTree(openApi, viz, TraverserDirection.down);
        ExtractedMetaData metaData = null;
        if (viz.name != null || viz.description != null) {
            metaData = new ExtractedMetaData();
        }
        if (viz.name != null) {
            metaData.setName(viz.name);
        }
        if (viz.description != null) {
            metaData.setDescription(viz.description);
        }
        return metaData;
    } catch (Exception e) {
        log.warn("Error extracting metadata from Open/Async API: {}", e.getMessage());
        return null;
    }
}
Also used : Document(io.apicurio.datamodels.core.models.Document)

Aggregations

Document (io.apicurio.datamodels.core.models.Document)21 Node (io.apicurio.datamodels.core.models.Node)7 Oas30Document (io.apicurio.datamodels.openapi.v3.models.Oas30Document)7 URL (java.net.URL)7 Description (org.junit.runner.Description)6 Statement (org.junit.runners.model.Statement)6 DocumentType (io.apicurio.datamodels.core.models.DocumentType)5 NodePath (io.apicurio.datamodels.core.models.NodePath)4 ValidationProblem (io.apicurio.datamodels.core.models.ValidationProblem)4 OasDocument (io.apicurio.datamodels.openapi.models.OasDocument)4 Oas20Document (io.apicurio.datamodels.openapi.v2.models.Oas20Document)4 Test (org.junit.Test)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 Aai20Document (io.apicurio.datamodels.asyncapi.v2.models.Aai20Document)2 DataModelReader (io.apicurio.datamodels.core.io.DataModelReader)2 ValidationProblemSeverity (io.apicurio.datamodels.core.models.ValidationProblemSeverity)2 IDocumentValidatorExtension (io.apicurio.datamodels.core.validation.IDocumentValidatorExtension)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 CompletableFuture (java.util.concurrent.CompletableFuture)2