Search in sources :

Example 16 with Topic

use of org.wso2.carbon.apimgt.api.model.webhooks.Topic 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 17 with Topic

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

the class BallerinaWebSubConnectionListener method autoRespondToIntentVerification.

/**
 * Method to automatically respond to intent verification requests for subscriptions/unsubscriptions if a resource
 * named {@link WebSubSubscriberConstants#RESOURCE_NAME_VERIFY_INTENT} is not specified.
 *
 * @param httpCarbonMessage the message/request received
 */
private void autoRespondToIntentVerification(HTTPCarbonMessage httpCarbonMessage) {
    String annotatedTopic = httpCarbonMessage.getProperty(WebSubSubscriberConstants.ANNOTATED_TOPIC).toString();
    PrintStream console = System.out;
    if (httpCarbonMessage.getProperty(HttpConstants.QUERY_STR) != null) {
        String queryString = (String) httpCarbonMessage.getProperty(HttpConstants.QUERY_STR);
        BMap<String, BString> params = new BMap<>();
        try {
            HTTPCarbonMessage response = HttpUtil.createHttpCarbonMessage(false);
            response.waitAndReleaseAllEntities();
            URIUtil.populateQueryParamMap(queryString, params);
            String mode = params.get(WebSubSubscriberConstants.PARAM_HUB_MODE).stringValue();
            if ((WebSubSubscriberConstants.SUBSCRIBE.equals(mode) || WebSubSubscriberConstants.UNSUBSCRIBE.equals(mode)) && annotatedTopic.equals(params.get(WebSubSubscriberConstants.PARAM_HUB_TOPIC).stringValue())) {
                String challenge = params.get(WebSubSubscriberConstants.PARAM_HUB_CHALLENGE).stringValue();
                response.addHttpContent(new DefaultLastHttpContent(Unpooled.wrappedBuffer(challenge.getBytes(StandardCharsets.UTF_8))));
                response.setProperty(HttpConstants.HTTP_STATUS_CODE, 202);
                console.println("ballerina: Intent Verification agreed - Mode [" + mode + "], Topic [" + annotatedTopic + "], Lease Seconds [" + params.get(WebSubSubscriberConstants.PARAM_HUB_LEASE_SECONDS) + "]");
            } else {
                console.println("ballerina: Intent Verification denied - Mode [" + mode + "] for Incorrect Topic [" + annotatedTopic + "]");
                response.setProperty(HttpConstants.HTTP_STATUS_CODE, 404);
            }
            HttpUtil.sendOutboundResponse(httpCarbonMessage, response);
        } catch (UnsupportedEncodingException e) {
            throw new BallerinaException("Error responding to intent verification request: " + e.getMessage());
        }
    }
}
Also used : PrintStream(java.io.PrintStream) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) BMap(org.ballerinalang.model.values.BMap) BString(org.ballerinalang.model.values.BString) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BString(org.ballerinalang.model.values.BString) BallerinaException(org.ballerinalang.util.exceptions.BallerinaException)

Example 18 with Topic

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

the class WebhooksDAO method updateDeliveryStatus.

/*
     * This method can be used to update webhooks callback url delivery data to the database
     *
     * @param properties Subscription request properties
     * */
