Search in sources :

Example 56 with Broker

use of org.wso2.broker.core.Broker in project siddhi by wso2.

the class SingleClientDistributedTransportTestCases method singleClientRoundRobin.

@Test
public void singleClientRoundRobin() throws InterruptedException {
    log.info("Test inMemorySink And EventMapping With SiddhiQL Dynamic Params");
    InMemoryBroker.Subscriber subscriptionWSO2 = new InMemoryBroker.Subscriber() {

        @Override
        public void onMessage(Object msg) {
            topic1Count.incrementAndGet();
        }

        @Override
        public String getTopic() {
            return "topic1";
        }
    };
    InMemoryBroker.Subscriber subscriptionIBM = new InMemoryBroker.Subscriber() {

        @Override
        public void onMessage(Object msg) {
            topic2Count.incrementAndGet();
        }

        @Override
        public String getTopic() {
            return "topic2";
        }
    };
    // subscribe to "inMemory" broker per topic
    InMemoryBroker.subscribe(subscriptionWSO2);
    InMemoryBroker.subscribe(subscriptionIBM);
    String streams = "" + "@app:name('TestSiddhiApp')" + "define stream FooStream (symbol string, price float, volume long); " + "@sink(type='inMemory', @map(type='passThrough'), " + "   @distribution(strategy='roundRobin', " + "       @destination(topic = 'topic1'), " + "       @destination(topic = 'topic2'))) " + "define stream BarStream (symbol string, price float, volume long); ";
    String query = "" + "from FooStream " + "select * " + "insert into BarStream; ";
    SiddhiManager siddhiManager = new SiddhiManager();
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);
    InputHandler stockStream = siddhiAppRuntime.getInputHandler("FooStream");
    siddhiAppRuntime.start();
    stockStream.send(new Object[] { "WSO2", 55.6f, 100L });
    stockStream.send(new Object[] { "WSO2", 75.6f, 100L });
    stockStream.send(new Object[] { "WSO2", 57.6f, 100L });
    stockStream.send(new Object[] { "WSO2", 57.6f, 100L });
    stockStream.send(new Object[] { "WSO2", 57.6f, 100L });
    Thread.sleep(100);
    // assert event count
    AssertJUnit.assertEquals("Number of WSO2 events", 3, topic1Count.get());
    AssertJUnit.assertEquals("Number of IBM events", 2, topic2Count.get());
    siddhiAppRuntime.shutdown();
    // unsubscribe from "inMemory" broker per topic
    InMemoryBroker.unsubscribe(subscriptionWSO2);
    InMemoryBroker.unsubscribe(subscriptionIBM);
}
Also used : InputHandler(org.wso2.siddhi.core.stream.input.InputHandler) InMemoryBroker(org.wso2.siddhi.core.util.transport.InMemoryBroker) SiddhiAppRuntime(org.wso2.siddhi.core.SiddhiAppRuntime) SiddhiManager(org.wso2.siddhi.core.SiddhiManager) Test(org.testng.annotations.Test)

Example 57 with Broker

use of org.wso2.broker.core.Broker in project product-iots by wso2.

