Search in sources :

Example 21 with Event

use of org.wso2.siddhi.core.event.Event in project carbon-apimgt by wso2.

the class FunctionDAOImplIT method testAddGetDeleteEventFunctionMapping.

@Test
public void testAddGetDeleteEventFunctionMapping() throws Exception {
    FunctionDAO functionDAO = DAOFactory.getFunctionDAO();
    Function function1 = SampleTestObjectCreator.createDefaultFunction();
    Function function2 = SampleTestObjectCreator.createAlternativeFunction();
    Function function3 = SampleTestObjectCreator.createAlternativeFunction2();
    functionDAO.updateUserDeployedFunctions(ADMIN, Arrays.asList(function1, function2, function3));
    try {
        functionDAO.addEventFunctionMapping(null, Event.API_CREATION, function1.getName());
        Assert.fail("Expected IllegalArgumentException when username is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Username must not be null"));
    }
    try {
        functionDAO.addEventFunctionMapping(ADMIN, null, function1.getName());
        Assert.fail("Expected IllegalArgumentException when Event is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Event must not be null"));
    }
    try {
        functionDAO.addEventFunctionMapping(ADMIN, Event.API_CREATION, null);
        Assert.fail("Expected IllegalArgumentException when function name is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Function name must not be null"));
    }
    functionDAO.addEventFunctionMapping(ADMIN, Event.API_CREATION, function1.getName());
    functionDAO.addEventFunctionMapping(ADMIN, Event.API_UPDATE, function1.getName());
    functionDAO.addEventFunctionMapping(ADMIN, Event.APP_CREATION, function2.getName());
    functionDAO.addEventFunctionMapping(ADMIN, Event.APP_MODIFICATION, function2.getName());
    functionDAO.addEventFunctionMapping(ADMIN, Event.API_CREATION, function3.getName());
    functionDAO.addEventFunctionMapping(ADMIN, Event.APP_CREATION, function3.getName());
    // Validate getTriggersForUserFunction() args
    try {
        functionDAO.getTriggersForUserFunction(null, function3.getName());
        Assert.fail("Expected IllegalArgumentException when username is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Username must not be null"));
    }
    try {
        functionDAO.getTriggersForUserFunction(ADMIN, null);
        Assert.fail("Expected IllegalArgumentException when function name is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Function name must not be null"));
    }
    // Check events for functions
    List<Event> eventsFromDB = functionDAO.getTriggersForUserFunction(ADMIN, function3.getName());
    Assert.assertEquals(eventsFromDB.size(), 2);
    Assert.assertTrue(eventsFromDB.get(0).equals(Event.API_CREATION) || eventsFromDB.get(0).equals(Event.APP_CREATION));
    Assert.assertTrue(eventsFromDB.get(1).equals(Event.API_CREATION) || eventsFromDB.get(1).equals(Event.APP_CREATION));
    // Validate getUserFunctionsForEvent() args
    try {
        functionDAO.getUserFunctionsForEvent(null, Event.API_UPDATE);
        Assert.fail("Expected IllegalArgumentException when username is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Username must not be null"));
    }
    try {
        functionDAO.getUserFunctionsForEvent(ADMIN, null);
        Assert.fail("Expected IllegalArgumentException when Event is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Event must not be null"));
    }
    // Check functions for events
    List<Function> functionsForAPIUpdateFromDB = functionDAO.getUserFunctionsForEvent(ADMIN, Event.API_UPDATE);
    Assert.assertEquals(functionsForAPIUpdateFromDB.size(), 1);
    Assert.assertTrue(functionsForAPIUpdateFromDB.get(0).equals(function1));
    List<Function> functionsForAPICreateFromDB = functionDAO.getUserFunctionsForEvent(ADMIN, Event.API_CREATION);
    Assert.assertEquals(functionsForAPICreateFromDB.size(), 2);
    Assert.assertTrue(functionsForAPICreateFromDB.get(0).equals(function1) || functionsForAPICreateFromDB.get(0).equals(function3));
    Assert.assertTrue(functionsForAPICreateFromDB.get(1).equals(function1) || functionsForAPICreateFromDB.get(1).equals(function3));
    // Validate deleteEventFunctionMapping() args
    try {
        functionDAO.deleteEventFunctionMapping(null, Event.API_CREATION, function1.getName());
        Assert.fail("Expected IllegalArgumentException when username is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Username must not be null"));
    }
    try {
        functionDAO.deleteEventFunctionMapping(ADMIN, null, function1.getName());
        Assert.fail("Expected IllegalArgumentException when Event is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Event must not be null"));
    }
    try {
        functionDAO.deleteEventFunctionMapping(ADMIN, Event.API_CREATION, null);
        Assert.fail("Expected IllegalArgumentException when function name is null.");
    } catch (IllegalArgumentException e) {
        Assert.assertTrue(e.getMessage().contains("Function name must not be null"));
    }
    // Check deletion
    functionDAO.deleteEventFunctionMapping(ADMIN, Event.API_CREATION, function3.getName());
    List<Function> functionsForAPICreateFromDBAfterDeletion = functionDAO.getUserFunctionsForEvent(ADMIN, Event.API_CREATION);
    Assert.assertEquals(functionsForAPICreateFromDBAfterDeletion.size(), 1);
    Assert.assertEquals(functionsForAPICreateFromDBAfterDeletion.get(0), function1);
}
Also used : Function(org.wso2.carbon.apimgt.core.models.Function) Event(org.wso2.carbon.apimgt.core.models.Event) FunctionDAO(org.wso2.carbon.apimgt.core.dao.FunctionDAO) Test(org.testng.annotations.Test)

