use of io.github.microcks.domain.Service in project microcks by microcks.
the class ProtobufImporterTest method testSimpleProtobufImport.
@Test
public void testSimpleProtobufImport() {
ProtobufImporter importer = null;
try {
importer = new ProtobufImporter("target/test-classes/io/github/microcks/util/grpc/hello-v1.proto", null);
} catch (IOException ioe) {
fail("Exception should not be thrown");
}
// Check that basic service properties are there.
List<Service> services = null;
try {
services = importer.getServiceDefinitions();
} catch (MockRepositoryImportException e) {
fail("Service definition import should not fail");
}
assertEquals(1, services.size());
Service service = services.get(0);
assertEquals("HelloService", service.getName());
assertEquals(ServiceType.GRPC, service.getType());
assertEquals("v1", service.getVersion());
assertEquals("io.github.microcks.grpc.hello.v1", service.getXmlNS());
// Check that resources have been parsed, correctly renamed, etc...
List<Resource> resources = null;
try {
resources = importer.getResourceDefinitions(service);
} catch (MockRepositoryImportException mrie) {
fail("Resource definition import should not fail");
}
assertEquals(2, resources.size());
for (Resource resource : resources) {
assertNotNull(resource.getContent());
if (ResourceType.PROTOBUF_SCHEMA.equals(resource.getType())) {
assertEquals("HelloService-v1.proto", resource.getName());
} else if (ResourceType.PROTOBUF_DESCRIPTOR.equals(resource.getType())) {
assertEquals("HelloService-v1.pbb", resource.getName());
} else {
fail("Resource has not the expected type");
}
}
// Check that operations and input/output have been found.
assertEquals(1, service.getOperations().size());
Operation operation = service.getOperations().get(0);
assertEquals("greeting", operation.getName());
assertEquals(".io.github.microcks.grpc.hello.v1.HelloRequest", operation.getInputName());
assertEquals(".io.github.microcks.grpc.hello.v1.HelloResponse", operation.getOutputName());
}
use of io.github.microcks.domain.Service in project microcks by microcks.
the class MetadataImporterTest method testAPIMetadataImport.
@Test
public void testAPIMetadataImport() {
MetadataImporter importer = null;
try {
importer = new MetadataImporter("target/test-classes/io/github/microcks/util/metadata/hello-grpc-v1-metadata.yml");
} catch (IOException ioe) {
ioe.printStackTrace();
fail("Exception should not be thrown");
}
// Check that basic service properties are there.
List<Service> services = null;
try {
services = importer.getServiceDefinitions();
} catch (MockRepositoryImportException e) {
fail("Exception should not be thrown");
}
assertEquals(1, services.size());
Service service = services.get(0);
assertEquals("HelloService", service.getName());
assertEquals("v1", service.getVersion());
assertEquals(3, service.getMetadata().getLabels().size());
assertEquals("greeting", service.getMetadata().getLabels().get("domain"));
assertEquals("stable", service.getMetadata().getLabels().get("status"));
assertEquals("Team A", service.getMetadata().getLabels().get("team"));
assertEquals(1, service.getOperations().size());
Operation operation = service.getOperations().get(0);
assertEquals("POST /greeting", operation.getName());
assertEquals(Long.valueOf(100), operation.getDefaultDelay());
assertEquals(DispatchStyles.JSON_BODY, operation.getDispatcher());
assertNotNull(operation.getDispatcherRules());
}
use of io.github.microcks.domain.Service in project microcks by microcks.
the class ServiceController method getService.
@RequestMapping(value = "/services/{id:.+}", method = RequestMethod.GET)
public ResponseEntity<?> getService(@PathVariable("id") String serviceId, @RequestParam(value = "messages", required = false, defaultValue = "true") boolean messages) {
log.debug("Retrieving service with id {}", serviceId);
Service service = null;
// serviceId may have the form of <service_name>:<service_version>
if (serviceId.contains(":")) {
String name = serviceId.substring(0, serviceId.indexOf(':'));
String version = serviceId.substring(serviceId.indexOf(':') + 1);
// If service name was encoded with '+' instead of '%20', replace them.
if (name.contains("+")) {
name = name.replace('+', ' ');
}
service = serviceRepository.findByNameAndVersion(name, version);
} else {
service = serviceRepository.findById(serviceId).orElse(null);
}
if (messages) {
// Put messages into a map where key is operation name.
Map<String, List<? extends Exchange>> messagesMap = new HashMap<>();
for (Operation operation : service.getOperations()) {
if (service.getType() == ServiceType.EVENT) {
// If an event, we should explicitly retrieve event messages.
List<UnidirectionalEvent> events = messageService.getEventByOperation(IdBuilder.buildOperationId(service, operation));
messagesMap.put(operation.getName(), events);
} else {
// Otherwise we have traditional request / response pairs.
List<RequestResponsePair> pairs = messageService.getRequestResponseByOperation(IdBuilder.buildOperationId(service, operation));
messagesMap.put(operation.getName(), pairs);
}
}
return new ResponseEntity<>(new ServiceView(service, messagesMap), HttpStatus.OK);
}
return new ResponseEntity<>(service, HttpStatus.OK);
}
use of io.github.microcks.domain.Service in project microcks by microcks.
the class SoapController method execute.
@RequestMapping(value = "/{service}/{version}/**", method = RequestMethod.POST)
public ResponseEntity<?> execute(@PathVariable("service") String serviceName, @PathVariable("version") String version, @RequestParam(value = "validate", required = false) Boolean validate, @RequestParam(value = "delay", required = false) Long delay, @RequestBody String body, HttpServletRequest request) {
log.info("Servicing mock response for service [{}, {}]", serviceName, version);
log.debug("Request body: " + body);
long startTime = System.currentTimeMillis();
// If serviceName was encoded with '+' instead of '%20', replace them.
if (serviceName.contains("+")) {
serviceName = serviceName.replace('+', ' ');
}
log.info("Service name: " + serviceName);
// Retrieve service and correct operation.
Service service = serviceRepository.findByNameAndVersion(serviceName, version);
Operation rOperation = null;
// Enhancement : retrieve SOAPAction from request headers
String action = extractSoapAction(request);
log.debug("Extracted SOAP action from headers: {}", action);
if (action != null && action.length() > 0) {
for (Operation operation : service.getOperations()) {
if (action.equals(operation.getAction())) {
rOperation = operation;
log.info("Found valid operation {}", rOperation.getName());
break;
}
}
}
// Enhancement : if not found, try getting operation from soap:body directly!
if (rOperation == null) {
String operationName = extractOperationName(body);
log.debug("Extracted operation name from payload: {}", operationName);
if (operationName != null) {
for (Operation operation : service.getOperations()) {
if (operationName.equals(operation.getInputName()) || operationName.equals(operation.getName())) {
rOperation = operation;
log.info("Found valid operation {}", rOperation.getName());
break;
}
}
}
}
// Now processing the request and send a response.
if (rOperation != null) {
log.debug("Found a valid operation with rules: {}", rOperation.getDispatcherRules());
if (validate != null && validate) {
log.debug("Soap message validation is turned on, validating...");
try {
List<XmlError> errors = SoapMessageValidator.validateSoapMessage(rOperation.getInputName(), service.getXmlNS(), body, resourceUrl + UriUtils.encodePath(service.getName() + "-" + version, "UTF-8") + ".wsdl", true);
log.debug("SoapBody validation errors: " + errors.size());
// Return a 400 http code with errors.
if (errors != null && errors.size() > 0) {
return new ResponseEntity<Object>(errors, HttpStatus.BAD_REQUEST);
}
} catch (Exception e) {
log.error("Error during Soap validation", e);
return new ResponseEntity<Object>("Error during Soap validation: " + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
// We must find dispatcher and its rules. Default to operation ones but
// if we have a Fallback this is the one who is holding the first pass rules.
String dispatcher = rOperation.getDispatcher();
String dispatcherRules = rOperation.getDispatcherRules();
FallbackSpecification fallback = MockControllerCommons.getFallbackIfAny(rOperation);
if (fallback != null) {
dispatcher = fallback.getDispatcher();
dispatcherRules = fallback.getDispatcherRules();
}
Response response = null;
String dispatchCriteria = null;
// Depending on dispatcher, evaluate request with rules.
if (DispatchStyles.QUERY_MATCH.equals(dispatcher)) {
dispatchCriteria = getDispatchCriteriaFromXPathEval(dispatcherRules, body);
} else if (DispatchStyles.SCRIPT.equals(dispatcher)) {
dispatchCriteria = getDispatchCriteriaFromScriptEval(dispatcherRules, body, request);
}
log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
if (responses.isEmpty() && fallback != null) {
// If we've found nothing and got a fallback, that's the moment!
responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), fallback.getFallback());
}
if (!responses.isEmpty()) {
response = responses.get(0);
}
// Set Content-Type to "text/xml".
HttpHeaders responseHeaders = new HttpHeaders();
// Check to see if we are processing a SOAP 1.2 request
if (request.getContentType().startsWith("application/soap+xml")) {
// we are; set Content-Type to "application/soap+xml"
responseHeaders.setContentType(MediaType.valueOf("application/soap+xml;charset=UTF-8"));
} else {
// Set Content-Type to "text/xml".
responseHeaders.setContentType(MediaType.valueOf("text/xml;charset=UTF-8"));
}
// Render response content before waiting and returning.
String responseContent = MockControllerCommons.renderResponseContent(body, null, request, response);
// Setting delay to default one if not set.
if (delay == null && rOperation.getDefaultDelay() != null) {
delay = rOperation.getDefaultDelay();
}
MockControllerCommons.waitForDelay(startTime, delay);
// Publish an invocation event before returning if enabled.
if (enableInvocationStats) {
MockControllerCommons.publishMockInvocation(applicationContext, this, service, response, startTime);
}
if (response.isFault()) {
return new ResponseEntity<Object>(responseContent, responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<Object>(responseContent, responseHeaders, HttpStatus.OK);
}
log.debug("No valid operation found by Microcks...");
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
use of io.github.microcks.domain.Service in project microcks by microcks.
the class JobService method doImportJob.
/**
* Realize the import of a repository defined into an import job.
* @param job The job containing information onto the repository.
*/
public void doImportJob(ImportJob job) {
log.info("Starting import for job '{}'", job.getName());
// Retrieve associated secret if any.
Secret jobSecret = null;
if (job.getSecretRef() != null) {
log.debug("Retrieving secret {} for job {}", job.getSecretRef().getName(), job.getName());
jobSecret = secretRepository.findById(job.getSecretRef().getSecretId()).orElse(null);
}
// Reinitialize service references and import errors before new import.
job.setServiceRefs(null);
job.setLastImportError(null);
List<Service> services = null;
try {
services = serviceService.importServiceDefinition(job.getRepositoryUrl(), jobSecret, job.isRepositoryDisableSSLValidation(), job.isMainArtifact());
} catch (MockRepositoryImportException mrie) {
log.warn("MockRepositoryImportException while importing job '{}' : {}", job.getName(), mrie.getMessage());
job.setLastImportError(mrie.getMessage());
}
// Add service references if any.
if (services != null) {
for (Service service : services) {
job.addServiceRef(new ServiceRef(service.getId(), service.getName(), service.getVersion()));
}
}
job.setLastImportDate(new Date());
jobRepository.save(job);
log.info("Import of job '{}' done", job.getName());
}
Aggregations