the class VirtualFireAlarmTestCase method testPolicyPublishing.

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = { "testEventPublishing" })
public void testPolicyPublishing() throws Exception {
    String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2;
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + "/operation/#";
    String clientId = deviceId2 + ":" + DEVICE_TYPE;
    HttpResponse response = restClient.post("/api/device-mgt/v1.0/policies", PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.VirtualFireAlarmConstants.POLICY_DATA).toString());
    Assert.assertEquals("Policy creation for virtual fire alarm failed", HttpStatus.SC_CREATED, response.getResponseCode());
    JsonObject jsonObject = new JsonParser().parse(response.getData()).getAsJsonObject();
    String policyId = jsonObject.getAsJsonPrimitive("id").getAsString();
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(new JsonPrimitive(policyId));
    response = restClient.post(Constants.VirtualFireAlarmConstants.ACTIVATE_POLICY_ENDPOINT, jsonArray.toString());
    Assert.assertEquals("Policy activation for virtual fire alarm failed", HttpStatus.SC_OK, response.getResponseCode());
    MqttSubscriberClient mqttSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    response = restClient.put(Constants.VirtualFireAlarmConstants.APPLY_CHANGES_ENDPOINT, "");
    Assert.assertEquals("Applying changes to policy for virtual fire alarm failed", HttpStatus.SC_OK, response.getResponseCode());
    // Allow some time for message delivery
    Thread.sleep(20000);
    ArrayList<MqttMessage> mqttMessages = mqttSubscriberClient.getMqttMessages();
    Assert.assertEquals("Policy published message is not received by the mqtt listener. ", 2, mqttMessages.size());
}
Also used : JsonArray(com.google.gson.JsonArray) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) JsonPrimitive(com.google.gson.JsonPrimitive) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) JsonObject(com.google.gson.JsonObject) MqttSubscriberClient(org.wso2.iot.integration.common.MqttSubscriberClient) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Example 58 with Broker

use of org.wso2.broker.core.Broker in project product-iots by wso2.

the class DeviceTypeManagementJMeterTestCase method testMqttFlow.

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = { "DeviceTypeManagementTest" })
public void testMqttFlow() throws Exception {
    String deviceId = "123422578912";
    String deviceType = "firealarmmqtt";
    String payload = "{\"deviceIdentifiers\":[123422578912],\"operation\":{\"code\":\"ring\",\"type\":\"CONFIG\"," + "\"payLoad\":\"volume:30%\"}}";
    String topic = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId + "/operation/#";
    String clientId = deviceId + ":firealarmmqtt";
    MqttSubscriberClient mqttDeviceSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    restClient.post("/api/device-mgt/v1.0/devices/" + deviceType + "/operations", payload);
    // Allow some time for message delivery
    Thread.sleep(10000);
    ArrayList<MqttMessage> mqttMessages = mqttDeviceSubscriberClient.getMqttMessages();
    Assert.assertEquals("listener did not recieve mqtt messages ", 1, mqttMessages.size());
    String topicPub = automationContext.getContextTenant().getDomain() + "/" + deviceType + "/" + deviceId + "/events";
    int qos = 2;
    String clientIdPub = deviceId + ":firealarmmqttpub";
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientIdPub, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(false);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    for (int i = 0; i < 100; i++) {
        payload = "{\"temperature\":%d,\"status\":\"workingh\",\"humidity\":20}";
        MqttMessage message = new MqttMessage(String.format(payload, i).getBytes());
        message.setQos(qos);
        sampleClient.publish(topicPub, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    log.info("Mqtt Client is Disconnected");
    // Allow some time for message delivery
    HttpResponse response = restClient.get("/api/device-mgt/v1.0/events/last-known/" + deviceType + "/" + deviceId);
    Assert.assertEquals("No published event found (mqtt)", HttpStatus.SC_OK, response.getResponseCode());
    log.error(response.getData());
    JsonElement jsonElement = new JsonParser().parse(response.getData()).getAsJsonObject().get("count");
    int count = jsonElement.getAsInt();
    Assert.assertTrue("Event count does not match published event count, " + response.getData(), count > 0);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) JsonElement(com.google.gson.JsonElement) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) MqttSubscriberClient(org.wso2.iot.integration.common.MqttSubscriberClient) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test) JMeterTest(org.wso2.carbon.automation.extensions.jmeter.JMeterTest)

Example 59 with Broker

use of org.wso2.broker.core.Broker in project carbon-apimgt by wso2.

the class ExternalGatewayNotifier method deployApi.

/**
 * Deploy APIs to external gateway
 *
 * @param deployAPIInGatewayEvent DeployAPIInGatewayEvent to deploy APIs to external gateway
 * @throws NotifierException if error occurs when deploying APIs to external gateway
 */
