Search in sources :

Example 21 with Broker

use of org.wso2.carbon.apimgt.core.api.Broker in project product-iots by wso2.

the class AndroidSenseEnrollment method testEventPublishing.

@Test(description = "Test an Android sense device data publishing.", dependsOnMethods = { "testEnrollment" })
public void testEventPublishing() throws Exception {
    String DEVICE_TYPE = "android_sense";
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + DEVICE_ID + "/data";
    int qos = 2;
    String broker = "tcp://localhost:1886";
    String clientId = DEVICE_ID + ":" + DEVICE_TYPE;
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessToken);
    connOpts.setPassword("".toCharArray());
    connOpts.setKeepAliveInterval(120);
    connOpts.setCleanSession(true);
    log.info("Connecting to broker: " + broker);
    sampleClient.connect(connOpts);
    log.info("Connected");
    MqttMessage message = new MqttMessage(PayloadGenerator.getJsonArray(Constants.AndroidSenseEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.AndroidSenseEnrollment.PUBLISH_DATA_OPERATION).toString().getBytes());
    message.setQos(qos);
    for (int i = 0; i < 100; i++) {
        sampleClient.publish(topic, message);
        log.info("Message is published to Mqtt Client");
        Thread.sleep(1000);
    }
    sampleClient.disconnect();
    HttpResponse response = analyticsClient.get(Constants.AndroidSenseEnrollment.IS_TABLE_EXIST_CHECK_URL + "?table=" + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME);
    Assert.assertEquals("ORG_WSO2_IOT_ANDROID_BATTERY_STATS table does not exist. Problem with the android sense " + "analytics", HttpStatus.SC_OK, response.getResponseCode());
    // Allow some time to perform the analytics tasks.
    log.info("Mqtt Client is Disconnected");
    String url = Constants.AndroidSenseEnrollment.RETRIEVER_ENDPOINT + Constants.AndroidSenseEnrollment.BATTERY_STATS_TABLE_NAME + "/";
    Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 3600000);
    url += timestamp.getTime() + "/" + new Timestamp(System.currentTimeMillis()).getTime() + "/0/100";
    response = analyticsClient.get(url);
    JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray();
// TODO: temporarily commenting out untill new changes are merged
// Assert.assertEquals(
// "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
// HttpStatus.SC_OK, response.getResponseCode());
// Assert.assertTrue(
// "Published event for the device with the id " + DEVICE_ID + " is not inserted to analytics table",
// jsonArray.size() > 0);
}
Also used : MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) JsonArray(com.google.gson.JsonArray) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) MemoryPersistence(org.eclipse.paho.client.mqttv3.persist.MemoryPersistence) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) Timestamp(java.sql.Timestamp) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Example 22 with Broker

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

the class WebhooksSubscriptionEventHandler method sendSubscriptionNotificationOnRealtime.

/**
 * Method to publish the subscription request on to the realtime message broker
 *
 * @param event realtime notification data read from the event
 */
private void sendSubscriptionNotificationOnRealtime(WebhooksSubscriptionEvent event, boolean isSuccess) {
    Object[] objects = new Object[] { event.getApiUUID(), event.getApiName(), event.getApiContext(), event.getApiVersion(), event.getAppID(), event.getTenantDomain(), event.getTenantId(), event.getCallback(), event.getTopic(), event.getMode(), event.getSecret(), event.getExpiryTime(), event.getSubscriberName(), event.getApplicationTier(), event.getTier(), event.getApiTier(), !isSuccess };
    EventPublisherEvent asyncWebhooksEvent = new EventPublisherEvent(APIConstants.WEBHOOKS_SUBSCRIPTION_STREAM_ID, System.currentTimeMillis(), objects);
    APIUtil.publishEvent(EventPublisherType.ASYNC_WEBHOOKS, asyncWebhooksEvent, asyncWebhooksEvent.toString());
}
Also used : EventPublisherEvent(org.wso2.carbon.apimgt.eventing.EventPublisherEvent)

Example 23 with Broker

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

the class AdditionalSubscriptionInfoMappingUtil method mapSolaceURLsToStoreDTO.

/**
 * Sets the Endpoint URLs For Solace API according to the protocols
 *
 * @param organizationName Solace broker organization name
 * @param environmentName      Name of the  Solace environment
 * @param availableProtocols List of available protocols
 * @return List containing AdditionalSubscriptionInfoSolaceURLsDTO
 * @throws APIManagementException if error occurred when retrieving protocols URLs from Solace broker
 */
