org.springframework.util.xml.SimpleNamespaceContext#com.consol.citrus.context.TestContext源码实例Demo

下面列出了org.springframework.util.xml.SimpleNamespaceContext#com.consol.citrus.context.TestContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: yaks   文件: InjectEnvVarsHook.java
@Before
public void injectEnvVars(Scenario scenario) {
    runner.run(new AbstractTestAction() {
        @Override
        public void doExecute(TestContext context) {
            if (scenario != null) {
                context.setVariable("SCENARIO_ID", scenario.getId());
                context.setVariable("SCENARIO_NAME", scenario.getName());
            }

            Optional<String> namespaceEnv = getEnvSetting(YAKS_NAMESPACE);
            Optional<String> domainEnv = getEnvSetting(CLUSTER_WILDCARD_DOMAIN);

            if (namespaceEnv.isPresent()) {
                context.setVariable(YAKS_NAMESPACE, namespaceEnv.get());

                if (!domainEnv.isPresent()) {
                    context.setVariable(CLUSTER_WILDCARD_DOMAIN, namespaceEnv.get() + DEFAULT_DOMAIN_SUFFIX);
                }
            }

            domainEnv.ifPresent(var -> context.setVariable(CLUSTER_WILDCARD_DOMAIN, var));
        }
    });
}
 
源代码2 项目: yaks   文件: InjectEnvVarsHookTest.java
@Test
@SuppressWarnings("CucumberJavaStepDefClassIsPublic")
public void shouldInjectEnvVars() {
    InjectEnvVarsHook hook = new InjectEnvVarsHook() {
        @Override
        protected Optional<String> getEnvSetting(String name) {
            return Optional.of("foo");
        }
    };

    TestContext context = TestContextFactory.newInstance().getObject();
    TestCaseRunner runner = new DefaultTestCaseRunner(context);
    CitrusAnnotations.injectTestRunner(hook, runner);

    hook.injectEnvVars(null);

    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.YAKS_NAMESPACE)).isEqualTo("foo");
    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.CLUSTER_WILDCARD_DOMAIN)).isEqualTo("foo");
}
 
源代码3 项目: yaks   文件: InjectEnvVarsHookTest.java
@Test
@SuppressWarnings("CucumberJavaStepDefClassIsPublic")
public void shouldInjectEnvVarsDefaultValues() {
    InjectEnvVarsHook hook = new InjectEnvVarsHook() {
        @Override
        protected Optional<String> getEnvSetting(String name) {
            if (name.equals(InjectEnvVarsHook.YAKS_NAMESPACE)) {
                return Optional.of("foo");
            }

            return Optional.empty();
        }
    };

    TestContext context = TestContextFactory.newInstance().getObject();
    TestCaseRunner runner = new DefaultTestCaseRunner(context);
    CitrusAnnotations.injectTestRunner(hook, runner);

    hook.injectEnvVars(null);

    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.YAKS_NAMESPACE)).isEqualTo("foo");
    Assertions.assertThat(context.getVariable(InjectEnvVarsHook.CLUSTER_WILDCARD_DOMAIN)).isEqualTo("foo" + InjectEnvVarsHook.DEFAULT_DOMAIN_SUFFIX);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, InterruptedException {
	description("Import an API, export it afterwards and validate it equals to the imported API");
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/api/test/"+this.getClass().getSimpleName()+"-${apiNumber}");
	variable("apiName", this.getClass().getSimpleName()+"-${apiNumber}");
	variable("state", "published");
	
	echo("####### Importing the API, which should exported in the second step #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/test/export/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/test/export/files/basic/complete-config.json");
	createVariable("image", "/com/axway/apim/test/files/basic/API-Logo.jpg");
	createVariable("expectedReturnCode", "0");
	
	swaggerImport.doExecute(context);
	if(APIManagerAdapter.hasAPIManagerVersion("7.7.20200130")) {
		Thread.sleep(1000); // Starting with this version, we need to wait a few milliseconds, otherwise the REST-API doesn't return the complete set of quotas
	}
	
	exportAPI(context, false);
	exportAPI(context, true);
}
 