private void deployApi(DeployAPIInGatewayEvent deployAPIInGatewayEvent) throws NotifierException {
    boolean deployed;
    Set<String> gateways = deployAPIInGatewayEvent.getGatewayLabels();
    String apiId = deployAPIInGatewayEvent.getUuid();
    try {
        Map<String, Environment> environments = APIUtil.getEnvironments(deployAPIInGatewayEvent.getTenantDomain());
        APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(CarbonContext.getThreadLocalCarbonContext().getUsername());
        API api = apiProvider.getAPIbyUUID(apiId, apiMgtDAO.getOrganizationByAPIUUID(apiId));
        for (String deploymentEnv : gateways) {
            if (environments.containsKey(deploymentEnv)) {
                ExternalGatewayDeployer deployer = ServiceReferenceHolder.getInstance().getExternalGatewayDeployer(environments.get(deploymentEnv).getProvider());
                if (deployer != null) {
                    try {
                        deployed = deployer.deploy(api, environments.get(deploymentEnv));
                        if (!deployed) {
                            throw new APIManagementException("Error while deploying API product to Solace broker");
                        }
                    } catch (DeployerException e) {
                        throw new APIManagementException(e.getMessage());
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ExternalGatewayDeployer(org.wso2.carbon.apimgt.impl.deployer.ExternalGatewayDeployer) Environment(org.wso2.carbon.apimgt.api.model.Environment) DeployerException(org.wso2.carbon.apimgt.impl.deployer.exceptions.DeployerException) API(org.wso2.carbon.apimgt.api.model.API) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)

Example 60 with Broker

use of org.wso2.broker.core.Broker in project carbon-apimgt by wso2.

the class ExternallyDeployedApiNotifier method undeployWhenDeleting.

/**
 * Undeploy APIs from external gateway when API is deleted
 *
 * @param apiEvent APIEvent to undeploy APIs from external gateway
 * @throws NotifierException if error occurs when undeploying APIs from external gateway
 */
private void undeployWhenDeleting(APIEvent apiEvent) throws NotifierException {
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    boolean deleted;
    String apiId = apiEvent.getUuid();
    try {
        List<APIRevisionDeployment> test = apiMgtDAO.getAPIRevisionDeploymentsByApiUUID(apiId);
        for (APIRevisionDeployment deployment : test) {
            String deploymentEnv = deployment.getDeployment();
            if (gatewayEnvironments.containsKey(deploymentEnv)) {
                ExternalGatewayDeployer deployer = ServiceReferenceHolder.getInstance().getExternalGatewayDeployer(gatewayEnvironments.get(deploymentEnv).getProvider());
                if (deployer != null) {
                    try {
                        deleted = deployer.undeploy(apiEvent.getApiName(), apiEvent.getApiVersion(), apiEvent.getApiContext(), gatewayEnvironments.get(deploymentEnv));
                        if (!deleted) {
                            throw new NotifierException("Error while deleting API product from Solace broker");
                        }
                    } catch (DeployerException e) {
                        throw new NotifierException(e.getMessage());
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ExternalGatewayDeployer(org.wso2.carbon.apimgt.impl.deployer.ExternalGatewayDeployer) Environment(org.wso2.carbon.apimgt.api.model.Environment) DeployerException(org.wso2.carbon.apimgt.impl.deployer.exceptions.DeployerException) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)

Aggregations

Test (org.testng.annotations.Test)19 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)19 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)16 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)16 InMemoryBroker (org.wso2.siddhi.core.util.transport.InMemoryBroker)16 Environment (org.wso2.carbon.apimgt.api.model.Environment)15 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)13 ArrayList (java.util.ArrayList)11 SolaceAdminApis (org.wso2.carbon.apimgt.solace.SolaceAdminApis)9 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)8 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)7 DeployerException (org.wso2.carbon.apimgt.impl.deployer.exceptions.DeployerException)7 NotifierException (org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)7 IOException (java.io.IOException)6 Broker (org.wso2.carbon.apimgt.core.api.Broker)6 Test (org.junit.Test)5 API (org.wso2.carbon.apimgt.core.models.API)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4 ExternalGatewayDeployer (org.wso2.carbon.apimgt.impl.deployer.ExternalGatewayDeployer)4 JsonParser (com.google.gson.JsonParser)3