Search in sources :

Example 1 with Metadata

use of io.github.microcks.domain.Metadata in project microcks by microcks.

the class JobController method createJob.

@RequestMapping(value = "/jobs", method = RequestMethod.POST)
public ResponseEntity<ImportJob> createJob(@RequestBody ImportJob job) {
    log.debug("Creating new job: {}", job);
    job.setMetadata(new Metadata());
    job.setCreatedDate(new Date());
    return new ResponseEntity<>(jobRepository.save(job), HttpStatus.CREATED);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) Metadata(io.github.microcks.domain.Metadata) Date(java.util.Date) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with Metadata

use of io.github.microcks.domain.Metadata in project microcks by microcks.

the class MetadataImporter method getServiceDefinitions.

@Override
public List<Service> getServiceDefinitions() throws MockRepositoryImportException {
    List<Service> result = new ArrayList<>();
    // Build a new service.
    Service service = new Service();
    JsonNode metadataNode = spec.get("metadata");
    if (metadataNode == null) {
        log.error("Missing mandatory metadata in {}", spec.asText());
        throw new MockRepositoryImportException("Mandatory metadata property is missing in APIMetadata");
    }
    service.setName(metadataNode.path("name").asText());
    service.setVersion(metadataNode.path("version").asText());
    Metadata metadata = new Metadata();
    MetadataExtractor.completeMetadata(metadata, metadataNode);
    service.setMetadata(metadata);
    // Then build its operations.
    service.setOperations(extractOperations());
    result.add(service);
    return result;
}
Also used : ArrayList(java.util.ArrayList) Metadata(io.github.microcks.domain.Metadata) Service(io.github.microcks.domain.Service) JsonNode(com.fasterxml.jackson.databind.JsonNode) MockRepositoryImportException(io.github.microcks.util.MockRepositoryImportException)

Example 3 with Metadata

use of io.github.microcks.domain.Metadata in project microcks by microcks.

the class ServiceService method createGenericResourceService.

/**
 * Create a new Service concerning a GenericResource for dynamic mocking.
 * @param name The name of the new Service to create
 * @param version The version of the new Service to create
 * @param resource The resource that will be exposed as CRUD operations for this service
 * @return The newly created Service object
 * @throws EntityAlreadyExistsException if a Service with same name and version is already present in store
 */
public Service createGenericResourceService(String name, String version, String resource) throws EntityAlreadyExistsException {
    log.info("Creating a new Service '{}-{}' for generic resource {}", name, version, resource);
    // Check if corresponding Service already exists.
    Service existingService = serviceRepository.findByNameAndVersion(name, version);
    if (existingService != null) {
        log.warn("A Service '{}-{}' is already existing. Throwing an Exception", name, version);
        throw new EntityAlreadyExistsException(String.format("Service '%s-%s' is already present in store", name, version));
    }
    // Create new service with GENERIC_REST type.
    Service service = new Service();
    service.setName(name);
    service.setVersion(version);
    service.setType(ServiceType.GENERIC_REST);
    service.setMetadata(new Metadata());
    // Now create basic crud operations for the resource.
    Operation createOp = new Operation();
    createOp.setName("POST /" + resource);
    createOp.setMethod("POST");
    service.addOperation(createOp);
    Operation getOp = new Operation();
    getOp.setName("GET /" + resource + "/:id");
    getOp.setMethod("GET");
    getOp.setDispatcher(DispatchStyles.URI_PARTS);
    getOp.setDispatcherRules("id");
    service.addOperation(getOp);
    Operation updateOp = new Operation();
    updateOp.setName("PUT /" + resource + "/:id");
    updateOp.setMethod("PUT");
    updateOp.setDispatcher(DispatchStyles.URI_PARTS);
    updateOp.setDispatcherRules("id");
    service.addOperation(updateOp);
    Operation listOp = new Operation();
    listOp.setName("GET /" + resource);
    listOp.setMethod("GET");
    service.addOperation(listOp);
    Operation delOp = new Operation();
    delOp.setName("DELETE /" + resource + "/:id");
    delOp.setMethod("DELETE");
    delOp.setDispatcher(DispatchStyles.URI_PARTS);
    delOp.setDispatcherRules("id");
    service.addOperation(delOp);
    serviceRepository.save(service);
    log.info("Having create Service '{}' for generic resource {}", service.getId(), resource);
    return service;
}
Also used : EntityAlreadyExistsException(io.github.microcks.util.EntityAlreadyExistsException) Metadata(io.github.microcks.domain.Metadata) Service(io.github.microcks.domain.Service) Operation(io.github.microcks.domain.Operation)

Example 4 with Metadata

use of io.github.microcks.domain.Metadata in project microcks by microcks.