@CitrusTest
@Test @Parameters("context")
public void runInboundCorsProfileValidation(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Is the CORS-Profile not know - Error must be handled");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/basic-method-level-api-${apiNumber}");
	variable("apiName", "Basic Method-Level-API-${apiNumber}");
	
	echo("####### Try to replicate an API having invalid profiles referenced #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/methodLevel/method-level-inbound-invalidCorsProfileRefercence.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "73");
	swaggerImport.doExecute(context);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Make sure, the error that an invalid operationId is given is properly handled.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/basic-method-level-api-${apiNumber}");
	variable("apiName", "Basic Method-Level-API-${apiNumber}");
	
	echo("####### Try to replicate an API having Method-Level settings declared #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/methodLevel/method-level-inbound-invalidOperation.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "72");
	createVariable("securityProfileName", "APIKeyBased${apiNumber}");
	swaggerImport.doExecute(context);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	
	description("But OrgAdmins should not being allowed to register published APIs.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/org-admin-published-${apiNumber}");
	variable("apiName", "OrgAdmin-Published-${apiNumber}");
	variable("ignoreAdminAccount", "true"); // This tests simulate to use only an Org-Admin-Account
	variable("allowOrgAdminsToPublish", "false"); // Disable OrgAdmins to publish APIs

	echo("####### Calling the tool with a Non-Admin-User. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/2_initially_published.json");
	createVariable("expectedReturnCode", "17");
	createVariable("apiManagerUser", "${oadminUsername1}"); // This is an org-admin user
	createVariable("apiManagerPass", "${oadminPassword1}");
	swaggerImport.doExecute(context);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("If no api-definition is passed as argument and no apiDefinition attribute is found in configuration file, the tool must fail with a dedicated return code.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/my-no-api-def-${apiNumber}");
	variable("apiName", "No-API-DEF-CONFIGURED-${apiNumber}");

	echo("####### Calling the tool with a Non-Admin-User. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config.json");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", String.valueOf(ErrorCode.NO_API_DEFINITION_CONFIGURED.getCode()));
	swaggerImport.doExecute(context);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Try to import an API with invalid quota configuration.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/invalid-quota-api-${apiNumber}");
	variable("apiName", "Invalid Quota-API-${apiNumber}");

	echo("####### Trying to import API: '${apiName}' on path: '${apiPath}' with invalid quota config #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/quota/issue-109-invalid-quota-config-1.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "71");
	swaggerImport.doExecute(context);
	
	echo("####### Trying to import API: '${apiName}' on path: '${apiPath}' with invalid quota config #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/quota/issue-109-invalid-quota-config-2.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "71");
	swaggerImport.doExecute(context);
}
 
源代码10 项目: allure-java   文件: AllureCitrusTest.java
@AllureFeatures.FailedTests
@Test
void shouldSetFailedStatus() {
    final DefaultTestDesigner designer = new DefaultTestDesigner();
    designer.name("Simple test");
    designer.action(new AbstractTestAction() {
        @Override
        public void doExecute(final TestContext context) {
            assertThat(true).isFalse();
        }
    });

    final AllureResults results = run(designer);
    assertThat(results.getTestResults())
            .extracting(TestResult::getStatus)
            .containsExactly(Status.FAILED);
}
 
源代码11 项目: syndesis   文件: WebHookToFtp_IT.java
@Override
public void doExecute(TestContext testContext) {
    Path publicUserDir = getFtpUserHome().resolve("public");
    Assert.assertTrue( "Missing ftp user home directory", publicUserDir.toFile().exists());

    File ftpUploadFile = publicUserDir.resolve(UPLOAD_FILENAME).toFile();
    Assert.assertTrue(String.format("Missing ftp upload file '%s'", UPLOAD_FILENAME), ftpUploadFile.exists());
    try {
        JsonTextMessageValidator validator = new JsonTextMessageValidator();
        validator.validateMessage(new DefaultMessage(FileUtils.readToString(ftpUploadFile)),
                                    new DefaultMessage("{\"message\" : \"${first_name},${company},${email}\"}"),
                                    testContext,
                                    new JsonMessageValidationContext());
    } catch (IOException e) {
        throw new CitrusRuntimeException(String.format("Failed to verify ftp upload file '%s'", UPLOAD_FILENAME), e);
    }
}
 
源代码12 项目: dew   文件: Verify.java
/**
 * Verify resource descriptors.
 *
 * @param message      the message
 * @param expectedText the expected text
 * @param actualText   the actual text
 * @throws IOException    the io exception
 * @throws ParseException the parse exception
 */
default void verifyResourceDescriptors(String message, String expectedText, String actualText) throws IOException, ParseException {
    JsonTextMessageValidator validator = new JsonTextMessageValidator();
    validator.setStrict(false);

    TestContext context = new TestContext();
    context.getValidationMatcherRegistry()
            .getValidationMatcherLibraries()
            .add(new ValidationMatcherConfig().getValidationMatcherLibrary());

    validator.validateJson(message,
            (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(actualText)),
            (JSONObject) new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE).parse(toJson(expectedText)),
            new JsonMessageValidationContext(),
            context,
            JsonPath.parse(actualText));
}
 
@Override
public <T> T translate(Node node, T value, TestContext context) {
    if (value instanceof String) {
        String toTranslate;
        if (!mappings.isEmpty()) {
            toTranslate = (String) super.translate(node, value, context);
        } else {
            toTranslate = (String) value;
        }

        if (toTranslate.equals(value)) {
            if (toTranslate.equals("true") || toTranslate.equals("false")) {
                return (T) toTranslate;
            } else if (Character.isDigit(toTranslate.charAt(0))) {
                return (T) (context.replaceDynamicContentInString("citrus:randomNumber(" + toTranslate.length() + ")"));
            } else if (toTranslate.startsWith("string")) {
                return (T) (context.replaceDynamicContentInString("citrus:randomString(" + toTranslate.length() + ")"));
            }
        } else {
            return (T) toTranslate;
        }
    }

    return super.translate(node, value, context);
}
 
@Override
public <T> T translate(Node node, T value, TestContext context) {
    for (Map.Entry<String, String> expressionEntry : mappings.entrySet()) {
        String expression = expressionEntry.getKey();

        SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
        namespaceContext.setBindings(context.getNamespaceContextBuilder().getNamespaceMappings());

        NodeList findings = (NodeList) XPathUtils.evaluateExpression(node.getOwnerDocument(), expression, namespaceContext, XPathConstants.NODESET);

        if (findings != null && containsNode(findings, node)) {
            return convertIfNecessary(context.replaceDynamicContentInString(expressionEntry.getValue()), value);
        }
    }

    return value;
}
 
源代码15 项目: citrus-simulator   文件: EndpointMessageHandler.java
private void saveScenarioMessage(Message message, TestContext context, Direction direction) {
    Optional<Long> executionId = extractExecutionId(context);
    Optional<String> citrusMessageId = extractCitrusMessageId(message);
    if (executionId.isPresent() && citrusMessageId.isPresent()) {
        activityService.saveScenarioMessage(executionId.get(), direction,
                message.getPayload(String.class), citrusMessageId.get(), message.getHeaders());
    }
}
 
源代码16 项目: citrus-simulator   文件: CalculateIban.java
private TestAction calculateIban() {
    return new AbstractTestAction() {
        @Override
        public void doExecute(TestContext context) {
            final String queryParams = context.getVariable(QUERY_PARAMS.name(), String.class);
            final String sortCode = queryParameterService.getSortCode(queryParams);
            final String bankAccountNumber = queryParameterService.getBankAccountNumber(queryParams);
            final String jsonResponse = bankService.calculate(sortCode, bankAccountNumber).asJson();
            context.setVariable(JSON_RESPONSE.name(), jsonResponse);
        }
    };
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Test to validate behavior if OutboundProfiles are set, but no AuthN-Profile. It should result into no AuthN.");

	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/issue-133-noauth-${apiNumber}");
	variable("apiName", "Issue 133 No-Auth ${apiNumber}");
	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' Outbound-Profiles (for policies) not containing a AuthN-Profile. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/security/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/security/issue-133-outbound-profile-no-auth.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' with outbound security set to No-AuthN as this should be the default. #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").name("api").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
			.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
			.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
			.validate("$.[?(@.path=='${apiPath}')].authenticationProfiles[0].name", "_default")
			.validate("$.[?(@.path=='${apiPath}')].authenticationProfiles[0].type", "none")
			.validate("$.[?(@.path=='${apiPath}')].authenticationProfiles[0].isDefault", "true")
			.validate("$.[?(@.path=='${apiPath}')].outboundProfiles._default.authenticationProfile", "_default")
			.validate("$.[?(@.path=='${apiPath}')].outboundProfiles._default.routeType", "policy")
			.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
	
	echo("####### No-Change test for '${apiName}' on path: '${apiPath}' #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/security/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/security/issue-133-outbound-profile-no-auth.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
}
 
@Override
public void doExecute(TestContext context) {
    CorrelationHandlerRegistry handlerRegistry = context.getApplicationContext().getBean(CorrelationHandlerRegistry.class);

    if (handlerRegistry != null) {
        handlerRegistry.remove(correlationHandler);
    } else {
        throw new SimulatorException("Failed to get correlation handler registry in application context");
    }
}
 
private Optional<TestContext> getTestContext(MethodInvocation methodInvocation) {
    final Object[] arguments = methodInvocation.getArguments();
    if (arguments != null) {
        return Arrays.stream(arguments)
                .filter(TestContext.class::isInstance)
                .map(TestContext.class::cast)
                .findFirst();
    }
    return Optional.empty();
}
 
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Object result = methodInvocation.proceed();
    if (isSendMethod(methodInvocation)) {
        final Optional<TestContext> testContext = getArgument(methodInvocation, TestContext.class);
        final Optional<Message> message = getArgument(methodInvocation, Message.class);
        if (testContext.isPresent() && message.isPresent()) {
            endpointMessageHandler.handleSentMessage(message.get(), testContext.get());
        }
    }
    return result;
}
 
源代码21 项目: citrus-simulator   文件: ScenarioEndpoint.java
@Override
public void send(Message message, TestContext context) {
    messageSent(message, context);
    if (responseFutures.isEmpty()) {
        throw new SimulatorException("Failed to process scenario response message - missing response consumer");
    } else {
        responseFutures.pop().complete(message);
    }
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Making sure, organization are not conisdered as changes if desired state is Unpublished");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/no-change-org-unpublished-${apiNumber}");
	variable("apiName", "No-Change-Org-Unpublished-${apiNumber}");

	// Replication must fail, is Query-String option is enabled, but API-Manager hasn't configured it 
	echo("####### API-Config without queryString option - Must fail #######");		
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/organizations/1_api-with-client-orgs.json");
	createVariable("state", "unpublished");
	createVariable("orgName", "${orgName}");
	createVariable("orgName2", "${orgName2}");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Re-Import the same - Must lead to a No-Change! #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/organizations/1_api-with-client-orgs.json");
	createVariable("state", "unpublished");
	createVariable("orgName", "${orgName}");
	createVariable("orgName2", "${orgName2}");
	createVariable("expectedReturnCode", "10"); // No-Change is expected!
	swaggerImport.doExecute(context);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();	
	description("Test a Routing-Policy");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/routing-policy-test-${apiNumber}");
	variable("apiName", "Routing Policy Test ${apiNumber}");
	variable("status", "unpublished");
	

	echo("####### Importing API: '${apiName}' on path: '${apiPath}' with following settings: #######");
	createVariable("routePolicy", "Routing policy 1");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/security/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/policies/1_routing-policy.json");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has correct settings #######");
	http(builder -> builder.client("apiManager").send()	.get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager")
		.receive()
		.response(HttpStatus.OK)
		.messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
		.validate("$.[?(@.path=='${apiPath}')].outboundProfiles._default.routePolicy", "@assertThat(containsString(Routing policy 1))@")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Import an API which initially has the status published.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/initially-published-${apiNumber}");
	variable("apiName", "Initially-Published-API-${apiNumber}");

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time #######");
	
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/2_initially_published.json");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "published")
		.validate("$.[?(@.path=='${apiPath}')].securityProfiles[0].devices[0].type", "apiKey")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
}
 
/**
 * Add new correlation manager to registry.
 * @param handler
 */
public void register(CorrelationHandler handler, TestContext context) {
    if (!registeredHandlers.keySet().contains(handler)) {
        registeredHandlers.put(handler, context);
    }

    while (registeredHandlers.size() > queueCapacity) {
        Stream.of(registeredHandlers.keySet()).limit(queueCapacity / 10)
                .collect(Collectors.toList())
                .parallelStream()
                .forEach(toDelete -> registeredHandlers.remove(toDelete));
    }
}
 
/**
 * Finds handler in registered handlers that is able to handle given message. When handler is found return true
 * otherwise false.
 * @param request
 * @return
 */
public CorrelationHandler findHandlerFor(Message request) {
    for (Map.Entry<CorrelationHandler, TestContext> handlerEntry : registeredHandlers.entrySet()) {
        if (handlerEntry.getKey().isHandlerFor(request, handlerEntry.getValue())) {
            return handlerEntry.getKey();
        }
    }

    return null;
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Import an API having some special characters in the Swagger & API-Config-File.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/special-chars-${apiNumber}");
	variable("apiName", "Special-Chars-${apiNumber}");

	echo("####### Importing Special-Chars API: '${apiName}' on path: '${apiPath}' #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore-special-chars.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/special-chars-config.json");
	createVariable("state", "unpublished");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);

	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		// TODO: Find a way to validate unicode characters as well
		//.validate("$.[?(@.path=='${apiPath}')].summary", "�дпат или умри.")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));

	echo("####### RE-Importing same API: '${apiName}' on path: '${apiPath}' without changes. Expecting failure with RC 99. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore-special-chars.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/special-chars-config.json");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Validates a Swagger-File can be taken from a URL using a REF-File described in API json configuration");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/ref-file-swagger-in-configuration-${apiNumber}");
	variable("apiName", "Ref-File-Swagger in configuration from URL-${apiNumber}");
	

	
	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time from URL #######");
	createVariable(ImportTestAction.API_DEFINITION,  "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config-with-api-definition.json");
	createVariable("testAPIDefinition","./src/test/resources/com/axway/apim/test/files/basic/swagger-file-with-username.url");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);
	
	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].state", "unpublished")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));
	
	echo("####### Re-Import API from URL without a change #######");
	createVariable(ImportTestAction.API_DEFINITION,  "");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/minimal-config-with-api-definition.json");
	createVariable("testAPIDefinition","./src/test/resources/com/axway/apim/test/files/basic/swagger-file-with-username.url");
	createVariable("status", "unpublished");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
}
 