Example 22 with Event

use of org.wso2.siddhi.core.event.Event in project carbon-apimgt by wso2.

the class ConfigureXmlAnalyzer method execute.

@Override
public BValue[] execute(Context context) {
    String event = getStringArgument(context, 0);
    BStruct xmlInfo = ((BStruct) getRefArgument(context, 0));
    if (xmlInfo != null) {
        String xmlPolicyId = xmlInfo.getStringField(0);
        switch(event) {
            case THREAT_PROTECTION_POLICY_ADD:
            case THREAT_PROTECTION_POLICY_UPDATE:
                String name = xmlInfo.getStringField(1);
                boolean dtdEnabled = xmlInfo.getBooleanField(0) != 0;
                boolean externalEntitiesEnabled = xmlInfo.getBooleanField(1) != 0;
                int maxXMLDepth = (int) xmlInfo.getIntField(0);
                int elementCount = (int) xmlInfo.getIntField(1);
                int attributeCount = (int) xmlInfo.getIntField(2);
                int attributeLength = (int) xmlInfo.getIntField(3);
                int entityExpansionLimit = (int) xmlInfo.getIntField(4);
                int childrenPerElement = (int) xmlInfo.getIntField(5);
                XMLConfig xmlConfig = new XMLConfig();
                xmlConfig.setName(name);
                xmlConfig.setDtdEnabled(dtdEnabled);
                xmlConfig.setExternalEntitiesEnabled(externalEntitiesEnabled);
                xmlConfig.setMaxDepth(maxXMLDepth);
                xmlConfig.setMaxElementCount(elementCount);
                xmlConfig.setMaxAttributeCount(attributeCount);
                xmlConfig.setMaxAttributeLength(attributeLength);
                xmlConfig.setEntityExpansionLimit(entityExpansionLimit);
                xmlConfig.setMaxChildrenPerElement(childrenPerElement);
                // put into ConfigurationHolder
                ConfigurationHolder.addXmlConfig(xmlPolicyId, xmlConfig);
                break;
            case THREAT_PROTECTION_POLICY_DELETE:
                ConfigurationHolder.removeXmlConfig(xmlPolicyId);
                break;
            default:
                log.warn("Unknown event type for XML Threat Protection Policy. Event: " + event);
                break;
        }
    }
    return getBValues(new BBoolean(true));
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) XMLConfig(org.wso2.carbon.apimgt.ballerina.threatprotection.configurations.XMLConfig) BBoolean(org.ballerinalang.model.values.BBoolean)

Example 23 with Event

use of org.wso2.siddhi.core.event.Event in project carbon-apimgt by wso2.

the class Publish method execute.