the class ServiceService method importServiceDefinition.

/**
 * Import definitions of services and bounded resources and messages into Microcks
 * repository. This uses a MockRepositoryImporter under hood.
 * @param repositoryFile The File for mock repository.
 * @param referenceResolver The Resolver to be used during import (may be null).
 * @param artifactInfo The essential information on Artifact to import.
 * @return The list of imported Services
 * @throws MockRepositoryImportException if something goes wrong (URL not reachable nor readable, etc...)
 */
public List<Service> importServiceDefinition(File repositoryFile, ReferenceResolver referenceResolver, ArtifactInfo artifactInfo) throws MockRepositoryImportException {
    // Retrieve the correct importer based on file path.
    MockRepositoryImporter importer = null;
    try {
        importer = MockRepositoryImporterFactory.getMockRepositoryImporter(repositoryFile, referenceResolver);
    } catch (IOException ioe) {
        log.error("Exception while accessing file " + repositoryFile.getPath(), ioe);
        throw new MockRepositoryImportException(ioe.getMessage(), ioe);
    }
    Service reference = null;
    boolean serviceUpdate = false;
    List<Service> services = importer.getServiceDefinitions();
    for (Service service : services) {
        Service existingService = serviceRepository.findByNameAndVersion(service.getName(), service.getVersion());
        log.debug("Service [{}, {}] exists ? {}", service.getName(), service.getVersion(), existingService != null);
        // If it's the main artifact: retrieve previous id and props if update, save anyway.
        if (artifactInfo.isMainArtifact()) {
            if (existingService != null) {
                // Retrieve its previous identifier and metadatas
                // (backup metadata that may have been imported with extensions).
                Metadata backup = service.getMetadata();
                service.setId(existingService.getId());
                service.setMetadata(existingService.getMetadata());
                // If there was metadata found through extensions, overwrite historical ones.
                if (backup != null) {
                    existingService.getMetadata().setLabels(backup.getLabels());
                    existingService.getMetadata().setAnnotations(backup.getAnnotations());
                }
                // Keep its overriden operation properties.
                copyOverridenOperations(existingService, service);
                serviceUpdate = true;
            }
            if (service.getMetadata() == null) {
                service.setMetadata(new Metadata());
            }
            // For services of type EVENT, we should put default values on frequency and bindings.
            if (service.getType().equals(ServiceType.EVENT)) {
                manageEventServiceDefaults(service);
            }
            service.getMetadata().objectUpdated();
            service.setSourceArtifact(artifactInfo.getArtifactName());
            service = serviceRepository.save(service);
            // We're dealing with main artifact so reference is saved or updated one.
            reference = service;
        } else {
            // It's a secondary artifact just for messages or metadata. We'll have problems if not having an existing service...
            if (existingService == null) {
                log.warn("Trying to import {} as a secondary artifact but there's no existing [{}, {}] Service. Just skipping.", artifactInfo.getArtifactName(), service.getName(), service.getVersion());
                break;
            }
            // update the existing service with them.
            if (service.getMetadata() != null) {
                existingService.getMetadata().setLabels(service.getMetadata().getLabels());
                existingService.getMetadata().setAnnotations(service.getMetadata().getAnnotations());
            }
            for (Operation operation : service.getOperations()) {
                Operation existingOp = existingService.getOperations().stream().filter(op -> op.getName().equals(operation.getName())).findFirst().orElse(null);
                if (existingOp != null) {
                    if (operation.getDefaultDelay() != null) {
                        existingOp.setDefaultDelay(operation.getDefaultDelay());
                    }
                    if (operation.getDispatcher() != null) {
                        existingOp.setDispatcher(operation.getDispatcher());
                    }
                    if (operation.getDispatcherRules() != null) {
                        existingOp.setDispatcherRules(operation.getDispatcherRules());
                    }
                }
            }
            // We're dealing with secondary artifact so reference is the pre-existing one.
            // Moreover, we should replace current imported service (unbound/unsaved)
            // by reference in the results list.
            reference = existingService;
            services.remove(service);
            services.add(reference);
        }
        // Remove resources previously attached to service.
        List<Resource> existingResources = resourceRepository.findByServiceIdAndSourceArtifact(reference.getId(), artifactInfo.getArtifactName());
        if (existingResources != null && existingResources.size() > 0) {
            resourceRepository.deleteAll(existingResources);
        }
        // Save new resources.
        List<Resource> resources = importer.getResourceDefinitions(service);
        for (Resource resource : resources) {
            resource.setServiceId(reference.getId());
            resource.setSourceArtifact(artifactInfo.getArtifactName());
        }
        resourceRepository.saveAll(resources);
        for (Operation operation : reference.getOperations()) {
            String operationId = IdBuilder.buildOperationId(reference, operation);
            // Remove messages previously attached to service.
            requestRepository.deleteAll(requestRepository.findByOperationIdAndSourceArtifact(operationId, artifactInfo.getArtifactName()));
            responseRepository.deleteAll(responseRepository.findByOperationIdAndSourceArtifact(operationId, artifactInfo.getArtifactName()));
            eventMessageRepository.deleteAll(eventMessageRepository.findByOperationIdAndSourceArtifact(operationId, artifactInfo.getArtifactName()));
            List<Exchange> exchanges = importer.getMessageDefinitions(service, operation);
            for (Exchange exchange : exchanges) {
                if (exchange instanceof RequestResponsePair) {
                    RequestResponsePair pair = (RequestResponsePair) exchange;
                    // Associate request and response with operation and artifact.
                    pair.getRequest().setOperationId(operationId);
                    pair.getResponse().setOperationId(operationId);
                    pair.getRequest().setSourceArtifact(artifactInfo.getArtifactName());
                    pair.getResponse().setSourceArtifact(artifactInfo.getArtifactName());
                    // Save response and associate request with response before saving it.
                    responseRepository.save(pair.getResponse());
                    pair.getRequest().setResponseId(pair.getResponse().getId());
                    requestRepository.save(pair.getRequest());
                } else if (exchange instanceof UnidirectionalEvent) {
                    UnidirectionalEvent event = (UnidirectionalEvent) exchange;
                    // Associate event message with operation and artifact before saving it..
                    event.getEventMessage().setOperationId(operationId);
                    event.getEventMessage().setSourceArtifact(artifactInfo.getArtifactName());
                    eventMessageRepository.save(event.getEventMessage());
                }
            }
        }
        // When extracting message information, we may have modified Operation because discovered new resource paths
        // depending on variable URI parts. As a consequence, we got to update Service in repository.
        serviceRepository.save(reference);
        // Publish a Service update event before returning.
        publishServiceChangeEvent(reference, serviceUpdate ? ChangeType.UPDATED : ChangeType.CREATED);
    }
    log.info("Having imported {} services definitions into repository", services.size());
    return services;
}
Also used : RequestResponsePair(io.github.microcks.domain.RequestResponsePair) Metadata(io.github.microcks.domain.Metadata) Resource(io.github.microcks.domain.Resource) UnidirectionalEvent(io.github.microcks.domain.UnidirectionalEvent) Service(io.github.microcks.domain.Service) MockRepositoryImporter(io.github.microcks.util.MockRepositoryImporter) IOException(java.io.IOException) Operation(io.github.microcks.domain.Operation) MockRepositoryImportException(io.github.microcks.util.MockRepositoryImportException) Exchange(io.github.microcks.domain.Exchange)

