Search in sources :

Example 1 with EventMessage

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

the class AsyncAPIImporter method extractFromAsyncAPI21Example.

/**
 * Extract example using the AsyncAPI 2.1 new 'name' property.
 */
private EventMessage extractFromAsyncAPI21Example(String contentType, JsonNode exampleNode) {
    // Retrieve name & payload value.
    String exampleName = exampleNode.path("name").asText();
    String exampleValue = getExamplePayload(exampleNode);
    // Build and store a request object.
    EventMessage eventMessage = new EventMessage();
    eventMessage.setName(exampleName);
    eventMessage.setContent(exampleValue);
    eventMessage.setMediaType(contentType);
    // Now complete with specified headers.
    List<Header> headers = getExampleHeaders(exampleNode);
    for (Header header : headers) {
        eventMessage.addHeader(header);
    }
    return eventMessage;
}
Also used : EventMessage(io.github.microcks.domain.EventMessage) Header(io.github.microcks.domain.Header)

Example 2 with EventMessage

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

the class AsyncAPIImporter method getMessageDefinitions.

@Override
public List<Exchange> getMessageDefinitions(Service service, Operation operation) throws MockRepositoryImportException {
    List<Exchange> result = new ArrayList<>();
    // Retrieve default content type, defaulting to application/json.
    String defaultContentType = "application/json";
    if (spec.has("defaultContentType")) {
        defaultContentType = spec.get("defaultContentType").asText("application/json");
    }
    // Iterate on specification "channels" nodes.
    Iterator<Entry<String, JsonNode>> channels = spec.path("channels").fields();
    while (channels.hasNext()) {
        Entry<String, JsonNode> channel = channels.next();
        String channelName = channel.getKey();
        Map<String, Map<String, String>> pathParametersByExample = extractParametersByExample(channel.getValue());
        // Iterate on specification path, "verbs" nodes.
        Iterator<Entry<String, JsonNode>> verbs = channel.getValue().fields();
        while (verbs.hasNext()) {
            Entry<String, JsonNode> verb = verbs.next();
            String verbName = verb.getKey();
            // Find the correct operation.
            if (operation.getName().equals(verbName.toUpperCase() + " " + channelName.trim())) {
                JsonNode messageBody = verb.getValue().path("message");
                // If it's a $ref or multi-structure (oneOf, anyOf, allOf), then navigate to them.
                List<JsonNode> messageBodies = followRefsIfAny(messageBody);
                for (JsonNode extractedMsgBody : messageBodies) {
                    // Get message content type.
                    String contentType = defaultContentType;
                    if (extractedMsgBody.has("contentType")) {
                        contentType = extractedMsgBody.path("contentType").asText();
                    }
                    // No need to go further if no examples.
                    if (extractedMsgBody.has("examples")) {
                        Iterator<JsonNode> examples = extractedMsgBody.path("examples").elements();
                        int exampleIndex = 0;
                        while (examples.hasNext()) {
                            JsonNode exampleNode = examples.next();
                            EventMessage eventMessage = null;
                            if (exampleNode.has("name")) {
                                // As of AsyncAPI 2.1.0 () we can now have a 'name' property for examples!
                                eventMessage = extractFromAsyncAPI21Example(contentType, exampleNode);
                            } else if (exampleNode.has("payload")) {
                                // As of https://github.com/microcks/microcks/issues/385, we should support the restriction
                                // coming from AsyncAPI GItHub master revision and associated tooling...
                                eventMessage = extractFromAsyncAPIExample(contentType, exampleNode, channelName.trim() + "-" + exampleIndex);
                            } else {
                                eventMessage = extractFromMicrocksExample(contentType, exampleNode);
                            }
                            // add this event message as a valid event in results exchanges.
                            if (eventMessage != null) {
                                if (DispatchStyles.URI_PARTS.equals(operation.getDispatcher())) {
                                    String resourcePathPattern = channelName;
                                    Map<String, String> parts = pathParametersByExample.get(eventMessage.getName());
                                    String resourcePath = URIBuilder.buildURIFromPattern(resourcePathPattern, parts);
                                    operation.addResourcePath(resourcePath);
                                    eventMessage.setDispatchCriteria(DispatchCriteriaHelper.buildFromPartsMap(parts));
                                }
                                result.add(new UnidirectionalEvent(eventMessage));
                            }
                            exampleIndex++;
                        }
                    }
                }
            }
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) UnidirectionalEvent(io.github.microcks.domain.UnidirectionalEvent) JsonNode(com.fasterxml.jackson.databind.JsonNode) Exchange(io.github.microcks.domain.Exchange) Entry(java.util.Map.Entry) EventMessage(io.github.microcks.domain.EventMessage) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with EventMessage

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

the class ProducerManager method produceAsyncMockMessagesAt.

/**
 * Produce all the async mock messages corresponding to specified frequency.
 * @param frequency The frequency to emit messages for
 */
public void produceAsyncMockMessagesAt(Long frequency) {
    logger.info("Producing async mock messages for frequency: " + frequency);
    Set<AsyncMockDefinition> mockDefinitions = mockRepository.getMockDefinitionsByFrequency(frequency);
    for (AsyncMockDefinition definition : mockDefinitions) {
        logger.debugf("Processing definition of service {%s}", definition.getOwnerService().getName() + ':' + definition.getOwnerService().getVersion());
        for (String binding : definition.getOperation().getBindings().keySet()) {
            // Ensure this minion supports this binding.
            if (Arrays.asList(supportedBindings).contains(binding)) {
                Binding bindingDef = definition.getOperation().getBindings().get(binding);
                switch(BindingType.valueOf(binding)) {
                    case KAFKA:
                        for (EventMessage eventMessage : definition.getEventMessages()) {
                            String topic = kafkaProducerManager.getTopicName(definition, eventMessage);
                            String key = String.valueOf(System.currentTimeMillis());
                            String message = renderEventMessageContent(eventMessage);
                            // Check it Avro binary is expected, we should convert to bytes.
                            if (Constants.AVRO_BINARY_CONTENT_TYPES.contains(eventMessage.getMediaType())) {
                                // Build the name of expected schema.
                                String schemaName = IdBuilder.buildResourceFullName(definition.getOwnerService(), definition.getOperation());
                                String schemaContent = schemaRegistry.getSchemaEntryContent(definition.getOwnerService(), schemaName);
                                try {
                                    if (Constants.REGISTRY_AVRO_ENCODING.equals(defaultAvroEncoding) && kafkaProducerManager.isRegistryEnabled()) {
                                        logger.debug("Using a registry and converting message to Avro record");
                                        GenericRecord avroRecord = AvroUtil.jsonToAvroRecord(message, schemaContent);
                                        kafkaProducerManager.publishMessage(topic, key, avroRecord, kafkaProducerManager.renderEventMessageHeaders(TemplateEngineFactory.getTemplateEngine(), eventMessage.getHeaders()));
                                    } else {
                                        logger.debug("Converting message to Avro bytes array");
                                        byte[] avroBinary = AvroUtil.jsonToAvro(message, schemaContent);
                                        kafkaProducerManager.publishMessage(topic, key, avroBinary, kafkaProducerManager.renderEventMessageHeaders(TemplateEngineFactory.getTemplateEngine(), eventMessage.getHeaders()));
                                    }
                                } catch (Exception e) {
                                    logger.errorf("Exception while converting {%s} to Avro using schema {%s}", message, schemaContent, e);
                                }
                            } else {
                                kafkaProducerManager.publishMessage(topic, key, message, kafkaProducerManager.renderEventMessageHeaders(TemplateEngineFactory.getTemplateEngine(), eventMessage.getHeaders()));
                            }
                        }
                        break;
                    case MQTT:
                        for (EventMessage eventMessage : definition.getEventMessages()) {
                            String topic = mqttProducerManager.getTopicName(definition, eventMessage);
                            String message = renderEventMessageContent(eventMessage);
                            mqttProducerManager.publishMessage(topic, message);
                        }
                        break;
                    case WS:
                        for (EventMessage eventMessage : definition.getEventMessages()) {
                            String channel = wsProducerManager.getRequestURI(definition, eventMessage);
                            String message = renderEventMessageContent(eventMessage);
                            wsProducerManager.publishMessage(channel, message, eventMessage.getHeaders());
                        }
                        break;
                    case AMQP:
                        for (EventMessage eventMessage : definition.getEventMessages()) {
                            String destinationName = amqpProducerManager.getDestinationName(definition, eventMessage);
                            String message = renderEventMessageContent(eventMessage);
                            amqpProducerManager.publishMessage(bindingDef.getDestinationType(), destinationName, message, amqpProducerManager.renderEventMessageHeaders(TemplateEngineFactory.getTemplateEngine(), eventMessage.getHeaders()));
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
Also used : Binding(io.github.microcks.domain.Binding) EventMessage(io.github.microcks.domain.EventMessage) GenericRecord(org.apache.avro.generic.GenericRecord) AsyncMockDefinition(io.github.microcks.minion.async.AsyncMockDefinition)

Example 4 with EventMessage

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

the class AsyncAPIImporter method extractFromAsyncAPIExample.

/**
 * Extract example using the AsyncAPI master branch restrictions.
 */
private EventMessage extractFromAsyncAPIExample(String contentType, JsonNode exampleNode, String exampleName) {
    // Retrieve payload value.
    String exampleValue = getExamplePayload(exampleNode);
    // Build and store a request object.
    EventMessage eventMessage = new EventMessage();
    eventMessage.setName(exampleName);
    eventMessage.setContent(exampleValue);
    eventMessage.setMediaType(contentType);
    // Now complete with specified headers.
    List<Header> headers = getExampleHeaders(exampleNode);
    for (Header header : headers) {
        eventMessage.addHeader(header);
    }
    return eventMessage;
}
Also used : EventMessage(io.github.microcks.domain.EventMessage) Header(io.github.microcks.domain.Header)

Example 5 with EventMessage

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

the class AsyncAPIImporter method extractFromMicrocksExample.

/**
 * Extract example using the Microcks (and Apicurio) extended notation.
 */
private EventMessage extractFromMicrocksExample(String contentType, JsonNode exampleNode) {
    EventMessage eventMessage = null;
    Iterator<String> exampleNames = exampleNode.fieldNames();
    while (exampleNames.hasNext()) {
        String exampleName = exampleNames.next();
        JsonNode example = exampleNode.path(exampleName);
        // No need to go further if no payload.
        if (example.has("payload")) {
            String exampleValue = getExamplePayload(example);
            // Build and store a request object.
            eventMessage = new EventMessage();
            eventMessage.setName(exampleName);
            eventMessage.setContent(exampleValue);
            eventMessage.setMediaType(contentType);
            // Now complete with specified headers.
            List<Header> headers = getExampleHeaders(example);
            for (Header header : headers) {
                eventMessage.addHeader(header);
            }
        }
    }
    return eventMessage;
}
Also used : EventMessage(io.github.microcks.domain.EventMessage) Header(io.github.microcks.domain.Header) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Aggregations

EventMessage (io.github.microcks.domain.EventMessage)5 Header (io.github.microcks.domain.Header)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Binding (io.github.microcks.domain.Binding)1 Exchange (io.github.microcks.domain.Exchange)1 UnidirectionalEvent (io.github.microcks.domain.UnidirectionalEvent)1 AsyncMockDefinition (io.github.microcks.minion.async.AsyncMockDefinition)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 GenericRecord (org.apache.avro.generic.GenericRecord)1