@Override
public BValue execute(Context context) {
    log.info("publishing event to DAS");
    BConnector bConnector = (BConnector) getRefArgument(context, 0);
    BJSON json = (BJSON) getRefArgument(context, 1);
    String streamName = json.value().get(Constants.STREAM_NAME).asText();
    String streamVersion = json.value().get(Constants.STREAM_VERSION).asText();
    ArrayNode metaData = (ArrayNode) json.value().get(Constants.META_DATA);
    ArrayNode correlationData = (ArrayNode) json.value().get(Constants.CORRELATION_DATA);
    ArrayNode payloadData = (ArrayNode) json.value().get(Constants.PAYLOAD_DATA);
    Object[] metaDataArr = new Object[metaData.size()];
    JSONArray jsonMetaData = new JSONArray(metaData.toString());
    for (int i = 0; i < jsonMetaData.length(); i++) {
        metaDataArr[i] = jsonMetaData.get(i);
    }
    Object[] correlationDataArr = new Object[correlationData.size()];
    JSONArray jsonCorrelationData = new JSONArray(correlationData.toString());
    for (int i = 0; i < jsonCorrelationData.length(); i++) {
        correlationDataArr[i] = jsonCorrelationData.get(i);
    }
    Object[] payloadDataArr = new Object[payloadData.size()];
    JSONArray jsonPayloadData = new JSONArray(payloadData.toString());
    for (int i = 0; i < jsonPayloadData.length(); i++) {
        payloadDataArr[i] = jsonPayloadData.get(i);
    }
    BMap sharedMap = (BMap) bConnector.getRefField(1);
    EventPublisher pub = (EventPublisher) sharedMap.get(Constants.PUBLISHER_INSTANCE);
    Event event = new Event();
    event.setStreamId(DataBridgeCommonsUtils.generateStreamId(streamName, streamVersion));
    event.setMetaData(metaDataArr);
    event.setCorrelationData(correlationDataArr);
    event.setPayloadData(payloadDataArr);
    pub.publish(event);
    return null;
}
Also used : BConnector(org.ballerinalang.model.values.BConnector) BMap(org.ballerinalang.model.values.BMap) JSONArray(org.json.JSONArray) Event(org.wso2.carbon.databridge.commons.Event) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) BJSON(org.ballerinalang.model.values.BJSON)

Example 24 with Event

use of org.wso2.siddhi.core.event.Event in project carbon-apimgt by wso2.

the class DASThriftTestServer method start.