Example 5 with Metadata

use of io.github.microcks.domain.Metadata in project microcks by microcks.

the class AsyncAPIImporter method getServiceDefinitions.

@Override
public List<Service> getServiceDefinitions() throws MockRepositoryImportException {
    List<Service> result = new ArrayList<>();
    // Build a new service.
    Service service = new Service();
    service.setName(spec.path("info").path("title").asText());
    service.setVersion(spec.path("info").path("version").asText());
    service.setType(ServiceType.EVENT);
    // Complete metadata if specified via extension.
    if (spec.path("info").has(MetadataExtensions.MICROCKS_EXTENSION)) {
        Metadata metadata = new Metadata();
        MetadataExtractor.completeMetadata(metadata, spec.path("info").path(MetadataExtensions.MICROCKS_EXTENSION));
        service.setMetadata(metadata);
    }
    // Then build its operations.
    service.setOperations(extractOperations());
    result.add(service);
    return result;
}
Also used : ArrayList(java.util.ArrayList) Metadata(io.github.microcks.domain.Metadata) Service(io.github.microcks.domain.Service)

Aggregations

Metadata (io.github.microcks.domain.Metadata)5 Service (io.github.microcks.domain.Service)4 Operation (io.github.microcks.domain.Operation)2 MockRepositoryImportException (io.github.microcks.util.MockRepositoryImportException)2 ArrayList (java.util.ArrayList)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 Exchange (io.github.microcks.domain.Exchange)1 RequestResponsePair (io.github.microcks.domain.RequestResponsePair)1 Resource (io.github.microcks.domain.Resource)1 UnidirectionalEvent (io.github.microcks.domain.UnidirectionalEvent)1 EntityAlreadyExistsException (io.github.microcks.util.EntityAlreadyExistsException)1 MockRepositoryImporter (io.github.microcks.util.MockRepositoryImporter)1 IOException (java.io.IOException)1 Date (java.util.Date)1 ResponseEntity (org.springframework.http.ResponseEntity)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1