Search in sources :

Example 1 with Service

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

the class ResourceController method getServiceResource.

@RequestMapping(value = "/resources/{serviceId}/{resourceType}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getServiceResource(@PathVariable("serviceId") String serviceId, @PathVariable("resourceType") String resourceType, HttpServletResponse response) {
    log.info("Requesting {} resource for service {}", resourceType, serviceId);
    Service service = serviceRepository.findById(serviceId).orElse(null);
    if (service != null && ServiceType.GENERIC_REST.equals(service.getType())) {
        // Prepare HttpHeaders.
        InputStream stream = null;
        String resource = findResource(service);
        HttpHeaders headers = new HttpHeaders();
        // Get the correct template depending on resource type.
        if (SWAGGER_20.equals(resourceType)) {
            org.springframework.core.io.Resource template = new ClassPathResource("templates/swagger-2.0.json");
            try {
                stream = template.getInputStream();
            } catch (IOException e) {
                log.error("IOException while reading swagger-2.0.json template", e);
            }
            headers.setContentType(MediaType.APPLICATION_JSON);
        } else if (OPENAPI_30.equals(resourceType)) {
            org.springframework.core.io.Resource template = new ClassPathResource("templates/openapi-3.0.yaml");
            try {
                stream = template.getInputStream();
            } catch (IOException e) {
                log.error("IOException while reading openapi-3.0.yaml template", e);
            }
            headers.set("Content-Type", "text/yaml");
        }
        // Now process the stream, replacing patterns by value.
        if (stream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringWriter writer = new StringWriter();
            try (Stream<String> lines = reader.lines()) {
                lines.map(line -> replaceInLine(line, service, resource)).forEach(line -> writer.write(line + "\n"));
            }
            return new ResponseEntity<>(writer.toString().getBytes(), headers, HttpStatus.OK);
        }
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) URLDecoder(java.net.URLDecoder) LoggerFactory(org.slf4j.LoggerFactory) ClassPathResource(org.springframework.core.io.ClassPathResource) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ServiceRepository(io.github.microcks.repository.ServiceRepository) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContentDisposition(org.springframework.http.ContentDisposition) Resource(io.github.microcks.domain.Resource) ResourceRepository(io.github.microcks.repository.ResourceRepository) Logger(org.slf4j.Logger) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) StandardCharsets(java.nio.charset.StandardCharsets) HttpStatus(org.springframework.http.HttpStatus) Service(io.github.microcks.domain.Service) List(java.util.List) Stream(java.util.stream.Stream) Operation(io.github.microcks.domain.Operation) ServiceType(io.github.microcks.domain.ServiceType) java.io(java.io) ResponseEntity(org.springframework.http.ResponseEntity) HttpHeaders(org.springframework.http.HttpHeaders) java.io(java.io) ClassPathResource(org.springframework.core.io.ClassPathResource) Resource(io.github.microcks.domain.Resource) Service(io.github.microcks.domain.Service) ClassPathResource(org.springframework.core.io.ClassPathResource) ResponseEntity(org.springframework.http.ResponseEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with Service

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

the class RestController method execute.

@RequestMapping(value = "/{service}/{version}/**", method = { RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE })
public ResponseEntity<?> execute(@PathVariable("service") String serviceName, @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay, @RequestBody(required = false) String body, HttpServletRequest request) {
    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version, request.getRequestURI(), request.getMethod());
    log.debug("Request body: {}", body);
    long startTime = System.currentTimeMillis();
    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;
    // Build the encoded URI fragment to retrieve simple resourcePath.
    serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
    resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    // resourcePath = UriUtils.decode(resourcePath, "UTF-8");
    log.debug("Found resourcePath: {}", resourcePath);
    // If serviceName was encoded with '+' instead of '%20', remove them.
    if (serviceName.contains("+")) {
        serviceName = serviceName.replace('+', ' ');
    }
    // If resourcePath was encoded with '+' instead of '%20', replace them .
    if (resourcePath.contains("+")) {
        resourcePath = resourcePath.replace("+", "%20");
    }
    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths() != null && operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }
    // using a Fallback dispatcher. Try again, just considering the verb and path pattern of operation.
    if (rOperation == null) {
        for (Operation operation : service.getOperations()) {
            // Select operation based onto Http verb (GET, POST, PUT, etc ...)
            if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
                // ... then check is current resource path matches operation path pattern.
                if (operation.getResourcePaths() != null) {
                    // Produce a matching regexp removing {part} and :part from pattern.
                    String operationPattern = getURIPattern(operation.getName());
                    operationPattern = operationPattern.replaceAll("\\{.+\\}", "(.)+");
                    operationPattern = operationPattern.replaceAll("(/:[^:^/]+)", "\\/(.+)");
                    if (resourcePath.matches(operationPattern)) {
                        rOperation = operation;
                        break;
                    }
                }
            }
        }
    }
    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(), rOperation.getDispatcherRules());
        String violationMsg = validateParameterConstraintsIfAny(rOperation, request);
        if (violationMsg != null) {
            return new ResponseEntity<Object>(violationMsg + ". Check parameter constraints.", 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();
        }
        // 
        String dispatchCriteria = computeDispatchCriteria(dispatcher, dispatcherRules, getURIPattern(rOperation.getName()), UriUtils.decode(resourcePath, "UTF-8"), request, body);
        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        Response response = null;
        // Filter depending on requested media type.
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        response = getResponseByMediaType(responses, request);
        if (response == null) {
            // When using the SCRIPT or JSON_BODY dispatchers, return of evaluation may be the name of response.
            responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
            response = getResponseByMediaType(responses, request);
        }
        if (response == null && fallback != null) {
            // If we've found nothing and got a fallback, that's the moment!
            responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), fallback.getFallback());
            response = getResponseByMediaType(responses, request);
        }
        if (response == null) {
            // In case no response found (because dispatcher is null for example), just get one for the operation.
            // This will allow also OPTIONS operations (like pre-flight requests) with no dispatch criteria to work.
            log.debug("No responses found so far, tempting with just bare operationId...");
            responses = responseRepository.findByOperationId(IdBuilder.buildOperationId(service, rOperation));
            if (!responses.isEmpty()) {
                response = getResponseByMediaType(responses, request);
            }
        }
        if (response != null) {
            HttpStatus status = (response.getStatus() != null ? HttpStatus.valueOf(Integer.parseInt(response.getStatus())) : HttpStatus.OK);
            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }
            // Deal with headers from parameter constraints if any?
            recopyHeadersFromParameterConstraints(rOperation, request, responseHeaders);
            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/rest" + serviceAndVersion + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            // Render response content before waiting and returning.
            String responseContent = MockControllerCommons.renderResponseContent(body, resourcePath, 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);
            }
            return new ResponseEntity<Object>(responseContent, responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    } else // Handle OPTIONS request if CORS policy is enabled.
    if (enableCorsPolicy && "OPTIONS".equals(request.getMethod().toUpperCase())) {
        log.debug("No valid operation found but Microcks configured to apply CORS policy");
        return handleCorsRequest(request);
    }
    log.debug("No valid operation found and Microcks configured to not apply CORS policy...");
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
Also used : Response(io.github.microcks.domain.Response) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) Header(io.github.microcks.domain.Header) FallbackSpecification(io.github.microcks.util.dispatcher.FallbackSpecification) HttpStatus(org.springframework.http.HttpStatus) Service(io.github.microcks.domain.Service) Operation(io.github.microcks.domain.Operation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with Service

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

the class ServiceRepositoryTest method setUp.

@Before
public void setUp() {
    // Create a bunch of services...
    Service service = new Service();
    service.setName("HelloWorld");
    service.setVersion("1.2");
    repository.save(service);
    // with same name and different version ...
    service = new Service();
    service.setName("HelloWorld");
    service.setVersion("1.1");
    repository.save(service);
    // with different name ...
    service = new Service();
    service.setName("MyService-hello");
    service.setVersion("1.1");
    repository.save(service);
    serviceId = service.getId();
}
Also used : Service(io.github.microcks.domain.Service) Before(org.junit.Before)

Example 4 with Service

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

the class ImportExportServiceTest method setUp.

@Before
public void setUp() {
    // Create a bunch of services...
    Service service = new Service();
    service.setName("HelloWorld");
    service.setVersion("1.2");
    repository.save(service);
    ids.add(service.getId());
    // with same name and different version ...
    service = new Service();
    service.setName("HelloWorld");
    service.setVersion("1.1");
    repository.save(service);
    ids.add(service.getId());
    // with different name ...
    service = new Service();
    service.setName("MyService-hello");
    service.setVersion("1.1");
    repository.save(service);
    ids.add(service.getId());
    // Create associated resources.
    Resource resource = new Resource();
    resource.setServiceId(ids.get(0));
    resource.setName("Resource 1");
    resource.setType(ResourceType.WSDL);
    resource.setContent("<wsdl></wsdl>");
    resourceRepository.save(resource);
}
Also used : Resource(io.github.microcks.domain.Resource) Service(io.github.microcks.domain.Service) Before(org.junit.Before)

Example 5 with Service

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

the class ImportExportServiceTest method testImportRepository.

@Test
public void testImportRepository() {
    // Setup and export result.
    String json = "{\"services\":[{\"name\":\"Imp1\",\"version\":\"1.2\",\"xmlNS\":null,\"type\":null,\"operations\":[],\"id\":25638445759706201468670970602}," + "{\"name\":\"Imp2\",\"version\":\"1.1\",\"xmlNS\":null,\"type\":null,\"operations\":[],\"id\":25638445759706201468670970603}], " + "\"resources\":[{\"name\":\"Resource 1\",\"content\":\"<wsdl></wsdl>\",\"type\":\"WSDL\",\"serviceId\":25638445759706201468670970602,\"id\":25638445759706201468670970605}], " + "\"requests\":[], \"responses\":[]}";
    boolean result = service.importRepository(json);
    // Get imported service and assert on content.
    Service service = repository.findByNameAndVersion("Imp1", "1.2");
    assertNotNull(service);
    assertEquals("Imp1", service.getName());
    assertEquals("1.2", service.getVersion());
    assertEquals("25638445759706201468670970602", service.getId().toString());
    // Get imported resources and assert on content.
    List<Resource> resources = resourceRepository.findByServiceId(service.getId());
    assertEquals(1, resources.size());
    assertEquals("Resource 1", resources.get(0).getName());
    assertEquals("<wsdl></wsdl>", resources.get(0).getContent());
    assertEquals(ResourceType.WSDL, resources.get(0).getType());
}
Also used : Resource(io.github.microcks.domain.Resource) Service(io.github.microcks.domain.Service) Test(org.junit.Test)

Aggregations

Service (io.github.microcks.domain.Service)42 MockRepositoryImportException (io.github.microcks.util.MockRepositoryImportException)18 Operation (io.github.microcks.domain.Operation)15 Test (org.junit.Test)15 Resource (io.github.microcks.domain.Resource)12 IOException (java.io.IOException)10 ResponseEntity (org.springframework.http.ResponseEntity)7 Response (io.github.microcks.domain.Response)6 File (java.io.File)6 ArrayList (java.util.ArrayList)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 Exchange (io.github.microcks.domain.Exchange)4 Request (io.github.microcks.domain.Request)4 RequestResponsePair (io.github.microcks.domain.RequestResponsePair)4 UnidirectionalEvent (io.github.microcks.domain.UnidirectionalEvent)4 List (java.util.List)4 HttpHeaders (org.springframework.http.HttpHeaders)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 Header (io.github.microcks.domain.Header)3 Metadata (io.github.microcks.domain.Metadata)3