public void start(int receiverPort) throws DataBridgeException {
    DataPublisherTestUtil.setKeyStoreParams();
    streamDefinitionStore = getStreamDefinitionStore();
    numberOfEventsReceived = new AtomicInteger(0);
    DataBridge databridge = new DataBridge(new AuthenticationHandler() {

        public boolean authenticate(String userName, String password) {
            // allays authenticate to true
            return true;
        }

        public void initContext(AgentSession agentSession) {
        // To change body of implemented methods use File | Settings |
        // File Templates.
        }

        public void destroyContext(AgentSession agentSession) {
        }
    }, streamDefinitionStore, DataPublisherTestUtil.getDataBridgeConfigPath());
    thriftDataReceiver = new ThriftDataReceiver(receiverPort, databridge);
    databridge.subscribe(new AgentCallback() {

        int totalSize = 0;

        @Override
        public void definedStream(StreamDefinition streamDefinition) {
            log.info("StreamDefinition " + streamDefinition);
        }

        @Override
        public void removeStream(StreamDefinition streamDefinition) {
            log.info("StreamDefinition remove " + streamDefinition);
        }

        /**
         * Retrving and handling all the events to DAS event receiver
         * @param eventList list of event it received
         * @param credentials client credentials
         */
        public void receive(List<Event> eventList, Credentials credentials) {
            for (Event event : eventList) {
                String streamKey = event.getStreamId();
                if (!dataTables.containsKey(streamKey)) {
                    dataTables.put(streamKey, new ArrayList<Event>());
                }
                dataTables.get(streamKey).add(event);
                log.info("===  " + event.toString());
            }
            numberOfEventsReceived.addAndGet(eventList.size());
            log.info("Received events : " + numberOfEventsReceived);
        }
    });
    String address = "localhost";
    log.info("DAS Test Thrift Server starting on " + address);
    thriftDataReceiver.start(address);
    log.info("DAS Test Thrift Server Started");
}
Also used : AgentSession(org.wso2.carbon.databridge.core.Utils.AgentSession) StreamDefinition(org.wso2.carbon.databridge.commons.StreamDefinition) ArrayList(java.util.ArrayList) AgentCallback(org.wso2.carbon.databridge.core.AgentCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThriftDataReceiver(org.wso2.carbon.databridge.receiver.thrift.ThriftDataReceiver) Event(org.wso2.carbon.databridge.commons.Event) AuthenticationHandler(org.wso2.carbon.databridge.core.internal.authentication.AuthenticationHandler) Credentials(org.wso2.carbon.databridge.commons.Credentials) DataBridge(org.wso2.carbon.databridge.core.DataBridge)

Example 25 with Event

use of org.wso2.siddhi.core.event.Event in project carbon-apimgt by wso2.

the class FunctionTriggerTestCase method testCaptureEvent.

@Test(description = "Test method for capturing event")
public void testCaptureEvent() throws APIManagementException, URISyntaxException {
    FunctionDAO functionDAO = Mockito.mock(FunctionDAO.class);
    RestCallUtil restCallUtil = Mockito.mock(RestCallUtil.class);
    FunctionTrigger functionTrigger = new FunctionTrigger(functionDAO, restCallUtil);
    URI testUri = new URI("http://testEndpointUri");
    List<Function> functions = new ArrayList<>();
    Function function = new Function(FUNCTION_NAME, testUri);
    functions.add(function);
    HttpResponse response = new HttpResponse();
    response.setResponseCode(200);
    Event event = Event.API_CREATION;
    ZonedDateTime eventTime = ZonedDateTime.now();
    Mockito.when(functionDAO.getUserFunctionsForEvent(USER_NAME, event)).thenReturn(functions);
    Mockito.when(restCallUtil.postRequest(Mockito.eq(function.getEndpointURI()), Mockito.eq(null), Mockito.eq(null), Mockito.any(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(Collections.emptyMap()))).thenReturn(response);
    functionTrigger.captureEvent(event, USER_NAME, eventTime, new HashMap<>());
    // When the event parameter is null
    try {
        functionTrigger.captureEvent(null, USER_NAME, eventTime, new HashMap<>());
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Event must not be null");
    }
    // When the username parameter is null
    try {
        functionTrigger.captureEvent(event, null, eventTime, new HashMap<>());
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Username must not be null");
    }
    // When the eventTime parameter is null
    try {
        functionTrigger.captureEvent(event, USER_NAME, null, new HashMap<>());
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Event_time must not be null");
    }
    // When the metadata parameter is null
    try {
        functionTrigger.captureEvent(event, USER_NAME, eventTime, null);
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Payload must not be null");
    }
}
Also used : Function(org.wso2.carbon.apimgt.core.models.Function) ZonedDateTime(java.time.ZonedDateTime) RestCallUtil(org.wso2.carbon.apimgt.core.api.RestCallUtil) ArrayList(java.util.ArrayList) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse) Event(org.wso2.carbon.apimgt.core.models.Event) URI(java.net.URI) FunctionDAO(org.wso2.carbon.apimgt.core.dao.FunctionDAO) Test(org.testng.annotations.Test)

Aggregations

APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)8 GatewayException (org.wso2.carbon.apimgt.core.exception.GatewayException)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)5 Event (org.wso2.carbon.apimgt.core.models.Event)5 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 Test (org.testng.annotations.Test)4 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)4 Function (org.wso2.carbon.apimgt.core.models.Function)4 ZonedDateTime (java.time.ZonedDateTime)3 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)3 API (org.wso2.carbon.apimgt.core.models.API)3 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)3 ApplicationEvent (org.wso2.carbon.apimgt.core.models.events.ApplicationEvent)3 PolicyEvent (org.wso2.carbon.apimgt.core.models.events.PolicyEvent)3 ThreatProtectionEvent (org.wso2.carbon.apimgt.core.models.events.ThreatProtectionEvent)3 Gson (com.google.gson.Gson)2 URI (java.net.URI)2