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);
}
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());
}
}
}
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);
}
}
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;
}
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;
}
Aggregations