Search in sources :

Example 16 with Event

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

the class ThrottleTimeBatchWindowTestCase method throttleTimeWindowBatchTest3.

@Ignore
public void throttleTimeWindowBatchTest3() throws InterruptedException {
    SiddhiManager siddhiManager = new SiddhiManager();
    String cseEventStream = "" + "define stream cseEventStream (symbol string, price float, volume int);";
    String query = "" + "@info(name = 'query1') " + "from cseEventStream#throttler:timeBatch(1 min , 0) " + "select symbol,sum(price) as sumPrice,volume, expiryTimeStamp " + "insert all events into outputStream ;";
    SiddhiAppRuntime executionPlanRuntime = siddhiManager.createSiddhiAppRuntime(cseEventStream + query);
    executionPlanRuntime.addCallback("query1", new QueryCallback() {

        @Override
        public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
            EventPrinter.print(timeStamp, inEvents, removeEvents);
            if (inEvents != null) {
                inEventCount = inEventCount + inEvents.length;
                lastCurrentEvent = inEvents[inEvents.length - 1];
            } else if (removeEvents != null) {
                removeEventCount = removeEventCount + removeEvents.length;
                lastRemoveEvent = removeEvents[removeEvents.length - 1];
            }
            eventArrived = true;
        }
    });
    InputHandler inputHandler = executionPlanRuntime.getInputHandler("cseEventStream");
    executionPlanRuntime.start();
    inputHandler.send(new Object[] { "IBM", 700f, 0 });
    inputHandler.send(new Object[] { "WSO2", 60.5f, 1 });
    Thread.sleep(260000);
    inputHandler.send(new Object[] { "IBM", 700f, 0 });
    Assert.assertEquals(3, inEventCount);
    Assert.assertTrue("Event expiry time is not valid for the current batch", (Long) (lastCurrentEvent.getData()[3]) >= System.currentTimeMillis());
    Assert.assertTrue(eventArrived);
    executionPlanRuntime.shutdown();
}
Also used : InputHandler(org.wso2.siddhi.core.stream.input.InputHandler) SiddhiAppRuntime(org.wso2.siddhi.core.SiddhiAppRuntime) Event(org.wso2.siddhi.core.event.Event) SiddhiManager(org.wso2.siddhi.core.SiddhiManager) QueryCallback(org.wso2.siddhi.core.query.output.callback.QueryCallback) Ignore(org.junit.Ignore)

Example 17 with Event

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

the class EmitOnStateChange method process.

@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor processor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
    while (streamEventChunk.hasNext()) {
        StreamEvent event = streamEventChunk.next();
        Boolean currentThrottleState = (Boolean) isThrottledExpressionExecutor.execute(event);
        String key = (String) keyExpressionExecutor.execute(event);
        Boolean lastThrottleState = (Boolean) throttleStateMap.get(key);
        if (currentThrottleState.equals(lastThrottleState) && !currentThrottleState) {
            streamEventChunk.remove();
        } else {
            throttleStateMap.put(key, currentThrottleState);
        }
    }
    nextProcessor.process(streamEventChunk);
}
Also used : StreamEvent(org.wso2.siddhi.core.event.stream.StreamEvent)

Example 18 with Event

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

the class APIPublisherImpl method updateAPI.