private static List<AdditionalSubscriptionInfoSolaceURLsDTO> mapSolaceURLsToStoreDTO(String organizationName, String environmentName, List<String> availableProtocols) throws APIManagementException {
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    Environment solaceEnvironment = null;
    // Get Solace broker environment details
    for (Map.Entry<String, Environment> entry : gatewayEnvironments.entrySet()) {
        if (SolaceConstants.SOLACE_ENVIRONMENT.equals(entry.getValue().getProvider())) {
            solaceEnvironment = entry.getValue();
        }
    }
    if (solaceEnvironment != null) {
        List<SolaceURLsDTO> solaceURLsDTOEntries = SolaceStoreUtils.getSolaceURLsInfo(solaceEnvironment, organizationName, environmentName, availableProtocols);
        List<AdditionalSubscriptionInfoSolaceURLsDTO> solaceURLsDTOs = new ArrayList<>();
        for (SolaceURLsDTO entry : solaceURLsDTOEntries) {
            AdditionalSubscriptionInfoSolaceURLsDTO subscriptionInfoSolaceProtocolURLsDTO = new AdditionalSubscriptionInfoSolaceURLsDTO();
            subscriptionInfoSolaceProtocolURLsDTO.setProtocol(entry.getProtocol());
            subscriptionInfoSolaceProtocolURLsDTO.setEndpointURL(entry.getEndpointURL());
            solaceURLsDTOs.add(subscriptionInfoSolaceProtocolURLsDTO);
        }
        return solaceURLsDTOs;
    } else {
        throw new APIManagementException("Solace Environment configurations are not provided properly");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) AdditionalSubscriptionInfoSolaceURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceURLsDTO) SolaceURLsDTO(org.wso2.carbon.apimgt.solace.dtos.SolaceURLsDTO) Map(java.util.Map) AdditionalSubscriptionInfoSolaceURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceURLsDTO)

Example 24 with Broker

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

the class AdditionalSubscriptionInfoMappingUtil method setSolaceEnvironmentDetailsForSubscription.

/**
 * Sets the solace environment details For Solace API subscription with the protocol details
 *
 * @param api          API object
 * @param tenantDomain Tenant Domain
 * @return List containing AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO
 * @throws APIManagementException if error occurred when retrieving protocols URLs
 */
private static List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> setSolaceEnvironmentDetailsForSubscription(API api, String tenantDomain) throws APIManagementException {
    APIDTO apidto = APIMappingUtil.fromAPItoDTO(api, tenantDomain);
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    List<APIRevisionDeployment> revisionDeployments = apiConsumer.getAPIRevisionDeploymentListOfAPI(apidto.getId());
    List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> solaceEndpointURLsList = new ArrayList<>();
    // Get revision list of APIs and check Solace deployment environment
    for (APIRevisionDeployment revisionDeployment : revisionDeployments) {
        if (revisionDeployment.isDisplayOnDevportal()) {
            if (gatewayEnvironments != null) {
                // Deployed environment
                Environment environment = gatewayEnvironments.get(revisionDeployment.getDeployment());
                if (environment != null) {
                    // Set solace environment details if deployment is in Solace broker
                    if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(environment.getProvider())) {
                        AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO solaceEnvironmentDTO = new AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO();
                        solaceEnvironmentDTO.setEnvironmentName(environment.getName());
                        solaceEnvironmentDTO.setEnvironmentDisplayName(environment.getDisplayName());
                        solaceEnvironmentDTO.setOrganizationName(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION));
                        // Get Solace endpoint URLs for provided protocols
                        solaceEnvironmentDTO.setSolaceURLs(mapSolaceURLsToStoreDTO(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION), environment.getName(), apidto.getAsyncTransportProtocols()));
                        solaceEndpointURLsList.add(solaceEnvironmentDTO);
                    }
                }
            }
        }
    }
    return solaceEndpointURLsList;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 25 with Broker

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

the class ExternallyDeployedApiNotifier method undeployApiWhenRetiring.

/**
 * Undeploy APIs from external gateway when life cycle state changed to retire
 *
 * @param apiEvent APIEvent to undeploy APIs from external gateway
 * @throws NotifierException if error occurs when undeploying APIs from external gateway
 */
private void undeployApiWhenRetiring(APIEvent apiEvent) throws NotifierException {
    apiMgtDAO = ApiMgtDAO.getInstance();
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    boolean deleted;
    String apiId = apiEvent.getUuid();
    if (!APIConstants.RETIRED.equals(apiEvent.getApiStatus())) {
        return;
    }
    try {
        APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(CarbonContext.getThreadLocalCarbonContext().getUsername());
        API api = apiProvider.getAPIbyUUID(apiId, apiMgtDAO.getOrganizationByAPIUUID(apiId));
        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.undeployWhenRetire(api, 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) API(org.wso2.carbon.apimgt.api.model.API) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) 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