Search in sources :

Example 11 with Topic

use of org.wso2.carbon.apimgt.api.model.webhooks.Topic in project siddhi by wso2.

the class MultiClientDistributedSinkTestCase method multiClientFailingBroadcast2.

@Test
public void multiClientFailingBroadcast2() 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 "WSO2";
        }
    };
    InMemoryBroker.Subscriber subscriptionIBM = new InMemoryBroker.Subscriber() {

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

        @Override
        public String getTopic() {
            return "IBM";
        }
    };
    // 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='testFailingInMemory2', @map(type='passThrough'), " + "   @distribution(strategy='broadcast'," + "       @destination(topic = 'IBM', test='1'), " + "       @destination(topic = 'WSO2',  test='2'))) " + "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[] { "IBM", 75.6f, 100L });
    stockStream.send(new Object[] { "WSO2", 57.6f, 100L });
    TestFailingInMemorySink2.failOnce = true;
    stockStream.send(new Object[] { "IBM", 57.6f, 100L });
    Thread.sleep(6000);
    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 topic 1 events", 7, topic1Count.get());
    AssertJUnit.assertEquals("Number of topic 2 events", 6, 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 12 with Topic

use of org.wso2.carbon.apimgt.api.model.webhooks.Topic in project carbon-apimgt by wso2.

the class BrokerUtil method publishToTopic.

/**
 * Publish to broker topic
 *
 * @param topicName     publishing topic name
 * @param gatewayEvent    topic message data object
 */
public static void publishToTopic(String topicName, GatewayEvent gatewayEvent) throws GatewayException {
    TopicSession topicSession = null;
    Topic topic = null;
    TopicPublisher topicPublisher = null;
    TopicConnection topicConnection = null;
    try {
        topicConnection = getTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = topicSession.createTopic(topicName);
        topicPublisher = topicSession.createPublisher(topic);
        TextMessage textMessage = topicSession.createTextMessage(new Gson().toJson(gatewayEvent));
        topicPublisher.publish(textMessage);
    } catch (JMSException e) {
        String errorMessage = "Error occurred while publishing " + gatewayEvent.getEventType() + " event to JMS " + "topic :" + topicName;
        log.error(errorMessage, e);
        throw new GatewayException(errorMessage, ExceptionCodes.GATEWAY_EXCEPTION);
    } catch (BrokerException e) {
        String errorMessage = "Error occurred while obtaining broker topic connection for topic : " + topicName;
        log.error(errorMessage, e);
        throw new GatewayException(errorMessage, ExceptionCodes.GATEWAY_EXCEPTION);
    } finally {
        if (topicPublisher != null) {
            try {
                topicPublisher.close();
            } catch (JMSException e) {
                log.error("Error occurred while closing topic publisher for topic : " + topicName);
            }
        }
        if (topicSession != null) {
            try {
                topicSession.close();
            } catch (JMSException e) {
                log.error("Error occurred while closing topic session for topic : " + topicName);
            }
        }
        if (topicConnection != null) {
            try {
                topicConnection.close();
            } catch (JMSException e) {
                log.error("Error occurred while closing topic connection for topic : " + topicName);
            }
        }
    }
}
Also used : TopicSession(javax.jms.TopicSession) BrokerException(org.wso2.carbon.apimgt.core.exception.BrokerException) TopicPublisher(javax.jms.TopicPublisher) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) Gson(com.google.gson.Gson) JMSException(javax.jms.JMSException) Topic(javax.jms.Topic) TopicConnection(javax.jms.TopicConnection) TextMessage(javax.jms.TextMessage)

Example 13 with Topic

use of org.wso2.carbon.apimgt.api.model.webhooks.Topic in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultSiddhiAppForAPIThrottlePolicy.