/**
 * Updates design and implementation of an existing API. This method must not be used to change API status.
 * Implementations should throw an exceptions when such attempts are made. All life cycle state changes
 * should be carried out using the changeAPIStatus method of this interface.
 *
 * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
 * @throws APIManagementException if failed to update API
 */
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    apiBuilder.updatedBy(getUsername());
    try {
        API originalAPI = getAPIbyUUID(apiBuilder.getId());
        if (originalAPI != null) {
            // Checks whether the logged in user has the "UPDATE" permission for the API
            verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
            apiBuilder.createdTime(originalAPI.getCreatedTime());
            // workflow status is an internal property and shouldn't be allowed to update externally
            apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
            if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
                if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                    apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
                    Map<String, Integer> roleNamePermissionList;
                    roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                    apiBuilder.permissionMap(roleNamePermissionList);
                }
                Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
                validateEndpoints(apiEndpointMap, true);
                validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
                createUriTemplateList(apiBuilder, true);
                validateApiPolicy(apiBuilder.getApiPolicy());
                validateSubscriptionPolicies(apiBuilder);
                String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
                String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
                GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
                APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
                gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
                String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
                API api = apiBuilder.build();
                // Add API to gateway
                gateway.updateAPI(api);
                if (log.isDebugEnabled()) {
                    log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
                }
                if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
                    if (!checkIfAPIContextExists(api.getContext())) {
                        // if the API has public visibility, update the API without any role checking
                        if (API.Visibility.PUBLIC == api.getVisibility()) {
                            getApiDAO().updateAPI(api.getId(), api);
                        } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                            // get all the roles in the system
                            Set<String> availableRoles = APIUtils.getAllAvailableRoles();
                            // get the roles needed to be associated with the API
                            Set<String> apiRoleList = api.getVisibleRoles();
                            // if the API has role based visibility, update the API with role checking
                            if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
                                getApiDAO().updateAPI(api.getId(), api);
                            }
                        }
                        getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                        getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                    } else {
                        throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
                    }
                } else {
                    // if the API has public visibility, update the API without any role checking
                    if (API.Visibility.PUBLIC == api.getVisibility()) {
                        getApiDAO().updateAPI(api.getId(), api);
                    } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                        // get all the roles in the system
                        Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                        // get the roles needed to be associated with the API
                        Set<String> apiRoleList = api.getVisibleRoles();
                        // if the API has role based visibility, update the API with role checking
                        if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                            getApiDAO().updateAPI(api.getId(), api);
                        }
                    }
                    getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                    getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                }
                if (log.isDebugEnabled()) {
                    log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
                    // 'API_M Functions' related code
                    // Create a payload with event specific details
                    Map<String, String> eventPayload = new HashMap<>();
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
                    // This will notify all the EventObservers(Asynchronous)
                    ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
                    ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
                }
            } else {
                APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
            }
        } else {
            log.error("Couldn't found API with ID " + apiBuilder.getId());
            throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ParseException(org.json.simple.parser.ParseException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 19 with Event

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

the class FunctionTrigger method captureEvent.

/**
 * Used to observe all the {@link org.wso2.carbon.apimgt.core.models.Event} occurrences
 * in an {@link org.wso2.carbon.apimgt.core.api.APIMObservable} object and trigger corresponding function that is
 * mapped to the particular {@link org.wso2.carbon.apimgt.core.models.Event} occurred.
 * <p>
 * This is a specific implementation for
 * {@link org.wso2.carbon.apimgt.core.api.EventObserver#captureEvent(Event, String, ZonedDateTime, Map)} method,
 * provided by {@link org.wso2.carbon.apimgt.core.impl.FunctionTrigger} which implements
 * {@link org.wso2.carbon.apimgt.core.api.EventObserver} interface.
 * <p>
 * {@inheritDoc}
 *
 * @see org.wso2.carbon.apimgt.core.impl.EventLogger#captureEvent(Event, String, ZonedDateTime, Map)
 */
@Override
public void captureEvent(Event event, String username, ZonedDateTime eventTime, Map<String, String> metadata) {
    List<Function> functions = null;
    String jsonPayload = null;
    if (event == null) {
        throw new IllegalArgumentException("Event must not be null");
    }
    if (username == null) {
        throw new IllegalArgumentException("Username must not be null");
    }
    if (eventTime == null) {
        throw new IllegalArgumentException("Event_time must not be null");
    }
    if (metadata == null) {
        throw new IllegalArgumentException("Payload must not be null");
    }
    // Add general attributes to payload
    metadata.put(APIMgtConstants.FunctionsConstants.EVENT, event.getEventAsString());
    metadata.put(APIMgtConstants.FunctionsConstants.COMPONENT, event.getComponent().getComponentAsString());
    metadata.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
    metadata.put(APIMgtConstants.FunctionsConstants.EVENT_TIME, eventTime.toString());
    try {
        functions = functionDAO.getUserFunctionsForEvent(username, event);
        jsonPayload = new Gson().toJson(metadata);
    } catch (APIMgtDAOException e) {
        String message = "Error loading functions for event from DB: -event: " + event + " -Username: " + username;
        log.error(message, new APIManagementException("Problem invoking 'getUserFunctionsForEvent' method in " + "'FunctionDAO' ", e, ExceptionCodes.APIMGT_DAO_EXCEPTION));
    }
    if (functions != null && !functions.isEmpty()) {
        for (Function function : functions) {
            HttpResponse response = null;
            try {
                response = restCallUtil.postRequest(function.getEndpointURI(), null, null, Entity.json(jsonPayload), MediaType.APPLICATION_JSON_TYPE, Collections.EMPTY_MAP);
            } catch (APIManagementException e) {
                log.error("Failed to make http request: -function: " + function.getName() + " -endpoint URI: " + function.getEndpointURI() + " -event: " + event + " -Username: " + username, e);
            }
            if (response != null) {
                int responseStatusCode = response.getResponseCode();
                // Benefit of integer division used to ensure all possible success response codes covered
                if (responseStatusCode / 100 == 2) {
                    log.info("Function successfully invoked: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
                } else {
                    log.error("Problem invoking function: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
                }
            }
        }
    }
}
Also used : Function(org.wso2.carbon.apimgt.core.models.Function) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Gson(com.google.gson.Gson) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse)

Example 20 with Event

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

the class APIPublisherImpl method deleteAPI.

/**
 * Delete an API
 *
 * @param identifier UUID of the API.
 * @throws APIManagementException if failed to remove the API
 */
@Override
public void deleteAPI(String identifier) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    try {
        if (getAPISubscriptionCountByAPI(identifier) == 0) {
            API api = getAPIbyUUID(identifier);
            // Checks whether the user has required permissions to delete the API
            verifyUserPermissionsToDeleteAPI(getUsername(), api);
            String apiWfStatus = api.getWorkflowStatus();
            API.APIBuilder apiBuilder = new API.APIBuilder(api);
            // Delete API in gateway
            gateway.deleteAPI(api);
            if (log.isDebugEnabled()) {
                log.debug("API : " + api.getName() + " has been successfully removed from the gateway");
            }
            if (!getApiDAO().isAPIVersionsExist(api.getName())) {
                Map<String, String> scopeMap = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(identifier));
                for (String scope : scopeMap.keySet()) {
                    try {
                        getKeyManager().deleteScope(scope);
                    } catch (KeyManagementException e) {
                        // We ignore the error due to if scope get deleted from other end that will affect to delete
                        // api.
                        log.warn("Scope couldn't delete from Key Manager", e);
                    }
                }
            }
            getApiDAO().deleteAPI(identifier);
            // Deleting API specific endpoints
            if (api.getEndpoint() != null) {
                for (Map.Entry<String, Endpoint> entry : api.getEndpoint().entrySet()) {
                    Endpoint endpoint = entry.getValue();
                    if (APIMgtConstants.API_SPECIFIC_ENDPOINT.equals(endpoint.getApplicableLevel())) {
                        deleteEndpoint(endpoint.getId());
                    }
                }
            }
            getApiLifecycleManager().removeLifecycle(apiBuilder.getLifecycleInstanceId());
            APIUtils.logDebug("API with id " + identifier + " was deleted successfully.", log);
            if (APILCWorkflowStatus.PENDING.toString().equals(apiWfStatus)) {
                cleanupPendingTaskForAPIStateChange(identifier);
            }
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PROVIDER, api.getProvider());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_DELETION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            throw new ApiDeleteFailureException("API with " + identifier + " already have subscriptions");
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while deleting the API with id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Error occurred while Disassociating the API with Lifecycle id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while deleting API with id - " + identifier + " from gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) ApiDeleteFailureException(org.wso2.carbon.apimgt.core.exception.ApiDeleteFailureException) HashMap(java.util.HashMap) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) Map(java.util.Map) HashMap(java.util.HashMap)

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