@Override
public void doExecute(TestContext context) {
    CorrelationHandlerRegistry handlerRegistry = context.getApplicationContext().getBean(CorrelationHandlerRegistry.class);

    if (handlerRegistry != null) {
        handlerRegistry.register(correlationHandler, context);
    } else {
        throw new SimulatorException("Failed to get correlation handler registry in application context");
    }
}
 
@CitrusTest
@Test @Parameters("context")
public void run(@Optional @CitrusResource TestContext context) throws IOException, AppException {
	swaggerImport = new ImportTestAction();
	description("Import an API and re-import it without any change. It must be detected, that no change happened.");
	
	variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true));
	variable("apiPath", "/my-no-change-${apiNumber}");
	variable("apiName", "No-Change-${apiNumber}");

	echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/1_no-change-config.json");
	createVariable("expectedReturnCode", "0");
	swaggerImport.doExecute(context);

	echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######");
	http(builder -> builder.client("apiManager").send().get("/proxies").header("Content-Type", "application/json"));

	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"));

	echo("####### RE-Importing same API: '${apiName}' on path: '${apiPath}' without changes. Expecting failure with RC 99. #######");
	createVariable(ImportTestAction.API_DEFINITION,  "/com/axway/apim/test/files/basic/petstore.json");
	createVariable(ImportTestAction.API_CONFIG,  "/com/axway/apim/test/files/basic/1_no-change-config.json");
	createVariable("expectedReturnCode", "10");
	swaggerImport.doExecute(context);
	
	echo("####### Make sure, the API-ID hasn't changed #######");
	http(builder -> builder.client("apiManager").send().get("/proxies/${apiId}").header("Content-Type", "application/json"));

	// Check the API is still exposed on the same path
	http(builder -> builder.client("apiManager").receive().response(HttpStatus.OK).messageType(MessageType.JSON)
		.validate("$.[?(@.path=='${apiPath}')].name", "${apiName}")
		.validate("$.[?(@.path=='${apiPath}')].id", "${apiId}")); // Must be the same API-ID as before!
}