public static String createDefaultSiddhiAppForAPIThrottlePolicy() {
    APIPolicy apiPolicy = createDefaultAPIPolicy();
    String siddhiApp = "\n@App:name('resource_" + apiPolicy.getPolicyName() + "_condition_0')" + "\n@App:description('ExecutionPlan for resource_" + apiPolicy.getPolicyName() + "_condition_0')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))" + "\ndefine stream RequestStream (messageID string, appKey string, appTier string, " + "subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string," + " resourceTier string, userId string,  apiContext string, apiVersion string, " + "appTenant string, apiTenant " + "string, appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text')," + "\nfactory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', " + "destination='TEST.FOO', connection.factory.type='topic'," + "\nconnection.factory.jndi.name='TopicConnectionFactory')" + "\ndefine stream GlobalThrottleStream (throttleKey string, isThrottled bool," + " expiryTimeStamp long);\n" + "\nFROM RequestStream" + "\nSELECT messageID, (resourceTier == 'SampleAPIPolicy' AND (regex:find('Chrome'," + "cast(map:get(propertiesMap,'Browser')," + "'string'))) AND (regex:find('attributed'," + "cast(map:get(propertiesMap,'/path/path2'),'string'))) AND " + "(cast(map:get(propertiesMap,'Location'),'string')=='Colombo'))" + " AS isEligible, str:concat(resourceKey," + "'_condition_0') AS throttleKey, propertiesMap" + "\nINSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(1 s, 0)" + "\nselect throttleKey, (count(messageID) >= 1000) as isThrottled," + " expiryTimeStamp group by throttleKey" + "\nINSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + "\nselect *" + "\ninsert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 14 with Topic

use of org.wso2.carbon.apimgt.api.model.webhooks.Topic in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultSiddhiAppforSubscriptionPolicy.

public static String createDefaultSiddhiAppforSubscriptionPolicy() {
    SubscriptionPolicy policy = createDefaultSubscriptionPolicy();
    RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
    String siddhiApp = "@App:name('subscription_" + policy.getPolicyName() + "')\n" + "\n@App:description('ExecutionPlan for subscription_" + policy.getPolicyName() + "')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))\n" + "define stream RequestStream (messageID string, appKey string, appTier string," + " subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string, resourceTier string," + " userId string,  apiContext string, apiVersion string, appTenant string, apiTenant string, " + "appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text'),\n" + "factory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', destination='TEST.FOO', connection.factory." + "type='topic',\n" + "connection.factory.jndi.name='TopicConnectionFactory')\n" + "define stream GlobalThrottleStream (throttleKey string, isThrottled bool" + ", expiryTimeStamp long);\n" + "\nFROM RequestStream\n" + "SELECT messageID, (subscriptionTier == '" + policy.getPolicyName() + "')" + " AS isEligible, subscriptionKey AS throttleKey, propertiesMap\n" + "INSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(" + policy.getDefaultQuotaPolicy().getLimit().getUnitTime() + " " + policy.getDefaultQuotaPolicy().getLimit().getTimeUnit() + ", 0)\n" + "select throttleKey, (count(messageID) >= " + limit.getRequestCount() + ")" + " as isThrottled, expiryTimeStamp group by throttleKey\n" + "INSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + " select * " + "insert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)

Example 15 with Topic

use of org.wso2.carbon.apimgt.api.model.webhooks.Topic in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultCustomPolicySiddhiApp.

public static String createDefaultCustomPolicySiddhiApp() {
    CustomPolicy policy = createDefaultCustomPolicy();
    String siddhiApp = "@App:name('custom_" + policy.getPolicyName() + "')" + "\n@App:description('ExecutionPlan for custom_" + policy.getPolicyName() + "')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))\n" + "define stream RequestStream (messageID string, appKey string, appTier string, " + "subscriptionKey string, apiKey string, apiTier string, subscriptionTier string," + " resourceKey string, resourceTier string, userId string,  apiContext string, " + "apiVersion string, appTenant string, apiTenant string, appId string, apiName string, " + "propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text'),\n" + "factory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', destination='TEST.FOO'," + " connection.factory.type='topic',\n" + "connection.factory.jndi.name='TopicConnectionFactory')\n" + "define stream GlobalThrottleStream (throttleKey string, isThrottled bool, " + "expiryTimeStamp long);\n" + "\n" + policy.getSiddhiQuery() + "\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + "\nselect *\n" + "insert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy)

Aggregations

Test (org.testng.annotations.Test)28 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)25 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)25 InMemoryBroker (org.wso2.siddhi.core.util.transport.InMemoryBroker)16 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)13 Event (org.wso2.siddhi.core.event.Event)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 HashMap (java.util.HashMap)5 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 Timestamp (java.sql.Timestamp)4 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 LinkedHashSet (java.util.LinkedHashSet)4 JsonParser (com.google.gson.JsonParser)3 ResultSet (java.sql.ResultSet)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)3