public void updateDeliveryStatus(String apiUUID, String appID, String tenantDomain, String callback, String topic, int state) throws APIManagementException {
    try (Connection conn = APIMgtDBUtil.getConnection()) {
        conn.setAutoCommit(false);
        try (PreparedStatement prepareStmt = conn.prepareStatement(SQLConstants.WebhooksSqlConstants.UPDATE_DELIVERY_STATE)) {
            Date currentTime = new Date();
            Timestamp updatedTimestamp = new Timestamp(currentTime.getTime());
            prepareStmt.setTimestamp(1, updatedTimestamp);
            prepareStmt.setInt(2, state);
            prepareStmt.setString(3, apiUUID);
            prepareStmt.setString(4, appID);
            prepareStmt.setString(5, tenantDomain);
            prepareStmt.setString(6, callback);
            prepareStmt.setString(7, topic);
            prepareStmt.executeUpdate();
            conn.commit();
        } catch (SQLException e) {
            handleConnectionRollBack(conn);
            throw new APIManagementException("Error while storing webhooks delivery status data for callback" + callback + " for the API " + apiUUID, e);
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while storing webhooks delivery status data for callback " + callback + " for the API " + apiUUID, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) Date(java.util.Date)

Example 19 with Topic

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

the class ApiMgtDAO method getTopicSubscriptionsByApiUUID.

/**
 * Retrieves the web hook topc subscriptions from an application to a given api.
 *
 * @param applicationId application uuid
 * @param apiId         api uuid
 * @return set of web hook topic subscriptions
 * @throws APIManagementException
 */
public Set<Subscription> getTopicSubscriptionsByApiUUID(String applicationId, String apiId) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    String getTopicSubscriptionsByApiIdQuery = SQLConstants.GET_WH_TOPIC_SUBSCRIPTIONS_BY_API_KEY;
    Set<Subscription> subscriptionSet = new HashSet();
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(getTopicSubscriptionsByApiIdQuery);
        ps.setString(1, applicationId);
        ps.setString(2, apiId);
        resultSet = ps.executeQuery();
        while (resultSet.next()) {
            Subscription subscription = new Subscription();
            subscription.setApiUuid(resultSet.getString("API_UUID"));
            subscription.setCallback(resultSet.getString("HUB_CALLBACK_URL"));
            Timestamp deliveryTime = resultSet.getTimestamp("DELIVERED_AT");
            if (deliveryTime != null) {
                subscription.setLastDelivery(new Date(deliveryTime.getTime()));
            }
            subscription.setLastDeliveryState(resultSet.getInt("DELIVERY_STATE"));
            subscription.setTopic(resultSet.getString("HUB_TOPIC"));
            subscription.setAppID(resultSet.getString("APPLICATION_ID"));
            subscriptionSet.add(subscription);
        }
        return subscriptionSet;
    } catch (SQLException e) {
        handleException("Failed to retrieve topic subscriptions for application  " + applicationId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
    }
    return null;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Subscription(org.wso2.carbon.apimgt.api.model.webhooks.Subscription) Timestamp(java.sql.Timestamp) Date(java.util.Date) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 20 with Topic

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

the class ApiMgtDAO method getTopicSubscriptions.

/**
 * Retrieves set of web hook topic subscriptions for a application.
 *
 * @param applicationId application UUID
 * @return set of web hook subscriptions.
 * @throws APIManagementException if failed to retrieve web hook topc subscriptions
 */
public Set<Subscription> getTopicSubscriptions(String applicationId) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    String getTopicSubscriptionsQuery = SQLConstants.GET_WH_TOPIC_SUBSCRIPTIONS;
    Set<Subscription> subscriptionSet = new HashSet();
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(getTopicSubscriptionsQuery);
        ps.setString(1, applicationId);
        resultSet = ps.executeQuery();
        while (resultSet.next()) {
            Subscription subscription = new Subscription();
            subscription.setApiUuid(resultSet.getString("API_UUID"));
            subscription.setCallback(resultSet.getString("HUB_CALLBACK_URL"));
            Timestamp deliveryTime = resultSet.getTimestamp("DELIVERED_AT");
            if (deliveryTime != null) {
                subscription.setLastDelivery(new Date(deliveryTime.getTime()));
            }
            subscription.setLastDeliveryState(resultSet.getInt("DELIVERY_STATE"));
            subscription.setTopic(resultSet.getString("HUB_TOPIC"));
            subscription.setAppID(resultSet.getString("APPLICATION_ID"));
            subscriptionSet.add(subscription);
        }
    } catch (SQLException e) {
        handleException("Failed to retrieve topic subscriptions for application  " + applicationId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
    }
    return null;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Subscription(org.wso2.carbon.apimgt.api.model.webhooks.Subscription) Timestamp(java.sql.Timestamp) Date(java.util.Date) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

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