From f40f8d02e04e02a8671a3e943e8f510a2cde6827 Mon Sep 17 00:00:00 2001 From: Ace Date: Sun, 15 Nov 2020 22:56:10 +0530 Subject: [PATCH 01/21] Adding operation partitioning functionality --- .../apimgt/integration/client/util/Utils.java | 2 +- .../internal/DeviceManagementDataHolder.java | 2 +- .../pom.xml | 180 +++++++++++++++ ...ContentProcessingInterruptedException.java | 45 ++++ .../framework/ContentProviderInfo.java | 55 +++++ .../framework/EmailContentProvider.java | 28 +++ .../EmailContentProviderFactory.java | 27 +++ .../allocation/framework/EmailContext.java | 138 ++++++++++++ .../task/allocation/framework/EmailData.java | 48 ++++ .../framework/EmailSenderConfig.java | 106 +++++++++ ...ailSenderConfigurationFailedException.java | 45 ++++ .../allocation/framework/EmailSenderUtil.java | 44 ++++ .../EmailSendingFailedException.java | 45 ++++ .../EmailTransportNotConfiguredException.java | 44 ++++ .../InvalidConfigurationStateException.java | 74 +++++++ .../RegistryBasedResourceLoader.java | 71 ++++++ .../task/allocation/framework/TypedValue.java | 50 +++++ .../VelocityBasedEmailContentProvider.java | 87 ++++++++ ...EmailSenderAxis2ConfigContextObserver.java | 55 +++++ .../internal/EmailSenderDataHolder.java | 69 ++++++ .../internal/EmailSenderServiceComponent.java | 127 +++++++++++ .../framework/internal/EmailUtils.java | 87 ++++++++ .../framework/service/EmailSenderService.java | 28 +++ .../service/EmailSenderServiceImpl.java | 150 +++++++++++++ .../src/test/resources/log4j.properties | 32 +++ .../src/test/resources/testng.xml | 29 +++ .../pom.xml | 185 ++++++++++++++++ .../beacon/HeartBeatBeaconUtils.java | 96 ++++++++ .../config/datasource/DataSourceConfig.java | 40 ++++ .../datasource/JNDILookupDefinition.java | 83 +++++++ .../beacon/dao/HeartBeatBeaconDAOFactory.java | 205 ++++++++++++++++++ .../heartbeat/beacon/dao/HeartBeatDAO.java | 42 ++++ .../dao/exception/HeartBeatDAOException.java | 78 +++++++ .../dao/impl/GenericHeartBeatDAOImpl.java | 166 ++++++++++++++ .../dao/util/HeartBeatBeaconDAOUtil.java | 91 ++++++++ .../heartbeat/beacon/dto/HeartBeatEvent.java | 49 +++++ .../heartbeat/beacon/dto/ServerContext.java | 68 ++++++ .../HeartBeatManagementException.java | 45 ++++ .../InvalidConfigurationStateException.java | 74 +++++++ .../ServerStatusUpdationFailedException.java | 45 ++++ .../internal/HeartBeatBeaconComponent.java | 72 ++++++ .../internal/HeartBeatBeaconDataHolder.java | 52 +++++ .../internal/HeartBeatInternalUtils.java | 77 +++++++ .../service/HeartBeatManagementService.java | 34 +++ .../HeartBeatManagementServiceImpl.java | 135 ++++++++++++ .../src/test/resources/log4j.properties | 32 +++ .../src/test/resources/testng.xml | 29 +++ components/task-allocation/pom.xml | 40 ++++ pom.xml | 1 + 49 files changed, 3405 insertions(+), 2 deletions(-) create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties create mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml create mode 100644 components/task-allocation/pom.xml diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java index 29845990d7..369f357ddd 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java @@ -235,4 +235,4 @@ public class Utils { throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { return loadKeyStore(trustStorePath,tsPassword,TRUST_STORE_TYPE); } -} \ No newline at end of file +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index e65ebe2fa4..88b662e1b2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -286,4 +286,4 @@ public class DeviceManagementDataHolder { public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) { this.deviceInformationManager = deviceInformationManager; } -} \ No newline at end of file +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml new file mode 100644 index 0000000000..c95d8f2d6f --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml @@ -0,0 +1,180 @@ + + + + + + + org.wso2.carbon.devicemgt + task-allocation + 4.1.11-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.dynamic.task.allocation.framework + bundle + Entgra - Task Allocation Framework + Entgra - Framework for partitioning tasks evenly amongst multiple nodes + http://entgra.io + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Entgra - Task Allocation Framework Bundle + io.entgra.dynamic.task.allocation.framework.internal + + org.apache.axis2.*;version="${axis2.osgi.version.range}", + org.apache.axiom.*; version="${axiom.osgi.version.range}", + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, + org.wso2.carbon.context, + org.wso2.carbon.utils.*, + org.wso2.carbon.registry.api, + org.w3c.dom, + org.apache.velocity;version="${velocity.version}", + org.apache.velocity.app;version="${velocity.version}", + org.apache.velocity.context;version="${velocity.version}", + org.apache.velocity.exception;version="${velocity.version}", + org.apache.velocity.runtime.resource;version="${velocity.version}", + org.apache.velocity.runtime.resource.loader;version="${velocity.version}", + org.apache.commons.io, + org.apache.axis2.transport.mail, + org.wso2.carbon.registry.core.service, + org.wso2.carbon.registry.core.session, + org.apache.commons.collections + + + !io.entgra.dynamic.task.allocation.framework.internal, + io.entgra.dynamic.task.allocation.framework.* + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.testng + testng + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + org.wso2.carbon + org.wso2.carbon.base + + + org.apache.axis2.wso2 + axis2 + + + org.wso2.orbit.org.apache.velocity + velocity + + + commons-io.wso2 + commons-io + + + org.apache.axis2.transport + axis2-transport-mail + + + org.wso2.carbon + org.wso2.carbon.registry.core + + + commons-collections.wso2 + commons-collections + + + + + diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java new file mode 100644 index 0000000000..ccf4358c35 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +public class ContentProcessingInterruptedException extends Exception { + + private static final long serialVersionUID = -3151279311929070298L; + + public ContentProcessingInterruptedException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public ContentProcessingInterruptedException(String message, Throwable cause) { + super(message, cause); + } + + public ContentProcessingInterruptedException(String msg) { + super(msg); + } + + public ContentProcessingInterruptedException() { + super(); + } + + public ContentProcessingInterruptedException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java new file mode 100644 index 0000000000..0bfe4339f8 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import java.util.Map; + +public class ContentProviderInfo { + + private String template; + private Map, Object>> params; + + public ContentProviderInfo(final String template, final Map, Object>> params) { + if (template == null || template.isEmpty()) { + throw new IllegalArgumentException("Template name cannot be null or empty"); + } + this.template = template; + if (params == null) { + throw new IllegalArgumentException("Place-holder parameter map cannot be null"); + } + this.params = params; + } + + public String getTemplate() { + return template; + } + + public Map, Object>> getParams() { + return params; + } + + public void addParam(String name, TypedValue, Object> param) { + params.put(name, param); + } + + public TypedValue, Object> getParam(String name) { + return params.get(name); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java new file mode 100644 index 0000000000..dd0005282a --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import java.util.Map; + +public interface EmailContentProvider { + + EmailData getContent(String path, + Map, Object>> params) throws ContentProcessingInterruptedException; + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java new file mode 100644 index 0000000000..2b75d014fc --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +public class EmailContentProviderFactory { + + public static EmailContentProvider getContentProvider() { + return new VelocityBasedEmailContentProvider(); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java new file mode 100644 index 0000000000..0e645cc564 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import java.util.*; + +public class EmailContext { + + private Set recipients; + private Properties properties; + private ContentProviderInfo contentProviderInfo; + + private EmailContext(final ContentProviderInfo contentProviderInfo, final Set recipients, final Properties properties) { + if (contentProviderInfo == null) { + throw new IllegalArgumentException("Content provider information cannot be null"); + } + this.contentProviderInfo = contentProviderInfo; + if (recipients == null) { + throw new IllegalArgumentException("Recipient list cannot be null"); + } + if (recipients.size() == 0) { + throw new IllegalArgumentException("No recipient is configured. Recipient list should carry at " + + "least one recipient"); + } + this.recipients = recipients; + if (properties == null) { + throw new IllegalArgumentException("Email Context property bag cannot be null"); + } + this.properties = properties; + } + + private EmailContext(final ContentProviderInfo contentProviderInfo, final String recipient, final Properties properties) { + if (contentProviderInfo == null) { + throw new IllegalArgumentException("Content provider information cannot be null"); + } + this.contentProviderInfo = contentProviderInfo; + if (recipient == null || recipient.isEmpty()) { + throw new IllegalArgumentException("Recipient can't be null or empty. Please specify a valid " + + "recipient email address"); + } + this.recipients = new HashSet() {{ + add(recipient); + }}; + if (properties == null) { + throw new IllegalArgumentException("Email Context property bag cannot be null"); + } + this.properties = properties; + } + + public Set getRecipients() { + return recipients; + } + + public Properties getProperties() { + return properties; + } + + public String getProperty(String name) { + return (String) properties.get(name); + } + + public void addProperty(String name, String value) { + properties.put(name, value); + } + + public ContentProviderInfo getContentProviderInfo() { + return contentProviderInfo; + } + + public static class EmailContextBuilder { + + private Set recipients; + private ContentProviderInfo contentProviderInfo; + private Properties properties; + + public EmailContextBuilder(final ContentProviderInfo contentProviderInfo, Set recipients) { + if (contentProviderInfo == null) { + throw new IllegalArgumentException("Content provider information cannot be null"); + } + this.contentProviderInfo = contentProviderInfo; + if (recipients == null) { + throw new IllegalArgumentException("Recipient list cannot be null"); + } + if (recipients.size() == 0) { + throw new IllegalArgumentException("No recipient is configured. Recipient list should carry at " + + "least one recipient"); + } + this.recipients = recipients; + this.properties = new Properties(); + } + + public EmailContextBuilder(final ContentProviderInfo contentProviderInfo, final String recipient, + final Properties properties) { + if (contentProviderInfo == null) { + throw new IllegalArgumentException("Content provider information cannot be null"); + } + this.contentProviderInfo = contentProviderInfo; + if (recipient == null || recipient.isEmpty()) { + throw new IllegalArgumentException("Recipient can't be null or empty. Please specify a valid " + + "recipient email address"); + } + this.recipients = new HashSet() {{ + add(recipient); + }}; + if (properties == null) { + throw new IllegalArgumentException("Email Context property bag cannot be null"); + } + this.properties = properties; + } + + public EmailContextBuilder addProperty(String name, String value) { + properties.setProperty(name, value); + return this; + } + + public EmailContext build() { + return new EmailContext(contentProviderInfo, recipients, properties); + } + + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java new file mode 100644 index 0000000000..73381ddf7c --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "EmailConfig") +public class EmailData { + + private String subject; + private String body; + + @XmlElement(name = "Subject", required = true) + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + @XmlElement(name = "Body", required = true) + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java new file mode 100644 index 0000000000..c356b4a117 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import org.w3c.dom.Document; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.File; + +@XmlRootElement(name = "EmailSenderConfig") +public class EmailSenderConfig { + + private int minThreads; + private int maxThreads; + private int keepAliveDuration; + private int threadQueueCapacity; + + private static EmailSenderConfig config; + + private static final String EMAIL_SENDER_CONFIG_PATH = + CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "email-sender-config.xml"; + + private EmailSenderConfig() { + } + + public static EmailSenderConfig getInstance() { + if (config == null) { + throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " + + "initialized properly"); + } + return config; + } + + @XmlElement(name = "MinThreads", required = true) + public int getMinThreads() { + return minThreads; + } + + public void setMinThreads(int minThreads) { + this.minThreads = minThreads; + } + + @XmlElement(name = "MaxThreads", required = true) + public int getMaxThreads() { + return maxThreads; + } + + public void setMaxThreads(int maxThreads) { + this.maxThreads = maxThreads; + } + + @XmlElement(name = "KeepAliveDuration", required = true) + public int getKeepAliveDuration() { + return keepAliveDuration; + } + + public void setKeepAliveDuration(int keepAliveDuration) { + this.keepAliveDuration = keepAliveDuration; + } + @XmlElement(name = "ThreadQueueCapacity", required = true) + public int getThreadQueueCapacity() { + return threadQueueCapacity; + } + + public void setThreadQueueCapacity(int threadQueueCapacity) { + this.threadQueueCapacity = threadQueueCapacity; + } + + public static void init() throws EmailSenderConfigurationFailedException { + try { + File emailSenderConfig = new File(EMAIL_SENDER_CONFIG_PATH); + Document doc = EmailSenderUtil.convertToDocument(emailSenderConfig); + + /* Un-marshaling Email Sender configuration */ + JAXBContext ctx = JAXBContext.newInstance(EmailSenderConfig.class); + Unmarshaller unmarshaller = ctx.createUnmarshaller(); + //unmarshaller.setSchema(getSchema()); + config = (EmailSenderConfig) unmarshaller.unmarshal(doc); + } catch (JAXBException e) { + throw new EmailSenderConfigurationFailedException("Error occurred while un-marshalling Email " + + "Sender Config", e); + } + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java new file mode 100644 index 0000000000..ee0535c30a --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +public class EmailSenderConfigurationFailedException extends Exception { + + private static final long serialVersionUID = -3151279312929070298L; + + public EmailSenderConfigurationFailedException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public EmailSenderConfigurationFailedException(String message, Throwable cause) { + super(message, cause); + } + + public EmailSenderConfigurationFailedException(String msg) { + super(msg); + } + + public EmailSenderConfigurationFailedException() { + super(); + } + + public EmailSenderConfigurationFailedException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java new file mode 100644 index 0000000000..2861585306 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import org.w3c.dom.Document; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; + +public class EmailSenderUtil { + + public static Document convertToDocument(File file) throws EmailSenderConfigurationFailedException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new EmailSenderConfigurationFailedException("Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document", e); + } + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java new file mode 100644 index 0000000000..914f30b5f7 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +public class EmailSendingFailedException extends Exception { + + private static final long serialVersionUID = -3151279311929070294L; + + public EmailSendingFailedException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public EmailSendingFailedException(String message, Throwable cause) { + super(message, cause); + } + + public EmailSendingFailedException(String msg) { + super(msg); + } + + public EmailSendingFailedException() { + super(); + } + + public EmailSendingFailedException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java new file mode 100644 index 0000000000..da23fcbeb1 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.dynamic.task.allocation.framework; + +public class EmailTransportNotConfiguredException extends Exception { + + private static final long serialVersionUID = -3151279311929070294L; + + public EmailTransportNotConfiguredException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public EmailTransportNotConfiguredException(String message, Throwable cause) { + super(message, cause); + } + + public EmailTransportNotConfiguredException(String msg) { + super(msg); + } + + public EmailTransportNotConfiguredException() { + super(); + } + + public EmailTransportNotConfiguredException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java new file mode 100644 index 0000000000..3b222d4988 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +public class InvalidConfigurationStateException extends RuntimeException { + + private static final long serialVersionUID = -3151279311329070297L; + + private String errorMessage; + private int errorCode; + + public InvalidConfigurationStateException(int errorCode, String message) { + super(message); + this.errorCode = errorCode; + } + + public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) { + super(message, cause); + this.errorCode = errorCode; + } + + public int getErrorCode() { + return errorCode; + } + + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public InvalidConfigurationStateException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public InvalidConfigurationStateException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public InvalidConfigurationStateException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public InvalidConfigurationStateException() { + super(); + } + + public InvalidConfigurationStateException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java new file mode 100644 index 0000000000..fc08058ca8 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import org.apache.commons.collections.ExtendedProperties; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.resource.Resource; +import org.apache.velocity.runtime.resource.loader.ResourceLoader; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.RegistryType; +import org.wso2.carbon.registry.api.Registry; +import org.wso2.carbon.registry.api.RegistryException; + +import java.io.InputStream; + +public class RegistryBasedResourceLoader extends ResourceLoader { + + private static final String EMAIL_CONFIG_BASE_LOCATION = "email-templates"; + + @Override + public void init(ExtendedProperties extendedProperties) { + + } + + @Override + public InputStream getResourceStream(String name) throws ResourceNotFoundException { + try { + Registry registry = + CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION); + if (registry == null) { + throw new IllegalStateException("No valid registry instance is attached to the current carbon context"); + } + if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) { + throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); + } + org.wso2.carbon.registry.api.Resource resource = + registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name); + resource.setMediaType("text/plain"); + return resource.getContentStream(); + } catch (RegistryException e) { + throw new ResourceNotFoundException("Error occurred while retrieving resource", e); + } + } + + @Override + public boolean isSourceModified(Resource resource) { + return false; + } + + @Override + public long getLastModified(Resource resource) { + return 0; + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java new file mode 100644 index 0000000000..3b95e30fd3 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +public class TypedValue { + + private final T type; + private final V value; + + public TypedValue(T type, V value) { + this.type = type; + this.value = value; + } + + public T getType() { + return type; + } + + public V getValue() { + return value; + } + + @Override + public int hashCode() { + return (type.hashCode() ^ value.hashCode()); + } + + @Override + public boolean equals(Object o) { + return o instanceof TypedValue && (this.type == ((TypedValue) o).getType() && + this.value == ((TypedValue) o).getValue()); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java new file mode 100644 index 0000000000..d48b1298ea --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.resource.loader.ResourceLoader; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.RegistryType; +import org.wso2.carbon.registry.api.Registry; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.Map; + +public class VelocityBasedEmailContentProvider implements EmailContentProvider { + + private VelocityEngine engine; + private static final Log log = LogFactory.getLog(VelocityBasedEmailContentProvider.class); + + public VelocityBasedEmailContentProvider() { + engine = new VelocityEngine(); + engine.setProperty("resource.loader", "registry"); + engine.setProperty("velocimacro.library", ""); + engine.setProperty("registry.resource.loader.class", + "org.wso2.carbon.email.sender.core.RegistryBasedResourceLoader"); + engine.init(); + } + + @Override + public EmailData getContent(String name, Map, Object>> params) throws ContentProcessingInterruptedException { + VelocityContext ctx = new VelocityContext(); + for (Map.Entry, Object>> param : params.entrySet()) { + ctx.put(param.getKey(), param.getValue().getValue()); + } + Template template = engine.getTemplate(name); + + StringWriter content = new StringWriter(); + template.merge(ctx, content); + + InputStream is = null; + try { + JAXBContext jaxbCtx = JAXBContext.newInstance(EmailData.class); + Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); + + is = new ByteArrayInputStream(content.toString().getBytes()); + return (EmailData) unmarshaller.unmarshal(is); + } catch (JAXBException e) { + throw new ContentProcessingInterruptedException("Error occurred while parsing email data", e); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + log.warn("Error occurred while closing input stream used to convert email configuration " + + "to an internal object model", e); + } + } + } + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java new file mode 100644 index 0000000000..d04fccec1e --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.dynamic.task.allocation.framework.internal; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import io.entgra.dynamic.task.allocation.framework.EmailSenderConfigurationFailedException; +import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; + +class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver { + + private static final Log log = LogFactory.getLog(EmailSenderAxis2ConfigContextObserver.class); + + @Override + public void creatingConfigurationContext(int tenantId) { + + } + + @Override + public void createdConfigurationContext(ConfigurationContext configurationContext) { + try { + EmailUtils.setupEmailTemplates(); + } catch (EmailSenderConfigurationFailedException e) { + log.error("Error occurred while setting up email templates", e); + } + } + + @Override + public void terminatingConfigurationContext(ConfigurationContext configurationContext) { + + } + + @Override + public void terminatedConfigurationContext(ConfigurationContext configurationContext) { + + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java new file mode 100644 index 0000000000..e8dded0590 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.dynamic.task.allocation.framework.internal; + +import io.entgra.dynamic.task.allocation.framework.service.EmailSenderService; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.utils.ConfigurationContextService; + +public class EmailSenderDataHolder { + + private RegistryService registryService; + private ConfigurationContextService configurationContextService; + private EmailSenderService emailServiceProvider; + + private static EmailSenderDataHolder thisInstance = new EmailSenderDataHolder(); + + private EmailSenderDataHolder() {} + + public static EmailSenderDataHolder getInstance() { + return thisInstance; + } + + public RegistryService getRegistryService() { + if (registryService == null) { + throw new IllegalStateException("Registry service is not initialized properly"); + } + return registryService; + } + + public void setRegistryService(RegistryService registryService) { + this.registryService = registryService; + } + + public ConfigurationContextService getConfigurationContextService() { + if (configurationContextService == null) { + throw new IllegalStateException("ConfigurationContext service is not initialized properly"); + } + return configurationContextService; + } + + public void setConfigurationContextService(ConfigurationContextService configurationContextService) { + this.configurationContextService = configurationContextService; + } + + public EmailSenderService getEmailServiceProvider() { + return emailServiceProvider; + } + + public void setEmailServiceProvider(EmailSenderService emailServiceProvider) { + this.emailServiceProvider = emailServiceProvider; + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java new file mode 100644 index 0000000000..d9f1167535 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.dynamic.task.allocation.framework.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import io.entgra.dynamic.task.allocation.framework.EmailSenderConfig; +import io.entgra.dynamic.task.allocation.framework.service.EmailSenderService; +import io.entgra.dynamic.task.allocation.framework.service.EmailSenderServiceImpl; +import org.wso2.carbon.registry.core.service.RegistryService; +import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; +import org.wso2.carbon.utils.ConfigurationContextService; + +/** + * @scr.component name="org.wso2.carbon.email.sender.emailsendereervicecomponent" + * immediate="true" + * @scr.reference name="registry.service" + * interface="org.wso2.carbon.registry.core.service.RegistryService" + * cardinality="1..1" + * policy="dynamic" + * bind="setRegistryService" + * unbind="unsetRegistryService" + * @scr.reference name="config.context.service" + * interface="org.wso2.carbon.utils.ConfigurationContextService" + * cardinality="0..1" + * policy="dynamic" + * bind="setConfigurationContextService" + * unbind="unsetConfigurationContextService" + */ +public class EmailSenderServiceComponent { + + private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class); + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + try { + if (log.isDebugEnabled()) { + log.debug("Initializing email sender core bundle"); + } + /* Initializing email sender configuration */ + EmailSenderConfig.init(); + + /* Setting up default email templates */ + EmailUtils.setupEmailTemplates(); + + /* Registering declarative service instances exposed by EmailSenderServiceComponent */ + this.registerServices(componentContext); + + if (log.isDebugEnabled()) { + log.debug("Email sender core bundle has been successfully initialized"); + } + componentContext.getBundleContext().registerService(Axis2ConfigurationContextObserver.class.getName(), + new EmailSenderAxis2ConfigContextObserver(), null); + } catch (Throwable e) { + log.error("Error occurred while initializing email sender core bundle", e); + } + } + + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { + //do nothing + } + + private void registerServices(ComponentContext componentContext) { + if (log.isDebugEnabled()) { + log.debug("Registering email sender service"); + } + EmailSenderService emailServiceProvider = new EmailSenderServiceImpl(); + EmailSenderDataHolder.getInstance().setEmailServiceProvider(emailServiceProvider); + componentContext.getBundleContext().registerService(EmailSenderService.class, emailServiceProvider, null); + } + + /** + * Sets Registry Service. + * + * @param registryService An instance of RegistryService + */ + protected void setRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Setting Registry Service"); + } + EmailSenderDataHolder.getInstance().setRegistryService(registryService); + } + + /** + * Unsets Registry Service. + * + * @param registryService An instance of RegistryService + */ + protected void unsetRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Registry Service"); + } + EmailSenderDataHolder.getInstance().setRegistryService(null); + } + + protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + EmailSenderDataHolder.getInstance().setConfigurationContextService(configurationContextService); + } + + protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + EmailSenderDataHolder.getInstance().setConfigurationContextService(null); + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java new file mode 100644 index 0000000000..20372239bd --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.dynamic.task.allocation.framework.internal; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import io.entgra.dynamic.task.allocation.framework.EmailSenderConfigurationFailedException; +import org.wso2.carbon.registry.api.Collection; +import org.wso2.carbon.registry.api.Registry; +import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.utils.CarbonUtils; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.io.IOException; + +class EmailUtils { + + private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "/email-templates"; + private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class); + + static void setupEmailTemplates() throws EmailSenderConfigurationFailedException { + File templateDir = + new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + + "resources" + File.separator + "email-templates"); + if (!templateDir.exists()) { + if (log.isDebugEnabled()) { + log.debug("The directory that is expected to use as the container for all email templates is not " + + "available. Therefore, no template is uploaded to the registry"); + } + } + if (templateDir.canRead()) { + File[] templates = templateDir.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + name = name.toLowerCase(); + return name.endsWith(".vm"); + } + }); + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + Registry registry = + EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId); + if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) { + Collection collection = registry.newCollection(); + registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection); + for (File template : templates) { + Resource resource = registry.newResource(); + resource.setMediaType("text/plain"); + String contents = FileUtils.readFileToString(template); + resource.setContent(contents); + registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + + template.getName().replace(".vm", ""), resource); + } + } + } catch (RegistryException e) { + throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e); + } catch (FileNotFoundException e) { + throw new EmailSenderConfigurationFailedException("Error occurred while writing template file " + + "contents as an input stream of a resource", e); + } catch (IOException e) { + throw new EmailSenderConfigurationFailedException("Error occurred while serializing file " + + "contents to a string", e); + } + } + } + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java new file mode 100644 index 0000000000..fc6b4663a2 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.dynamic.task.allocation.framework.service; + +import io.entgra.dynamic.task.allocation.framework.EmailContext; +import io.entgra.dynamic.task.allocation.framework.EmailSendingFailedException; +import io.entgra.dynamic.task.allocation.framework.EmailTransportNotConfiguredException; + +public interface EmailSenderService { + + void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException, EmailTransportNotConfiguredException; + +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java new file mode 100644 index 0000000000..32bb4ebdb6 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.dynamic.task.allocation.framework.service; + +import io.entgra.dynamic.task.allocation.framework.ContentProcessingInterruptedException; +import io.entgra.dynamic.task.allocation.framework.ContentProviderInfo; +import io.entgra.dynamic.task.allocation.framework.EmailContentProvider; +import io.entgra.dynamic.task.allocation.framework.EmailContentProviderFactory; +import io.entgra.dynamic.task.allocation.framework.EmailContext; +import io.entgra.dynamic.task.allocation.framework.EmailData; +import io.entgra.dynamic.task.allocation.framework.EmailSenderConfig; +import io.entgra.dynamic.task.allocation.framework.EmailSendingFailedException; +import io.entgra.dynamic.task.allocation.framework.EmailTransportNotConfiguredException; +import io.entgra.dynamic.task.allocation.framework.internal.EmailSenderDataHolder; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.llom.util.AXIOMUtil; +import org.apache.axis2.AxisFault; +import org.apache.axis2.Constants; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.context.ConfigurationContext; +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.transport.mail.MailConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.email.sender.core.*; +import org.wso2.carbon.utils.ConfigurationContextService; + +import javax.xml.stream.XMLStreamException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +public class EmailSenderServiceImpl implements EmailSenderService { + + private static ThreadPoolExecutor threadPoolExecutor; + private EmailContentProvider contentProvider; + private static final String TRANSPORT_SENDER_NAME = "mailto"; + + static { + EmailSenderConfig config = EmailSenderConfig.getInstance(); + threadPoolExecutor = new ThreadPoolExecutor(config.getMinThreads(), config.getMaxThreads(), + config.getKeepAliveDuration(), TimeUnit.SECONDS, + new LinkedBlockingQueue(config.getThreadQueueCapacity())); + } + + private static final String EMAIL_URI_SCHEME = "mailto:"; + private static Log log = LogFactory.getLog(EmailSenderServiceImpl.class); + + public EmailSenderServiceImpl() { + this.contentProvider = EmailContentProviderFactory.getContentProvider(); + } + + private boolean isMailServerConfigured() { + return (EmailSenderDataHolder.getInstance().getConfigurationContextService().getServerConfigContext(). + getAxisConfiguration().getTransportOut(TRANSPORT_SENDER_NAME) != null); + } + + @Override + public void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException, + EmailTransportNotConfiguredException { + if (this.isMailServerConfigured()) { + for (String recipient : emailCtx.getRecipients()) { + ContentProviderInfo info = emailCtx.getContentProviderInfo(); + EmailData emailData; + try { + emailData = contentProvider.getContent(info.getTemplate(), info.getParams()); + threadPoolExecutor.submit(new EmailSender(recipient, emailData.getSubject(), emailData.getBody())); + } catch (ContentProcessingInterruptedException e) { + throw new EmailSendingFailedException("Error occurred while retrieving email content to be " + + "sent for recipient '" + recipient + "'", e); + } + } + } else { + String msg = "Email sender transport is not configured. Please configure the 'mailto' sender" + + " transport in axis2.xml."; + log.warn(msg); + throw new EmailTransportNotConfiguredException(msg); + } + } + + public static class EmailSender implements Runnable { + + String to; + String subject; + String body; + + EmailSender(String to, String subject, String body) { + this.to = to; + this.subject = subject; + this.body = body; + } + + public void run() { + OMElement payload = null; + try { + payload = AXIOMUtil.stringToOM(body); + } catch (XMLStreamException e) { + log.error("Error occurred while converting email body contents to an XML", e); + } + try { + ConfigurationContextService configCtxService = + EmailSenderDataHolder.getInstance().getConfigurationContextService(); + if (configCtxService == null) { + throw new IllegalStateException("Configuration Context Service is not available"); + } + ConfigurationContext configCtx = configCtxService.getServerConfigContext(); + ServiceClient serviceClient = new ServiceClient(configCtx, null); + + Map headerMap = new HashMap<>(); + headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, subject); + + Options options = new Options(); + options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); + options.setProperty("FORCE_CONTENT_TYPE_BASED_FORMATTER", "true"); + options.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml"); + options.setProperty(Constants.Configuration.CONTENT_TYPE, "text/html"); + options.setTo(new EndpointReference(EMAIL_URI_SCHEME + to)); + + serviceClient.setOptions(options); + serviceClient.fireAndForget(payload); + if (log.isDebugEnabled()) { + log.debug("Email has been successfully sent to '" + to + "'"); + } + } catch (AxisFault e) { + log.error("Error occurred while delivering the message, subject: '" + subject + "', to: '" + to + + "'", e); + } + } + } +} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties new file mode 100644 index 0000000000..dc3d465fc0 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties @@ -0,0 +1,32 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# +# This is the log4j configuration file used by WSO2 Carbon +# +# IMPORTANT : Please do not remove or change the names of any +# of the Appenders defined here. The layout pattern & log file +# can be changed using the WSO2 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=INFO, STD_OUT + +# Redirect log messages to console +log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender +log4j.appender.STD_OUT.Target=System.out +log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout +log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml new file mode 100644 index 0000000000..7b13a25f89 --- /dev/null +++ b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml new file mode 100644 index 0000000000..818d3f35d7 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -0,0 +1,185 @@ + + + + + + + org.wso2.carbon.devicemgt + task-allocation + 4.1.11-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.server.bootup.heartbeat.beacon + bundle + Entgra - Heartbeat Beacon + Entgra - Server Startup and Heartbeat Monitoring Component + http://wso2.org + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Server Startup Heart Beat Beacon Bundle + io.entgra.server.bootup.heartbeat.beacon.internal + + org.apache.axis2.*;version="${axis2.osgi.version.range}", + org.apache.axiom.*; version="${axiom.osgi.version.range}", + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, + org.wso2.carbon.context, + org.wso2.carbon.utils.*, + org.wso2.carbon.registry.api, + org.w3c.dom, + org.apache.velocity;version="${velocity.version}", + org.apache.velocity.app;version="${velocity.version}", + org.apache.velocity.context;version="${velocity.version}", + org.apache.velocity.exception;version="${velocity.version}", + org.apache.velocity.runtime.resource;version="${velocity.version}", + org.apache.velocity.runtime.resource.loader;version="${velocity.version}", + org.apache.commons.io, + org.apache.axis2.transport.mail, + org.wso2.carbon.registry.core.service, + org.wso2.carbon.registry.core.session, + org.apache.commons.collections, + org.wso2.carbon.device.mgt.common.* + + + !io.entgra.server.bootup.heartbeat.beacon.internal, + io.entgra.server.bootup.heartbeat.beacon.* + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.testng + testng + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + org.wso2.carbon + org.wso2.carbon.base + + + org.apache.axis2.wso2 + axis2 + + + org.wso2.orbit.org.apache.velocity + velocity + + + commons-io.wso2 + commons-io + + + org.apache.axis2.transport + axis2-transport-mail + + + org.wso2.carbon + org.wso2.carbon.registry.core + + + commons-collections.wso2 + commons-collections + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + + + diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java new file mode 100644 index 0000000000..225438c913 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.server.bootup.heartbeat.beacon; + +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Hashtable; + +public class HeartBeatBeaconUtils { + + private static Log log = LogFactory.getLog(HeartBeatBeaconUtils.class); + + public static Document convertToDocument(File file) + throws HeartBeatBeaconConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new HeartBeatBeaconConfigurationException("Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document", e); + } + } + + /** + * Lookup datasource using name and jndi properties + * + * @param dataSourceName Name of datasource to lookup + * @param jndiProperties Hash table of JNDI Properties + * @return datasource looked + */ + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } + + + public static ServerContext getServerDetails() throws UnknownHostException, SocketException { + InetAddress localHost = InetAddress.getLocalHost(); + NetworkInterface ni = NetworkInterface.getByInetAddress(localHost); + byte[] hardwareAddress = ni.getHardwareAddress(); + String[] hexadecimal = new String[hardwareAddress.length]; + for (int i = 0; i < hardwareAddress.length; i++) { + hexadecimal[i] = String.format("%02X", hardwareAddress[i]); + } + String macAddress = String.join("-", hexadecimal); + + ServerContext ctx = new ServerContext(); + ctx.setHostName(localHost.getHostName()); + ctx.setMacAddress(macAddress); + + return ctx; + } + + + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java new file mode 100644 index 0000000000..d06ee05df6 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.config.datasource; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Class for holding data source configuration in cdm-config.xml at parsing with JAXB + */ +@XmlRootElement(name = "DataSourceConfiguration") +public class DataSourceConfig { + + private JNDILookupDefinition jndiLookupDefinition; + + @XmlElement(name = "JndiLookupDefinition", nillable = true) + public JNDILookupDefinition getJndiLookupDefinition() { + return jndiLookupDefinition; + } + + public void setJndiLookupDefinition(JNDILookupDefinition jndiLookupDefinition) { + this.jndiLookupDefinition = jndiLookupDefinition; + } +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java new file mode 100644 index 0000000000..96ae86fa1a --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.config.datasource; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlValue; +import java.util.List; + +/** + * Class for hold JndiLookupDefinition of cdm-config.xml at parsing with JAXB + */ +@XmlRootElement(name = "JndiLookupDefinition") +public class JNDILookupDefinition { + + private String jndiName; + private List jndiProperties; + + @XmlElement(name = "Name", nillable = false) + public String getJndiName() { + return jndiName; + } + + public void setJndiName(String jndiName) { + this.jndiName = jndiName; + } + + @XmlElementWrapper(name = "Environment", nillable = false) + @XmlElement(name = "Property", nillable = false) + public List getJndiProperties() { + return jndiProperties; + } + + public void setJndiProperties(List jndiProperties) { + this.jndiProperties = jndiProperties; + } + + @XmlRootElement(name = "Property") + public static class JNDIProperty { + + private String name; + + private String value; + + @XmlAttribute(name = "Name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + +} + diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java new file mode 100644 index 0000000000..93d6a612b3 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dao; + +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; +import io.entgra.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; +import io.entgra.server.bootup.heartbeat.beacon.config.datasource.JNDILookupDefinition; +import io.entgra.server.bootup.heartbeat.beacon.dao.impl.GenericHeartBeatDAOImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.exceptions.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineException; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; + +/** + * This class represents factory for group management data operations + */ +public class HeartBeatBeaconDAOFactory { + + private static final Log log = LogFactory.getLog(HeartBeatBeaconDAOFactory.class); + private static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal<>(); + + /** + * Get instance of GroupDAO + * + * @return instance of GroupDAO implementation + */ + public static HeartBeatDAO getHeartBeatDAO() { + return new GenericHeartBeatDAOImpl(); + } + + public static void init(DataSourceConfig config) { + dataSource = resolveDataSource(config); + } + + public static void init(DataSource dtSource) { + dataSource = dtSource; + } + + /** + * Begin transaction with datasource for write data + * + * @throws TransactionManagementException + */ + public static void beginTransaction() throws TransactionManagementException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + try { + conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + } + } + + /** + * Open connection to the datasource for read data + * + * @throws SQLException + */ + public static void openConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("A transaction is already active within the context of " + + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); + } + conn = dataSource.getConnection(); + currentConnection.set(conn); + } + + /** + * Get current connection to datasource + * + * @return current connection + * @throws SQLException + */ + public static Connection getConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + return conn; + } + + /** + * Commit current transaction to the datasource + */ + public static void commitTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating " + + "the transaction via 'beginTransaction'/'openConnection' methods"); + } + try { + conn.commit(); + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + + /** + * Rollback current transaction on failure + */ + public static void rollbackTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating " + + "the transaction via 'beginTransaction'/'openConnection' methods"); + } + try { + conn.rollback(); + } catch (SQLException e) { + log.warn("Error occurred while roll-backing the transaction", e); + } + } + + /** + * Close data connection associated with current transaction + */ + public static void closeConnection() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly " + + "initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while close the connection"); + } + currentConnection.remove(); + } + + + /** + * Resolve data source from the data source definition + * + * @param config data source configuration + * @return data source resolved from the data source definition + */ + private static DataSource resolveDataSource(DataSourceConfig config) { + DataSource dataSource = null; + if (config == null) { + throw new RuntimeException( + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized"); + } + JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); + if (jndiConfig != null) { + if (log.isDebugEnabled()) { + log.debug("Initializing Device Management Repository data source using the JNDI " + + "Lookup Definition"); + } + List jndiPropertyList = + jndiConfig.getJndiProperties(); + if (jndiPropertyList != null) { + Hashtable jndiProperties = new Hashtable<>(); + for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { + jndiProperties.put(prop.getName(), prop.getValue()); + } + dataSource = HeartBeatBeaconUtils.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); + } else { + dataSource = HeartBeatBeaconUtils.lookupDataSource(jndiConfig.getJndiName(), null); + } + } + return dataSource; + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java new file mode 100644 index 0000000000..46412a8916 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dao; + +import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; + +import java.util.List; + +/** + * This interface represents the key operations associated with persisting group related information. + */ +public interface HeartBeatDAO { + + String recordServerCtx(ServerContext ctx) throws HeartBeatDAOException; + + boolean recordHeatBeat(HeartBeatEvent event) throws HeartBeatDAOException; + + String retrieveExistingServerCtx(ServerContext ctx) throws HeartBeatDAOException; + + int getActiveServerCount(int elapsedTimeInSeconds) throws HeartBeatDAOException; + + List getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException; + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java new file mode 100644 index 0000000000..ec6a4d3575 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dao.exception; + +/** + * Custom exception class for group management data access related exceptions. + */ +public class HeartBeatDAOException extends Exception { + + private static final long serialVersionUID = 2021891706072918864L; + private String message; + + /** + * Constructs a new exception with the specified detail message and nested exception. + * + * @param message error message + * @param nestedException exception + */ + public HeartBeatDAOException(String message, Exception nestedException) { + super(message, nestedException); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message and cause. + * + * @param message the detail message. + * @param cause the cause of this exception. + */ + public HeartBeatDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message + * + * @param message the detail message. + */ + public HeartBeatDAOException(String message) { + super(message); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified and cause. + * + * @param cause the cause of this exception. + */ + public HeartBeatDAOException(Throwable cause) { + super(cause); + } + + public String getMessage() { + return message; + } + + public void setErrorMessage(String errorMessage) { + this.message = errorMessage; + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java new file mode 100644 index 0000000000..20ef8228b2 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dao.impl; + +import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; +import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; +import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; +import io.entgra.server.bootup.heartbeat.beacon.dao.util.HeartBeatBeaconDAOUtil; +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * This class represents implementation of HeartBeatDAO + */ +public class GenericHeartBeatDAOImpl implements HeartBeatDAO { + + @Override + public String recordServerCtx(ServerContext ctx) throws HeartBeatDAOException { + PreparedStatement stmt = null; + String uuid = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + + String sql; + sql = "INSERT INTO SERVER_HEART_BEAT_EVENTS(HOST_NAME, MAC, UUID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(sql, new String[]{"UUID"}); + stmt.setString(1, ctx.getHostName()); + stmt.setString(2, ctx.getMacAddress()); + stmt.setString(3, UUID.randomUUID().toString()); + + stmt.executeUpdate(); + ResultSet result = stmt.getGeneratedKeys(); + if (result.next()){ + uuid = result.getString("UUID"); + } + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while persisting server context for : '" + + "mac '" + ctx.getMacAddress() + "' " + + "hostname : '" + ctx.getHostName() + "' ", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + } + return uuid; + } + + @Override + public boolean recordHeatBeat(HeartBeatEvent event) throws HeartBeatDAOException { + PreparedStatement stmt = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql; + sql = "UPDATE SERVER_HEART_BEAT_EVENTS SET LAST_UPDATED_TIMESTAMP = ? WHERE UUID = ?"; + stmt = conn.prepareStatement(sql, new String[]{"ID"}); + stmt.setTimestamp(1, event.getTime()); + stmt.setString(2, event.getServerUUID()); + + return stmt.executeUpdate() > 0; + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while updating heartbeat event against server with UUID : '" + + event.getServerUUID() + "' and timestamp " + event.getTime(), e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public String retrieveExistingServerCtx(ServerContext ctx) throws HeartBeatDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + String uuid = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql = "SELECT UUID FROM SERVER_HEART_BEAT_EVENTS WHERE HOST_NAME = ? AND MAC = ?"; + stmt = conn.prepareStatement(sql, new String[]{"UUID"}); + stmt.setString(1, ctx.getHostName()); + stmt.setString(2, ctx.getMacAddress()); + + resultSet = stmt.executeQuery(); + if (resultSet.next()){ + uuid = resultSet.getString("UUID"); + } + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while retrieving meta information for heart beat event from " + + "mac '" + ctx.getMacAddress() + "' " + + "hostname : '" + ctx.getHostName() + "' ", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + } + return uuid; + } + + @Override + public int getActiveServerCount(int elapsedTimeInSeconds) throws HeartBeatDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + int count = -1; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql = "SELECT COUNT(ID) AS COUNT from SERVER_HEART_BEAT_EVENTS WHERE " + + "LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND)"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, elapsedTimeInSeconds); + resultSet = stmt.executeQuery(); + if (resultSet.next()) { + count = resultSet.getInt("COUNT"); + } + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while retrieving acting server count with " + + "heartbeat updates within " + elapsedTimeInSeconds + " seconds.", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + } + return count; + } + + @Override + public List getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + List ctxList = new ArrayList<>(); + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, MAC from " + + "SERVER_HEART_BEAT_EVENTS WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " + + "ORDER BY UUID"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, elapsedTimeInSeconds); + stmt.execute("SET @row_number = 0"); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + ctxList.add(HeartBeatBeaconDAOUtil.populateContext(resultSet)); + } + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while retrieving acting server count with " + + "heartbeat updates within " + elapsedTimeInSeconds + " seconds.", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + } + return ctxList; + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java new file mode 100644 index 0000000000..46e992f8c3 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dao.util; + +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Hashtable; + +/** + * This class represents utilities required to work with group management data + */ +public final class HeartBeatBeaconDAOUtil { + + private static final Log log = LogFactory.getLog(HeartBeatBeaconDAOUtil.class); + + /** + * Cleanup resources used to transaction + * + * @param stmt Prepared statement used + * @param rs Obtained results set + */ + public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + } + + /** + * Lookup datasource using name and jndi properties + * + * @param dataSourceName Name of datasource to lookup + * @param jndiProperties Hash table of JNDI Properties + * @return datasource looked + */ + public static DataSource lookupDataSource(String dataSourceName, + final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } + + + public static ServerContext populateContext(ResultSet resultSet) throws SQLException { + ServerContext ctx = new ServerContext(); + ctx.setIndex(resultSet.getInt("IDX")); + ctx.setUuid(resultSet.getString("UUID")); + ctx.setHostName(resultSet.getString("HOST_NAME")); + ctx.setMacAddress(resultSet.getString("MAC")); + return ctx; + } +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java new file mode 100644 index 0000000000..d17ffaf447 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon.dto; + +import java.sql.Timestamp; + +public class HeartBeatEvent { + + private String serverUUID; + private Timestamp time; + + public HeartBeatEvent(String serverUUID){ + this.serverUUID = serverUUID; + this.time = new Timestamp(System.currentTimeMillis()); + } + + public String getServerUUID() { + return serverUUID; + } + + public void setServerUUID(String serverUUID) { + this.serverUUID = serverUUID; + } + + public Timestamp getTime() { + return time; + } + + public void setTime(Timestamp time) { + this.time = time; + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java new file mode 100644 index 0000000000..9facab390f --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon.dto; + +public class ServerContext { + + private String hostName; + private String macAddress; + private String serverHash; + private String uuid; + private int index; + + public String getHostName() { + return hostName; + } + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + public String getMacAddress() { + return macAddress; + } + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + public String getServerHash() { + return serverHash; + } + + public void setServerHash(String serverHash) { + this.serverHash = serverHash; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java new file mode 100644 index 0000000000..eeb44e6d7a --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon.exception; + +public class HeartBeatManagementException extends Exception { + + private static final long serialVersionUID = 5304352685379661115L; + + public HeartBeatManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public HeartBeatManagementException(String message, Throwable cause) { + super(message, cause); + } + + public HeartBeatManagementException(String msg) { + super(msg); + } + + public HeartBeatManagementException() { + super(); + } + + public HeartBeatManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java new file mode 100644 index 0000000000..215b6ceb11 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon.exception; + +public class InvalidConfigurationStateException extends RuntimeException { + + private static final long serialVersionUID = -3151279311329070297L; + + private String errorMessage; + private int errorCode; + + public InvalidConfigurationStateException(int errorCode, String message) { + super(message); + this.errorCode = errorCode; + } + + public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) { + super(message, cause); + this.errorCode = errorCode; + } + + public int getErrorCode() { + return errorCode; + } + + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public InvalidConfigurationStateException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public InvalidConfigurationStateException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public InvalidConfigurationStateException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public InvalidConfigurationStateException() { + super(); + } + + public InvalidConfigurationStateException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java new file mode 100644 index 0000000000..a23ccbe7c0 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon.exception; + +public class ServerStatusUpdationFailedException extends Exception { + + private static final long serialVersionUID = -2610630531027402610L; + + public ServerStatusUpdationFailedException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public ServerStatusUpdationFailedException(String message, Throwable cause) { + super(message, cause); + } + + public ServerStatusUpdationFailedException(String msg) { + super(msg); + } + + public ServerStatusUpdationFailedException() { + super(); + } + + public ServerStatusUpdationFailedException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java new file mode 100644 index 0000000000..e936ea1593 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.server.bootup.heartbeat.beacon.internal; + +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementServiceImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; + +/** + * @scr.component name="io.entgra.server.bootup.heartbeat.beacon.heartbeatBeaconComponent" + * immediate="true" + */ +public class HeartBeatBeaconComponent { + + private static Log log = LogFactory.getLog(HeartBeatBeaconComponent.class); + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + try { + if (log.isDebugEnabled()) { + log.debug("Initializing email sender core bundle"); + } + //heart beat notifier configuration */ + HeartBeatBeaconConfig.init(); + + this.registerHeartBeatServices(componentContext); + + //Setting up executors to notify heart beat status */ + HeartBeatInternalUtils.setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); + + if (log.isDebugEnabled()) { + log.debug("Email sender core bundle has been successfully initialized"); + } + } catch (Throwable e) { + log.error("Error occurred while initializing email sender core bundle", e); + } + } + + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { + //do nothing + } + + private void registerHeartBeatServices(ComponentContext componentContext) { + if (log.isDebugEnabled()) { + log.debug("Registering Heart Beat Management service"); + } + HeartBeatManagementService heartBeatServiceProvider = new HeartBeatManagementServiceImpl(); + HeartBeatBeaconDataHolder.getInstance().setHeartBeatManagementService(heartBeatServiceProvider); + componentContext.getBundleContext().registerService(HeartBeatManagementService.class, heartBeatServiceProvider, null); + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java new file mode 100644 index 0000000000..a04ab9508a --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.internal; + +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; + +public class HeartBeatBeaconDataHolder { + + private HeartBeatManagementService heartBeatManagementService; + private String localServerUUID; + + private static HeartBeatBeaconDataHolder thisInstance = new HeartBeatBeaconDataHolder(); + + private HeartBeatBeaconDataHolder() {} + + public static HeartBeatBeaconDataHolder getInstance() { + return thisInstance; + } + + public HeartBeatManagementService getHeartBeatManagementService() { + return heartBeatManagementService; + } + + public void setHeartBeatManagementService(HeartBeatManagementService heartBeatManagementService) { + this.heartBeatManagementService = heartBeatManagementService; + } + + public String getLocalServerUUID() { + return localServerUUID; + } + + public void setLocalServerUUID(String localServerUUID) { + this.localServerUUID = localServerUUID; + } +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java new file mode 100644 index 0000000000..4b01bf33b6 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.server.bootup.heartbeat.beacon.internal; + +import com.sun.security.ntlm.Server; +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException; +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +public class HeartBeatInternalUtils { + + private static Log log = LogFactory.getLog(HeartBeatInternalUtils.class); + private static final int DEFAULT__NOTIFIER_INTERVAL = 5; + private static final int DEFAULT_NOTIFIER_DELAY = 5; + private static HeartBeatBeaconConfig CONFIG; + + static { + CONFIG = HeartBeatBeaconConfig.getInstance(); + } + + static void setUpNotifiers(ServerContext ctx) throws HeartBeatBeaconConfigurationException { + ScheduledExecutorService executor = + Executors.newSingleThreadScheduledExecutor(); + + if(CONFIG == null){ + throw new HeartBeatBeaconConfigurationException("Error while initiating schedule taks for recording heartbeats."); + } + + try { + String uuid = HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().updateServerContext(ctx); + HeartBeatBeaconDataHolder.getInstance().setLocalServerUUID(uuid); + Runnable periodicTask = new Runnable() { + public void run() { + try { + recordHeartBeat(uuid); + } catch (HeartBeatManagementException e) { + log.error("Error while executing record heart beat task. This will result in schedule operation malfunction.", e); + } + } + }; + executor.scheduleAtFixedRate(periodicTask, + CONFIG.getNotifierDelay() != 0 ? CONFIG.getNotifierDelay() : DEFAULT_NOTIFIER_DELAY, + CONFIG.getNotifierFrequency() != 0 ? CONFIG.getNotifierFrequency() : DEFAULT__NOTIFIER_INTERVAL, + TimeUnit.SECONDS); + } catch (HeartBeatManagementException e) { + throw new HeartBeatBeaconConfigurationException("Error occured while updating initial server context."); + } + } + + static void recordHeartBeat(String uuid) throws HeartBeatManagementException { + HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().recordHeartBeat(new HeartBeatEvent(uuid)); + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java new file mode 100644 index 0000000000..65e21da3ca --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package io.entgra.server.bootup.heartbeat.beacon.service; + +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; + +public interface HeartBeatManagementService { + + int getActiveServerCount() throws HeartBeatManagementException; + + int getServerLocalHashIndex() throws HeartBeatManagementException; + + String updateServerContext(ServerContext ctx) throws HeartBeatManagementException; + + boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException; + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java new file mode 100644 index 0000000000..41fbf1418f --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.service; + +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; +import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; +import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; +import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconDataHolder; + +import java.sql.SQLException; +import java.util.List; + +public class HeartBeatManagementServiceImpl implements HeartBeatManagementService { + + @Override + public int getActiveServerCount() throws HeartBeatManagementException { + HeartBeatDAO heartBeatDAO; + int activeServerCount = -1; + try { + HeartBeatBeaconDAOFactory.openConnection(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + + int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); + activeServerCount = heartBeatDAO.getActiveServerCount(timeOutIntervalInSeconds); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } catch (HeartBeatDAOException e) { + String msg = "Error Occured while retrieving active server count."; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + return activeServerCount; + } + + @Override + public int getServerLocalHashIndex() throws HeartBeatManagementException { + HeartBeatDAO heartBeatDAO; + int hashIndex = -1; + ServerContext localServerCtx = null; + try { + HeartBeatBeaconDAOFactory.openConnection(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + + int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); + String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); + List serverCtxList = heartBeatDAO.getActiveServerDetails(timeOutIntervalInSeconds); + for(ServerContext ctx : serverCtxList){ + if(ctx.getUuid() == localServerUUID){ + localServerCtx = ctx; + break; + } + } + if(localServerCtx != null){ + hashIndex = localServerCtx.getIndex(); + } + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } catch (HeartBeatDAOException e) { + String msg = "Error Occured while retrieving active server count."; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + return hashIndex; + } + + @Override + public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { + HeartBeatDAO heartBeatDAO; + String uuid = null; + try { + HeartBeatBeaconDAOFactory.openConnection(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + + uuid = heartBeatDAO.retrieveExistingServerCtx(ctx); + if(uuid == null){ + uuid = heartBeatDAO.recordServerCtx(ctx); + } + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } catch (HeartBeatDAOException e) { + String msg = "Error Occured while retrieving active server count."; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + return uuid; + } + + + @Override + public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { + HeartBeatDAO heartBeatDAO; + boolean operationSuccess = false; + try { + HeartBeatBeaconDAOFactory.openConnection(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + operationSuccess = heartBeatDAO.recordHeatBeat(event); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } catch (HeartBeatDAOException e) { + String msg = "Error Occured while retrieving active server count."; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + return operationSuccess; + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties new file mode 100644 index 0000000000..dc3d465fc0 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties @@ -0,0 +1,32 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# +# This is the log4j configuration file used by WSO2 Carbon +# +# IMPORTANT : Please do not remove or change the names of any +# of the Appenders defined here. The layout pattern & log file +# can be changed using the WSO2 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=INFO, STD_OUT + +# Redirect log messages to console +log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender +log4j.appender.STD_OUT.Target=System.out +log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout +log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml new file mode 100644 index 0000000000..2da3b26042 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + diff --git a/components/task-allocation/pom.xml b/components/task-allocation/pom.xml new file mode 100644 index 0000000000..d7f3ae778e --- /dev/null +++ b/components/task-allocation/pom.xml @@ -0,0 +1,40 @@ + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 4.1.11-SNAPSHOT + ../../pom.xml + + + 4.0.0 + task-allocation + pom + Entgra - Task Allocation Framework + http://wso2.org + + + io.entgra.dynamic.task.allocation.framework + io.entgra.server.bootup.heartbeat.beacon + + + diff --git a/pom.xml b/pom.xml index d12b76d9f4..f3f45141cd 100644 --- a/pom.xml +++ b/pom.xml @@ -45,6 +45,7 @@ components/webapp-authenticator-framework components/email-sender components/ui-request-interceptor + components/task-allocation features/device-mgt features/apimgt-extensions features/application-mgt From eadc1a19926f7da0310bd0418eb74e821c3ce151 Mon Sep 17 00:00:00 2001 From: Ace Date: Sun, 15 Nov 2020 22:56:46 +0530 Subject: [PATCH 02/21] Adding operation partitioning functionality - missing files --- .../beacon/HeartBeatBeaconConfig.java | 98 +++++++++++++++++++ ...HeartBeatBeaconConfigurationException.java | 45 +++++++++ 2 files changed, 143 insertions(+) create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java create mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java new file mode 100644 index 0000000000..5c5cc9def0 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon; + +import io.entgra.server.bootup.heartbeat.beacon.exception.InvalidConfigurationStateException; +import org.w3c.dom.Document; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.File; + +@XmlRootElement(name = "HeartBeatBeaconConfig") +public class HeartBeatBeaconConfig { + + private int notifierFrequency; + private int notifierDelay; + private int serverTimeOutInterval; + + private static HeartBeatBeaconConfig config; + + private static final String HEART_BEAT_NOTIFIER_CONFIG_PATH = + CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "heart-beat-config.xml"; + + private HeartBeatBeaconConfig() { + } + + public static HeartBeatBeaconConfig getInstance() { + if (config == null) { + throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " + + "initialized properly"); + } + return config; + } + + @XmlElement(name = "NotifierInitialDelay", required = true) + public int getNotifierDelay() { + return notifierDelay; + } + + public void setNotifierDelay(int notifierDelay) { + this.notifierDelay = notifierDelay; + } + + @XmlElement(name = "NotifierFrequency", required = true) + public int getNotifierFrequency() { + return notifierFrequency; + } + + public void setNotifierFrequency(int notifierFrequency) { + this.notifierFrequency = notifierFrequency; + } + + @XmlElement(name = "ServerTimeOutIntervalInSeconds", required = true) + public int getServerTimeOutIntervalInSeconds() { + return serverTimeOutInterval; + } + + public void setServerTimeOutInterval(int serverTimeOutInterval) { + this.serverTimeOutInterval = serverTimeOutInterval; + } + + public static void init() throws HeartBeatBeaconConfigurationException { + try { + File emailSenderConfig = new File(HEART_BEAT_NOTIFIER_CONFIG_PATH); + Document doc = HeartBeatBeaconUtils.convertToDocument(emailSenderConfig); + + /* Un-marshaling Email Sender configuration */ + JAXBContext ctx = JAXBContext.newInstance(HeartBeatBeaconConfig.class); + Unmarshaller unmarshaller = ctx.createUnmarshaller(); + //unmarshaller.setSchema(getSchema()); + config = (HeartBeatBeaconConfig) unmarshaller.unmarshal(doc); + } catch (JAXBException e) { + throw new HeartBeatBeaconConfigurationException("Error occurred while un-marshalling " + + "heart beat configuration file", e); + } + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java new file mode 100644 index 0000000000..c784318249 --- /dev/null +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package io.entgra.server.bootup.heartbeat.beacon; + +public class HeartBeatBeaconConfigurationException extends Exception { + + private static final long serialVersionUID = -1043317705230442099L; + + public HeartBeatBeaconConfigurationException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public HeartBeatBeaconConfigurationException(String message, Throwable cause) { + super(message, cause); + } + + public HeartBeatBeaconConfigurationException(String msg) { + super(msg); + } + + public HeartBeatBeaconConfigurationException() { + super(); + } + + public HeartBeatBeaconConfigurationException(Throwable cause) { + super(cause); + } + +} From 7b28665135a6e1bb44d0f7f17d6604d72b59b58d Mon Sep 17 00:00:00 2001 From: Ace Date: Mon, 16 Nov 2020 09:19:21 +0530 Subject: [PATCH 03/21] Defining interfaces and other adjustments --- .../DynamicPartitionedScheduleTask.java | 10 + .../carbon/device/mgt/core/dao/DeviceDAO.java | 12 ++ .../core/dao/impl/AbstractDeviceDAOImpl.java | 59 ++++++ .../DeviceManagementProviderService.java | 11 ++ .../DeviceManagementProviderServiceImpl.java | 40 ++++ .../pom.xml | 180 ------------------ ...ContentProcessingInterruptedException.java | 45 ----- .../framework/ContentProviderInfo.java | 55 ------ .../framework/EmailContentProvider.java | 28 --- .../EmailContentProviderFactory.java | 27 --- .../allocation/framework/EmailContext.java | 138 -------------- .../task/allocation/framework/EmailData.java | 48 ----- .../framework/EmailSenderConfig.java | 106 ----------- ...ailSenderConfigurationFailedException.java | 45 ----- .../allocation/framework/EmailSenderUtil.java | 44 ----- .../EmailSendingFailedException.java | 45 ----- .../EmailTransportNotConfiguredException.java | 44 ----- .../InvalidConfigurationStateException.java | 74 ------- .../RegistryBasedResourceLoader.java | 71 ------- .../task/allocation/framework/TypedValue.java | 50 ----- .../VelocityBasedEmailContentProvider.java | 87 --------- ...EmailSenderAxis2ConfigContextObserver.java | 55 ------ .../internal/EmailSenderDataHolder.java | 69 ------- .../internal/EmailSenderServiceComponent.java | 127 ------------ .../framework/internal/EmailUtils.java | 87 --------- .../framework/service/EmailSenderService.java | 28 --- .../service/EmailSenderServiceImpl.java | 150 --------------- .../src/test/resources/log4j.properties | 32 ---- .../src/test/resources/testng.xml | 29 --- .../pom.xml | 11 -- .../dao/impl/GenericHeartBeatDAOImpl.java | 4 +- .../internal/HeartBeatInternalUtils.java | 1 - components/task-allocation/pom.xml | 1 - 33 files changed, 134 insertions(+), 1679 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties delete mode 100644 components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java new file mode 100644 index 0000000000..897f80e951 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java @@ -0,0 +1,10 @@ +package org.wso2.carbon.device.mgt.common.dynamic.task.allocation; + +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.ntask.core.Task; + +import java.util.List; + +public abstract class DynamicPartitionedScheduleTask implements Task { + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 537539864c..b2cb5ac269 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -325,6 +325,18 @@ public interface DeviceDAO { */ List getDevices(String type, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the list of devices attributed to a specific node + * when using dynamic partitioning to allocate tasks given the tenant and device type + * along with activeServerCount and serverIndex + * + * @param type device type. + * @param tenantId tenant id. + * @return returns list of devices of provided type. + * @throws DeviceManagementDAOException + */ + List getDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException; + List getDevices(long timestamp, int tenantId) throws DeviceManagementDAOException; /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 4eff108ba5..9aef3887d3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -800,6 +800,65 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return devices; } + + @Override + public List getDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List devices = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID," + + " d1.DESCRIPTION," + + " d1.NAME AS DEVICE_NAME," + + " d1.DEVICE_TYPE," + + " d1.DEVICE_IDENTIFICATION," + + " e.OWNER," + + " e.OWNERSHIP," + + " e.STATUS," + + " e.IS_TRANSFERRED," + + " e.DATE_OF_LAST_UPDATE," + + " e.DATE_OF_ENROLMENT," + + " e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e," + + " (SELECT d.ID," + + " d.DESCRIPTION," + + " d.NAME," + + " d.DEVICE_IDENTIFICATION," + + " t.NAME AS DEVICE_TYPE" + + " FROM DM_DEVICE d, DM_DEVICE_TYPE t" + + " WHERE DEVICE_TYPE_ID = t.ID" + + " AND t.NAME = ?" + + " AND t.ID = d.DEVICE_TYPE_ID" + + " AND d.TENANT_ID = ?) d1" + + "WHERE d1.ID = e.DEVICE_ID" + + " AND TENANT_ID = ?" + + " AND MOD(d1.ID, 3) = 2" + + "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + + stmt = conn.prepareStatement(sql); + stmt.setString(1, type); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + stmt.setInt(4, activeServerCount); + stmt.setInt(5, serverIndex); + rs = stmt.executeQuery(); + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadActiveDevice(rs, false); + if (device != null) { + devices.add(device); + } + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return devices; + } + @Override public List getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException { Connection conn; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 2fb5ce6f3e..70c506ee8b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -107,6 +107,17 @@ public interface DeviceManagementProviderService { */ List getAllDevices(String deviceType, boolean requireDeviceInfo) throws DeviceManagementException; + + /** + * Method returns a list of devices allocated to a specific node of the server, given the serverIndex and active server count + * @param deviceType + * @param activeServerCount + * @param serverIndex + * @return + * @throws DeviceManagementException + */ + List getAllocatedDevices(String deviceType, int activeServerCount, int serverIndex) throws DeviceManagementException; + /** * Method to retrieve all the devices registered in the system. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 2afa4bbdb6..be2cabefb0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -765,6 +765,46 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return allDevices; } + @Override + public List getAllocatedDevices(String deviceType, int activeServerCount, int serverIndex) throws DeviceManagementException { + if (deviceType == null) { + String msg = "Device type is empty for method getAllDevices"; + log.error(msg); + throw new DeviceManagementException(msg); + } + if (log.isDebugEnabled()) { + log.debug("Getting allocated Devices for Server with index "+ serverIndex + " and" + + " type '" + deviceType); + } + List allocatedDevices; + try { + DeviceManagementDAOFactory.openConnection(); + allocatedDevices = deviceDAO.getDevices(deviceType, this.getTenantId(), activeServerCount, serverIndex); + if (allocatedDevices == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the type '" + deviceType + "'"); + } + return null; + } + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving all devices of type '" + + deviceType + "' that are being managed within the scope of current tenant"; + log.error(msg); + throw new DeviceManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred while getting all devices of device type '" + deviceType + "'"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + return allocatedDevices; + } + @Override public List getAllDevices() throws DeviceManagementException { return this.getAllDevices(true); diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml deleted file mode 100644 index c95d8f2d6f..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/pom.xml +++ /dev/null @@ -1,180 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt - task-allocation - 4.1.11-SNAPSHOT - ../pom.xml - - - 4.0.0 - io.entgra.dynamic.task.allocation.framework - bundle - Entgra - Task Allocation Framework - Entgra - Framework for partitioning tasks evenly amongst multiple nodes - http://entgra.io - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.device.mgt.version} - Entgra - Task Allocation Framework Bundle - io.entgra.dynamic.task.allocation.framework.internal - - org.apache.axis2.*;version="${axis2.osgi.version.range}", - org.apache.axiom.*; version="${axiom.osgi.version.range}", - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging, - javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, - org.wso2.carbon.context, - org.wso2.carbon.utils.*, - org.wso2.carbon.registry.api, - org.w3c.dom, - org.apache.velocity;version="${velocity.version}", - org.apache.velocity.app;version="${velocity.version}", - org.apache.velocity.context;version="${velocity.version}", - org.apache.velocity.exception;version="${velocity.version}", - org.apache.velocity.runtime.resource;version="${velocity.version}", - org.apache.velocity.runtime.resource.loader;version="${velocity.version}", - org.apache.commons.io, - org.apache.axis2.transport.mail, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.core.session, - org.apache.commons.collections - - - !io.entgra.dynamic.task.allocation.framework.internal, - io.entgra.dynamic.task.allocation.framework.* - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - file:src/test/resources/log4j.properties - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.testng - testng - - - org.wso2.carbon - org.wso2.carbon.registry.api - - - org.wso2.carbon - org.wso2.carbon.base - - - org.apache.axis2.wso2 - axis2 - - - org.wso2.orbit.org.apache.velocity - velocity - - - commons-io.wso2 - commons-io - - - org.apache.axis2.transport - axis2-transport-mail - - - org.wso2.carbon - org.wso2.carbon.registry.core - - - commons-collections.wso2 - commons-collections - - - - - diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java deleted file mode 100644 index ccf4358c35..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProcessingInterruptedException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -public class ContentProcessingInterruptedException extends Exception { - - private static final long serialVersionUID = -3151279311929070298L; - - public ContentProcessingInterruptedException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public ContentProcessingInterruptedException(String message, Throwable cause) { - super(message, cause); - } - - public ContentProcessingInterruptedException(String msg) { - super(msg); - } - - public ContentProcessingInterruptedException() { - super(); - } - - public ContentProcessingInterruptedException(Throwable cause) { - super(cause); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java deleted file mode 100644 index 0bfe4339f8..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/ContentProviderInfo.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import java.util.Map; - -public class ContentProviderInfo { - - private String template; - private Map, Object>> params; - - public ContentProviderInfo(final String template, final Map, Object>> params) { - if (template == null || template.isEmpty()) { - throw new IllegalArgumentException("Template name cannot be null or empty"); - } - this.template = template; - if (params == null) { - throw new IllegalArgumentException("Place-holder parameter map cannot be null"); - } - this.params = params; - } - - public String getTemplate() { - return template; - } - - public Map, Object>> getParams() { - return params; - } - - public void addParam(String name, TypedValue, Object> param) { - params.put(name, param); - } - - public TypedValue, Object> getParam(String name) { - return params.get(name); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java deleted file mode 100644 index dd0005282a..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProvider.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import java.util.Map; - -public interface EmailContentProvider { - - EmailData getContent(String path, - Map, Object>> params) throws ContentProcessingInterruptedException; - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java deleted file mode 100644 index 2b75d014fc..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContentProviderFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -public class EmailContentProviderFactory { - - public static EmailContentProvider getContentProvider() { - return new VelocityBasedEmailContentProvider(); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java deleted file mode 100644 index 0e645cc564..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailContext.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import java.util.*; - -public class EmailContext { - - private Set recipients; - private Properties properties; - private ContentProviderInfo contentProviderInfo; - - private EmailContext(final ContentProviderInfo contentProviderInfo, final Set recipients, final Properties properties) { - if (contentProviderInfo == null) { - throw new IllegalArgumentException("Content provider information cannot be null"); - } - this.contentProviderInfo = contentProviderInfo; - if (recipients == null) { - throw new IllegalArgumentException("Recipient list cannot be null"); - } - if (recipients.size() == 0) { - throw new IllegalArgumentException("No recipient is configured. Recipient list should carry at " + - "least one recipient"); - } - this.recipients = recipients; - if (properties == null) { - throw new IllegalArgumentException("Email Context property bag cannot be null"); - } - this.properties = properties; - } - - private EmailContext(final ContentProviderInfo contentProviderInfo, final String recipient, final Properties properties) { - if (contentProviderInfo == null) { - throw new IllegalArgumentException("Content provider information cannot be null"); - } - this.contentProviderInfo = contentProviderInfo; - if (recipient == null || recipient.isEmpty()) { - throw new IllegalArgumentException("Recipient can't be null or empty. Please specify a valid " + - "recipient email address"); - } - this.recipients = new HashSet() {{ - add(recipient); - }}; - if (properties == null) { - throw new IllegalArgumentException("Email Context property bag cannot be null"); - } - this.properties = properties; - } - - public Set getRecipients() { - return recipients; - } - - public Properties getProperties() { - return properties; - } - - public String getProperty(String name) { - return (String) properties.get(name); - } - - public void addProperty(String name, String value) { - properties.put(name, value); - } - - public ContentProviderInfo getContentProviderInfo() { - return contentProviderInfo; - } - - public static class EmailContextBuilder { - - private Set recipients; - private ContentProviderInfo contentProviderInfo; - private Properties properties; - - public EmailContextBuilder(final ContentProviderInfo contentProviderInfo, Set recipients) { - if (contentProviderInfo == null) { - throw new IllegalArgumentException("Content provider information cannot be null"); - } - this.contentProviderInfo = contentProviderInfo; - if (recipients == null) { - throw new IllegalArgumentException("Recipient list cannot be null"); - } - if (recipients.size() == 0) { - throw new IllegalArgumentException("No recipient is configured. Recipient list should carry at " + - "least one recipient"); - } - this.recipients = recipients; - this.properties = new Properties(); - } - - public EmailContextBuilder(final ContentProviderInfo contentProviderInfo, final String recipient, - final Properties properties) { - if (contentProviderInfo == null) { - throw new IllegalArgumentException("Content provider information cannot be null"); - } - this.contentProviderInfo = contentProviderInfo; - if (recipient == null || recipient.isEmpty()) { - throw new IllegalArgumentException("Recipient can't be null or empty. Please specify a valid " + - "recipient email address"); - } - this.recipients = new HashSet() {{ - add(recipient); - }}; - if (properties == null) { - throw new IllegalArgumentException("Email Context property bag cannot be null"); - } - this.properties = properties; - } - - public EmailContextBuilder addProperty(String name, String value) { - properties.setProperty(name, value); - return this; - } - - public EmailContext build() { - return new EmailContext(contentProviderInfo, recipients, properties); - } - - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java deleted file mode 100644 index 73381ddf7c..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailData.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "EmailConfig") -public class EmailData { - - private String subject; - private String body; - - @XmlElement(name = "Subject", required = true) - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - @XmlElement(name = "Body", required = true) - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java deleted file mode 100644 index c356b4a117..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfig.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import org.w3c.dom.Document; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.io.File; - -@XmlRootElement(name = "EmailSenderConfig") -public class EmailSenderConfig { - - private int minThreads; - private int maxThreads; - private int keepAliveDuration; - private int threadQueueCapacity; - - private static EmailSenderConfig config; - - private static final String EMAIL_SENDER_CONFIG_PATH = - CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "email-sender-config.xml"; - - private EmailSenderConfig() { - } - - public static EmailSenderConfig getInstance() { - if (config == null) { - throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " + - "initialized properly"); - } - return config; - } - - @XmlElement(name = "MinThreads", required = true) - public int getMinThreads() { - return minThreads; - } - - public void setMinThreads(int minThreads) { - this.minThreads = minThreads; - } - - @XmlElement(name = "MaxThreads", required = true) - public int getMaxThreads() { - return maxThreads; - } - - public void setMaxThreads(int maxThreads) { - this.maxThreads = maxThreads; - } - - @XmlElement(name = "KeepAliveDuration", required = true) - public int getKeepAliveDuration() { - return keepAliveDuration; - } - - public void setKeepAliveDuration(int keepAliveDuration) { - this.keepAliveDuration = keepAliveDuration; - } - @XmlElement(name = "ThreadQueueCapacity", required = true) - public int getThreadQueueCapacity() { - return threadQueueCapacity; - } - - public void setThreadQueueCapacity(int threadQueueCapacity) { - this.threadQueueCapacity = threadQueueCapacity; - } - - public static void init() throws EmailSenderConfigurationFailedException { - try { - File emailSenderConfig = new File(EMAIL_SENDER_CONFIG_PATH); - Document doc = EmailSenderUtil.convertToDocument(emailSenderConfig); - - /* Un-marshaling Email Sender configuration */ - JAXBContext ctx = JAXBContext.newInstance(EmailSenderConfig.class); - Unmarshaller unmarshaller = ctx.createUnmarshaller(); - //unmarshaller.setSchema(getSchema()); - config = (EmailSenderConfig) unmarshaller.unmarshal(doc); - } catch (JAXBException e) { - throw new EmailSenderConfigurationFailedException("Error occurred while un-marshalling Email " + - "Sender Config", e); - } - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java deleted file mode 100644 index ee0535c30a..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderConfigurationFailedException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -public class EmailSenderConfigurationFailedException extends Exception { - - private static final long serialVersionUID = -3151279312929070298L; - - public EmailSenderConfigurationFailedException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public EmailSenderConfigurationFailedException(String message, Throwable cause) { - super(message, cause); - } - - public EmailSenderConfigurationFailedException(String msg) { - super(msg); - } - - public EmailSenderConfigurationFailedException() { - super(); - } - - public EmailSenderConfigurationFailedException(Throwable cause) { - super(cause); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java deleted file mode 100644 index 2861585306..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSenderUtil.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import org.w3c.dom.Document; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; - -public class EmailSenderUtil { - - public static Document convertToDocument(File file) throws EmailSenderConfigurationFailedException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new EmailSenderConfigurationFailedException("Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document", e); - } - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java deleted file mode 100644 index 914f30b5f7..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailSendingFailedException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -public class EmailSendingFailedException extends Exception { - - private static final long serialVersionUID = -3151279311929070294L; - - public EmailSendingFailedException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public EmailSendingFailedException(String message, Throwable cause) { - super(message, cause); - } - - public EmailSendingFailedException(String msg) { - super(msg); - } - - public EmailSendingFailedException() { - super(); - } - - public EmailSendingFailedException(Throwable cause) { - super(cause); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java deleted file mode 100644 index da23fcbeb1..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/EmailTransportNotConfiguredException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package io.entgra.dynamic.task.allocation.framework; - -public class EmailTransportNotConfiguredException extends Exception { - - private static final long serialVersionUID = -3151279311929070294L; - - public EmailTransportNotConfiguredException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public EmailTransportNotConfiguredException(String message, Throwable cause) { - super(message, cause); - } - - public EmailTransportNotConfiguredException(String msg) { - super(msg); - } - - public EmailTransportNotConfiguredException() { - super(); - } - - public EmailTransportNotConfiguredException(Throwable cause) { - super(cause); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java deleted file mode 100644 index 3b222d4988..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/InvalidConfigurationStateException.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -public class InvalidConfigurationStateException extends RuntimeException { - - private static final long serialVersionUID = -3151279311329070297L; - - private String errorMessage; - private int errorCode; - - public InvalidConfigurationStateException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public InvalidConfigurationStateException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public InvalidConfigurationStateException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException() { - super(); - } - - public InvalidConfigurationStateException(Throwable cause) { - super(cause); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java deleted file mode 100644 index fc08058ca8..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/RegistryBasedResourceLoader.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import org.apache.commons.collections.ExtendedProperties; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.apache.velocity.runtime.resource.Resource; -import org.apache.velocity.runtime.resource.loader.ResourceLoader; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.RegistryType; -import org.wso2.carbon.registry.api.Registry; -import org.wso2.carbon.registry.api.RegistryException; - -import java.io.InputStream; - -public class RegistryBasedResourceLoader extends ResourceLoader { - - private static final String EMAIL_CONFIG_BASE_LOCATION = "email-templates"; - - @Override - public void init(ExtendedProperties extendedProperties) { - - } - - @Override - public InputStream getResourceStream(String name) throws ResourceNotFoundException { - try { - Registry registry = - CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION); - if (registry == null) { - throw new IllegalStateException("No valid registry instance is attached to the current carbon context"); - } - if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) { - throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); - } - org.wso2.carbon.registry.api.Resource resource = - registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name); - resource.setMediaType("text/plain"); - return resource.getContentStream(); - } catch (RegistryException e) { - throw new ResourceNotFoundException("Error occurred while retrieving resource", e); - } - } - - @Override - public boolean isSourceModified(Resource resource) { - return false; - } - - @Override - public long getLastModified(Resource resource) { - return 0; - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java deleted file mode 100644 index 3b95e30fd3..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/TypedValue.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -public class TypedValue { - - private final T type; - private final V value; - - public TypedValue(T type, V value) { - this.type = type; - this.value = value; - } - - public T getType() { - return type; - } - - public V getValue() { - return value; - } - - @Override - public int hashCode() { - return (type.hashCode() ^ value.hashCode()); - } - - @Override - public boolean equals(Object o) { - return o instanceof TypedValue && (this.type == ((TypedValue) o).getType() && - this.value == ((TypedValue) o).getValue()); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java deleted file mode 100644 index d48b1298ea..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/VelocityBasedEmailContentProvider.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.resource.loader.ResourceLoader; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.RegistryType; -import org.wso2.carbon.registry.api.Registry; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.util.Map; - -public class VelocityBasedEmailContentProvider implements EmailContentProvider { - - private VelocityEngine engine; - private static final Log log = LogFactory.getLog(VelocityBasedEmailContentProvider.class); - - public VelocityBasedEmailContentProvider() { - engine = new VelocityEngine(); - engine.setProperty("resource.loader", "registry"); - engine.setProperty("velocimacro.library", ""); - engine.setProperty("registry.resource.loader.class", - "org.wso2.carbon.email.sender.core.RegistryBasedResourceLoader"); - engine.init(); - } - - @Override - public EmailData getContent(String name, Map, Object>> params) throws ContentProcessingInterruptedException { - VelocityContext ctx = new VelocityContext(); - for (Map.Entry, Object>> param : params.entrySet()) { - ctx.put(param.getKey(), param.getValue().getValue()); - } - Template template = engine.getTemplate(name); - - StringWriter content = new StringWriter(); - template.merge(ctx, content); - - InputStream is = null; - try { - JAXBContext jaxbCtx = JAXBContext.newInstance(EmailData.class); - Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); - - is = new ByteArrayInputStream(content.toString().getBytes()); - return (EmailData) unmarshaller.unmarshal(is); - } catch (JAXBException e) { - throw new ContentProcessingInterruptedException("Error occurred while parsing email data", e); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - log.warn("Error occurred while closing input stream used to convert email configuration " + - "to an internal object model", e); - } - } - } - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java deleted file mode 100644 index d04fccec1e..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderAxis2ConfigContextObserver.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.dynamic.task.allocation.framework.internal; - -import org.apache.axis2.context.ConfigurationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import io.entgra.dynamic.task.allocation.framework.EmailSenderConfigurationFailedException; -import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; - -class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver { - - private static final Log log = LogFactory.getLog(EmailSenderAxis2ConfigContextObserver.class); - - @Override - public void creatingConfigurationContext(int tenantId) { - - } - - @Override - public void createdConfigurationContext(ConfigurationContext configurationContext) { - try { - EmailUtils.setupEmailTemplates(); - } catch (EmailSenderConfigurationFailedException e) { - log.error("Error occurred while setting up email templates", e); - } - } - - @Override - public void terminatingConfigurationContext(ConfigurationContext configurationContext) { - - } - - @Override - public void terminatedConfigurationContext(ConfigurationContext configurationContext) { - - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java deleted file mode 100644 index e8dded0590..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderDataHolder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package io.entgra.dynamic.task.allocation.framework.internal; - -import io.entgra.dynamic.task.allocation.framework.service.EmailSenderService; -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.utils.ConfigurationContextService; - -public class EmailSenderDataHolder { - - private RegistryService registryService; - private ConfigurationContextService configurationContextService; - private EmailSenderService emailServiceProvider; - - private static EmailSenderDataHolder thisInstance = new EmailSenderDataHolder(); - - private EmailSenderDataHolder() {} - - public static EmailSenderDataHolder getInstance() { - return thisInstance; - } - - public RegistryService getRegistryService() { - if (registryService == null) { - throw new IllegalStateException("Registry service is not initialized properly"); - } - return registryService; - } - - public void setRegistryService(RegistryService registryService) { - this.registryService = registryService; - } - - public ConfigurationContextService getConfigurationContextService() { - if (configurationContextService == null) { - throw new IllegalStateException("ConfigurationContext service is not initialized properly"); - } - return configurationContextService; - } - - public void setConfigurationContextService(ConfigurationContextService configurationContextService) { - this.configurationContextService = configurationContextService; - } - - public EmailSenderService getEmailServiceProvider() { - return emailServiceProvider; - } - - public void setEmailServiceProvider(EmailSenderService emailServiceProvider) { - this.emailServiceProvider = emailServiceProvider; - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java deleted file mode 100644 index d9f1167535..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailSenderServiceComponent.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package io.entgra.dynamic.task.allocation.framework.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import io.entgra.dynamic.task.allocation.framework.EmailSenderConfig; -import io.entgra.dynamic.task.allocation.framework.service.EmailSenderService; -import io.entgra.dynamic.task.allocation.framework.service.EmailSenderServiceImpl; -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.utils.Axis2ConfigurationContextObserver; -import org.wso2.carbon.utils.ConfigurationContextService; - -/** - * @scr.component name="org.wso2.carbon.email.sender.emailsendereervicecomponent" - * immediate="true" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="1..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - * @scr.reference name="config.context.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" - * cardinality="0..1" - * policy="dynamic" - * bind="setConfigurationContextService" - * unbind="unsetConfigurationContextService" - */ -public class EmailSenderServiceComponent { - - private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class); - - @SuppressWarnings("unused") - protected void activate(ComponentContext componentContext) { - try { - if (log.isDebugEnabled()) { - log.debug("Initializing email sender core bundle"); - } - /* Initializing email sender configuration */ - EmailSenderConfig.init(); - - /* Setting up default email templates */ - EmailUtils.setupEmailTemplates(); - - /* Registering declarative service instances exposed by EmailSenderServiceComponent */ - this.registerServices(componentContext); - - if (log.isDebugEnabled()) { - log.debug("Email sender core bundle has been successfully initialized"); - } - componentContext.getBundleContext().registerService(Axis2ConfigurationContextObserver.class.getName(), - new EmailSenderAxis2ConfigContextObserver(), null); - } catch (Throwable e) { - log.error("Error occurred while initializing email sender core bundle", e); - } - } - - @SuppressWarnings("unused") - protected void deactivate(ComponentContext componentContext) { - //do nothing - } - - private void registerServices(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("Registering email sender service"); - } - EmailSenderService emailServiceProvider = new EmailSenderServiceImpl(); - EmailSenderDataHolder.getInstance().setEmailServiceProvider(emailServiceProvider); - componentContext.getBundleContext().registerService(EmailSenderService.class, emailServiceProvider, null); - } - - /** - * Sets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void setRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Setting Registry Service"); - } - EmailSenderDataHolder.getInstance().setRegistryService(registryService); - } - - /** - * Unsets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void unsetRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Registry Service"); - } - EmailSenderDataHolder.getInstance().setRegistryService(null); - } - - protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Setting ConfigurationContextService"); - } - EmailSenderDataHolder.getInstance().setConfigurationContextService(configurationContextService); - } - - protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Un-setting ConfigurationContextService"); - } - EmailSenderDataHolder.getInstance().setConfigurationContextService(null); - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java deleted file mode 100644 index 20372239bd..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/internal/EmailUtils.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package io.entgra.dynamic.task.allocation.framework.internal; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import io.entgra.dynamic.task.allocation.framework.EmailSenderConfigurationFailedException; -import org.wso2.carbon.registry.api.Collection; -import org.wso2.carbon.registry.api.Registry; -import org.wso2.carbon.registry.api.RegistryException; -import org.wso2.carbon.registry.api.Resource; -import org.wso2.carbon.utils.CarbonUtils; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FilenameFilter; -import java.io.IOException; - -class EmailUtils { - - private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "/email-templates"; - private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class); - - static void setupEmailTemplates() throws EmailSenderConfigurationFailedException { - File templateDir = - new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + - "resources" + File.separator + "email-templates"); - if (!templateDir.exists()) { - if (log.isDebugEnabled()) { - log.debug("The directory that is expected to use as the container for all email templates is not " + - "available. Therefore, no template is uploaded to the registry"); - } - } - if (templateDir.canRead()) { - File[] templates = templateDir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - name = name.toLowerCase(); - return name.endsWith(".vm"); - } - }); - try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - Registry registry = - EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId); - if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) { - Collection collection = registry.newCollection(); - registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection); - for (File template : templates) { - Resource resource = registry.newResource(); - resource.setMediaType("text/plain"); - String contents = FileUtils.readFileToString(template); - resource.setContent(contents); - registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" - + template.getName().replace(".vm", ""), resource); - } - } - } catch (RegistryException e) { - throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e); - } catch (FileNotFoundException e) { - throw new EmailSenderConfigurationFailedException("Error occurred while writing template file " + - "contents as an input stream of a resource", e); - } catch (IOException e) { - throw new EmailSenderConfigurationFailedException("Error occurred while serializing file " + - "contents to a string", e); - } - } - } - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java deleted file mode 100644 index fc6b4663a2..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package io.entgra.dynamic.task.allocation.framework.service; - -import io.entgra.dynamic.task.allocation.framework.EmailContext; -import io.entgra.dynamic.task.allocation.framework.EmailSendingFailedException; -import io.entgra.dynamic.task.allocation.framework.EmailTransportNotConfiguredException; - -public interface EmailSenderService { - - void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException, EmailTransportNotConfiguredException; - -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java deleted file mode 100644 index 32bb4ebdb6..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/main/java/io/entgra/dynamic/task/allocation/framework/service/EmailSenderServiceImpl.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package io.entgra.dynamic.task.allocation.framework.service; - -import io.entgra.dynamic.task.allocation.framework.ContentProcessingInterruptedException; -import io.entgra.dynamic.task.allocation.framework.ContentProviderInfo; -import io.entgra.dynamic.task.allocation.framework.EmailContentProvider; -import io.entgra.dynamic.task.allocation.framework.EmailContentProviderFactory; -import io.entgra.dynamic.task.allocation.framework.EmailContext; -import io.entgra.dynamic.task.allocation.framework.EmailData; -import io.entgra.dynamic.task.allocation.framework.EmailSenderConfig; -import io.entgra.dynamic.task.allocation.framework.EmailSendingFailedException; -import io.entgra.dynamic.task.allocation.framework.EmailTransportNotConfiguredException; -import io.entgra.dynamic.task.allocation.framework.internal.EmailSenderDataHolder; -import org.apache.axiom.om.OMElement; -import org.apache.axiom.om.impl.llom.util.AXIOMUtil; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.MessageContext; -import org.apache.axis2.transport.mail.MailConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.email.sender.core.*; -import org.wso2.carbon.utils.ConfigurationContextService; - -import javax.xml.stream.XMLStreamException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -public class EmailSenderServiceImpl implements EmailSenderService { - - private static ThreadPoolExecutor threadPoolExecutor; - private EmailContentProvider contentProvider; - private static final String TRANSPORT_SENDER_NAME = "mailto"; - - static { - EmailSenderConfig config = EmailSenderConfig.getInstance(); - threadPoolExecutor = new ThreadPoolExecutor(config.getMinThreads(), config.getMaxThreads(), - config.getKeepAliveDuration(), TimeUnit.SECONDS, - new LinkedBlockingQueue(config.getThreadQueueCapacity())); - } - - private static final String EMAIL_URI_SCHEME = "mailto:"; - private static Log log = LogFactory.getLog(EmailSenderServiceImpl.class); - - public EmailSenderServiceImpl() { - this.contentProvider = EmailContentProviderFactory.getContentProvider(); - } - - private boolean isMailServerConfigured() { - return (EmailSenderDataHolder.getInstance().getConfigurationContextService().getServerConfigContext(). - getAxisConfiguration().getTransportOut(TRANSPORT_SENDER_NAME) != null); - } - - @Override - public void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException, - EmailTransportNotConfiguredException { - if (this.isMailServerConfigured()) { - for (String recipient : emailCtx.getRecipients()) { - ContentProviderInfo info = emailCtx.getContentProviderInfo(); - EmailData emailData; - try { - emailData = contentProvider.getContent(info.getTemplate(), info.getParams()); - threadPoolExecutor.submit(new EmailSender(recipient, emailData.getSubject(), emailData.getBody())); - } catch (ContentProcessingInterruptedException e) { - throw new EmailSendingFailedException("Error occurred while retrieving email content to be " + - "sent for recipient '" + recipient + "'", e); - } - } - } else { - String msg = "Email sender transport is not configured. Please configure the 'mailto' sender" + - " transport in axis2.xml."; - log.warn(msg); - throw new EmailTransportNotConfiguredException(msg); - } - } - - public static class EmailSender implements Runnable { - - String to; - String subject; - String body; - - EmailSender(String to, String subject, String body) { - this.to = to; - this.subject = subject; - this.body = body; - } - - public void run() { - OMElement payload = null; - try { - payload = AXIOMUtil.stringToOM(body); - } catch (XMLStreamException e) { - log.error("Error occurred while converting email body contents to an XML", e); - } - try { - ConfigurationContextService configCtxService = - EmailSenderDataHolder.getInstance().getConfigurationContextService(); - if (configCtxService == null) { - throw new IllegalStateException("Configuration Context Service is not available"); - } - ConfigurationContext configCtx = configCtxService.getServerConfigContext(); - ServiceClient serviceClient = new ServiceClient(configCtx, null); - - Map headerMap = new HashMap<>(); - headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, subject); - - Options options = new Options(); - options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); - options.setProperty("FORCE_CONTENT_TYPE_BASED_FORMATTER", "true"); - options.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml"); - options.setProperty(Constants.Configuration.CONTENT_TYPE, "text/html"); - options.setTo(new EndpointReference(EMAIL_URI_SCHEME + to)); - - serviceClient.setOptions(options); - serviceClient.fireAndForget(payload); - if (log.isDebugEnabled()) { - log.debug("Email has been successfully sent to '" + to + "'"); - } - } catch (AxisFault e) { - log.error("Error occurred while delivering the message, subject: '" + subject + "', to: '" + to + - "'", e); - } - } - } -} diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties deleted file mode 100644 index dc3d465fc0..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/log4j.properties +++ /dev/null @@ -1,32 +0,0 @@ -# -# Copyright 2009 WSO2, Inc. (http://wso2.com) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# -# This is the log4j configuration file used by WSO2 Carbon -# -# IMPORTANT : Please do not remove or change the names of any -# of the Appenders defined here. The layout pattern & log file -# can be changed using the WSO2 Carbon Management Console, and those -# settings will override the settings in this file. -# - -log4j.rootLogger=INFO, STD_OUT - -# Redirect log messages to console -log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender -log4j.appender.STD_OUT.Target=System.out -log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout -log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml b/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml deleted file mode 100644 index 7b13a25f89..0000000000 --- a/components/task-allocation/io.entgra.dynamic.task.allocation.framework/src/test/resources/testng.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml index 818d3f35d7..91679597c6 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -59,7 +59,6 @@ javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.wso2.carbon.context, org.wso2.carbon.utils.*, - org.wso2.carbon.registry.api, org.w3c.dom, org.apache.velocity;version="${velocity.version}", org.apache.velocity.app;version="${velocity.version}", @@ -69,8 +68,6 @@ org.apache.velocity.runtime.resource.loader;version="${velocity.version}", org.apache.commons.io, org.apache.axis2.transport.mail, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.core.session, org.apache.commons.collections, org.wso2.carbon.device.mgt.common.* @@ -143,10 +140,6 @@ org.testng testng - - org.wso2.carbon - org.wso2.carbon.registry.api - org.wso2.carbon org.wso2.carbon.base @@ -167,10 +160,6 @@ org.apache.axis2.transport axis2-transport-mail - - org.wso2.carbon - org.wso2.carbon.registry.core - commons-collections.wso2 commons-collections diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index 20ef8228b2..99207d42eb 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -145,11 +145,11 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, MAC from " + - "SERVER_HEART_BEAT_EVENTS WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " + + "SERVER_HEART_BEAT_EVENTS, (SELECT @row_number:=-1) AS TEMP " + + "WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " + "ORDER BY UUID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, elapsedTimeInSeconds); - stmt.execute("SET @row_number = 0"); resultSet = stmt.executeQuery(); while (resultSet.next()) { ctxList.add(HeartBeatBeaconDAOUtil.populateContext(resultSet)); diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java index 4b01bf33b6..acc19bb927 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java @@ -17,7 +17,6 @@ */ package io.entgra.server.bootup.heartbeat.beacon.internal; -import com.sun.security.ntlm.Server; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; diff --git a/components/task-allocation/pom.xml b/components/task-allocation/pom.xml index d7f3ae778e..69c44d0d82 100644 --- a/components/task-allocation/pom.xml +++ b/components/task-allocation/pom.xml @@ -33,7 +33,6 @@ http://wso2.org - io.entgra.dynamic.task.allocation.framework io.entgra.server.bootup.heartbeat.beacon From 37ef7b9047bb0ce20277d408f06f133468426a40 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 17 Nov 2020 09:02:45 +0530 Subject: [PATCH 04/21] Adding interface for dynamic task allocation --- .../device/mgt/common/ServerCtxInfo.java | 45 ++++++++++++++++++ .../DynamicPartitionedScheduleTask.java | 10 ---- .../org.wso2.carbon.device.mgt.core/pom.xml | 7 ++- .../core/dao/impl/AbstractDeviceDAOImpl.java | 2 +- .../internal/DeviceManagementDataHolder.java | 11 +++++ .../DeviceManagementServiceComponent.java | 29 ++++++++++++ .../impl/DynamicPartitionedScheduleTask.java | 43 +++++++++++++++++ .../beacon/HeartBeatBeaconUtils.java | 2 + .../heartbeat/beacon/dao/HeartBeatDAO.java | 5 +- .../dao/impl/GenericHeartBeatDAOImpl.java | 40 ++++------------ .../dao/util/HeartBeatBeaconDAOUtil.java | 1 + .../heartbeat/beacon/dto/ServerContext.java | 18 ++++---- .../service/HeartBeatManagementService.java | 5 +- .../HeartBeatManagementServiceImpl.java | 46 +++++-------------- pom.xml | 7 ++- 15 files changed, 179 insertions(+), 92 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ServerCtxInfo.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ServerCtxInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ServerCtxInfo.java new file mode 100644 index 0000000000..898793476a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/ServerCtxInfo.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common; + +public class ServerCtxInfo { + private int activeServerCount; + private int localServerHashIdx; + + public ServerCtxInfo(int activeServerCount, int localServerHashIdx){ + this.activeServerCount = activeServerCount; + this.localServerHashIdx = localServerHashIdx; + } + + public int getActiveServerCount() { + return activeServerCount; + } + + public void setActiveServerCount(int activeServerCount) { + this.activeServerCount = activeServerCount; + } + + public int getLocalServerHashIdx() { + return localServerHashIdx; + } + + public void setLocalServerHashIdx(int localServerHashIdx) { + this.localServerHashIdx = localServerHashIdx; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java deleted file mode 100644 index 897f80e951..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/dynamic/task/allocation/DynamicPartitionedScheduleTask.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.wso2.carbon.device.mgt.common.dynamic.task.allocation; - -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.ntask.core.Task; - -import java.util.List; - -public abstract class DynamicPartitionedScheduleTask implements Task { - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 347c710be6..fafc2fdece 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -114,7 +114,8 @@ org.scannotation.*, org.wso2.carbon.event.processor.stub, org.wso2.carbon.identity.jwt.client.extension.service, - org.apache.commons.codec.binary + org.apache.commons.codec.binary, + io.entgra.server.bootup.heartbeat.beacon !org.wso2.carbon.device.mgt.core.internal, @@ -364,6 +365,10 @@ commons-validator commons-validator + + org.wso2.carbon.devicemgt + io.entgra.server.bootup.heartbeat.beacon + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 9aef3887d3..1ceb85d868 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -834,7 +834,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { " AND d.TENANT_ID = ?) d1" + "WHERE d1.ID = e.DEVICE_ID" + " AND TENANT_ID = ?" + - " AND MOD(d1.ID, 3) = 2" + + " AND MOD(d1.ID, ?) = ?" + "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index 88b662e1b2..ec8f74c3fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.internal; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; @@ -56,6 +57,7 @@ public class DeviceManagementDataHolder { private DeviceInformationManager deviceInformationManager; private LicenseManager licenseManager; private RegistryService registryService; + private HeartBeatManagementService heartBeatService; private LicenseConfig licenseConfig; private ApplicationManager appManager; private AppManagementConfig appManagerConfig; @@ -286,4 +288,13 @@ public class DeviceManagementDataHolder { public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) { this.deviceInformationManager = deviceInformationManager; } + + public HeartBeatManagementService getHeartBeatService() { + return heartBeatService; + } + + public void setHeartBeatService( + HeartBeatManagementService heartBeatService) { + this.heartBeatService = heartBeatService; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 60b309ad76..2642d904ba 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -17,6 +17,7 @@ */ package org.wso2.carbon.device.mgt.core.internal; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -134,6 +135,12 @@ import java.util.concurrent.TimeUnit; * policy="dynamic" * bind="setDeviceTypeGeneratorService" * unbind="unsetDeviceTypeGeneratorService" + * @scr.reference name="entgra.heart.beat.service" + * interface="io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService" + * cardinality="0..1" + * policy="dynamic" + * bind="setHeartBeatService" + * unbind="unsetHeartBeatService" */ public class DeviceManagementServiceComponent { @@ -479,6 +486,28 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setRegistryService(null); } + /** + * Sets HeartBeatManagementService Service. + * + * @param heartBeatService An instance of HeartBeatManagementService + */ + protected void setHeartBeatService(HeartBeatManagementService heartBeatService) { + if (log.isDebugEnabled()) { + log.debug("Setting Heart Beat Service"); + } + DeviceManagementDataHolder.getInstance().setHeartBeatService(heartBeatService); + } + + /** + * Unsets Registry Service. + */ + protected void unsetHeartBeatService(HeartBeatManagementService heartBeatService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Heart Beat Service"); + } + DeviceManagementDataHolder.getInstance().setHeartBeatService(null); + } + protected void setDataSourceService(DataSourceService dataSourceService) { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java new file mode 100644 index 0000000000..02cc5315c8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -0,0 +1,43 @@ +package org.wso2.carbon.device.mgt.core.task.impl; + +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.ServerCtxInfo; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.ntask.core.Task; + + +public abstract class DynamicPartitionedScheduleTask implements Task { + + private static final Log log = LogFactory.getLog(DynamicPartitionedScheduleTask.class); + + private static int serverHashIndex; + private static int activeServerCount; + + @Override + public final void init() { + try { + ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); + if(ctxInfo!=null){ + activeServerCount = ctxInfo.getActiveServerCount(); + serverHashIndex = ctxInfo.getLocalServerHashIdx(); + setup(); + } else { + log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function."); + } + } catch (HeartBeatManagementException e) { + log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function." , e); + } + } + + protected abstract void setup(); + + public int getLocalServerHash(){ + return serverHashIndex; + } + + public int getActiveServerCount(){ + return activeServerCount; + } +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java index 225438c913..aa9e34bd71 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -83,10 +83,12 @@ public class HeartBeatBeaconUtils { hexadecimal[i] = String.format("%02X", hardwareAddress[i]); } String macAddress = String.join("-", hexadecimal); + int iotsCorePort = Integer.parseInt(System.getProperty("iot.core.https.port")); ServerContext ctx = new ServerContext(); ctx.setHostName(localHost.getHostName()); ctx.setMacAddress(macAddress); + ctx.setCarbonServerPort(iotsCorePort); return ctx; } diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java index 46412a8916..46f7091436 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java @@ -23,6 +23,7 @@ import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import java.util.List; +import java.util.Map; /** * This interface represents the key operations associated with persisting group related information. @@ -35,8 +36,6 @@ public interface HeartBeatDAO { String retrieveExistingServerCtx(ServerContext ctx) throws HeartBeatDAOException; - int getActiveServerCount(int elapsedTimeInSeconds) throws HeartBeatDAOException; - - List getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException; + Map getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException; } diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index 99207d42eb..832b7fd58c 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -30,7 +30,9 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; /** @@ -46,11 +48,12 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql; - sql = "INSERT INTO SERVER_HEART_BEAT_EVENTS(HOST_NAME, MAC, UUID) VALUES (?, ?, ?)"; + sql = "INSERT INTO SERVER_HEART_BEAT_EVENTS(HOST_NAME, MAC, UUID, SERVER_PORT) VALUES (?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, new String[]{"UUID"}); stmt.setString(1, ctx.getHostName()); stmt.setString(2, ctx.getMacAddress()); stmt.setString(3, UUID.randomUUID().toString()); + stmt.setInt(4, ctx.getCarbonServerPort()); stmt.executeUpdate(); ResultSet result = stmt.getGeneratedKeys(); @@ -94,10 +97,11 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { String uuid = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); - String sql = "SELECT UUID FROM SERVER_HEART_BEAT_EVENTS WHERE HOST_NAME = ? AND MAC = ?"; + String sql = "SELECT UUID FROM SERVER_HEART_BEAT_EVENTS WHERE HOST_NAME = ? AND MAC = ? AND SERVER_PORT = ?"; stmt = conn.prepareStatement(sql, new String[]{"UUID"}); stmt.setString(1, ctx.getHostName()); stmt.setString(2, ctx.getMacAddress()); + stmt.setInt(3, ctx.getCarbonServerPort()); resultSet = stmt.executeQuery(); if (resultSet.next()){ @@ -114,37 +118,13 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { } @Override - public int getActiveServerCount(int elapsedTimeInSeconds) throws HeartBeatDAOException { + public Map getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; - int count = -1; + Map ctxList = new HashMap<>(); try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); - String sql = "SELECT COUNT(ID) AS COUNT from SERVER_HEART_BEAT_EVENTS WHERE " + - "LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND)"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, elapsedTimeInSeconds); - resultSet = stmt.executeQuery(); - if (resultSet.next()) { - count = resultSet.getInt("COUNT"); - } - } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while retrieving acting server count with " + - "heartbeat updates within " + elapsedTimeInSeconds + " seconds.", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); - } - return count; - } - - @Override - public List getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; - List ctxList = new ArrayList<>(); - try { - Connection conn = HeartBeatBeaconDAOFactory.getConnection(); - String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, MAC from " + + String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, MAC, SERVER_PORT from " + "SERVER_HEART_BEAT_EVENTS, (SELECT @row_number:=-1) AS TEMP " + "WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " + "ORDER BY UUID"; @@ -152,7 +132,7 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { stmt.setInt(1, elapsedTimeInSeconds); resultSet = stmt.executeQuery(); while (resultSet.next()) { - ctxList.add(HeartBeatBeaconDAOUtil.populateContext(resultSet)); + ctxList.put(resultSet.getString("UUID"), HeartBeatBeaconDAOUtil.populateContext(resultSet)); } } catch (SQLException e) { throw new HeartBeatDAOException("Error occurred while retrieving acting server count with " + diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java index 46e992f8c3..31b72ad2ef 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java @@ -86,6 +86,7 @@ public final class HeartBeatBeaconDAOUtil { ctx.setUuid(resultSet.getString("UUID")); ctx.setHostName(resultSet.getString("HOST_NAME")); ctx.setMacAddress(resultSet.getString("MAC")); + ctx.setCarbonServerPort(resultSet.getInt("SERVER_PORT")); return ctx; } } diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java index 9facab390f..b98f1f63d7 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java @@ -22,7 +22,7 @@ public class ServerContext { private String hostName; private String macAddress; - private String serverHash; + private int carbonServerPort; private String uuid; private int index; @@ -42,14 +42,6 @@ public class ServerContext { this.macAddress = macAddress; } - public String getServerHash() { - return serverHash; - } - - public void setServerHash(String serverHash) { - this.serverHash = serverHash; - } - public String getUuid() { return uuid; } @@ -65,4 +57,12 @@ public class ServerContext { public void setIndex(int index) { this.index = index; } + + public int getCarbonServerPort() { + return carbonServerPort; + } + + public void setCarbonServerPort(int carbonServerPort) { + this.carbonServerPort = carbonServerPort; + } } diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index 65e21da3ca..2c1630cb9c 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -20,12 +20,11 @@ package io.entgra.server.bootup.heartbeat.beacon.service; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import org.wso2.carbon.device.mgt.common.ServerCtxInfo; public interface HeartBeatManagementService { - int getActiveServerCount() throws HeartBeatManagementException; - - int getServerLocalHashIndex() throws HeartBeatManagementException; + ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException; String updateServerContext(ServerContext ctx) throws HeartBeatManagementException; diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 41fbf1418f..9363d3ea07 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -26,65 +26,43 @@ import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconDataHolder; +import org.wso2.carbon.device.mgt.common.ServerCtxInfo; import java.sql.SQLException; -import java.util.List; +import java.util.Map; public class HeartBeatManagementServiceImpl implements HeartBeatManagementService { @Override - public int getActiveServerCount() throws HeartBeatManagementException { - HeartBeatDAO heartBeatDAO; - int activeServerCount = -1; - try { - HeartBeatBeaconDAOFactory.openConnection(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - - int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); - activeServerCount = heartBeatDAO.getActiveServerCount(timeOutIntervalInSeconds); - } catch (SQLException e) { - String msg = "Error occurred while opening a connection to the underlying data source"; - throw new HeartBeatManagementException(msg, e); - } catch (HeartBeatDAOException e) { - String msg = "Error Occured while retrieving active server count."; - throw new HeartBeatManagementException(msg, e); - } finally { - HeartBeatBeaconDAOFactory.closeConnection(); - } - return activeServerCount; - } - - @Override - public int getServerLocalHashIndex() throws HeartBeatManagementException { + public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { HeartBeatDAO heartBeatDAO; int hashIndex = -1; ServerContext localServerCtx = null; + ServerCtxInfo serverCtxInfo = null; try { HeartBeatBeaconDAOFactory.openConnection(); heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); - List serverCtxList = heartBeatDAO.getActiveServerDetails(timeOutIntervalInSeconds); - for(ServerContext ctx : serverCtxList){ - if(ctx.getUuid() == localServerUUID){ - localServerCtx = ctx; - break; + Map serverCtxMap = heartBeatDAO.getActiveServerDetails(timeOutIntervalInSeconds); + if(!serverCtxMap.isEmpty()) { + localServerCtx = serverCtxMap.get(localServerUUID); + if (localServerCtx != null) { + hashIndex = localServerCtx.getIndex(); + serverCtxInfo = new ServerCtxInfo(serverCtxMap.size(), hashIndex); } } - if(localServerCtx != null){ - hashIndex = localServerCtx.getIndex(); - } } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; throw new HeartBeatManagementException(msg, e); } catch (HeartBeatDAOException e) { - String msg = "Error Occured while retrieving active server count."; + String msg = "Error occurred while retrieving active server count."; throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); } - return hashIndex; + return serverCtxInfo; } @Override diff --git a/pom.xml b/pom.xml index f3f45141cd..c9022ab0f8 100644 --- a/pom.xml +++ b/pom.xml @@ -35,6 +35,7 @@ + components/task-allocation components/device-mgt components/device-mgt-extensions components/identity-extensions @@ -45,7 +46,6 @@ components/webapp-authenticator-framework components/email-sender components/ui-request-interceptor - components/task-allocation features/device-mgt features/apimgt-extensions features/application-mgt @@ -377,6 +377,11 @@ zip ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + io.entgra.server.bootup.heartbeat.beacon + ${carbon.device.mgt.version} + From 5ca299530ec173f13e30e9e4472989aee24b3d07 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 17 Nov 2020 10:44:23 +0530 Subject: [PATCH 05/21] refactoring and adding proper licenses --- .../pom.xml | 2 +- .../beacon/HeartBeatBeaconConfig.java | 44 ++++++++++------- ...HeartBeatBeaconConfigurationException.java | 26 +++++----- .../beacon/HeartBeatBeaconUtils.java | 7 +-- .../config/datasource/DataSourceConfig.java | 10 ++-- .../datasource/JNDILookupDefinition.java | 10 ++-- .../beacon/dao/HeartBeatBeaconDAOFactory.java | 4 +- .../heartbeat/beacon/dao/HeartBeatDAO.java | 4 +- .../dao/exception/HeartBeatDAOException.java | 4 +- .../dao/impl/GenericHeartBeatDAOImpl.java | 6 +-- .../dao/util/HeartBeatBeaconDAOUtil.java | 4 +- .../heartbeat/beacon/dto/HeartBeatEvent.java | 49 +++++++++++++++++++ .../heartbeat/beacon/dto/ServerContext.java | 26 +++++----- .../HeartBeatManagementException.java | 45 +++++++++++++++++ .../InvalidConfigurationStateException.java | 26 +++++----- .../ServerStatusUpdationFailedException.java | 26 +++++----- .../internal/HeartBeatBeaconComponent.java | 7 +-- .../internal/HeartBeatBeaconDataHolder.java | 25 +++++----- .../internal/HeartBeatInternalUtils.java | 7 +-- .../service/HeartBeatManagementService.java | 7 +-- .../HeartBeatManagementServiceImpl.java | 10 ++-- .../src/test/resources/log4j.properties | 0 .../src/test/resources/testng.xml | 0 .../pom.xml | 2 +- .../heartbeat/beacon/dto/HeartBeatEvent.java | 49 ------------------- .../HeartBeatManagementException.java | 45 ----------------- pom.xml | 2 +- 27 files changed, 231 insertions(+), 216 deletions(-) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/pom.xml (99%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java (69%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java (51%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java (94%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java (78%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java (86%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java (98%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java (89%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java (93%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java (96%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java (95%) create mode 100644 components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java (60%) create mode 100644 components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java (67%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java (51%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java (92%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java (58%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java (93%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java (83%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java (92%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties (100%) rename components/{task-allocation => heartbeat-management}/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml (100%) rename components/{task-allocation => heartbeat-management}/pom.xml (96%) delete mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java delete mode 100644 components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml similarity index 99% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml index 91679597c6..b5e7141461 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt - task-allocation + heartbeat-management 4.1.11-SNAPSHOT ../pom.xml diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java similarity index 69% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java index 5c5cc9def0..f8b741fec3 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java @@ -1,21 +1,21 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon; import io.entgra.server.bootup.heartbeat.beacon.exception.InvalidConfigurationStateException; @@ -34,7 +34,8 @@ public class HeartBeatBeaconConfig { private int notifierFrequency; private int notifierDelay; - private int serverTimeOutInterval; + private int serverTimeOutIntervalInSeconds; + private int timeSkew; private static HeartBeatBeaconConfig config; @@ -70,13 +71,22 @@ public class HeartBeatBeaconConfig { this.notifierFrequency = notifierFrequency; } + @XmlElement(name = "timeSkew", required = true) + public int getTimeSkew() { + return timeSkew; + } + + public void setTimeSkew(int timeSkew) { + this.timeSkew = timeSkew; + } + @XmlElement(name = "ServerTimeOutIntervalInSeconds", required = true) public int getServerTimeOutIntervalInSeconds() { - return serverTimeOutInterval; + return serverTimeOutIntervalInSeconds; } - public void setServerTimeOutInterval(int serverTimeOutInterval) { - this.serverTimeOutInterval = serverTimeOutInterval; + public void setServerTimeOutIntervalInSeconds(int serverTimeOutIntervalInSeconds) { + this.serverTimeOutIntervalInSeconds = serverTimeOutIntervalInSeconds; } public static void init() throws HeartBeatBeaconConfigurationException { diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java similarity index 51% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java index c784318249..fe7a26768d 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfigurationException.java @@ -1,21 +1,21 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon; public class HeartBeatBeaconConfigurationException extends Exception { diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java similarity index 94% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java index aa9e34bd71..8d9a69f703 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,10 +11,11 @@ * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java similarity index 78% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java index d06ee05df6..5ab3aa4dd1 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/DataSourceConfig.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. - * you may obtain a copy of the License at + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java similarity index 86% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java index 96ae86fa1a..befbf304b8 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/datasource/JNDILookupDefinition.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. - * you may obtain a copy of the License at + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java similarity index 98% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java index 93d6a612b3..97e1c3428b 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java similarity index 89% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java index 46f7091436..9a731ed8b1 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java similarity index 93% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java index ec6a4d3575..bf92afaaa8 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/exception/HeartBeatDAOException.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java similarity index 96% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index 832b7fd58c..f8ccfee414 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,7 +11,7 @@ * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java similarity index 95% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java index 31b72ad2ef..fa4e291d84 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java new file mode 100644 index 0000000000..4feb8b7fe7 --- /dev/null +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. + * + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dto; + +import java.sql.Timestamp; + +public class HeartBeatEvent { + + private String serverUUID; + private Timestamp time; + + public HeartBeatEvent(String serverUUID){ + this.serverUUID = serverUUID; + this.time = new Timestamp(System.currentTimeMillis()); + } + + public String getServerUUID() { + return serverUUID; + } + + public void setServerUUID(String serverUUID) { + this.serverUUID = serverUUID; + } + + public Timestamp getTime() { + return time; + } + + public void setTime(Timestamp time) { + this.time = time; + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java similarity index 60% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java index b98f1f63d7..25ea650e55 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java @@ -1,21 +1,21 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon.dto; public class ServerContext { diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java new file mode 100644 index 0000000000..9c90d3a9cb --- /dev/null +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. + * + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.exception; + +public class HeartBeatManagementException extends Exception { + + private static final long serialVersionUID = 5304352685379661115L; + + public HeartBeatManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public HeartBeatManagementException(String message, Throwable cause) { + super(message, cause); + } + + public HeartBeatManagementException(String msg) { + super(msg); + } + + public HeartBeatManagementException() { + super(); + } + + public HeartBeatManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java similarity index 67% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java index 215b6ceb11..cb7ebc4385 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/InvalidConfigurationStateException.java @@ -1,21 +1,21 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon.exception; public class InvalidConfigurationStateException extends RuntimeException { diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java similarity index 51% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java index a23ccbe7c0..63379d7c70 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/ServerStatusUpdationFailedException.java @@ -1,21 +1,21 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon.exception; public class ServerStatusUpdationFailedException extends Exception { diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java similarity index 92% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index e936ea1593..6d522910b8 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,10 +11,11 @@ * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon.internal; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java similarity index 58% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java index a04ab9508a..dc332a251e 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconDataHolder.java @@ -1,24 +1,23 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package io.entgra.server.bootup.heartbeat.beacon.internal; -import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; public class HeartBeatBeaconDataHolder { diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java similarity index 93% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java index acc19bb927..401483135f 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,10 +11,11 @@ * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon.internal; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java similarity index 83% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index 2c1630cb9c..0c0b04d6c8 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,10 +11,11 @@ * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ + package io.entgra.server.bootup.heartbeat.beacon.service; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java similarity index 92% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 9363d3ea07..87ba57df0e 100644 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra Pvt Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -11,7 +11,7 @@ * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @@ -44,8 +44,10 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); + int timeSkew = HeartBeatBeaconConfig.getInstance().getTimeSkew(); + int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); - Map serverCtxMap = heartBeatDAO.getActiveServerDetails(timeOutIntervalInSeconds); + Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumilativeTimeOut); if(!serverCtxMap.isEmpty()) { localServerCtx = serverCtxMap.get(localServerUUID); if (localServerCtx != null) { diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties similarity index 100% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml similarity index 100% rename from components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml diff --git a/components/task-allocation/pom.xml b/components/heartbeat-management/pom.xml similarity index 96% rename from components/task-allocation/pom.xml rename to components/heartbeat-management/pom.xml index 69c44d0d82..dc60f12880 100644 --- a/components/task-allocation/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -27,7 +27,7 @@ 4.0.0 - task-allocation + heartbeat-management pom Entgra - Task Allocation Framework http://wso2.org diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java deleted file mode 100644 index d17ffaf447..0000000000 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/HeartBeatEvent.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.server.bootup.heartbeat.beacon.dto; - -import java.sql.Timestamp; - -public class HeartBeatEvent { - - private String serverUUID; - private Timestamp time; - - public HeartBeatEvent(String serverUUID){ - this.serverUUID = serverUUID; - this.time = new Timestamp(System.currentTimeMillis()); - } - - public String getServerUUID() { - return serverUUID; - } - - public void setServerUUID(String serverUUID) { - this.serverUUID = serverUUID; - } - - public Timestamp getTime() { - return time; - } - - public void setTime(Timestamp time) { - this.time = time; - } - -} diff --git a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java b/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java deleted file mode 100644 index eeb44e6d7a..0000000000 --- a/components/task-allocation/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/exception/HeartBeatManagementException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.server.bootup.heartbeat.beacon.exception; - -public class HeartBeatManagementException extends Exception { - - private static final long serialVersionUID = 5304352685379661115L; - - public HeartBeatManagementException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public HeartBeatManagementException(String message, Throwable cause) { - super(message, cause); - } - - public HeartBeatManagementException(String msg) { - super(msg); - } - - public HeartBeatManagementException() { - super(); - } - - public HeartBeatManagementException(Throwable cause) { - super(cause); - } - -} diff --git a/pom.xml b/pom.xml index c9022ab0f8..6218cb046e 100644 --- a/pom.xml +++ b/pom.xml @@ -35,7 +35,7 @@ - components/task-allocation + components/heartbeat-management components/device-mgt components/device-mgt-extensions components/identity-extensions From c1652b61f8287226e5accfe675e043ad25694aa4 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 17 Nov 2020 11:57:58 +0530 Subject: [PATCH 06/21] Fixing issues with DS initialization --- .../heartbeat/beacon/HeartBeatBeaconConfig.java | 11 +++++++++++ .../beacon/internal/HeartBeatBeaconComponent.java | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java index f8b741fec3..1d3efd95fd 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java @@ -18,6 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon; +import io.entgra.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.server.bootup.heartbeat.beacon.exception.InvalidConfigurationStateException; import org.w3c.dom.Document; import org.wso2.carbon.utils.CarbonUtils; @@ -36,6 +37,7 @@ public class HeartBeatBeaconConfig { private int notifierDelay; private int serverTimeOutIntervalInSeconds; private int timeSkew; + private DataSourceConfig dataSourceConfig; private static HeartBeatBeaconConfig config; @@ -89,6 +91,15 @@ public class HeartBeatBeaconConfig { this.serverTimeOutIntervalInSeconds = serverTimeOutIntervalInSeconds; } + @XmlElement(name = "DataSourceConfiguration", required = true) + public DataSourceConfig getDataSourceConfig() { + return dataSourceConfig; + } + + public void setDataSourceConfig(DataSourceConfig dataSourceConfig) { + this.dataSourceConfig = dataSourceConfig; + } + public static void init() throws HeartBeatBeaconConfigurationException { try { File emailSenderConfig = new File(HEART_BEAT_NOTIFIER_CONFIG_PATH); diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index 6d522910b8..524814da8f 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -20,6 +20,8 @@ package io.entgra.server.bootup.heartbeat.beacon.internal; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; +import io.entgra.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; +import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementServiceImpl; import org.apache.commons.logging.Log; @@ -42,6 +44,8 @@ public class HeartBeatBeaconComponent { } //heart beat notifier configuration */ HeartBeatBeaconConfig.init(); + DataSourceConfig dsConfig = HeartBeatBeaconConfig.getInstance().getDataSourceConfig(); + HeartBeatBeaconDAOFactory.init(dsConfig); this.registerHeartBeatServices(componentContext); From 02fb5a09a89753fd190b8299fab51d640ed39385 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 17 Nov 2020 15:54:13 +0530 Subject: [PATCH 07/21] Adding new feature for heart beat functionality --- .../{ => config}/HeartBeatBeaconConfig.java | 10 +- .../internal/HeartBeatBeaconComponent.java | 2 +- .../internal/HeartBeatInternalUtils.java | 2 +- .../HeartBeatManagementServiceImpl.java | 2 +- .../pom.xml | 191 ++++++++++++++++++ .../src/main/resources/build.properties | 22 ++ .../main/resources/conf/heart-beat-config.xml | 31 +++ .../datasources/heart-beat-datasources.xml | 48 +++++ .../resources/dbscripts/heart-beat/h2.sql | 12 ++ .../resources/dbscripts/heart-beat/mssql.sql | 15 ++ .../resources/dbscripts/heart-beat/mysql.sql | 12 ++ .../resources/dbscripts/heart-beat/oracle.sql | 14 ++ .../dbscripts/heart-beat/postgresql.sql | 12 ++ .../src/main/resources/p2.inf | 11 + features/heartbeat-management/pom.xml | 41 ++++ pom.xml | 1 + 16 files changed, 419 insertions(+), 7 deletions(-) rename components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/{ => config}/HeartBeatBeaconConfig.java (90%) create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/build.properties create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql create mode 100644 features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf create mode 100644 features/heartbeat-management/pom.xml diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java similarity index 90% rename from components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java index 1d3efd95fd..7c1365a9d6 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java @@ -16,8 +16,10 @@ * under the License. */ -package io.entgra.server.bootup.heartbeat.beacon; +package io.entgra.server.bootup.heartbeat.beacon.config; +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException; +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; import io.entgra.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.server.bootup.heartbeat.beacon.exception.InvalidConfigurationStateException; import org.w3c.dom.Document; @@ -55,7 +57,7 @@ public class HeartBeatBeaconConfig { return config; } - @XmlElement(name = "NotifierInitialDelay", required = true) + @XmlElement(name = "NotifierInitialDelayInSeconds", required = true) public int getNotifierDelay() { return notifierDelay; } @@ -64,7 +66,7 @@ public class HeartBeatBeaconConfig { this.notifierDelay = notifierDelay; } - @XmlElement(name = "NotifierFrequency", required = true) + @XmlElement(name = "NotifierFrequencyInSeconds", required = true) public int getNotifierFrequency() { return notifierFrequency; } @@ -73,7 +75,7 @@ public class HeartBeatBeaconConfig { this.notifierFrequency = notifierFrequency; } - @XmlElement(name = "timeSkew", required = true) + @XmlElement(name = "TimeSkewInSeconds", required = true) public int getTimeSkew() { return timeSkew; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index 524814da8f..7cc795d4a6 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -18,7 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon.internal; -import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; +import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; import io.entgra.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java index 401483135f..1e5debde74 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java @@ -18,7 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon.internal; -import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; +import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 87ba57df0e..576b7c67df 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -18,7 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon.service; -import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig; +import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml new file mode 100644 index 0000000000..c1f137a61d --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml @@ -0,0 +1,191 @@ + + + + + + + org.wso2.carbon.devicemgt + heart-beat-feature + 4.1.11-SNAPSHOT + ../pom.xml + + + 4.0.0 + io.entgra.server.heart.beat.feature + pom + Entgra IoT - Heart Beat Feature + http://entgra.io + + This feature bundles for the heart beat beacon for Entgra IoT Server + + + + + com.h2database.wso2 + h2-database-engine + + + org.wso2.carbon.devicemgt + io.entgra.server.bootup.heartbeat.beacon + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.identity.inbound.auth.oauth2 + org.wso2.carbon.identity.oauth.stub + + + org.apache.axis2.wso2 + axis2-client + + + org.apache.geronimo.specs.wso2 + geronimo-stax-api_1.0_spec + + + org.apache.ws.commons.axiom.wso2 + axiom + + + org.codehaus.woodstox + woodstox-core-asl + + + org.codehaus.woodstox + wstx-asl + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics.data.publisher + + + org.wso2.carbon.analytics + org.wso2.carbon.analytics.api + + + + + + + + + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + create-heart-beat-mgt-schema + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + io.entgra.server.heart.beat + ../../../../features/etc/feature.properties + + + + org.wso2.carbon.p2.category.type:server + + org.eclipse.equinox.p2.type.group:true + + + + + + org.wso2.carbon.devicemgt:io.entgra.server.bootup.heartbeat.beacon:${carbon.device.mgt.version} + + + + org.wso2.carbon.core.server:${carbon.kernel.version} + + + + + + + + diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/build.properties b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..9404b75803 --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/build.properties @@ -0,0 +1,22 @@ +# +# Copyright (C) 2018 - 2020 Entgra (Pvt) Ltd, Inc - All Rights Reserved. +# +# Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. +# +# Licensed under the Entgra Commercial License, Version 1.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://entgra.io/licenses/entgra-commercial/1.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +jarProcessor.unsign=true +signJars=true +custom = true diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml new file mode 100644 index 0000000000..f025df0478 --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml @@ -0,0 +1,31 @@ + + + + + + + jdbc/ServerHeartBeat_DS + + + 30 + 300 + 5 + 600 + diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml new file mode 100644 index 0000000000..34c5d011b5 --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml @@ -0,0 +1,48 @@ + + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + + jdbc/ServerHeartBeat_DS + The datasource used for recording server Heart Beats + + jdbc/ServerHeartBeat_DS + + + + jdbc:h2:repository/database/HeartBeat_DB;DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql new file mode 100644 index 0000000000..570c2f78df --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `SERVER_HEART_BEAT_EVENTS` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + HOST_NAME VARCHAR(100) NOT NULL, + MAC VARCHAR(100) NOT NULL, + UUID VARCHAR(100) NOT NULL, + SERVER_PORT INTEGER NOT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (ID) +); diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql new file mode 100644 index 0000000000..830aaea26a --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql @@ -0,0 +1,15 @@ +-- ----------------------------------------------------- +-- Table `SERVER_HEART_BEAT_EVENTS` +-- ----------------------------------------------------- + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[SERVER_HEART_BEAT_EVENTS]') AND TYPE IN (N'U')) +CREATE TABLE SERVER_HEART_BEAT_EVENTS ( + ID INT NOT NULL AUTO_INCREMENT, + HOST_NAME VARCHAR(100) NOT NULL, + MAC VARCHAR(100) NOT NULL, + UUID VARCHAR(100) NOT NULL, + SERVER_PORT INT NOT NULL, + LAST_UPDATED_TIMESTAMP DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (ID)); + + diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql new file mode 100644 index 0000000000..4584426b5c --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `POWER_METER_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + HOST_NAME VARCHAR(100) NOT NULL, + MAC VARCHAR(100) NOT NULL, + UUID VARCHAR(100) NOT NULL, + SERVER_PORT INTEGER NOT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (ID) +); diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql new file mode 100644 index 0000000000..81ed4cfaad --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql @@ -0,0 +1,14 @@ +-- ----------------------------------------------------- +-- Table `SERVER_HEART_BEAT_EVENTS` +-- ----------------------------------------------------- + +CREATE TABLE SERVER_HEART_BEAT_EVENTS ( + ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, + HOST_NAME VARCHAR(100) NOT NULL, + MAC VARCHAR(100) NOT NULL, + UUID VARCHAR(100) NOT NULL, + SERVER_PORT INTEGER NOT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT PK_POWER_METER_DEVICE PRIMARY KEY (ID) +) +/ diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql new file mode 100644 index 0000000000..989ed77954 --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table SERVER_HEART_BEAT_EVENTS +-- ----------------------------------------------------- + CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( + ID INTEGER AUTO_INCREMENT NOT NULL, + HOST_NAME VARCHAR(100) NOT NULL, + MAC VARCHAR(100) NOT NULL, + UUID VARCHAR(100) NOT NULL, + SERVER_PORT INTEGER NOT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (ID) +); diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf new file mode 100644 index 0000000000..1a0593e92d --- /dev/null +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf @@ -0,0 +1,11 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/datasources/,target:${installFolder}/../../../conf/datasources/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/conf/heart-beat-config.xml,target:${installFolder}/../../../conf/heart-beat-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/dbscripts/heart-beat/,target:${installFolder}/../../../dbscripts/heart-beat,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/database/);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/database/,target:${installFolder}/../../../repository/database/,overwrite:true);\ + +instructions.unconfigure = \ +org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/heart-beat-datasources.xml);\ +org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/heart-beat);\ +org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/HeartBeat_DB.h2.db);\ diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml new file mode 100644 index 0000000000..049bf35a50 --- /dev/null +++ b/features/heartbeat-management/pom.xml @@ -0,0 +1,41 @@ + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 4.1.11-SNAPSHOT + ../../pom.xml + + + 4.0.0 + org.wso2.carbon.devicemgt + heart-beat-feature + 4.1.11-SNAPSHOT + pom + Entgra - Heart Beat Feature + http://wso2.org + + + io.entgra.server.heart.beat.feature + + + diff --git a/pom.xml b/pom.xml index 6218cb046e..3b8e07f718 100644 --- a/pom.xml +++ b/pom.xml @@ -54,6 +54,7 @@ features/certificate-mgt features/oauth-extensions features/email-sender + features/heartbeat-management features/ui-request-interceptor features/jwt-client features/device-mgt-extensions From 56f93161f044906034c9da440db655e1805236c3 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 17 Nov 2020 16:00:24 +0530 Subject: [PATCH 08/21] correcting db scripts --- .../src/main/resources/dbscripts/heart-beat/mysql.sql | 2 +- .../src/main/resources/dbscripts/heart-beat/oracle.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql index 4584426b5c..570c2f78df 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql @@ -1,5 +1,5 @@ -- ----------------------------------------------------- --- Table `POWER_METER_DEVICE` +-- Table `SERVER_HEART_BEAT_EVENTS` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( ID INTEGER AUTO_INCREMENT NOT NULL, diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql index 81ed4cfaad..3f435816f4 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql @@ -9,6 +9,6 @@ CREATE TABLE SERVER_HEART_BEAT_EVENTS ( UUID VARCHAR(100) NOT NULL, SERVER_PORT INTEGER NOT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT PK_POWER_METER_DEVICE PRIMARY KEY (ID) + CONSTRAINT PK_SERVER_HEART_BEAT_EVENTS PRIMARY KEY (ID) ) / From 3744a7cfc765bab7ed87a62487f0938f467dcfd7 Mon Sep 17 00:00:00 2001 From: Ace Date: Thu, 19 Nov 2020 11:57:59 +0530 Subject: [PATCH 09/21] adding fixes to the flow --- .../pom.xml | 11 ++ .../beacon/HeartBeatBeaconUtils.java | 13 +- .../beacon/config/HeartBeatBeaconConfig.java | 12 +- .../beacon/dao/HeartBeatBeaconDAOFactory.java | 3 +- .../dao/impl/GenericHeartBeatDAOImpl.java | 28 ++--- .../dao/util/HeartBeatBeaconDAOUtil.java | 1 - .../heartbeat/beacon/dto/ServerContext.java | 9 -- .../internal/HeartBeatBeaconComponent.java | 36 ++++-- .../internal/HeartBeatInternalUtils.java | 3 +- .../HeartBeatManagementServiceImpl.java | 115 +++++++++++------- .../pom.xml | 37 ------ .../main/resources/conf/heart-beat-config.xml | 5 +- .../datasources/heart-beat-datasources.xml | 18 ++- .../resources/dbscripts/heart-beat/h2.sql | 1 - .../resources/dbscripts/heart-beat/mssql.sql | 1 - .../resources/dbscripts/heart-beat/mysql.sql | 1 - .../resources/dbscripts/heart-beat/oracle.sql | 1 - .../dbscripts/heart-beat/postgresql.sql | 1 - .../src/main/resources/p2.inf | 7 +- 19 files changed, 149 insertions(+), 154 deletions(-) diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml index b5e7141461..5cb57f3dfb 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -59,6 +59,7 @@ javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, org.wso2.carbon.context, org.wso2.carbon.utils.*, + org.wso2.carbon.ndatasource.core, org.w3c.dom, org.apache.velocity;version="${velocity.version}", org.apache.velocity.app;version="${velocity.version}", @@ -168,6 +169,16 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.common + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + log4j + log4j + + + diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java index 8d9a69f703..9c5b91a93d 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -30,7 +30,6 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.net.InetAddress; -import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Hashtable; @@ -68,7 +67,7 @@ public class HeartBeatBeaconUtils { return (DataSource) InitialContext.doLookup(dataSourceName); } final InitialContext context = new InitialContext(jndiProperties); - return (DataSource) context.lookup(dataSourceName); + return (DataSource) context.doLookup(dataSourceName); } catch (Exception e) { throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); } @@ -77,20 +76,10 @@ public class HeartBeatBeaconUtils { public static ServerContext getServerDetails() throws UnknownHostException, SocketException { InetAddress localHost = InetAddress.getLocalHost(); - NetworkInterface ni = NetworkInterface.getByInetAddress(localHost); - byte[] hardwareAddress = ni.getHardwareAddress(); - String[] hexadecimal = new String[hardwareAddress.length]; - for (int i = 0; i < hardwareAddress.length; i++) { - hexadecimal[i] = String.format("%02X", hardwareAddress[i]); - } - String macAddress = String.join("-", hexadecimal); int iotsCorePort = Integer.parseInt(System.getProperty("iot.core.https.port")); - ServerContext ctx = new ServerContext(); ctx.setHostName(localHost.getHostName()); - ctx.setMacAddress(macAddress); ctx.setCarbonServerPort(iotsCorePort); - return ctx; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java index 7c1365a9d6..e2bb9e2fec 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java @@ -35,6 +35,7 @@ import java.io.File; @XmlRootElement(name = "HeartBeatBeaconConfig") public class HeartBeatBeaconConfig { + private boolean enabled; private int notifierFrequency; private int notifierDelay; private int serverTimeOutIntervalInSeconds; @@ -44,7 +45,7 @@ public class HeartBeatBeaconConfig { private static HeartBeatBeaconConfig config; private static final String HEART_BEAT_NOTIFIER_CONFIG_PATH = - CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "heart-beat-config.xml"; + CarbonUtils.getCarbonConfigDirPath() + File.separator + "heart-beat-config.xml"; private HeartBeatBeaconConfig() { } @@ -102,6 +103,15 @@ public class HeartBeatBeaconConfig { this.dataSourceConfig = dataSourceConfig; } + @XmlElement(name = "Enable", required = true) + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + public static void init() throws HeartBeatBeaconConfigurationException { try { File emailSenderConfig = new File(HEART_BEAT_NOTIFIER_CONFIG_PATH); diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java index 97e1c3428b..e8d3011be9 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatBeaconDAOFactory.java @@ -167,7 +167,6 @@ public class HeartBeatBeaconDAOFactory { currentConnection.remove(); } - /** * Resolve data source from the data source definition * @@ -190,7 +189,7 @@ public class HeartBeatBeaconDAOFactory { List jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { - Hashtable jndiProperties = new Hashtable<>(); + Hashtable jndiProperties = new Hashtable(); for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { jndiProperties.put(prop.getName(), prop.getValue()); } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index f8ccfee414..bdc7d6a52f 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -29,6 +29,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -46,23 +47,21 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { String uuid = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String serverUUID = UUID.randomUUID().toString(); String sql; - sql = "INSERT INTO SERVER_HEART_BEAT_EVENTS(HOST_NAME, MAC, UUID, SERVER_PORT) VALUES (?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, new String[]{"UUID"}); + sql = "INSERT INTO SERVER_HEART_BEAT_EVENTS(HOST_NAME, UUID, SERVER_PORT) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, ctx.getHostName()); - stmt.setString(2, ctx.getMacAddress()); - stmt.setString(3, UUID.randomUUID().toString()); - stmt.setInt(4, ctx.getCarbonServerPort()); + stmt.setString(2, serverUUID); + stmt.setInt(3, ctx.getCarbonServerPort()); - stmt.executeUpdate(); - ResultSet result = stmt.getGeneratedKeys(); - if (result.next()){ - uuid = result.getString("UUID"); + if(stmt.executeUpdate() > 0){ + uuid = serverUUID; } } catch (SQLException e) { throw new HeartBeatDAOException("Error occurred while persisting server context for : '" + - "mac '" + ctx.getMacAddress() + "' " + + "port '" + ctx.getCarbonServerPort() + "' " + "hostname : '" + ctx.getHostName() + "' ", e); } finally { HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); @@ -97,11 +96,10 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { String uuid = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); - String sql = "SELECT UUID FROM SERVER_HEART_BEAT_EVENTS WHERE HOST_NAME = ? AND MAC = ? AND SERVER_PORT = ?"; + String sql = "SELECT UUID FROM SERVER_HEART_BEAT_EVENTS WHERE HOST_NAME = ? AND SERVER_PORT = ?"; stmt = conn.prepareStatement(sql, new String[]{"UUID"}); stmt.setString(1, ctx.getHostName()); - stmt.setString(2, ctx.getMacAddress()); - stmt.setInt(3, ctx.getCarbonServerPort()); + stmt.setInt(2, ctx.getCarbonServerPort()); resultSet = stmt.executeQuery(); if (resultSet.next()){ @@ -109,7 +107,7 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { } } catch (SQLException e) { throw new HeartBeatDAOException("Error occurred while retrieving meta information for heart beat event from " + - "mac '" + ctx.getMacAddress() + "' " + + "port '" + ctx.getCarbonServerPort() + "' " + "hostname : '" + ctx.getHostName() + "' ", e); } finally { HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); @@ -124,7 +122,7 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { Map ctxList = new HashMap<>(); try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); - String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, MAC, SERVER_PORT from " + + String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, SERVER_PORT from " + "SERVER_HEART_BEAT_EVENTS, (SELECT @row_number:=-1) AS TEMP " + "WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " + "ORDER BY UUID"; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java index fa4e291d84..211a10635b 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java @@ -85,7 +85,6 @@ public final class HeartBeatBeaconDAOUtil { ctx.setIndex(resultSet.getInt("IDX")); ctx.setUuid(resultSet.getString("UUID")); ctx.setHostName(resultSet.getString("HOST_NAME")); - ctx.setMacAddress(resultSet.getString("MAC")); ctx.setCarbonServerPort(resultSet.getInt("SERVER_PORT")); return ctx; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java index 25ea650e55..bdb5abe76e 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ServerContext.java @@ -21,7 +21,6 @@ package io.entgra.server.bootup.heartbeat.beacon.dto; public class ServerContext { private String hostName; - private String macAddress; private int carbonServerPort; private String uuid; private int index; @@ -34,14 +33,6 @@ public class ServerContext { this.hostName = hostName; } - public String getMacAddress() { - return macAddress; - } - - public void setMacAddress(String macAddress) { - this.macAddress = macAddress; - } - public String getUuid() { return uuid; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index 7cc795d4a6..3435c16601 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -27,10 +27,17 @@ import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementServi import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.ndatasource.core.DataSourceService; /** * @scr.component name="io.entgra.server.bootup.heartbeat.beacon.heartbeatBeaconComponent" * immediate="true" + * @scr.reference name="org.wso2.carbon.ndatasource" + * interface="org.wso2.carbon.ndatasource.core.DataSourceService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDataSourceService" + * unbind="unsetDataSourceService" */ public class HeartBeatBeaconComponent { @@ -42,21 +49,24 @@ public class HeartBeatBeaconComponent { if (log.isDebugEnabled()) { log.debug("Initializing email sender core bundle"); } + this.registerHeartBeatServices(componentContext); + //heart beat notifier configuration */ HeartBeatBeaconConfig.init(); - DataSourceConfig dsConfig = HeartBeatBeaconConfig.getInstance().getDataSourceConfig(); - HeartBeatBeaconDAOFactory.init(dsConfig); - this.registerHeartBeatServices(componentContext); + if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + DataSourceConfig dsConfig = HeartBeatBeaconConfig.getInstance().getDataSourceConfig(); + HeartBeatBeaconDAOFactory.init(dsConfig); - //Setting up executors to notify heart beat status */ - HeartBeatInternalUtils.setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); + //Setting up executors to notify heart beat status */ + HeartBeatInternalUtils.setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); + } if (log.isDebugEnabled()) { - log.debug("Email sender core bundle has been successfully initialized"); + log.debug("Heart Beat Notifier bundle has been successfully initialized"); } } catch (Throwable e) { - log.error("Error occurred while initializing email sender core bundle", e); + log.error("Error occurred while initializing Heart Beat Notifier bundle", e); } } @@ -74,4 +84,16 @@ public class HeartBeatBeaconComponent { componentContext.getBundleContext().registerService(HeartBeatManagementService.class, heartBeatServiceProvider, null); } + protected void setDataSourceService(DataSourceService dataSourceService) { + /* This is to avoid mobile device management component getting initialized before the underlying datasources + are registered */ + if (log.isDebugEnabled()) { + log.debug("Data source service set to mobile service component"); + } + } + + protected void unsetDataSourceService(DataSourceService dataSourceService) { + //do nothing + } + } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java index 1e5debde74..c407348b4f 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java @@ -20,6 +20,7 @@ package io.entgra.server.bootup.heartbeat.beacon.internal; import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException; +import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; @@ -66,7 +67,7 @@ public class HeartBeatInternalUtils { CONFIG.getNotifierFrequency() != 0 ? CONFIG.getNotifierFrequency() : DEFAULT__NOTIFIER_INTERVAL, TimeUnit.SECONDS); } catch (HeartBeatManagementException e) { - throw new HeartBeatBeaconConfigurationException("Error occured while updating initial server context."); + throw new HeartBeatBeaconConfigurationException("Error occured while updating initial server context.", e); } } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 576b7c67df..362f97879e 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -27,6 +27,7 @@ import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementExc import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconDataHolder; import org.wso2.carbon.device.mgt.common.ServerCtxInfo; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import java.sql.SQLException; import java.util.Map; @@ -39,30 +40,35 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic int hashIndex = -1; ServerContext localServerCtx = null; ServerCtxInfo serverCtxInfo = null; - try { - HeartBeatBeaconDAOFactory.openConnection(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + HeartBeatBeaconDAOFactory.openConnection(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); - int timeSkew = HeartBeatBeaconConfig.getInstance().getTimeSkew(); - int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; - String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); - Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumilativeTimeOut); - if(!serverCtxMap.isEmpty()) { - localServerCtx = serverCtxMap.get(localServerUUID); - if (localServerCtx != null) { - hashIndex = localServerCtx.getIndex(); - serverCtxInfo = new ServerCtxInfo(serverCtxMap.size(), hashIndex); + int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); + int timeSkew = HeartBeatBeaconConfig.getInstance().getTimeSkew(); + int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; + String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); + Map serverCtxMap = heartBeatDAO.getActiveServerDetails(cumilativeTimeOut); + if (!serverCtxMap.isEmpty()) { + localServerCtx = serverCtxMap.get(localServerUUID); + if (localServerCtx != null) { + hashIndex = localServerCtx.getIndex(); + serverCtxInfo = new ServerCtxInfo(serverCtxMap.size(), hashIndex); + } } + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } catch (HeartBeatDAOException e) { + String msg = "Error occurred while retrieving active server count."; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); } - } catch (SQLException e) { - String msg = "Error occurred while opening a connection to the underlying data source"; - throw new HeartBeatManagementException(msg, e); - } catch (HeartBeatDAOException e) { - String msg = "Error occurred while retrieving active server count."; - throw new HeartBeatManagementException(msg, e); - } finally { - HeartBeatBeaconDAOFactory.closeConnection(); + } else { + String msg = "Heart Beat Configuration Disabled. Server Context Information Not available."; + throw new HeartBeatManagementException(msg); } return serverCtxInfo; } @@ -71,22 +77,29 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { HeartBeatDAO heartBeatDAO; String uuid = null; - try { - HeartBeatBeaconDAOFactory.openConnection(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + HeartBeatBeaconDAOFactory.beginTransaction(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - uuid = heartBeatDAO.retrieveExistingServerCtx(ctx); - if(uuid == null){ - uuid = heartBeatDAO.recordServerCtx(ctx); + uuid = heartBeatDAO.retrieveExistingServerCtx(ctx); + if (uuid == null) { + uuid = heartBeatDAO.recordServerCtx(ctx); + HeartBeatBeaconDAOFactory.commitTransaction(); + } + } catch (HeartBeatDAOException e) { + String msg = "Error Occured while retrieving server context."; + throw new HeartBeatManagementException(msg, e); + } catch (TransactionManagementException e) { + HeartBeatBeaconDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating server context. Issue in opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); } - } catch (SQLException e) { - String msg = "Error occurred while opening a connection to the underlying data source"; - throw new HeartBeatManagementException(msg, e); - } catch (HeartBeatDAOException e) { - String msg = "Error Occured while retrieving active server count."; - throw new HeartBeatManagementException(msg, e); - } finally { - HeartBeatBeaconDAOFactory.closeConnection(); + } else { + String msg = "Heart Beat Configuration Disabled. Updating Server Context Failed."; + throw new HeartBeatManagementException(msg); } return uuid; } @@ -96,18 +109,26 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { HeartBeatDAO heartBeatDAO; boolean operationSuccess = false; - try { - HeartBeatBeaconDAOFactory.openConnection(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - operationSuccess = heartBeatDAO.recordHeatBeat(event); - } catch (SQLException e) { - String msg = "Error occurred while opening a connection to the underlying data source"; - throw new HeartBeatManagementException(msg, e); - } catch (HeartBeatDAOException e) { - String msg = "Error Occured while retrieving active server count."; - throw new HeartBeatManagementException(msg, e); - } finally { - HeartBeatBeaconDAOFactory.closeConnection(); + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + HeartBeatBeaconDAOFactory.beginTransaction(); + heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + operationSuccess = heartBeatDAO.recordHeatBeat(event); + HeartBeatBeaconDAOFactory.commitTransaction(); + } catch (HeartBeatDAOException e) { + String msg = "Error occurred while recording heart beat."; + throw new HeartBeatManagementException(msg, e); + } catch (TransactionManagementException e) { + HeartBeatBeaconDAOFactory.rollbackTransaction(); + String msg = "Error occurred performing heart beat record transaction. " + + "Transaction rolled back."; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + } else { + String msg = "Heart Beat Configuration Disabled. Recording Heart Beat Failed."; + throw new HeartBeatManagementException(msg); } return operationSuccess; } diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml index c1f137a61d..7f6d79f526 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml @@ -87,7 +87,6 @@ - @@ -115,42 +114,6 @@ - - - org.apache.maven.plugins - maven-antrun-plugin - - - - create-heart-beat-mgt-schema - package - - run - - - - - - - - - - - - - - - - - - - - - - - - - org.wso2.maven carbon-p2-plugin diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml index f025df0478..8b3aa6a82a 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml @@ -19,9 +19,10 @@ --> - + true + - jdbc/ServerHeartBeat_DS + jdbc/HeartBeat_DS 30 diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml index 34c5d011b5..a3c656b757 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/datasources/heart-beat-datasources.xml @@ -16,25 +16,23 @@ ~ specific language governing permissions and limitations ~ under the License. --> - - + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader - - jdbc/ServerHeartBeat_DS - The datasource used for recording server Heart Beats + HeartBeat_DS + The datasource Server Heart Beat - jdbc/ServerHeartBeat_DS + jdbc/HeartBeat_DS - jdbc:h2:repository/database/HeartBeat_DB;DB_CLOSE_ON_EXIT=FALSE - wso2carbon - wso2carbon - org.h2.Driver + jdbc:mysql://localhost:3306/heart_beat + root + root + com.mysql.jdbc.Driver 50 60000 true diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql index 570c2f78df..3f5ad9652e 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql @@ -4,7 +4,6 @@ CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( ID INTEGER AUTO_INCREMENT NOT NULL, HOST_NAME VARCHAR(100) NOT NULL, - MAC VARCHAR(100) NOT NULL, UUID VARCHAR(100) NOT NULL, SERVER_PORT INTEGER NOT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql index 830aaea26a..a56b9f981b 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql @@ -6,7 +6,6 @@ IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[S CREATE TABLE SERVER_HEART_BEAT_EVENTS ( ID INT NOT NULL AUTO_INCREMENT, HOST_NAME VARCHAR(100) NOT NULL, - MAC VARCHAR(100) NOT NULL, UUID VARCHAR(100) NOT NULL, SERVER_PORT INT NOT NULL, LAST_UPDATED_TIMESTAMP DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql index 570c2f78df..3f5ad9652e 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql @@ -4,7 +4,6 @@ CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( ID INTEGER AUTO_INCREMENT NOT NULL, HOST_NAME VARCHAR(100) NOT NULL, - MAC VARCHAR(100) NOT NULL, UUID VARCHAR(100) NOT NULL, SERVER_PORT INTEGER NOT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql index 3f435816f4..f9ca7a4367 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql @@ -5,7 +5,6 @@ CREATE TABLE SERVER_HEART_BEAT_EVENTS ( ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL, HOST_NAME VARCHAR(100) NOT NULL, - MAC VARCHAR(100) NOT NULL, UUID VARCHAR(100) NOT NULL, SERVER_PORT INTEGER NOT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql index 989ed77954..85081a385b 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql @@ -4,7 +4,6 @@ CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( ID INTEGER AUTO_INCREMENT NOT NULL, HOST_NAME VARCHAR(100) NOT NULL, - MAC VARCHAR(100) NOT NULL, UUID VARCHAR(100) NOT NULL, SERVER_PORT INTEGER NOT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf index 1a0593e92d..6add373677 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/p2.inf @@ -1,11 +1,8 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/datasources/,target:${installFolder}/../../../conf/datasources/,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/conf/heart-beat-config.xml,target:${installFolder}/../../../conf/heart-beat-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/conf/heart-beat-config.xml,target:${installFolder}/../../conf/heart-beat-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/dbscripts/heart-beat/,target:${installFolder}/../../../dbscripts/heart-beat,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/database/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.server.heart.beat_${feature.version}/database/,target:${installFolder}/../../../repository/database/,overwrite:true);\ instructions.unconfigure = \ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/heart-beat-datasources.xml);\ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/heart-beat);\ -org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/HeartBeat_DB.h2.db);\ From e7b97d78c75a9b543f886ceffd5125425399bc6c Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 20 Nov 2020 05:48:54 +0530 Subject: [PATCH 10/21] Imrpoving task implementation --- .../device/mgt/common/DynamicTaskContext.java | 32 ++++ .../operation/mgt/OperationManager.java | 3 +- .../carbon/device/mgt/core/dao/DeviceDAO.java | 14 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 2 +- .../dao/impl/device/GenericDeviceDAOImpl.java | 135 +++++++++++++++++ .../dao/impl/device/OracleDeviceDAOImpl.java | 138 ++++++++++++++++++ .../impl/device/PostgreSQLDeviceDAOImpl.java | 126 ++++++++++++++++ .../impl/device/SQLServerDeviceDAOImpl.java | 137 +++++++++++++++++ .../operation/mgt/OperationManagerImpl.java | 14 +- .../DeviceManagementProviderService.java | 3 +- .../DeviceManagementProviderServiceImpl.java | 7 +- .../mgt/core/task/DeviceTaskManager.java | 4 +- .../task/impl/DeviceDetailsRetrieverTask.java | 13 +- .../core/task/impl/DeviceTaskManagerImpl.java | 5 +- .../impl/DynamicPartitionedScheduleTask.java | 28 ++-- .../mgt/core/task/DeviceTaskManagerTest.java | 6 +- .../policy/mgt/core/task/MonitoringTask.java | 21 ++- 17 files changed, 650 insertions(+), 38 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java new file mode 100644 index 0000000000..64a10265cd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java @@ -0,0 +1,32 @@ +package org.wso2.carbon.device.mgt.common; + +public class DynamicTaskContext { + + private int serverHashIndex; + private int activeServerCount; + private boolean partitioningEnabled = false; + + public int getServerHashIndex() { + return serverHashIndex; + } + + public void setServerHashIndex(int serverHashIndex) { + this.serverHashIndex = serverHashIndex; + } + + public int getActiveServerCount() { + return activeServerCount; + } + + public void setActiveServerCount(int activeServerCount) { + this.activeServerCount = activeServerCount; + } + + public boolean isPartitioningEnabled() { + return partitioningEnabled; + } + + public void setPartitioningEnabled(boolean partitioningEnabled) { + this.partitioningEnabled = partitioningEnabled; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index 9faa732090..ad59d5c4f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.common.operation.mgt; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.PaginationRequest; @@ -47,7 +48,7 @@ public interface OperationManager { void addTaskOperation(List devices, Operation operation) throws OperationManagementException; - void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException; + void addTaskOperation(String deviceType, Operation operation, DynamicTaskContext dynamicTaskContext) throws OperationManagementException; /** * Method to retrieve the list of all operations to a device. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index b2cb5ac269..2c1df83ad9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -295,6 +295,18 @@ public interface DeviceDAO { */ List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the devices of a given tenant as a paginated result, along the lines of + * activeServerCount and serverIndex + * + * @param request + * @param tenantId + * @param activeServerCount + * @param serverIndex + * @return + */ + List getAllocatedDevices(PaginationRequest request, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException; + /** * This method is used to search for devices within a specific group. * @@ -335,7 +347,7 @@ public interface DeviceDAO { * @return returns list of devices of provided type. * @throws DeviceManagementDAOException */ - List getDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException; + List getAllocatedDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException; List getDevices(long timestamp, int tenantId) throws DeviceManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 1ceb85d868..43889beb7d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -802,7 +802,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @Override - public List getDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException { + public List getAllocatedDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index f4bda81221..5aefd9f1dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -176,6 +176,141 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override + public List getAllocatedDevices(PaginationRequest request, int tenantId, int activeServerCount, int serverIndex) + throws DeviceManagementDAOException { + List devices; + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + boolean isPartitionedTask = false; + + try { + Connection conn = getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, " + + "d1.DESCRIPTION, " + + "d1.NAME AS DEVICE_NAME, " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; + //Add the query to filter active devices on timestamp + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + if (activeServerCount > 0){ + sql = sql + " AND MOD(d1.ID, ?) = ?"; + isPartitionedTask = true; + } + sql = sql + " LIMIT ?,?"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + if (isPartitionedTask) { + stmt.setInt(paramIdx++, activeServerCount); + stmt.setInt(paramIdx++, serverIndex); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 07bd3089ed..2c1cfe2cb4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -176,6 +176,144 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override + public List getAllocatedDevices(PaginationRequest request, int tenantId, + int activeServerCount, int serverIndex) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + boolean isPartitionedTask = false; + + try { + conn = getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, " + + "d1.DESCRIPTION, " + + "d1.NAME AS DEVICE_NAME, " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t "; + //Add the query to filter active devices on timestamp + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + if (activeServerCount > 0){ + sql = sql + " AND MOD(d1.ID, ?) = ?"; + isPartitionedTask = true; + } + sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + if (isPartitionedTask) { + stmt.setInt(paramIdx++, activeServerCount); + stmt.setInt(paramIdx++, serverIndex); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index da1c8a2630..d9b7cadf63 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -164,6 +164,132 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + public List getAllocatedDevices(PaginationRequest request, int tenantId, + int activeServerCount, int serverIndex) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + boolean isPartitionedTask = false; + + try { + conn = getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, " + + "d1.DESCRIPTION, " + + "d1.NAME AS DEVICE_NAME, " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t " + + "WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.TENANT_ID = ?"; + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + if (activeServerCount > 0){ + sql = sql + " AND MOD(d1.ID, ?) = ?"; + isPartitionedTask = true; + } + sql = sql + " LIMIT ? OFFSET ?"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + if (isPartitionedTask) { + stmt.setInt(paramIdx++, activeServerCount); + stmt.setInt(paramIdx++, serverIndex); + } + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 1d0d9c246c..5d30052869 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -176,6 +176,143 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override + public List getAllocatedDevices(PaginationRequest request, int tenantId, + int activeServerCount, int serverIndex) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String deviceType = request.getDeviceType(); + boolean isDeviceTypeProvided = false; + String deviceName = request.getDeviceName(); + boolean isDeviceNameProvided = false; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownerPattern = request.getOwnerPattern(); + boolean isOwnerPatternProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; + boolean isPartitionedTask = false; + + try { + conn = getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, " + + "d1.DESCRIPTION, " + + "d1.NAME AS DEVICE_NAME, " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; + //Add the query to filter active devices on timestamp + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } + //Add the query for device-type + if (deviceType != null && !deviceType.isEmpty()) { + sql = sql + " AND t.NAME = ?"; + isDeviceTypeProvided = true; + } + //Add the query for device-name + if (deviceName != null && !deviceName.isEmpty()) { + sql = sql + " AND d.NAME LIKE ?"; + isDeviceNameProvided = true; + } + sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } else if (ownerPattern != null && !ownerPattern.isEmpty()) { + sql = sql + " AND e.OWNER LIKE ?"; + isOwnerPatternProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + if (activeServerCount > 0){ + sql = sql + " AND d1.ID % ? = ?"; + isPartitionedTask = true; + } + sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + if (isPartitionedTask) { + stmt.setInt(paramIdx++, activeServerCount); + stmt.setInt(paramIdx++, serverIndex); + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index b2e7b769ae..a6db88ea5f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -24,6 +24,7 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.MonitoringOperation; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; @@ -300,7 +301,7 @@ public class OperationManagerImpl implements OperationManager { } @Override - public void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException { + public void addTaskOperation(String deviceType, Operation operation, DynamicTaskContext dynamicTaskContext) throws OperationManagementException { List validStatuses = Arrays.asList(EnrolmentInfo.Status.ACTIVE.toString(), EnrolmentInfo.Status.INACTIVE.toString(), EnrolmentInfo.Status.UNREACHABLE.toString()); @@ -316,7 +317,16 @@ public class OperationManagerImpl implements OperationManager { paginationRequest = new PaginationRequest(start, batchSize); paginationRequest.setStatusList(validStatuses); paginationRequest.setDeviceType(deviceType); - List devices = deviceDAO.getDevices(paginationRequest, tenantId); + List devices; + + if(dynamicTaskContext != null && dynamicTaskContext.isPartitioningEnabled()) { + devices = deviceDAO.getAllocatedDevices(paginationRequest, tenantId, + dynamicTaskContext.getActiveServerCount(), + dynamicTaskContext.getServerHashIndex()); + } else { + devices = deviceDAO.getDevices(paginationRequest, tenantId); + } + if (devices.size() == batchSize) { hasRecords = true; start += batchSize; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 70c506ee8b..abb957f9dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -37,6 +37,7 @@ package org.wso2.carbon.device.mgt.core.service; import org.apache.commons.collections.map.SingletonMap; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.PaginationRequest; @@ -664,7 +665,7 @@ public interface DeviceManagementProviderService { Activity addOperation(String type, Operation operation, List devices) throws OperationManagementException, InvalidDeviceException; - void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException; + void addTaskOperation(String deviceType, Operation operation, DynamicTaskContext taskContext) throws OperationManagementException; void addTaskOperation(String type, List devices, Operation operation) throws OperationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index be2cabefb0..e13c6d973f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -56,6 +56,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceNotification; import org.wso2.carbon.device.mgt.common.DevicePropertyNotification; import org.wso2.carbon.device.mgt.common.DeviceTransferRequest; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.InitialOperationConfig; @@ -779,7 +780,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List allocatedDevices; try { DeviceManagementDAOFactory.openConnection(); - allocatedDevices = deviceDAO.getDevices(deviceType, this.getTenantId(), activeServerCount, serverIndex); + allocatedDevices = deviceDAO.getAllocatedDevices(deviceType, this.getTenantId(), activeServerCount, serverIndex); if (allocatedDevices == null) { if (log.isDebugEnabled()) { log.debug("No device is found upon the type '" + deviceType + "'"); @@ -1874,8 +1875,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public void addTaskOperation(String type, Operation operation) throws OperationManagementException { - pluginRepository.getOperationManager(type, this.getTenantId()).addTaskOperation(type, operation); + public void addTaskOperation(String type, Operation operation, DynamicTaskContext taskContext) throws OperationManagementException { + pluginRepository.getOperationManager(type, this.getTenantId()).addTaskOperation(type, operation, taskContext); } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java index c4db7c3531..77310bbcf1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManager.java @@ -19,6 +19,8 @@ package org.wso2.carbon.device.mgt.core.task; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; + public interface DeviceTaskManager { // /** @@ -56,7 +58,7 @@ public interface DeviceTaskManager { * This method will add the operations to devices * @throws DeviceMgtTaskException */ - void addOperations() throws DeviceMgtTaskException; + void addOperations(DynamicTaskContext dynamicTaskContext) throws DeviceMgtTaskException; // /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index b3f4b850a6..b8da8e6124 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -39,6 +39,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.StartupOperationConfig; @@ -52,7 +53,7 @@ import org.wso2.carbon.user.api.UserStoreException; import java.util.List; import java.util.Map; -public class DeviceDetailsRetrieverTask implements Task { +public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { private static Log log = LogFactory.getLog(DeviceDetailsRetrieverTask.class); private String deviceType; @@ -63,10 +64,6 @@ public class DeviceDetailsRetrieverTask implements Task { deviceType = map.get("DEVICE_TYPE"); } - @Override - public void init() { - } - @Override public void execute() { deviceManagementProviderService = DeviceManagementDataHolder.getInstance() @@ -125,7 +122,7 @@ public class DeviceDetailsRetrieverTask implements Task { //pass the configurations also from here, monitoring tasks try { if (deviceManagementProviderService.isDeviceMonitoringEnabled(deviceType)) { - deviceTaskManager.addOperations(); + deviceTaskManager.addOperations(super.getTaskContext()); } } catch (DeviceMgtTaskException e) { log.error("Error occurred while trying to add the operations to " + @@ -133,4 +130,8 @@ public class DeviceDetailsRetrieverTask implements Task { } } + @Override + protected void setup() { + + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java index 1b15091cde..90d73320fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java @@ -44,6 +44,7 @@ import org.wso2.carbon.device.mgt.common.StartupOperationConfig; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; @@ -115,7 +116,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { @Override - public void addOperations() throws DeviceMgtTaskException { + public void addOperations(DynamicTaskContext dynamicTaskContext) throws DeviceMgtTaskException { DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance(). getDeviceManagementProvider(); //list operations for device type @@ -133,7 +134,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { operation.setType(Operation.Type.COMMAND); operation.setCode(str); try { - deviceManagementProviderService.addTaskOperation(deviceType, operation); + deviceManagementProviderService.addTaskOperation(deviceType, operation, dynamicTaskContext); } catch (OperationManagementException e) { throw new DeviceMgtTaskException("Error occurred while adding task operations to devices", e); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index 02cc5315c8..118497aef0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -4,6 +4,7 @@ import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementExc import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.ServerCtxInfo; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.ntask.core.Task; @@ -12,32 +13,39 @@ public abstract class DynamicPartitionedScheduleTask implements Task { private static final Log log = LogFactory.getLog(DynamicPartitionedScheduleTask.class); - private static int serverHashIndex; - private static int activeServerCount; + private static DynamicTaskContext taskContext = null; @Override public final void init() { try { ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); if(ctxInfo!=null){ - activeServerCount = ctxInfo.getActiveServerCount(); - serverHashIndex = ctxInfo.getLocalServerHashIdx(); - setup(); + taskContext = new DynamicTaskContext(); + taskContext.setActiveServerCount(ctxInfo.getActiveServerCount()); + taskContext.setServerHashIndex(ctxInfo.getLocalServerHashIdx()); + + if(ctxInfo.getActiveServerCount() > 0){ + taskContext.setPartitioningEnabled(true); + } + + if(log.isDebugEnabled()){ + log.debug("Initiating execution of dynamic task for server : " + taskContext.getServerHashIndex() + + " where active server count is : " + taskContext.getActiveServerCount() + + " partitioning task enabled : " + taskContext.isPartitioningEnabled()); + } } else { log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function."); } } catch (HeartBeatManagementException e) { log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function." , e); } + setup(); } protected abstract void setup(); - public int getLocalServerHash(){ - return serverHashIndex; + public static DynamicTaskContext getTaskContext() { + return taskContext; } - public int getActiveServerCount(){ - return activeServerCount; - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java index 5ee04dc92d..44554527bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java @@ -117,7 +117,7 @@ public class DeviceTaskManagerTest extends BaseDeviceManagementTest { @Test(groups = "Device Task Manager Test Group", description = "Testing adding operations to devices.") public void testAddOperation() throws DeviceMgtTaskException, OperationManagementException { log.info("Attempting to add operations for devices."); - this.deviceTaskManager.addOperations(); + this.deviceTaskManager.addOperations(null); for (DeviceIdentifier deviceId : deviceIds) { List operationList = this.operationManager.getOperations(deviceId); Assert.assertNotNull(operationList); @@ -133,7 +133,7 @@ public class DeviceTaskManagerTest extends BaseDeviceManagementTest { new TestDeviceManagementService(NEW_DEVICE_TYPE, TestDataHolder.SUPER_TENANT_DOMAIN)); DeviceTaskManager taskManager = new DeviceTaskManagerImpl(NEW_DEVICE_TYPE, TestDataHolder.generateMonitoringTaskConfig(true, 50000, 3)); - taskManager.addOperations(); + taskManager.addOperations(null); } @Test(groups = "Device Task Manager Test Group", dependsOnMethods = "testAddOperationsWithoutDevices", @@ -141,7 +141,7 @@ public class DeviceTaskManagerTest extends BaseDeviceManagementTest { public void testAddOperationsWithoutOperations() throws DeviceMgtTaskException { DeviceTaskManager taskManager = new DeviceTaskManagerImpl(NEW_DEVICE_TYPE, TestDataHolder.generateMonitoringTaskConfig(true, 50000, 3)); - taskManager.addOperations(); + taskManager.addOperations(null); } @Test(groups = "Device Task Manager Test Group", description = "Testing device detail retriever task execution") diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index 0acbac6a60..2129f78286 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -28,7 +28,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; @@ -36,7 +36,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class MonitoringTask implements Task { +public class MonitoringTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(MonitoringTask.class); @@ -44,10 +44,6 @@ public class MonitoringTask implements Task { public void setProperties(Map map) { } - @Override - public void init() { - } - @Override public void execute() { @@ -125,7 +121,14 @@ public class MonitoringTask implements Task { PolicyMonitoringManager monitoringService = PolicyManagementDataHolder.getInstance().getDeviceManagementService() .getPolicyMonitoringManager(deviceType); - List devices = deviceManagementProviderService.getAllDevices(deviceType, false); + List devices; + if(super.getTaskContext()!= null && super.getTaskContext().isPartitioningEnabled()){ + devices = deviceManagementProviderService.getAllocatedDevices(deviceType, + super.getTaskContext().getActiveServerCount(), + super.getTaskContext().getServerHashIndex()); + } else { + devices = deviceManagementProviderService.getAllDevices(deviceType, false); + } if (monitoringService != null && !devices.isEmpty()) { List notifiableDevices = new ArrayList<>(); if (log.isDebugEnabled()) { @@ -163,4 +166,8 @@ public class MonitoringTask implements Task { } } + @Override + protected void setup() { + + } } From 7cd1baf1af192a215db0cbefbc295c406efc50a6 Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 20 Nov 2020 05:52:38 +0530 Subject: [PATCH 11/21] Adding missing license headers --- .../device/mgt/common/DynamicTaskContext.java | 18 ++++++++++++++++++ .../impl/DynamicPartitionedScheduleTask.java | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java index 64a10265cd..e125e3a443 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DynamicTaskContext.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.common; public class DynamicTaskContext { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index 118497aef0..8568164571 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.core.task.impl; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; From ada570f0a017156513b24190e0d8635cff6629c3 Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 20 Nov 2020 16:11:43 +0530 Subject: [PATCH 12/21] fixing NPE when processing operations --- .../mgt/core/operation/mgt/dao/util/OperationDAOUtil.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index c58b75e745..0d83c755cd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -231,6 +231,10 @@ public class OperationDAOUtil { if (rs.getBoolean("IS_LARGE_RESPONSE")) { largeResponseIDs.add(rs.getInt("OP_RES_ID")); } else { + if(activityStatus.getResponses() == null){ + List operationResponses = new ArrayList<>(); + activityStatus.setResponses(operationResponses); + } activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); } } From b1d95af5b05f4d2b29a0a94c82727c11dbd58828 Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 20 Nov 2020 23:37:48 +0530 Subject: [PATCH 13/21] remvoing restriction that prevents activity count to be returned when if-modified-since header is present --- .../service/impl/ActivityProviderServiceImpl.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java index d115659e18..ed4d4edd05 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -298,11 +298,11 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService } activityList.setList(activities); activityList.setCount(count); - if (activities == null || activities.size() == 0) { - if (isIfModifiedSinceSet) { - return Response.notModified().build(); - } - } +// if (activities == null || activities.size() == 0) { +// if (isIfModifiedSinceSet) { +// return Response.notModified().build(); +// } +// } return Response.ok().entity(activityList).build(); } catch (OperationManagementException e) { String msg From 9d39197844cee6ef673c44fa44794b1f337a6718 Mon Sep 17 00:00:00 2001 From: Ace Date: Thu, 26 Nov 2020 19:16:49 +0530 Subject: [PATCH 14/21] Adding improvements to dynamic task allocation --- .../core/dao/impl/AbstractDeviceDAOImpl.java | 4 +- .../operation/mgt/OperationManagerImpl.java | 3 + .../mgt/dao/OperationMappingDAO.java | 33 +++++++++ .../mgt/dao/impl/OperationMappingDAOImpl.java | 74 +++++++++++++++++++ .../task/impl/DeviceStatusMonitoringTask.java | 47 ++++++++---- .../task/impl/DeviceDetailsRetrieverTask.java | 1 + .../impl/DynamicPartitionedScheduleTask.java | 22 +++++- .../core/TestHeartBeatManagementService.java | 24 ++++++ .../mgt/core/task/DeviceTaskManagerTest.java | 5 ++ .../beacon/HeartBeatBeaconUtils.java | 34 +++++++++ .../beacon/config/HeartBeatBeaconConfig.java | 7 ++ .../heartbeat/beacon/dao/HeartBeatDAO.java | 3 +- .../dao/impl/GenericHeartBeatDAOImpl.java | 34 ++++++++- .../internal/HeartBeatBeaconComponent.java | 4 +- ...ernalUtils.java => HeartBeatExecutor.java} | 22 ++++-- .../service/HeartBeatManagementService.java | 2 +- .../HeartBeatManagementServiceImpl.java | 26 ++++--- .../mgt/common/PolicyAdministratorPoint.java | 1 + .../mgt/core/cache/PolicyCacheManager.java | 1 + .../cache/impl/PolicyCacheManagerImpl.java | 1 + .../mgt/core/dao/impl/ProfileDAOImpl.java | 1 + .../mgt/core/enforcement/DelegationTask.java | 27 ++++--- .../impl/PolicyAdministratorPointImpl.java | 1 + .../policy/mgt/core/mgt/PolicyManager.java | 1 + .../mgt/core/mgt/impl/PolicyManagerImpl.java | 1 + .../mgt/core/mgt/impl/ProfileManagerImpl.java | 1 + .../policy/mgt/core/task/MonitoringTask.java | 5 +- .../core/PolicyManagerServiceImplTest.java | 6 +- .../mock/TestHeartBeatManagementService.java | 24 ++++++ 29 files changed, 361 insertions(+), 54 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java rename components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/{HeartBeatInternalUtils.java => HeartBeatExecutor.java} (80%) create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 43889beb7d..bff424c208 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -831,10 +831,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { " WHERE DEVICE_TYPE_ID = t.ID" + " AND t.NAME = ?" + " AND t.ID = d.DEVICE_TYPE_ID" + - " AND d.TENANT_ID = ?) d1" + + " AND d.TENANT_ID = ?) d1 " + "WHERE d1.ID = e.DEVICE_ID" + " AND TENANT_ID = ?" + - " AND MOD(d1.ID, ?) = ?" + + " AND MOD(d1.ID, ?) = ? " + "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index a6db88ea5f..e26b06292f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -342,6 +342,9 @@ public class OperationManagerImpl implements OperationManager { Map enrolments = new HashMap<>(); for (Device device : devices) { enrolments.put(device.getEnrolmentInfo().getId(), device); + if(log.isDebugEnabled()){ + log.info("Adding operation for device Id : " + device.getDeviceIdentifier()); + } } if (operationDto.getControl() == org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java index 4b57829274..0c604fa560 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java @@ -55,6 +55,24 @@ public interface OperationMappingDAO { long maxDuration, int deviceTypeId) throws OperationManagementDAOException; + + /** + * This method returns first pending/repeated operation available for each active enrolment of given device-type + * in a task partitioned execution scenario + * where the operation was created after the given timestamp. + * + * @param minDuration + * @param maxDuration + * @param deviceTypeId + * @param activeServerCount + * @param serverHashIndex + * @return + */ + List getFirstPendingOperationMappingsForActiveEnrolments(long minDuration, + long maxDuration, int deviceTypeId, + int activeServerCount, int serverHashIndex) + throws OperationManagementDAOException; + /** * This method returns the timestamp of last completed Operation for each active enrolment of given device-type * where the operation was completed after the given timestamp. @@ -67,4 +85,19 @@ public interface OperationMappingDAO { Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId) throws OperationManagementDAOException; + + /** + * This method returns the timestamp of last completed Operation for each active enrolment of given device-type + * in a task partitioned execution scenario + * where the operation was completed after the given timestamp. + * + * @param timeStamp + * @param deviceTypeId + * @param activeServerCount + * @param serverHashIndex + * @return + */ + Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId, int activeServerCount, int serverHashIndex) + throws OperationManagementDAOException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java index b57d313bdf..10742b5c28 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java @@ -227,6 +227,46 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { return enrolmentOperationMappingList; } + @Override + public List getFirstPendingOperationMappingsForActiveEnrolments(long minDuration, + long maxDuration, int deviceTypeId, + int activeServerCount, int serverHashIndex) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + List enrolmentOperationMappingList; + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + //We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want + //devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states. + String sql = "SELECT ENROLMENT_ID, D.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFIER, MIN(CREATED_TIMESTAMP) " + + "AS CREATED_TIMESTAMP, E.STATUS AS ENROLMENT_STATUS, E.TENANT_ID FROM " + + "DM_ENROLMENT_OP_MAPPING OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " + + "DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " + + "OP.STATUS IN ('"+ Operation.Status.PENDING.name() + "','" + Operation.Status.REPEATED.name() + "') " + + "AND OP.CREATED_TIMESTAMP BETWEEN ? AND ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() + + "','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? AND MOD(D.ID, ?) = ? GROUP BY ENROLMENT_ID," + + " D.DEVICE_IDENTIFICATION, E.STATUS, E.TENANT_ID"; + stmt = conn.prepareStatement(sql); + stmt.setLong(1, maxDuration); + stmt.setLong(2, minDuration); + stmt.setInt(3, deviceTypeId); + stmt.setInt(4, activeServerCount); + stmt.setInt(5, serverHashIndex); + rs = stmt.executeQuery(); + enrolmentOperationMappingList = new ArrayList<>(); + while (rs.next()) { + OperationEnrolmentMapping enrolmentOperationMapping = this.getEnrolmentOpMapping(rs); + enrolmentOperationMappingList.add(enrolmentOperationMapping); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while fetching pending operation mappings for " + + "active devices of type '" + deviceTypeId + "'", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return enrolmentOperationMappingList; + } + @Override public Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -259,6 +299,40 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { return lastConnectedTimeMap; } + @Override + public Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId, int activeServerCount, int serverHashIndex) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Map lastConnectedTimeMap = null; + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + //We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want + //devices to be active at that moment. Hence filtering by 'ACTIVE' & 'UNREACHABLE' device states. + String sql = "SELECT OP.ENROLMENT_ID AS EID, MAX(OP.UPDATED_TIMESTAMP) AS LAST_CONNECTED_TIME FROM " + + "DM_ENROLMENT_OP_MAPPING OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " + + "DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " + + "OP.STATUS = '" + Operation.Status.COMPLETED.name() + "'" + + "AND OP.UPDATED_TIMESTAMP >= ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() + + "','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? AND MOD(D.ID, ?) = ? GROUP BY ENROLMENT_ID"; + stmt = conn.prepareStatement(sql); + stmt.setLong(1, timeStamp); + stmt.setInt(2, deviceTypeId); + stmt.setInt(3, activeServerCount); + stmt.setInt(4, serverHashIndex); + rs = stmt.executeQuery(); + lastConnectedTimeMap = new HashMap<>(); + while (rs.next()) { + lastConnectedTimeMap.put(rs.getInt("EID"), rs.getLong("LAST_CONNECTED_TIME")); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while fetching last connected time for " + + "active devices of type '" + deviceTypeId + "'", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return lastConnectedTimeMap; + } + private OperationEnrolmentMapping getEnrolmentOpMapping(ResultSet rs) throws SQLException { OperationEnrolmentMapping enrolmentOperationMapping = new OperationEnrolmentMapping(); enrolmentOperationMapping.setEnrolmentId(rs.getInt("ENROLMENT_ID")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java index 1bffb03eb9..9aa430ee61 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java @@ -24,6 +24,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; @@ -33,6 +34,7 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskException; +import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; import org.wso2.carbon.ntask.core.Task; import java.sql.SQLException; @@ -44,7 +46,7 @@ import java.util.Map; * This implements the Task service which monitors the device activity periodically & update the device-status if * necessary. */ -public class DeviceStatusMonitoringTask implements Task { +public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(DeviceStatusMonitoringTask.class); private String deviceType; @@ -61,7 +63,7 @@ public class DeviceStatusMonitoringTask implements Task { } @Override - public void init() { + protected void setup() { } @@ -73,10 +75,11 @@ public class DeviceStatusMonitoringTask implements Task { EnrolmentInfo enrolmentInfo; DeviceIdentifier deviceIdentifier; Device device; + super.refreshContext(); try { - operationEnrolmentMappings = this.getOperationEnrolmentMappings(); + operationEnrolmentMappings = this.getOperationEnrolmentMappings(super.getTaskContext()); if (operationEnrolmentMappings.size() > 0) { - lastActivities = this.getLastDeviceActivities(); + lastActivities = this.getLastDeviceActivities(super.getTaskContext()); } } catch (DeviceStatusTaskException e) { log.error("Error occurred while fetching OperationEnrolment mappings of deviceType '" + deviceType + "'", e); @@ -104,6 +107,9 @@ public class DeviceStatusMonitoringTask implements Task { DeviceCacheManagerImpl.getInstance().addDeviceToCache(deviceIdentifier, device, mapping.getTenantId()); } enrolmentInfoTobeUpdated.add(enrolmentInfo); + if(log.isDebugEnabled()){ + log.debug("Enrollment Information updated for device ID : " + device.getDeviceIdentifier()); + } } } @@ -163,13 +169,21 @@ public class DeviceStatusMonitoringTask implements Task { return updateStatus; } - private List getOperationEnrolmentMappings() throws DeviceStatusTaskException { + private List getOperationEnrolmentMappings(DynamicTaskContext ctx) throws DeviceStatusTaskException { List operationEnrolmentMappings; try { OperationManagementDAOFactory.openConnection(); - operationEnrolmentMappings = OperationManagementDAOFactory. - getOperationMappingDAO().getFirstPendingOperationMappingsForActiveEnrolments(this.getMinTimeWindow(), - this.getMaxTimeWindow(), this.deviceTypeId); + if(ctx != null && ctx.isPartitioningEnabled()){ + operationEnrolmentMappings = OperationManagementDAOFactory. + getOperationMappingDAO().getFirstPendingOperationMappingsForActiveEnrolments(this.getMinTimeWindow(), + this.getMaxTimeWindow(), this.deviceTypeId, + ctx.getActiveServerCount(), ctx.getServerHashIndex()); + } else { + operationEnrolmentMappings = OperationManagementDAOFactory. + getOperationMappingDAO().getFirstPendingOperationMappingsForActiveEnrolments(this.getMinTimeWindow(), + this.getMaxTimeWindow(), this.deviceTypeId); + } + } catch (SQLException e) { throw new DeviceStatusTaskException("Error occurred while getting Enrolment operation mappings for " + "determining device status of deviceType '" + deviceType + "'", e); @@ -182,13 +196,20 @@ public class DeviceStatusMonitoringTask implements Task { return operationEnrolmentMappings; } - private Map getLastDeviceActivities() throws DeviceStatusTaskException { + private Map getLastDeviceActivities(DynamicTaskContext ctx) throws DeviceStatusTaskException { Map lastActivities; try { OperationManagementDAOFactory.openConnection(); - lastActivities = OperationManagementDAOFactory. - getOperationMappingDAO().getLastConnectedTimeForActiveEnrolments(this.getMaxTimeWindow(), - this.deviceTypeId); + if(ctx != null && ctx.isPartitioningEnabled()) { + lastActivities = OperationManagementDAOFactory. + getOperationMappingDAO().getLastConnectedTimeForActiveEnrolments(this.getMaxTimeWindow(), + this.deviceTypeId, + ctx.getActiveServerCount(), ctx.getServerHashIndex()); + } else { + lastActivities = OperationManagementDAOFactory. + getOperationMappingDAO().getLastConnectedTimeForActiveEnrolments(this.getMaxTimeWindow(), + this.deviceTypeId); + } } catch (SQLException e) { throw new DeviceStatusTaskException("Error occurred while getting last activities for " + "determining device status of deviceType '" + deviceType + "'", e); @@ -200,4 +221,4 @@ public class DeviceStatusMonitoringTask implements Task { } return lastActivities; } -} \ No newline at end of file +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index b8da8e6124..2c4425ff22 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -66,6 +66,7 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { @Override public void execute() { + super.refreshContext(); deviceManagementProviderService = DeviceManagementDataHolder.getInstance() .getDeviceManagementProvider(); OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementProviderService diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index 8568164571..d124874dbe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -39,8 +39,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task { ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); if(ctxInfo!=null){ taskContext = new DynamicTaskContext(); - taskContext.setActiveServerCount(ctxInfo.getActiveServerCount()); - taskContext.setServerHashIndex(ctxInfo.getLocalServerHashIdx()); + updateContext(ctxInfo); if(ctxInfo.getActiveServerCount() > 0){ taskContext.setPartitioningEnabled(true); @@ -60,6 +59,25 @@ public abstract class DynamicPartitionedScheduleTask implements Task { setup(); } + public DynamicTaskContext refreshContext(){ + try { + ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); + if(ctxInfo != null) { + updateContext(ctxInfo); + } else { + log.info("Dynamic Task Context not present. Tasks will run on regular worker/manager mode."); + } + } catch (HeartBeatManagementException e) { + log.error("Error refreshing Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function.", e); + } + return taskContext; + } + + private void updateContext(ServerCtxInfo ctxInfo) { + taskContext.setActiveServerCount(ctxInfo.getActiveServerCount()); + taskContext.setServerHashIndex(ctxInfo.getLocalServerHashIdx()); + } + protected abstract void setup(); public static DynamicTaskContext getTaskContext() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java new file mode 100644 index 0000000000..1d1efa10ec --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java @@ -0,0 +1,24 @@ +package org.wso2.carbon.device.mgt.core; + +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import org.wso2.carbon.device.mgt.common.ServerCtxInfo; + +public class TestHeartBeatManagementService implements HeartBeatManagementService { + @Override + public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { + return null; + } + + @Override + public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { + return null; + } + + @Override + public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { + return false; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java index 44554527bc..358d2fbf3c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerTest.java @@ -17,6 +17,7 @@ */ package org.wso2.carbon.device.mgt.core.task; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.powermock.api.mockito.PowerMockito; @@ -32,6 +33,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementExcept import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.TestDeviceManagementService; +import org.wso2.carbon.device.mgt.core.TestHeartBeatManagementService; import org.wso2.carbon.device.mgt.core.TestUtils; import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; @@ -83,6 +85,9 @@ public class DeviceTaskManagerTest extends BaseDeviceManagementTest { DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); DeviceManagementService deviceManagementService = new TestDeviceManagementService( TestDataHolder.TEST_DEVICE_TYPE, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + HeartBeatManagementService heartBeatManagementService = new TestHeartBeatManagementService(); + DeviceManagementDataHolder.getInstance() + .setHeartBeatService(heartBeatManagementService); this.operationManager = PowerMockito.spy( new OperationManagerImpl(TestDataHolder.TEST_DEVICE_TYPE, deviceManagementService)); try { diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java index 9c5b91a93d..570c6c56c9 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -18,6 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon; +import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -29,10 +30,16 @@ import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Hashtable; +import java.util.Properties; public class HeartBeatBeaconUtils { @@ -83,6 +90,33 @@ public class HeartBeatBeaconUtils { return ctx; } + public static void saveUUID(String text) throws IOException { + File serverDetails = new File(HeartBeatBeaconConfig.getInstance().getServerUUIDFileLocation()); + serverDetails.createNewFile(); // if file already exists will do nothing + FileOutputStream fos = new FileOutputStream(serverDetails, false); + Properties prop = new Properties(); + prop.setProperty("server.uuid", text); + prop.store(fos, null); + fos.close(); + } + + public static String readUUID() { + InputStream input = null; + String uuid = null; + try { + input = new FileInputStream(HeartBeatBeaconConfig.getInstance().getServerUUIDFileLocation()); + Properties props = new Properties(); + props.load(input); + uuid = props.getProperty("server.uuid"); + input.close(); + } catch (FileNotFoundException e) { + log.info("File : server-credentials.properties does not exist, new UUID will be generated for server."); + } catch (IOException e) { + log.error("Error accessing server-credentials.properties to locate server.uuid.", e); + } + return uuid; + } + } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java index e2bb9e2fec..e427dffc86 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/config/HeartBeatBeaconConfig.java @@ -47,6 +47,9 @@ public class HeartBeatBeaconConfig { private static final String HEART_BEAT_NOTIFIER_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator + "heart-beat-config.xml"; + private static final String SERVER_UUID_FILE_LOCATION = + CarbonUtils.getCarbonConfigDirPath() + File.separator + "server-credentials.properties"; + private HeartBeatBeaconConfig() { } @@ -112,6 +115,10 @@ public class HeartBeatBeaconConfig { this.enabled = enabled; } + public String getServerUUIDFileLocation(){ + return SERVER_UUID_FILE_LOCATION; + } + public static void init() throws HeartBeatBeaconConfigurationException { try { File emailSenderConfig = new File(HEART_BEAT_NOTIFIER_CONFIG_PATH); diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java index 9a731ed8b1..4948f95792 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java @@ -22,7 +22,6 @@ import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOExcept import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; -import java.util.List; import java.util.Map; /** @@ -34,6 +33,8 @@ public interface HeartBeatDAO { boolean recordHeatBeat(HeartBeatEvent event) throws HeartBeatDAOException; + boolean checkUUIDValidity(String uuid) throws HeartBeatDAOException; + String retrieveExistingServerCtx(ServerContext ctx) throws HeartBeatDAOException; Map getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index bdc7d6a52f..c6aaf04872 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -30,11 +30,11 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; -import java.util.ArrayList; +import java.sql.Timestamp; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.TimeUnit; /** * This class represents implementation of HeartBeatDAO @@ -89,6 +89,30 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { } } + @Override + public boolean checkUUIDValidity(String uuid) throws HeartBeatDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + boolean result = false; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql = "SELECT ID FROM SERVER_HEART_BEAT_EVENTS WHERE UUID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, uuid); + + resultSet = stmt.executeQuery(); + if(resultSet.next()){ + result = true; + } + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred checking existense of UUID" + uuid + + " amongst heartbeat meta info ", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + } + return result; + } + @Override public String retrieveExistingServerCtx(ServerContext ctx) throws HeartBeatDAOException { PreparedStatement stmt = null; @@ -116,7 +140,8 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { } @Override - public Map getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException { + public Map getActiveServerDetails(int elapsedTimeInSeconds) + throws HeartBeatDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; Map ctxList = new HashMap<>(); @@ -124,10 +149,11 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, SERVER_PORT from " + "SERVER_HEART_BEAT_EVENTS, (SELECT @row_number:=-1) AS TEMP " + - "WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " + + "WHERE LAST_UPDATED_TIMESTAMP > ? " + "ORDER BY UUID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, elapsedTimeInSeconds); + stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds))); resultSet = stmt.executeQuery(); while (resultSet.next()) { ctxList.put(resultSet.getString("UUID"), HeartBeatBeaconDAOUtil.populateContext(resultSet)); diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index 3435c16601..5d83a0acd3 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -18,8 +18,8 @@ package io.entgra.server.bootup.heartbeat.beacon.internal; -import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; +import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.config.datasource.DataSourceConfig; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; @@ -59,7 +59,7 @@ public class HeartBeatBeaconComponent { HeartBeatBeaconDAOFactory.init(dsConfig); //Setting up executors to notify heart beat status */ - HeartBeatInternalUtils.setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); + HeartBeatExecutor.setUpNotifiers(HeartBeatBeaconUtils.getServerDetails()); } if (log.isDebugEnabled()) { diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java similarity index 80% rename from components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java rename to components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java index c407348b4f..f215288852 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatInternalUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java @@ -18,22 +18,23 @@ package io.entgra.server.bootup.heartbeat.beacon.internal; -import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException; -import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; +import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconUtils; +import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -public class HeartBeatInternalUtils { +public class HeartBeatExecutor { - private static Log log = LogFactory.getLog(HeartBeatInternalUtils.class); + private static Log log = LogFactory.getLog(HeartBeatExecutor.class); private static final int DEFAULT__NOTIFIER_INTERVAL = 5; private static final int DEFAULT_NOTIFIER_DELAY = 5; private static HeartBeatBeaconConfig CONFIG; @@ -51,12 +52,17 @@ public class HeartBeatInternalUtils { } try { - String uuid = HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().updateServerContext(ctx); - HeartBeatBeaconDataHolder.getInstance().setLocalServerUUID(uuid); + String uuid = HeartBeatBeaconUtils.readUUID(); + if(uuid == null){ + uuid = HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().updateServerContext(ctx); + HeartBeatBeaconUtils.saveUUID(uuid); + } + final String designatedUUID = uuid; + HeartBeatBeaconDataHolder.getInstance().setLocalServerUUID(designatedUUID); Runnable periodicTask = new Runnable() { public void run() { try { - recordHeartBeat(uuid); + recordHeartBeat(designatedUUID); } catch (HeartBeatManagementException e) { log.error("Error while executing record heart beat task. This will result in schedule operation malfunction.", e); } @@ -68,6 +74,8 @@ public class HeartBeatInternalUtils { TimeUnit.SECONDS); } catch (HeartBeatManagementException e) { throw new HeartBeatBeaconConfigurationException("Error occured while updating initial server context.", e); + } catch (IOException e) { + throw new HeartBeatBeaconConfigurationException("Error while persisting UUID of server.", e); } } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index 0c0b04d6c8..90644cdd05 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -19,8 +19,8 @@ package io.entgra.server.bootup.heartbeat.beacon.service; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; -import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import org.wso2.carbon.device.mgt.common.ServerCtxInfo; public interface HeartBeatManagementService { diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 362f97879e..adc245e5ff 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -23,8 +23,8 @@ import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; -import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconDataHolder; import org.wso2.carbon.device.mgt.common.ServerCtxInfo; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; @@ -34,17 +34,21 @@ import java.util.Map; public class HeartBeatManagementServiceImpl implements HeartBeatManagementService { + private final HeartBeatDAO heartBeatDAO; + + public HeartBeatManagementServiceImpl(){ + this.heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); + } + + @Override public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { - HeartBeatDAO heartBeatDAO; int hashIndex = -1; ServerContext localServerCtx = null; ServerCtxInfo serverCtxInfo = null; if(HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.openConnection(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); int timeSkew = HeartBeatBeaconConfig.getInstance().getTimeSkew(); int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; @@ -75,13 +79,10 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { - HeartBeatDAO heartBeatDAO; String uuid = null; if(HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.beginTransaction(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - uuid = heartBeatDAO.retrieveExistingServerCtx(ctx); if (uuid == null) { uuid = heartBeatDAO.recordServerCtx(ctx); @@ -107,14 +108,17 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { - HeartBeatDAO heartBeatDAO; boolean operationSuccess = false; if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.beginTransaction(); - heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); - operationSuccess = heartBeatDAO.recordHeatBeat(event); - HeartBeatBeaconDAOFactory.commitTransaction(); + if(heartBeatDAO.checkUUIDValidity(event.getServerUUID())){ + operationSuccess = heartBeatDAO.recordHeatBeat(event); + HeartBeatBeaconDAOFactory.commitTransaction(); + } else { + String msg = "Server UUID Does not exist, heartbeat not recorded."; + throw new HeartBeatManagementException(msg); + } } catch (HeartBeatDAOException e) { String msg = "Error occurred while recording heart beat."; throw new HeartBeatManagementException(msg, e); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java index e9bdbdc014..db5ab41c07 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java @@ -18,6 +18,7 @@ package org.wso2.carbon.policy.mgt.common; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java index ce71b7a213..17b5669f3a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/PolicyCacheManager.java @@ -19,6 +19,7 @@ package org.wso2.carbon.policy.mgt.core.cache; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java index 51c0dc4e81..46e01793a9 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/cache/impl/PolicyCacheManagerImpl.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.cache.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java index 1483e6ebc7..66f7528d1b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.dao.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java index 2cb4a29573..bb070f792c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -26,7 +26,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; @@ -38,7 +38,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -public class DelegationTask implements Task { +public class DelegationTask extends DynamicPartitionedScheduleTask { private static final Log log = LogFactory.getLog(DelegationTask.class); private PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration(); @@ -48,14 +48,9 @@ public class DelegationTask implements Task { } - @Override - public void init() { - - } - @Override public void execute() { - + super.refreshContext(); try { PolicyManager policyManager = new PolicyManagerImpl(); UpdatedPolicyDeviceListBean updatedPolicyDeviceList = policyManager.applyChangesMadeToPolicies(); @@ -75,7 +70,13 @@ public class DelegationTask implements Task { try { devices = new ArrayList<>(); toBeNotified = new ArrayList<>(); - devices.addAll(service.getAllDevices(deviceType, false)); + if(super.getTaskContext() != null && super.getTaskContext().isPartitioningEnabled()) { + devices.addAll(service.getAllocatedDevices(deviceType, + super.getTaskContext().getActiveServerCount(), + super.getTaskContext().getServerHashIndex())); + } else { + devices.addAll(service.getAllDevices(deviceType, false)); + } //HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); for (Device device : devices) { // if (deviceIdPolicy.containsKey(device.getId())) { @@ -84,6 +85,9 @@ public class DelegationTask implements Task { toBeNotified.add(device); } // } + if(log.isDebugEnabled()){ + log.debug("Adding policy operation to device : " + device.getDeviceIdentifier()); + } } if (!toBeNotified.isEmpty()) { PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl @@ -102,4 +106,9 @@ public class DelegationTask implements Task { log.error("Error occurred while getting the policies applied to devices.", e); } } + + @Override + protected void setup() { + + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index c555b27b97..8a1546c20f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java index 886e0a5715..a31fe3d50a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java @@ -19,6 +19,7 @@ package org.wso2.carbon.policy.mgt.core.mgt; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.mgt.bean.UpdatedPolicyDeviceListBean; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index e39f061a65..a85828e2f5 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -39,6 +39,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 160d512ee5..30c01cc1fb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; import org.wso2.carbon.device.mgt.common.policy.mgt.Profile; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index 2129f78286..574f93f6e6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -96,7 +96,7 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { } private void executeTask() { - + super.refreshContext(); MonitoringManager monitoringManager = PolicyManagementDataHolder.getInstance().getMonitoringManager(); List deviceTypes = new ArrayList<>(); List configDeviceTypes = new ArrayList<>(); @@ -142,6 +142,9 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { status.equals(EnrolmentInfo.Status.UNREACHABLE)) { notifiableDevices.add(device); } + if(log.isDebugEnabled()){ + log.debug("Adding monitoring operation to device : " + device.getDeviceIdentifier()); + } } if (log.isDebugEnabled()) { log.debug("Following '" + deviceType + "' devices selected to send the notification " + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java index d372eb63d8..310003e829 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java @@ -17,6 +17,7 @@ */ package org.wso2.carbon.policy.mgt.core; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; @@ -51,6 +52,7 @@ import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.MonitoringManagerImpl; +import org.wso2.carbon.policy.mgt.core.mock.TestHeartBeatManagementService; import org.wso2.carbon.policy.mgt.core.mock.TypeXDeviceManagementService; import org.wso2.carbon.policy.mgt.core.task.MonitoringTask; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; @@ -93,6 +95,8 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest { DeviceManagementService deviceManagementService = new TypeXDeviceManagementService(DEVICE_TYPE_A); deviceMgtService.registerDeviceType(deviceManagementService); operationManager = new OperationManagerImpl(DEVICE_TYPE_A, deviceManagementService); + HeartBeatManagementService heartBeatManagementService = new TestHeartBeatManagementService(); + DeviceManagementDataHolder.getInstance().setHeartBeatService(heartBeatManagementService); enrollDevice(DEVICE1, DEVICE_TYPE_A); createDeviceGroup(GROUP1); DeviceGroup group1 = groupMgtService.getGroup(GROUP1, false); @@ -417,4 +421,4 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest { Assert.assertNotNull(currentProfile.getProfileFeaturesList().get(0).getFeatureCode(), updatedProfile.getProfileFeaturesList().get(0).getFeatureCode()); } -} \ No newline at end of file +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java new file mode 100644 index 0000000000..8b9f711aa0 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java @@ -0,0 +1,24 @@ +package org.wso2.carbon.policy.mgt.core.mock; + +import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; +import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService; +import org.wso2.carbon.device.mgt.common.ServerCtxInfo; + +public class TestHeartBeatManagementService implements HeartBeatManagementService { + @Override + public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { + return null; + } + + @Override + public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { + return null; + } + + @Override + public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { + return false; + } +} From c6db9eeecc4c424bc5a80b869782e1bbd206a426 Mon Sep 17 00:00:00 2001 From: Ace Date: Thu, 3 Dec 2020 21:09:50 +0530 Subject: [PATCH 15/21] adding randomly assigned task functionality and other improvements --- .../ScheduledAppSubscriptionCleanupTask.java | 26 ++-- .../task/ScheduledAppSubscriptionTask.java | 127 ++++++++-------- .../task/impl/DeviceStatusMonitoringTask.java | 3 +- .../task/impl/DeviceDetailsRetrieverTask.java | 3 +- .../impl/DynamicPartitionedScheduleTask.java | 67 ++++++--- .../impl/RandomlyAssignedScheduleTask.java | 76 ++++++++++ .../core/TestHeartBeatManagementService.java | 21 +++ .../heartbeat/beacon/dao/HeartBeatDAO.java | 10 ++ .../dao/impl/GenericHeartBeatDAOImpl.java | 86 ++++++++++- .../dao/util/HeartBeatBeaconDAOUtil.java | 37 +++++ .../beacon/dto/ElectedCandidate.java | 54 +++++++ .../internal/HeartBeatBeaconComponent.java | 4 +- .../beacon/internal/HeartBeatExecutor.java | 11 +- .../service/HeartBeatManagementService.java | 9 ++ .../HeartBeatManagementServiceImpl.java | 142 ++++++++++++++++++ .../mgt/core/enforcement/DelegationTask.java | 5 +- .../policy/mgt/core/task/MonitoringTask.java | 7 +- .../mock/TestHeartBeatManagementService.java | 21 +++ .../main/resources/conf/heart-beat-config.xml | 2 +- .../resources/dbscripts/heart-beat/h2.sql | 7 + .../resources/dbscripts/heart-beat/mssql.sql | 7 +- .../resources/dbscripts/heart-beat/mysql.sql | 7 + .../resources/dbscripts/heart-beat/oracle.sql | 8 + .../dbscripts/heart-beat/postgresql.sql | 7 + 24 files changed, 635 insertions(+), 112 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java create mode 100644 components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java index 38077daf93..113b16cf3f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionCleanupTask.java @@ -23,13 +23,14 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.exception.SubscriptionManagementException; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.core.impl.SubscriptionManagerImpl; -import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.device.mgt.core.task.impl.RandomlyAssignedScheduleTask; import java.util.Map; -public class ScheduledAppSubscriptionCleanupTask implements Task { +public class ScheduledAppSubscriptionCleanupTask extends RandomlyAssignedScheduleTask { private static Log log = LogFactory.getLog(ScheduledAppSubscriptionCleanupTask.class); private SubscriptionManager subscriptionManager; + private static final String TASK_NAME = "SCHEDULE_APP_SUBSCRIPTION_CLEANUP"; @Override public void setProperties(Map properties) { @@ -37,18 +38,25 @@ public class ScheduledAppSubscriptionCleanupTask implements Task { } @Override - public void init() { + public void executeRandomlyAssignedTask() { + try { + if(super.isQualifiedToExecuteTask()) { + subscriptionManager.cleanScheduledSubscriptions(); + } + } catch (SubscriptionManagementException e) { + log.error("Error occurred while cleaning up tasks."); + } + } + + @Override + protected void setup() { if (this.subscriptionManager == null) { this.subscriptionManager = new SubscriptionManagerImpl(); } } @Override - public void execute() { - try { - subscriptionManager.cleanScheduledSubscriptions(); - } catch (SubscriptionManagementException e) { - log.error("Error occurred while cleaning up tasks."); - } + public String getTaskName() { + return TASK_NAME; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java index afbab64d6d..caff4ec460 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/task/ScheduledAppSubscriptionTask.java @@ -33,15 +33,17 @@ import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManage import org.wso2.carbon.device.application.mgt.core.impl.SubscriptionManagerImpl; import org.wso2.carbon.device.application.mgt.core.util.Constants; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.device.mgt.core.task.impl.RandomlyAssignedScheduleTask; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; -public class ScheduledAppSubscriptionTask implements Task { +public class ScheduledAppSubscriptionTask extends RandomlyAssignedScheduleTask { private static Log log = LogFactory.getLog(ScheduledAppSubscriptionTask.class); + private static final String TASK_NAME = "SCHEDULE_APP_SUBSCRIPTION"; + private SubscriptionManager subscriptionManager; private String subscribers; private String subscriptionType; @@ -65,68 +67,75 @@ public class ScheduledAppSubscriptionTask implements Task { } @Override - public void init() { - if (this.subscriptionManager == null) { - this.subscriptionManager = new SubscriptionManagerImpl(); - } - } - - @Override - public void execute() { - try { - ScheduledSubscriptionDTO subscriptionDTO = subscriptionManager.getPendingScheduledSubscription( - this.taskName); - if (subscriptionDTO == null) { - log.error("Unable to execute the task. Task entry for [" + this.taskName + "] cannot be retrieved " + - "from the database."); - return; - } - if (StringUtils.isNotEmpty(this.subscribers)) { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - carbonContext.setTenantDomain(this.tenantDomain); - carbonContext.setTenantId(this.tenantId); - carbonContext.setUsername(this.subscriber); + public void executeRandomlyAssignedTask() { + if(super.isQualifiedToExecuteTask()) { + try { + ScheduledSubscriptionDTO subscriptionDTO = subscriptionManager.getPendingScheduledSubscription( + this.taskName); + if (subscriptionDTO == null) { + log.error("Unable to execute the task. Task entry for [" + this.taskName + "] cannot be retrieved " + + "from the database."); + return; + } + if (StringUtils.isNotEmpty(this.subscribers)) { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + carbonContext.setTenantDomain(this.tenantDomain); + carbonContext.setTenantId(this.tenantId); + carbonContext.setUsername(this.subscriber); - if (this.subscriptionType.equals(SubscriptionType.DEVICE.toString())) { - List deviceIdentifiers = new Gson().fromJson(this.subscribers, - new TypeToken>() { - }.getType()); - try { - subscriptionManager.performBulkAppOperation(this.application, deviceIdentifiers, - this.subscriptionType, this.action); - subscriptionDTO.setStatus(ExecutionStatus.EXECUTED); - } catch (ApplicationManagementException e) { - log.error( - "Error occurred while " + this.action + "ing application " + this.application - + "to/from the following devices: " + this.subscribers, e); - subscriptionDTO.setStatus(ExecutionStatus.FAILED); + if (this.subscriptionType.equals(SubscriptionType.DEVICE.toString())) { + List deviceIdentifiers = new Gson().fromJson(this.subscribers, + new TypeToken>() { + }.getType()); + try { + subscriptionManager.performBulkAppOperation(this.application, deviceIdentifiers, + this.subscriptionType, this.action); + subscriptionDTO.setStatus(ExecutionStatus.EXECUTED); + } catch (ApplicationManagementException e) { + log.error( + "Error occurred while " + this.action + "ing application " + this.application + + "to/from the following devices: " + this.subscribers, e); + subscriptionDTO.setStatus(ExecutionStatus.FAILED); + } + } else { + List subscriberList = Pattern.compile(",").splitAsStream(this.subscribers).collect( + Collectors.toList()); + try { + subscriptionManager.performBulkAppOperation(this.application, subscriberList, + this.subscriptionType, this.action); + subscriptionDTO.setStatus(ExecutionStatus.EXECUTED); + } catch (ApplicationManagementException e) { + log.error( + "Error occurred while " + this.action + "ing application " + this.application + + "to/from the following " + this.subscriptionType + "s: " + this.subscribers, e); + subscriptionDTO.setStatus(ExecutionStatus.FAILED); + } } } else { - List subscriberList = Pattern.compile(",").splitAsStream(this.subscribers).collect( - Collectors.toList()); - try { - subscriptionManager.performBulkAppOperation(this.application, subscriberList, - this.subscriptionType, this.action); - subscriptionDTO.setStatus(ExecutionStatus.EXECUTED); - } catch (ApplicationManagementException e) { - log.error( - "Error occurred while " + this.action + "ing application " + this.application - + "to/from the following " + this.subscriptionType + "s: " + this.subscribers, e); - subscriptionDTO.setStatus(ExecutionStatus.FAILED); - } + log.warn( + "Subscriber list is empty. Therefore skipping scheduled task to " + this.action + "application " + + this.application); + subscriptionDTO.setStatus(ExecutionStatus.FAILED); } - } else { - log.warn( - "Subscriber list is empty. Therefore skipping scheduled task to " + this.action + "application " - + this.application); - subscriptionDTO.setStatus(ExecutionStatus.FAILED); + subscriptionManager.updateScheduledSubscriptionStatus(subscriptionDTO.getId(), subscriptionDTO.getStatus()); + } catch (SubscriptionManagementException e) { + log.error("Error occurred while executing the task: " + this.taskName, e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } - subscriptionManager.updateScheduledSubscriptionStatus(subscriptionDTO.getId(), subscriptionDTO.getStatus()); - } catch (SubscriptionManagementException e) { - log.error("Error occurred while executing the task: " + this.taskName, e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); } } + + @Override + protected void setup() { + if (this.subscriptionManager == null) { + this.subscriptionManager = new SubscriptionManagerImpl(); + } + } + + @Override + public String getTaskName() { + return TASK_NAME; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java index 9aa430ee61..ce2ffddfec 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java @@ -68,14 +68,13 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask { } @Override - public void execute() { + public void executeDynamicTask() { List operationEnrolmentMappings; List enrolmentInfoTobeUpdated = new ArrayList<>(); Map lastActivities = null; EnrolmentInfo enrolmentInfo; DeviceIdentifier deviceIdentifier; Device device; - super.refreshContext(); try { operationEnrolmentMappings = this.getOperationEnrolmentMappings(super.getTaskContext()); if (operationEnrolmentMappings.size() > 0) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java index 2c4425ff22..360325e9ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java @@ -65,8 +65,7 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask { } @Override - public void execute() { - super.refreshContext(); + public void executeDynamicTask() { deviceManagementProviderService = DeviceManagementDataHolder.getInstance() .getDeviceManagementProvider(); OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementProviderService diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java index d124874dbe..2013105b6e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java @@ -36,22 +36,12 @@ public abstract class DynamicPartitionedScheduleTask implements Task { @Override public final void init() { try { - ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); - if(ctxInfo!=null){ + boolean dynamicTaskEnabled = DeviceManagementDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled(); + if(dynamicTaskEnabled){ taskContext = new DynamicTaskContext(); - updateContext(ctxInfo); - - if(ctxInfo.getActiveServerCount() > 0){ - taskContext.setPartitioningEnabled(true); - } - - if(log.isDebugEnabled()){ - log.debug("Initiating execution of dynamic task for server : " + taskContext.getServerHashIndex() + - " where active server count is : " + taskContext.getActiveServerCount() + - " partitioning task enabled : " + taskContext.isPartitioningEnabled()); - } + taskContext.setPartitioningEnabled(true); } else { - log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function."); + log.info("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function."); } } catch (HeartBeatManagementException e) { log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function." , e); @@ -59,29 +49,56 @@ public abstract class DynamicPartitionedScheduleTask implements Task { setup(); } - public DynamicTaskContext refreshContext(){ - try { - ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); - if(ctxInfo != null) { - updateContext(ctxInfo); - } else { - log.info("Dynamic Task Context not present. Tasks will run on regular worker/manager mode."); + @Override + public final void execute() { + refreshContext(); + executeDynamicTask(); + } + + public void refreshContext(){ + if(taskContext != null && taskContext.isPartitioningEnabled()) { + try { + updateContext(); + } catch (HeartBeatManagementException e) { + log.error("Error refreshing Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function.", e); } - } catch (HeartBeatManagementException e) { - log.error("Error refreshing Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function.", e); } - return taskContext; } - private void updateContext(ServerCtxInfo ctxInfo) { + private void updateContext() throws HeartBeatManagementException { + ServerCtxInfo ctxInfo = DeviceManagementDataHolder.getInstance().getHeartBeatService().getServerCtxInfo(); + if(ctxInfo != null) { + populateContext(ctxInfo); + } else { + log.info("Dynamic Task Context not present. Tasks will run on regular worker/manager mode."); + } + } + + private void populateContext(ServerCtxInfo ctxInfo) { taskContext.setActiveServerCount(ctxInfo.getActiveServerCount()); taskContext.setServerHashIndex(ctxInfo.getLocalServerHashIdx()); + + if(log.isDebugEnabled()){ + log.debug("Initiating execution of dynamic task for server : " + taskContext.getServerHashIndex() + + " where active server count is : " + taskContext.getActiveServerCount() + + " partitioning task enabled : " + taskContext.isPartitioningEnabled()); + } } protected abstract void setup(); + protected abstract void executeDynamicTask(); + public static DynamicTaskContext getTaskContext() { return taskContext; } + public static boolean isDynamicTaskEligible(){ + if(taskContext != null && taskContext.isPartitioningEnabled()) { + return true; + } else { + return false; + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java new file mode 100644 index 0000000000..56a1c498a0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/RandomlyAssignedScheduleTask.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.task.impl; + +import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.ntask.core.Task; + + +public abstract class RandomlyAssignedScheduleTask implements Task { + + private static final Log log = LogFactory.getLog(RandomlyAssignedScheduleTask.class); + + private static String taskName = "UNSPECIFIED"; + private static boolean qualifiedToExecuteTask = false; + private static boolean dynamicTaskEnabled = false; + + @Override + public final void init() { + try { + dynamicTaskEnabled = DeviceManagementDataHolder.getInstance().getHeartBeatService().isTaskPartitioningEnabled(); + } catch (HeartBeatManagementException e) { + log.error("Error Instantiating Variables necessary for Randomly Assigned Task Scheduling." , e); + } + //This is done so that sub class extending this abstract class is forced to specify a task name. + taskName = getTaskName(); + setup(); + } + + @Override + public final void execute() { + refreshContext(); + executeRandomlyAssignedTask(); + } + + public void refreshContext(){ + if(dynamicTaskEnabled) { + try { + qualifiedToExecuteTask = DeviceManagementDataHolder.getInstance().getHeartBeatService().isQualifiedToExecuteTask(); + log.info("## NODE Qualified to execute Randomly Assigned Task : " + taskName); + DeviceManagementDataHolder.getInstance().getHeartBeatService().updateTaskExecutionAcknowledgement(taskName); + } catch (HeartBeatManagementException e) { + log.error("Error refreshing Variables necessary for Randomly Assigned Scheduled Task. " + + "Dynamic Tasks will not function.", e); + } + } + } + + protected abstract void setup(); + + protected abstract void executeRandomlyAssignedTask(); + + public static boolean isQualifiedToExecuteTask() { + return qualifiedToExecuteTask; + } + + public abstract String getTaskName(); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java index 1d1efa10ec..54dcc96504 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java @@ -7,6 +7,11 @@ import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementServi import org.wso2.carbon.device.mgt.common.ServerCtxInfo; public class TestHeartBeatManagementService implements HeartBeatManagementService { + @Override + public boolean isTaskPartitioningEnabled() throws HeartBeatManagementException { + return false; + } + @Override public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { return null; @@ -21,4 +26,20 @@ public class TestHeartBeatManagementService implements HeartBeatManagementServic public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { return false; } + + @Override + public void electCandidate(int elapsedTimeInSeconds) throws HeartBeatManagementException { + + } + + @Override + public boolean updateTaskExecutionAcknowledgement(String newTask) + throws HeartBeatManagementException { + return false; + } + + @Override + public boolean isQualifiedToExecuteTask() throws HeartBeatManagementException { + return false; + } } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java index 4948f95792..9013e443f5 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/HeartBeatDAO.java @@ -19,9 +19,11 @@ package io.entgra.server.bootup.heartbeat.beacon.dao; import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; +import io.entgra.server.bootup.heartbeat.beacon.dto.ElectedCandidate; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import java.util.List; import java.util.Map; /** @@ -39,4 +41,12 @@ public interface HeartBeatDAO { Map getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException; + boolean recordElectedCandidate(String serverUUID) throws HeartBeatDAOException; + + void purgeCandidates() throws HeartBeatDAOException; + + ElectedCandidate retrieveCandidate() throws HeartBeatDAOException; + + boolean acknowledgeTask(String uuid, List taskList) throws HeartBeatDAOException; + } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index c6aaf04872..ae8bbd247f 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -22,8 +22,11 @@ import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; import io.entgra.server.bootup.heartbeat.beacon.dao.util.HeartBeatBeaconDAOUtil; +import io.entgra.server.bootup.heartbeat.beacon.dto.ElectedCandidate; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -32,6 +35,7 @@ import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -41,6 +45,8 @@ import java.util.concurrent.TimeUnit; */ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { + private static final Log log = LogFactory.getLog(GenericHeartBeatDAOImpl.class); + @Override public String recordServerCtx(ServerContext ctx) throws HeartBeatDAOException { PreparedStatement stmt = null; @@ -69,6 +75,83 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { return uuid; } + @Override + public boolean recordElectedCandidate(String serverUUID) throws HeartBeatDAOException { + PreparedStatement stmt = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql; + sql = "INSERT INTO ELECTED_LEADER_META_INFO(UUID) VALUES (?)"; + stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, serverUUID); + + return stmt.executeUpdate() > 0; + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while persisting UUID of chosen " + + "elected dynamic task execution candidate : " + serverUUID , e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void purgeCandidates() throws HeartBeatDAOException { + Statement stmt = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + conn.setAutoCommit(false); + String sql = "TRUNCATE TABLE ELECTED_LEADER_META_INFO"; + stmt = conn.createStatement(); + stmt.execute(sql); + conn.commit(); + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while truncating ELECTED_LEADER_META_INFO table.", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public ElectedCandidate retrieveCandidate() throws HeartBeatDAOException { + Statement stmt = null; + ResultSet resultSet = null; + ElectedCandidate candidate = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql = "SELECT * from ELECTED_LEADER_META_INFO"; + stmt = conn.createStatement(); + resultSet = stmt.executeQuery(sql); + while (resultSet.next()){ + candidate = HeartBeatBeaconDAOUtil.populateCandidate(resultSet); + } + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while retrieving meta information of elected candidate", e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + } + return candidate; + } + + @Override + public boolean acknowledgeTask(String uuid, List taskList) throws HeartBeatDAOException { + PreparedStatement stmt = null; + try { + Connection conn = HeartBeatBeaconDAOFactory.getConnection(); + String sql; + sql = "UPDATE ELECTED_LEADER_META_INFO SET ACKNOWLEDGED_TASK_LIST = ? WHERE UUID = ?"; + stmt = conn.prepareStatement(sql, new String[]{"UUID"}); + stmt.setString(1, String.join(",", taskList)); + stmt.setString(2, uuid); + + return stmt.executeUpdate() > 0; + } catch (SQLException e) { + throw new HeartBeatDAOException("Error occurred while updating task list of elected server : '" + + uuid + "' and task list " + taskList, e); + } finally { + HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + } + } + @Override public boolean recordHeatBeat(HeartBeatEvent event) throws HeartBeatDAOException { PreparedStatement stmt = null; @@ -152,8 +235,7 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { "WHERE LAST_UPDATED_TIMESTAMP > ? " + "ORDER BY UUID"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, elapsedTimeInSeconds); - stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds))); + stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds))); resultSet = stmt.executeQuery(); while (resultSet.next()) { ctxList.put(resultSet.getString("UUID"), HeartBeatBeaconDAOUtil.populateContext(resultSet)); diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java index 211a10635b..c131c3d43b 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java @@ -18,6 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon.dao.util; +import io.entgra.server.bootup.heartbeat.beacon.dto.ElectedCandidate; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -27,6 +28,8 @@ import javax.sql.DataSource; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; import java.util.Hashtable; /** @@ -59,6 +62,29 @@ public final class HeartBeatBeaconDAOUtil { } } + /** + * Cleanup resources used to transaction + * + * @param stmt Statement used + * @param rs Obtained results set + */ + public static void cleanupResources(Statement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing prepared statement", e); + } + } + } + /** * Lookup datasource using name and jndi properties * @@ -88,4 +114,15 @@ public final class HeartBeatBeaconDAOUtil { ctx.setCarbonServerPort(resultSet.getInt("SERVER_PORT")); return ctx; } + + public static ElectedCandidate populateCandidate(ResultSet resultSet) throws SQLException { + ElectedCandidate candidate = new ElectedCandidate(); + candidate.setServerUUID(resultSet.getString("UUID")); + candidate.setTimeOfElection(resultSet.getTimestamp("ELECTED_TIME")); + String tasksList = resultSet.getString("ACKNOWLEDGED_TASK_LIST"); + if(tasksList != null && !tasksList.isEmpty()){ + candidate.setAcknowledgedTaskList(Arrays.asList(tasksList.split(","))); + } + return candidate; + } } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java new file mode 100644 index 0000000000..a3920d362b --- /dev/null +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. + * + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package io.entgra.server.bootup.heartbeat.beacon.dto; + +import java.sql.Timestamp; +import java.util.List; + +public class ElectedCandidate { + + private String serverUUID; + private Timestamp timeOfElection; + private List acknowledgedTaskList = null; + + public List getAcknowledgedTaskList() { + return acknowledgedTaskList; + } + + public void setAcknowledgedTaskList(List acknowledgedTaskList) { + this.acknowledgedTaskList = acknowledgedTaskList; + } + + public String getServerUUID() { + return serverUUID; + } + + public void setServerUUID(String serverUUID) { + this.serverUUID = serverUUID; + } + + public Timestamp getTimeOfElection() { + return timeOfElection; + } + + public void setTimeOfElection(Timestamp timeOfElection) { + this.timeOfElection = timeOfElection; + } + +} diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java index 5d83a0acd3..dc111aef73 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatBeaconComponent.java @@ -47,7 +47,7 @@ public class HeartBeatBeaconComponent { protected void activate(ComponentContext componentContext) { try { if (log.isDebugEnabled()) { - log.debug("Initializing email sender core bundle"); + log.debug("Initializing heart beat management bundle"); } this.registerHeartBeatServices(componentContext); @@ -88,7 +88,7 @@ public class HeartBeatBeaconComponent { /* This is to avoid mobile device management component getting initialized before the underlying datasources are registered */ if (log.isDebugEnabled()) { - log.debug("Data source service set to mobile service component"); + log.debug("Data source service set to heart beat management component"); } } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java index f215288852..1187513daa 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java @@ -57,13 +57,17 @@ public class HeartBeatExecutor { uuid = HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().updateServerContext(ctx); HeartBeatBeaconUtils.saveUUID(uuid); } + int timeOutIntervalInSeconds = CONFIG.getServerTimeOutIntervalInSeconds(); + int timeSkew = CONFIG.getTimeSkew(); + int cumilativeTimeOut = timeOutIntervalInSeconds + timeSkew; final String designatedUUID = uuid; HeartBeatBeaconDataHolder.getInstance().setLocalServerUUID(designatedUUID); Runnable periodicTask = new Runnable() { public void run() { try { recordHeartBeat(designatedUUID); - } catch (HeartBeatManagementException e) { + electDynamicTaskExecutionCandidate(cumilativeTimeOut); + } catch (Exception e) { log.error("Error while executing record heart beat task. This will result in schedule operation malfunction.", e); } } @@ -83,4 +87,9 @@ public class HeartBeatExecutor { HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().recordHeartBeat(new HeartBeatEvent(uuid)); } + static void electDynamicTaskExecutionCandidate(int cumilativeTimeOut) throws HeartBeatManagementException { + HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().electCandidate(cumilativeTimeOut); + } + + } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index 90644cdd05..7038f6ee4c 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -18,6 +18,7 @@ package io.entgra.server.bootup.heartbeat.beacon.service; +import io.entgra.server.bootup.heartbeat.beacon.dto.ElectedCandidate; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; @@ -25,10 +26,18 @@ import org.wso2.carbon.device.mgt.common.ServerCtxInfo; public interface HeartBeatManagementService { + boolean isTaskPartitioningEnabled() throws HeartBeatManagementException; + ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException; String updateServerContext(ServerContext ctx) throws HeartBeatManagementException; boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException; + void electCandidate(int elapsedTimeInSeconds) throws HeartBeatManagementException; + + boolean updateTaskExecutionAcknowledgement(String newTask) throws HeartBeatManagementException; + + boolean isQualifiedToExecuteTask() throws HeartBeatManagementException; + } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index adc245e5ff..cd70914d46 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -22,18 +22,29 @@ import io.entgra.server.bootup.heartbeat.beacon.config.HeartBeatBeaconConfig; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatBeaconDAOFactory; import io.entgra.server.bootup.heartbeat.beacon.dao.HeartBeatDAO; import io.entgra.server.bootup.heartbeat.beacon.dao.exception.HeartBeatDAOException; +import io.entgra.server.bootup.heartbeat.beacon.dto.ElectedCandidate; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; import io.entgra.server.bootup.heartbeat.beacon.internal.HeartBeatBeaconDataHolder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.ServerCtxInfo; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.TimeUnit; public class HeartBeatManagementServiceImpl implements HeartBeatManagementService { + private static final Log log = LogFactory.getLog(HeartBeatManagementServiceImpl.class); + private final HeartBeatDAO heartBeatDAO; public HeartBeatManagementServiceImpl(){ @@ -77,6 +88,19 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic return serverCtxInfo; } + @Override + public boolean isTaskPartitioningEnabled() throws HeartBeatManagementException { + boolean enabled = false; + if(HeartBeatBeaconConfig.getInstance() != null){ + enabled = HeartBeatBeaconConfig.getInstance().isEnabled(); + } else { + String msg = "Issue instantiating heart beat config."; + throw new HeartBeatManagementException(msg); + } + return enabled; + } + + @Override public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { String uuid = null; @@ -105,6 +129,124 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic return uuid; } + @Override + public boolean isQualifiedToExecuteTask() throws HeartBeatManagementException { + boolean isQualified = false; + if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); + HeartBeatBeaconDAOFactory.openConnection(); + ElectedCandidate candidate = heartBeatDAO.retrieveCandidate(); + if(candidate != null && candidate.getServerUUID().equalsIgnoreCase(localServerUUID)){ + isQualified = true; + if(log.isDebugEnabled()){ + log.debug("Node : " + localServerUUID + " Qualified to execute randomly assigned task."); + } + } + } catch (HeartBeatDAOException e) { + String msg = "Error occurred while checking if server is qualified to execute randomly designated task."; + throw new HeartBeatManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + } else { + String msg = "Heart Beat Configuration Disabled. Error occurred while checking if server is qualified to execute randomly designated task."; + throw new HeartBeatManagementException(msg); + } + return isQualified; + } + + @Override + public boolean updateTaskExecutionAcknowledgement(String newTask) throws HeartBeatManagementException { + boolean result = false; + if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + String serverUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); + HeartBeatBeaconDAOFactory.beginTransaction(); + ElectedCandidate candidate = heartBeatDAO.retrieveCandidate(); + if(candidate != null && candidate.getServerUUID().equals(serverUUID)){ + List taskList = candidate.getAcknowledgedTaskList(); + boolean taskExecuted = false; + for(String task : taskList){ + if(task.equalsIgnoreCase(newTask)){ + taskExecuted = true; + break; + } + } + if(!taskExecuted) { + taskList.add(newTask); + result = heartBeatDAO.acknowledgeTask(serverUUID, taskList); + HeartBeatBeaconDAOFactory.commitTransaction(); + } + } + } catch (HeartBeatDAOException e) { + String msg = "Error occurred while updating acknowledged task."; + throw new HeartBeatManagementException(msg, e); + } catch (TransactionManagementException e) { + HeartBeatBeaconDAOFactory.rollbackTransaction(); + String msg = "Error occurred while updating acknowledged task.. Issue in opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + } else { + String msg = "Heart Beat Configuration Disabled. Updating acknowledged task list failed."; + throw new HeartBeatManagementException(msg); + } + return result; + } + + + @Override + public void electCandidate(int elapsedTimeInSeconds) throws HeartBeatManagementException { + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { + try { + HeartBeatBeaconDAOFactory.beginTransaction(); + Map servers = heartBeatDAO.getActiveServerDetails(elapsedTimeInSeconds); + if (servers != null && !servers.isEmpty()) { + ElectedCandidate presentCandidate = heartBeatDAO.retrieveCandidate(); + if (presentCandidate != null && + presentCandidate.getTimeOfElection().before(new Timestamp(System.currentTimeMillis() + - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds)))) { + heartBeatDAO.purgeCandidates(); + electCandidate(servers); + } else { + electCandidate(servers); + } + HeartBeatBeaconDAOFactory.commitTransaction(); + } + } catch (HeartBeatDAOException e) { + String msg = "Error occurred while electing candidate for dynamic task execution."; + throw new HeartBeatManagementException(msg, e); + } catch (TransactionManagementException e) { + HeartBeatBeaconDAOFactory.rollbackTransaction(); + String msg = "Error occurred while electing candidate for dynamic task execution. Issue in opening a connection to the underlying data source"; + throw new HeartBeatManagementException(msg, e); + } finally { + HeartBeatBeaconDAOFactory.closeConnection(); + } + } else { + String msg = "Heart Beat Configuration Disabled. Error electing candidate for dynamic task execution."; + throw new HeartBeatManagementException(msg); + } + } + + private void electCandidate(Map servers) throws HeartBeatDAOException { + String electedCandidate = getRandomElement(servers.keySet()); + heartBeatDAO.recordElectedCandidate(electedCandidate); + } + + + private String getRandomElement(Set valueSet) + { + Random rand = new Random(); + List items = new ArrayList<>(valueSet); + return items.get(rand.nextInt(items.size())); + } + @Override public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java index bb070f792c..7ffd6df4e2 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -49,8 +49,7 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { } @Override - public void execute() { - super.refreshContext(); + public void executeDynamicTask() { try { PolicyManager policyManager = new PolicyManagerImpl(); UpdatedPolicyDeviceListBean updatedPolicyDeviceList = policyManager.applyChangesMadeToPolicies(); @@ -70,7 +69,7 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { try { devices = new ArrayList<>(); toBeNotified = new ArrayList<>(); - if(super.getTaskContext() != null && super.getTaskContext().isPartitioningEnabled()) { + if(super.isDynamicTaskEligible()) { devices.addAll(service.getAllocatedDevices(deviceType, super.getTaskContext().getActiveServerCount(), super.getTaskContext().getServerHashIndex())); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index 574f93f6e6..e539ad2c61 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -45,12 +45,10 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { } @Override - public void execute() { - + public void executeDynamicTask() { if (log.isDebugEnabled()) { log.debug("Monitoring task started to run."); } - this.executeforAllTenants(); } @@ -96,7 +94,6 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { } private void executeTask() { - super.refreshContext(); MonitoringManager monitoringManager = PolicyManagementDataHolder.getInstance().getMonitoringManager(); List deviceTypes = new ArrayList<>(); List configDeviceTypes = new ArrayList<>(); @@ -122,7 +119,7 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { PolicyManagementDataHolder.getInstance().getDeviceManagementService() .getPolicyMonitoringManager(deviceType); List devices; - if(super.getTaskContext()!= null && super.getTaskContext().isPartitioningEnabled()){ + if(super.isDynamicTaskEligible()){ devices = deviceManagementProviderService.getAllocatedDevices(deviceType, super.getTaskContext().getActiveServerCount(), super.getTaskContext().getServerHashIndex()); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java index 8b9f711aa0..aa8b517717 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java @@ -7,6 +7,11 @@ import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementServi import org.wso2.carbon.device.mgt.common.ServerCtxInfo; public class TestHeartBeatManagementService implements HeartBeatManagementService { + @Override + public boolean isTaskPartitioningEnabled() throws HeartBeatManagementException { + return false; + } + @Override public ServerCtxInfo getServerCtxInfo() throws HeartBeatManagementException { return null; @@ -21,4 +26,20 @@ public class TestHeartBeatManagementService implements HeartBeatManagementServic public boolean recordHeartBeat(HeartBeatEvent event) throws HeartBeatManagementException { return false; } + + @Override + public void electCandidate(int elapsedTimeInSeconds) throws HeartBeatManagementException { + + } + + @Override + public boolean updateTaskExecutionAcknowledgement(String newTask) + throws HeartBeatManagementException { + return false; + } + + @Override + public boolean isQualifiedToExecuteTask() throws HeartBeatManagementException { + return false; + } } diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml index 8b3aa6a82a..814f2f1163 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml @@ -19,7 +19,7 @@ --> - true + false jdbc/HeartBeat_DS diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql index 3f5ad9652e..2a68137287 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/h2.sql @@ -9,3 +9,10 @@ CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (ID) ); + +CREATE TABLE IF NOT EXISTS ELECTED_LEADER_META_INFO ( + UUID VARCHAR(100) NOT NULL, + ELECTED_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ACKNOWLEDGED_TASK_LIST TEXT DEFAULT NULL, + PRIMARY KEY (UUID) +); diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql index a56b9f981b..05c4713620 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mssql.sql @@ -11,4 +11,9 @@ CREATE TABLE SERVER_HEART_BEAT_EVENTS ( LAST_UPDATED_TIMESTAMP DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (ID)); - +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[ELECTED_LEADER_META_INFO]') AND TYPE IN (N'U')) +CREATE TABLE ELECTED_LEADER_META_INFO ( + UUID VARCHAR(100) NOT NULL, + ELECTED_TIME DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + ACKNOWLEDGED_TASK_LIST VARCHAR(MAX) DEFAULT NULL, + PRIMARY KEY (UUID)); diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql index 3f5ad9652e..2a68137287 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/mysql.sql @@ -9,3 +9,10 @@ CREATE TABLE IF NOT EXISTS SERVER_HEART_BEAT_EVENTS ( LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (ID) ); + +CREATE TABLE IF NOT EXISTS ELECTED_LEADER_META_INFO ( + UUID VARCHAR(100) NOT NULL, + ELECTED_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ACKNOWLEDGED_TASK_LIST TEXT DEFAULT NULL, + PRIMARY KEY (UUID) +); diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql index f9ca7a4367..7d4649187f 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/oracle.sql @@ -11,3 +11,11 @@ CREATE TABLE SERVER_HEART_BEAT_EVENTS ( CONSTRAINT PK_SERVER_HEART_BEAT_EVENTS PRIMARY KEY (ID) ) / + +CREATE TABLE ELECTED_LEADER_META_INFO ( + UUID VARCHAR(100) NOT NULL, + ELECTED_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ACKNOWLEDGED_TASK_LIST BLOB DEFAULT NULL, + CONSTRAINT PK_SERVER_HEART_BEAT_EVENTS PRIMARY KEY (UUID) +) +/ diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql index 85081a385b..9b895c6f31 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/dbscripts/heart-beat/postgresql.sql @@ -9,3 +9,10 @@ LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (ID) ); + +CREATE TABLE IF NOT EXISTS ELECTED_LEADER_META_INFO ( + UUID VARCHAR(100) NOT NULL, + ELECTED_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ACKNOWLEDGED_TASK_LIST TEXT DEFAULT NULL, + PRIMARY KEY (UUID) +); From 7734dbd6541a79b738b21ed5229bddf769e3579d Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 4 Dec 2020 04:43:00 +0530 Subject: [PATCH 16/21] Fixing issue with candidate election --- .../beacon/service/HeartBeatManagementServiceImpl.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index cd70914d46..cb9fbb8568 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -212,10 +212,8 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic presentCandidate.getTimeOfElection().before(new Timestamp(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds)))) { heartBeatDAO.purgeCandidates(); - electCandidate(servers); - } else { - electCandidate(servers); } + electCandidate(servers); HeartBeatBeaconDAOFactory.commitTransaction(); } } catch (HeartBeatDAOException e) { From cfe206b32cb7d22403187241b56bff9e01efd6b6 Mon Sep 17 00:00:00 2001 From: Ace Date: Fri, 4 Dec 2020 07:26:29 +0530 Subject: [PATCH 17/21] correcting task random candidate election logic --- .../service/HeartBeatManagementServiceImpl.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index cb9fbb8568..6fe0d3a858 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -208,12 +208,17 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic Map servers = heartBeatDAO.getActiveServerDetails(elapsedTimeInSeconds); if (servers != null && !servers.isEmpty()) { ElectedCandidate presentCandidate = heartBeatDAO.retrieveCandidate(); - if (presentCandidate != null && - presentCandidate.getTimeOfElection().before(new Timestamp(System.currentTimeMillis() - - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds)))) { - heartBeatDAO.purgeCandidates(); + if (presentCandidate != null) { + //if candidate is older than stipulated elapsed-time, purge and re-elect + if (presentCandidate.getTimeOfElection().before(new Timestamp(System.currentTimeMillis() + - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds)))) { + heartBeatDAO.purgeCandidates(); + electCandidate(servers); + } + } else { + //first time execution, elect if not present + electCandidate(servers); } - electCandidate(servers); HeartBeatBeaconDAOFactory.commitTransaction(); } } catch (HeartBeatDAOException e) { From 4df57ede617848b88b7a8a3cd56016256cc38cba Mon Sep 17 00:00:00 2001 From: Ace Date: Mon, 7 Dec 2020 13:09:14 +0530 Subject: [PATCH 18/21] incoorporating review comments --- .../impl/ActivityProviderServiceImpl.java | 6 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 43 ++-- .../impl/device/PostgreSQLDeviceDAOImpl.java | 1 + .../mgt/dao/impl/OperationMappingDAOImpl.java | 77 ++++---- .../mgt/dao/util/OperationDAOUtil.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 2 +- .../core/TestHeartBeatManagementService.java | 18 ++ .../pom.xml | 34 ++-- .../beacon/HeartBeatBeaconUtils.java | 16 +- .../dao/impl/GenericHeartBeatDAOImpl.java | 187 +++++++++--------- .../beacon/internal/HeartBeatExecutor.java | 19 +- .../service/HeartBeatManagementService.java | 1 - .../HeartBeatManagementServiceImpl.java | 46 +++-- .../src/test/resources/log4j.properties | 4 +- .../src/test/resources/testng.xml | 10 +- components/heartbeat-management/pom.xml | 32 +-- .../mgt/core/enforcement/DelegationTask.java | 7 +- .../policy/mgt/core/task/MonitoringTask.java | 2 +- .../mock/TestHeartBeatManagementService.java | 18 ++ .../pom.xml | 13 +- features/heartbeat-management/pom.xml | 34 ++-- 21 files changed, 321 insertions(+), 251 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java index ed4d4edd05..d0605d5467 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -298,11 +298,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService } activityList.setList(activities); activityList.setCount(count); -// if (activities == null || activities.size() == 0) { -// if (isIfModifiedSinceSet) { -// return Response.notModified().build(); -// } -// } + return Response.ok().entity(activityList).build(); } catch (OperationManagementException e) { String msg diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index a8fee010df..996dca889e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -797,13 +797,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @Override - public List getAllocatedDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; + public List getAllocatedDevices(String type, int tenantId, int activeServerCount, + int serverIndex) throws DeviceManagementDAOException { List devices = null; try { - conn = this.getConnection(); + Connection conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID," + " d1.DESCRIPTION," + " d1.NAME AS DEVICE_NAME," + @@ -832,24 +830,31 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { " AND MOD(d1.ID, ?) = ? " + "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, type); - stmt.setInt(2, tenantId); - stmt.setInt(3, tenantId); - stmt.setInt(4, activeServerCount); - stmt.setInt(5, serverIndex); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadActiveDevice(rs, false); - if (device != null) { - devices.add(device); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, type); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + stmt.setInt(4, activeServerCount); + stmt.setInt(5, serverIndex); + devices = new ArrayList<>(); + + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadActiveDevice(rs, false); + if (device != null) { + devices.add(device); + } + } + } catch (Exception e) { + log.error("Error encountered while populating allocated active devices for server with index : " + serverIndex + + " active-server-count " + activeServerCount + " device-type " + type + " tenant-id " + tenantId); + throw new DeviceManagementDAOException("Error occurred while populating active devices '" + type + "'", e); } } } catch (SQLException e) { + log.error("Error encountered while retrieving allocated devices for server with index : " + serverIndex + + " active-server-count " + activeServerCount + " device-type " + type + " tenant-id " + tenantId); throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); } return devices; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 2cdacdcd21..49522ba74c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -165,6 +165,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + @Override public List getAllocatedDevices(PaginationRequest request, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java index 10742b5c28..df1ebd7b64 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java @@ -18,6 +18,8 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; @@ -39,6 +41,8 @@ import java.util.Map; public class OperationMappingDAOImpl implements OperationMappingDAO { + private static final Log log = LogFactory.getLog(OperationMappingDAOImpl.class); + @Override public void addOperationMapping(Operation operation, Integer deviceId, boolean isScheduled, Device device, Integer tenantId) throws OperationManagementDAOException { @@ -228,11 +232,10 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } @Override - public List getFirstPendingOperationMappingsForActiveEnrolments(long minDuration, - long maxDuration, int deviceTypeId, - int activeServerCount, int serverHashIndex) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; + public List getFirstPendingOperationMappingsForActiveEnrolments( + long minDuration, + long maxDuration, int deviceTypeId, + int activeServerCount, int serverHashIndex) throws OperationManagementDAOException { List enrolmentOperationMappingList; try { Connection conn = OperationManagementDAOFactory.getConnection(); @@ -242,27 +245,27 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { "AS CREATED_TIMESTAMP, E.STATUS AS ENROLMENT_STATUS, E.TENANT_ID FROM " + "DM_ENROLMENT_OP_MAPPING OP INNER JOIN DM_ENROLMENT E ON OP.ENROLMENT_ID = E.ID INNER JOIN " + "DM_DEVICE D ON E.DEVICE_ID = D.ID WHERE " + - "OP.STATUS IN ('"+ Operation.Status.PENDING.name() + "','" + Operation.Status.REPEATED.name() + "') " + + "OP.STATUS IN ('" + Operation.Status.PENDING.name() + "','" + Operation.Status.REPEATED.name() + "') " + "AND OP.CREATED_TIMESTAMP BETWEEN ? AND ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() + "','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? AND MOD(D.ID, ?) = ? GROUP BY ENROLMENT_ID," + " D.DEVICE_IDENTIFICATION, E.STATUS, E.TENANT_ID"; - stmt = conn.prepareStatement(sql); - stmt.setLong(1, maxDuration); - stmt.setLong(2, minDuration); - stmt.setInt(3, deviceTypeId); - stmt.setInt(4, activeServerCount); - stmt.setInt(5, serverHashIndex); - rs = stmt.executeQuery(); - enrolmentOperationMappingList = new ArrayList<>(); - while (rs.next()) { - OperationEnrolmentMapping enrolmentOperationMapping = this.getEnrolmentOpMapping(rs); - enrolmentOperationMappingList.add(enrolmentOperationMapping); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setLong(1, maxDuration); + stmt.setLong(2, minDuration); + stmt.setInt(3, deviceTypeId); + stmt.setInt(4, activeServerCount); + stmt.setInt(5, serverHashIndex); + try (ResultSet rs = stmt.executeQuery()) { + enrolmentOperationMappingList = new ArrayList<>(); + while (rs.next()) { + OperationEnrolmentMapping enrolmentOperationMapping = this.getEnrolmentOpMapping(rs); + enrolmentOperationMappingList.add(enrolmentOperationMapping); + } + } } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while fetching pending operation mappings for " + "active devices of type '" + deviceTypeId + "'", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); } return enrolmentOperationMappingList; } @@ -300,9 +303,11 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } @Override - public Map getLastConnectedTimeForActiveEnrolments(long timeStamp, int deviceTypeId, int activeServerCount, int serverHashIndex) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; + public Map getLastConnectedTimeForActiveEnrolments(long timeStamp, + int deviceTypeId, + int activeServerCount, + int serverHashIndex) + throws OperationManagementDAOException { Map lastConnectedTimeMap = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); @@ -314,21 +319,23 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { "OP.STATUS = '" + Operation.Status.COMPLETED.name() + "'" + "AND OP.UPDATED_TIMESTAMP >= ? AND E.STATUS IN ('" + EnrolmentInfo.Status.ACTIVE.name() + "','" + EnrolmentInfo.Status.UNREACHABLE.name() + "') AND D.DEVICE_TYPE_ID = ? AND MOD(D.ID, ?) = ? GROUP BY ENROLMENT_ID"; - stmt = conn.prepareStatement(sql); - stmt.setLong(1, timeStamp); - stmt.setInt(2, deviceTypeId); - stmt.setInt(3, activeServerCount); - stmt.setInt(4, serverHashIndex); - rs = stmt.executeQuery(); - lastConnectedTimeMap = new HashMap<>(); - while (rs.next()) { - lastConnectedTimeMap.put(rs.getInt("EID"), rs.getLong("LAST_CONNECTED_TIME")); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setLong(1, timeStamp); + stmt.setInt(2, deviceTypeId); + stmt.setInt(3, activeServerCount); + stmt.setInt(4, serverHashIndex); + try (ResultSet rs = stmt.executeQuery()) { + lastConnectedTimeMap = new HashMap<>(); + while (rs.next()) { + lastConnectedTimeMap.put(rs.getInt("EID"), rs.getLong("LAST_CONNECTED_TIME")); + } + } } } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while fetching last connected time for " + - "active devices of type '" + deviceTypeId + "'", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while fetching last connected time for " + + "active devices of type '" + deviceTypeId + "'"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); } return lastConnectedTimeMap; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index 0d83c755cd..6e20e1da81 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -231,7 +231,7 @@ public class OperationDAOUtil { if (rs.getBoolean("IS_LARGE_RESPONSE")) { largeResponseIDs.add(rs.getInt("OP_RES_ID")); } else { - if(activityStatus.getResponses() == null){ + if (activityStatus.getResponses() == null) { List operationResponses = new ArrayList<>(); activityStatus.setResponses(operationResponses); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index c260f32223..dba4736e0a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -795,7 +795,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } catch (DeviceManagementDAOException e) { String msg = "Error occurred while retrieving all devices of type '" + deviceType + "' that are being managed within the scope of current tenant"; - log.error(msg); + log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the data source"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java index 54dcc96504..7a97408415 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestHeartBeatManagementService.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. + * + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.core; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml index 5cb57f3dfb..42d318379d 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml @@ -1,21 +1,21 @@ + ~ Copyright (c) 2020, Entgra (Pvt) Ltd. (http://entgra.io) All Rights Reserved. + ~ + ~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + ~ Version 2.0 (the "License"); you may not use this file except + ~ in compliance with the License. + ~ You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --> @@ -31,7 +31,7 @@ bundle Entgra - Heartbeat Beacon Entgra - Server Startup and Heartbeat Monitoring Component - http://wso2.org + http://www.entgra.io diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java index 570c6c56c9..ec0ec4c915 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/HeartBeatBeaconUtils.java @@ -55,8 +55,10 @@ public class HeartBeatBeaconUtils { DocumentBuilder docBuilder = factory.newDocumentBuilder(); return docBuilder.parse(file); } catch (Exception e) { - throw new HeartBeatBeaconConfigurationException("Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document", e); + String msg = "Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document"; + log.error(msg, e); + throw new HeartBeatBeaconConfigurationException(msg, e); } } @@ -76,7 +78,9 @@ public class HeartBeatBeaconUtils { final InitialContext context = new InitialContext(jndiProperties); return (DataSource) context.doLookup(dataSourceName); } catch (Exception e) { - throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + String msg = "Error in looking up data source: " + e.getMessage(); + log.error(msg); + throw new RuntimeException(msg, e); } } @@ -110,7 +114,11 @@ public class HeartBeatBeaconUtils { uuid = props.getProperty("server.uuid"); input.close(); } catch (FileNotFoundException e) { - log.info("File : server-credentials.properties does not exist, new UUID will be generated for server."); + String msg = "File : server-credentials.properties does not exist, new UUID will be generated for server."; + if(log.isDebugEnabled()){ + log.debug(msg, e); + } + log.info(msg); } catch (IOException e) { log.error("Error accessing server-credentials.properties to locate server.uuid.", e); } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java index ae8bbd247f..ab20bd0f2c 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/impl/GenericHeartBeatDAOImpl.java @@ -49,7 +49,6 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { @Override public String recordServerCtx(ServerContext ctx) throws HeartBeatDAOException { - PreparedStatement stmt = null; String uuid = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); @@ -57,167 +56,167 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { String sql; sql = "INSERT INTO SERVER_HEART_BEAT_EVENTS(HOST_NAME, UUID, SERVER_PORT) VALUES (?, ?, ?)"; - stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - stmt.setString(1, ctx.getHostName()); - stmt.setString(2, serverUUID); - stmt.setInt(3, ctx.getCarbonServerPort()); - - if(stmt.executeUpdate() > 0){ - uuid = serverUUID; + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, ctx.getHostName()); + stmt.setString(2, serverUUID); + stmt.setInt(3, ctx.getCarbonServerPort()); + + if (stmt.executeUpdate() > 0) { + uuid = serverUUID; + } } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while persisting server context for : '" + - "port '" + ctx.getCarbonServerPort() + "' " + - "hostname : '" + ctx.getHostName() + "' ", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + String msg = "Error occurred while persisting server context for : '" + + "port '" + ctx.getCarbonServerPort() + "' " + + "hostname : '" + ctx.getHostName() + "'"; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } return uuid; } @Override public boolean recordElectedCandidate(String serverUUID) throws HeartBeatDAOException { - PreparedStatement stmt = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql; sql = "INSERT INTO ELECTED_LEADER_META_INFO(UUID) VALUES (?)"; - stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - stmt.setString(1, serverUUID); - - return stmt.executeUpdate() > 0; + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, serverUUID); + return stmt.executeUpdate() > 0; + } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while persisting UUID of chosen " + - "elected dynamic task execution candidate : " + serverUUID , e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + String msg = "Error occurred while persisting UUID of chosen " + + "elected dynamic task execution candidate : " + serverUUID; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } } @Override public void purgeCandidates() throws HeartBeatDAOException { - Statement stmt = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); conn.setAutoCommit(false); String sql = "TRUNCATE TABLE ELECTED_LEADER_META_INFO"; - stmt = conn.createStatement(); - stmt.execute(sql); - conn.commit(); + try (Statement stmt = conn.createStatement()) { + stmt.execute(sql); + conn.commit(); + } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while truncating ELECTED_LEADER_META_INFO table.", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + String msg = "Error occurred while truncating ELECTED_LEADER_META_INFO table."; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } } @Override public ElectedCandidate retrieveCandidate() throws HeartBeatDAOException { - Statement stmt = null; - ResultSet resultSet = null; ElectedCandidate candidate = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql = "SELECT * from ELECTED_LEADER_META_INFO"; - stmt = conn.createStatement(); - resultSet = stmt.executeQuery(sql); - while (resultSet.next()){ - candidate = HeartBeatBeaconDAOUtil.populateCandidate(resultSet); + + try (Statement stmt = conn.createStatement()) { + try (ResultSet resultSet = stmt.executeQuery(sql)) { + while (resultSet.next()) { + candidate = HeartBeatBeaconDAOUtil.populateCandidate(resultSet); + } + } } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while retrieving meta information of elected candidate", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + String msg = "Error occurred while retrieving meta information of elected candidate"; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } return candidate; } @Override - public boolean acknowledgeTask(String uuid, List taskList) throws HeartBeatDAOException { - PreparedStatement stmt = null; + public boolean acknowledgeTask(String uuid, List taskList) + throws HeartBeatDAOException { try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql; sql = "UPDATE ELECTED_LEADER_META_INFO SET ACKNOWLEDGED_TASK_LIST = ? WHERE UUID = ?"; - stmt = conn.prepareStatement(sql, new String[]{"UUID"}); - stmt.setString(1, String.join(",", taskList)); - stmt.setString(2, uuid); - return stmt.executeUpdate() > 0; + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[]{"UUID"})) { + stmt.setString(1, String.join(",", taskList)); + stmt.setString(2, uuid); + return stmt.executeUpdate() > 0; + } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while updating task list of elected server : '" + - uuid + "' and task list " + taskList, e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + String msg = "Error occurred while updating task list of elected server : '" + + uuid + "' and task list " + taskList; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } } @Override public boolean recordHeatBeat(HeartBeatEvent event) throws HeartBeatDAOException { - PreparedStatement stmt = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql; sql = "UPDATE SERVER_HEART_BEAT_EVENTS SET LAST_UPDATED_TIMESTAMP = ? WHERE UUID = ?"; - stmt = conn.prepareStatement(sql, new String[]{"ID"}); - stmt.setTimestamp(1, event.getTime()); - stmt.setString(2, event.getServerUUID()); - - return stmt.executeUpdate() > 0; + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[]{"ID"})) { + stmt.setTimestamp(1, event.getTime()); + stmt.setString(2, event.getServerUUID()); + return stmt.executeUpdate() > 0; + } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while updating heartbeat event against server with UUID : '" + - event.getServerUUID() + "' and timestamp " + event.getTime(), e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, null); + String msg = "Error occurred while updating heartbeat event against server with UUID : '" + + event.getServerUUID() + "' and timestamp " + event.getTime(); + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } } @Override public boolean checkUUIDValidity(String uuid) throws HeartBeatDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; boolean result = false; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql = "SELECT ID FROM SERVER_HEART_BEAT_EVENTS WHERE UUID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, uuid); - - resultSet = stmt.executeQuery(); - if(resultSet.next()){ - result = true; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, uuid); + try (ResultSet resultSet = stmt.executeQuery()) { + if (resultSet.next()) { + result = true; + } + } } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred checking existense of UUID" + uuid + - " amongst heartbeat meta info ", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + String msg = "Error occurred checking existense of UUID" + uuid + + " amongst heartbeat meta info."; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } return result; } @Override public String retrieveExistingServerCtx(ServerContext ctx) throws HeartBeatDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; String uuid = null; try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); String sql = "SELECT UUID FROM SERVER_HEART_BEAT_EVENTS WHERE HOST_NAME = ? AND SERVER_PORT = ?"; - stmt = conn.prepareStatement(sql, new String[]{"UUID"}); - stmt.setString(1, ctx.getHostName()); - stmt.setInt(2, ctx.getCarbonServerPort()); - resultSet = stmt.executeQuery(); - if (resultSet.next()){ - uuid = resultSet.getString("UUID"); + try (PreparedStatement stmt = conn.prepareStatement(sql, new String[]{"UUID"})) { + stmt.setString(1, ctx.getHostName()); + stmt.setInt(2, ctx.getCarbonServerPort()); + try (ResultSet resultSet = stmt.executeQuery()) { + if (resultSet.next()) { + uuid = resultSet.getString("UUID"); + } + } } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while retrieving meta information for heart beat event from " + - "port '" + ctx.getCarbonServerPort() + "' " + - "hostname : '" + ctx.getHostName() + "' ", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + String msg = "Error occurred while retrieving meta information for heart beat event from " + + "port '" + ctx.getCarbonServerPort() + "' " + + "hostname : '" + ctx.getHostName() + "'"; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } return uuid; } @@ -225,8 +224,6 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { @Override public Map getActiveServerDetails(int elapsedTimeInSeconds) throws HeartBeatDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; Map ctxList = new HashMap<>(); try { Connection conn = HeartBeatBeaconDAOFactory.getConnection(); @@ -234,17 +231,19 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO { "SERVER_HEART_BEAT_EVENTS, (SELECT @row_number:=-1) AS TEMP " + "WHERE LAST_UPDATED_TIMESTAMP > ? " + "ORDER BY UUID"; - stmt = conn.prepareStatement(sql); - stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds))); - resultSet = stmt.executeQuery(); - while (resultSet.next()) { - ctxList.put(resultSet.getString("UUID"), HeartBeatBeaconDAOUtil.populateContext(resultSet)); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(elapsedTimeInSeconds))); + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + ctxList.put(resultSet.getString("UUID"), HeartBeatBeaconDAOUtil.populateContext(resultSet)); + } + } } } catch (SQLException e) { - throw new HeartBeatDAOException("Error occurred while retrieving acting server count with " + - "heartbeat updates within " + elapsedTimeInSeconds + " seconds.", e); - } finally { - HeartBeatBeaconDAOUtil.cleanupResources(stmt, resultSet); + String msg = "Error occurred while retrieving acting server count with " + + "heartbeat updates within " + elapsedTimeInSeconds + " seconds."; + log.error(msg, e); + throw new HeartBeatDAOException(msg, e); } return ctxList; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java index 1187513daa..1f0d50539b 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/internal/HeartBeatExecutor.java @@ -47,13 +47,15 @@ public class HeartBeatExecutor { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - if(CONFIG == null){ - throw new HeartBeatBeaconConfigurationException("Error while initiating schedule taks for recording heartbeats."); + if (CONFIG == null) { + String msg = "Error while initiating schedule taks for recording heartbeats."; + log.error(msg); + throw new HeartBeatBeaconConfigurationException(msg); } try { String uuid = HeartBeatBeaconUtils.readUUID(); - if(uuid == null){ + if (uuid == null) { uuid = HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().updateServerContext(ctx); HeartBeatBeaconUtils.saveUUID(uuid); } @@ -77,9 +79,13 @@ public class HeartBeatExecutor { CONFIG.getNotifierFrequency() != 0 ? CONFIG.getNotifierFrequency() : DEFAULT__NOTIFIER_INTERVAL, TimeUnit.SECONDS); } catch (HeartBeatManagementException e) { - throw new HeartBeatBeaconConfigurationException("Error occured while updating initial server context.", e); + String msg = "Error occured while updating initial server context."; + log.error(msg); + throw new HeartBeatBeaconConfigurationException(msg, e); } catch (IOException e) { - throw new HeartBeatBeaconConfigurationException("Error while persisting UUID of server.", e); + String msg = "Error while persisting UUID of server."; + log.error(msg); + throw new HeartBeatBeaconConfigurationException(msg, e); } } @@ -87,7 +93,8 @@ public class HeartBeatExecutor { HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().recordHeartBeat(new HeartBeatEvent(uuid)); } - static void electDynamicTaskExecutionCandidate(int cumilativeTimeOut) throws HeartBeatManagementException { + static void electDynamicTaskExecutionCandidate(int cumilativeTimeOut) + throws HeartBeatManagementException { HeartBeatBeaconDataHolder.getInstance().getHeartBeatManagementService().electCandidate(cumilativeTimeOut); } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java index 7038f6ee4c..2edd5babdb 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementService.java @@ -18,7 +18,6 @@ package io.entgra.server.bootup.heartbeat.beacon.service; -import io.entgra.server.bootup.heartbeat.beacon.dto.ElectedCandidate; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; import io.entgra.server.bootup.heartbeat.beacon.dto.ServerContext; import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 6fe0d3a858..5c742a984e 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -47,7 +47,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic private final HeartBeatDAO heartBeatDAO; - public HeartBeatManagementServiceImpl(){ + public HeartBeatManagementServiceImpl() { this.heartBeatDAO = HeartBeatBeaconDAOFactory.getHeartBeatDAO(); } @@ -57,7 +57,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic int hashIndex = -1; ServerContext localServerCtx = null; ServerCtxInfo serverCtxInfo = null; - if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.openConnection(); int timeOutIntervalInSeconds = HeartBeatBeaconConfig.getInstance().getServerTimeOutIntervalInSeconds(); @@ -74,9 +74,11 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (HeartBeatDAOException e) { String msg = "Error occurred while retrieving active server count."; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); @@ -91,10 +93,11 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public boolean isTaskPartitioningEnabled() throws HeartBeatManagementException { boolean enabled = false; - if(HeartBeatBeaconConfig.getInstance() != null){ + if (HeartBeatBeaconConfig.getInstance() != null) { enabled = HeartBeatBeaconConfig.getInstance().isEnabled(); } else { String msg = "Issue instantiating heart beat config."; + log.error(msg); throw new HeartBeatManagementException(msg); } return enabled; @@ -104,7 +107,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public String updateServerContext(ServerContext ctx) throws HeartBeatManagementException { String uuid = null; - if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.beginTransaction(); uuid = heartBeatDAO.retrieveExistingServerCtx(ctx); @@ -114,10 +117,12 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } catch (HeartBeatDAOException e) { String msg = "Error Occured while retrieving server context."; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (TransactionManagementException e) { HeartBeatBeaconDAOFactory.rollbackTransaction(); String msg = "Error occurred while updating server context. Issue in opening a connection to the underlying data source"; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); @@ -132,22 +137,24 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic @Override public boolean isQualifiedToExecuteTask() throws HeartBeatManagementException { boolean isQualified = false; - if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { String localServerUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); HeartBeatBeaconDAOFactory.openConnection(); ElectedCandidate candidate = heartBeatDAO.retrieveCandidate(); - if(candidate != null && candidate.getServerUUID().equalsIgnoreCase(localServerUUID)){ + if (candidate != null && candidate.getServerUUID().equalsIgnoreCase(localServerUUID)) { isQualified = true; - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Node : " + localServerUUID + " Qualified to execute randomly assigned task."); } } } catch (HeartBeatDAOException e) { String msg = "Error occurred while checking if server is qualified to execute randomly designated task."; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); @@ -160,23 +167,24 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } @Override - public boolean updateTaskExecutionAcknowledgement(String newTask) throws HeartBeatManagementException { + public boolean updateTaskExecutionAcknowledgement(String newTask) + throws HeartBeatManagementException { boolean result = false; - if(HeartBeatBeaconConfig.getInstance().isEnabled()) { + if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { String serverUUID = HeartBeatBeaconDataHolder.getInstance().getLocalServerUUID(); HeartBeatBeaconDAOFactory.beginTransaction(); ElectedCandidate candidate = heartBeatDAO.retrieveCandidate(); - if(candidate != null && candidate.getServerUUID().equals(serverUUID)){ + if (candidate != null && candidate.getServerUUID().equals(serverUUID)) { List taskList = candidate.getAcknowledgedTaskList(); boolean taskExecuted = false; - for(String task : taskList){ - if(task.equalsIgnoreCase(newTask)){ + for (String task : taskList) { + if (task.equalsIgnoreCase(newTask)) { taskExecuted = true; break; } } - if(!taskExecuted) { + if (!taskExecuted) { taskList.add(newTask); result = heartBeatDAO.acknowledgeTask(serverUUID, taskList); HeartBeatBeaconDAOFactory.commitTransaction(); @@ -184,10 +192,12 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } catch (HeartBeatDAOException e) { String msg = "Error occurred while updating acknowledged task."; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (TransactionManagementException e) { HeartBeatBeaconDAOFactory.rollbackTransaction(); String msg = "Error occurred while updating acknowledged task.. Issue in opening a connection to the underlying data source"; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); @@ -223,10 +233,12 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } catch (HeartBeatDAOException e) { String msg = "Error occurred while electing candidate for dynamic task execution."; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } catch (TransactionManagementException e) { HeartBeatBeaconDAOFactory.rollbackTransaction(); String msg = "Error occurred while electing candidate for dynamic task execution. Issue in opening a connection to the underlying data source"; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); @@ -243,8 +255,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } - private String getRandomElement(Set valueSet) - { + private String getRandomElement(Set valueSet) { Random rand = new Random(); List items = new ArrayList<>(valueSet); return items.get(rand.nextInt(items.size())); @@ -257,11 +268,12 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic if (HeartBeatBeaconConfig.getInstance().isEnabled()) { try { HeartBeatBeaconDAOFactory.beginTransaction(); - if(heartBeatDAO.checkUUIDValidity(event.getServerUUID())){ + if (heartBeatDAO.checkUUIDValidity(event.getServerUUID())) { operationSuccess = heartBeatDAO.recordHeatBeat(event); HeartBeatBeaconDAOFactory.commitTransaction(); } else { String msg = "Server UUID Does not exist, heartbeat not recorded."; + log.error(msg); throw new HeartBeatManagementException(msg); } } catch (HeartBeatDAOException e) { @@ -271,12 +283,14 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic HeartBeatBeaconDAOFactory.rollbackTransaction(); String msg = "Error occurred performing heart beat record transaction. " + "Transaction rolled back."; + log.error(msg, e); throw new HeartBeatManagementException(msg, e); } finally { HeartBeatBeaconDAOFactory.closeConnection(); } } else { String msg = "Heart Beat Configuration Disabled. Recording Heart Beat Failed."; + log.error(msg); throw new HeartBeatManagementException(msg); } return operationSuccess; diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties index dc3d465fc0..18dca3223c 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/log4j.properties @@ -1,5 +1,5 @@ # -# Copyright 2009 WSO2, Inc. (http://wso2.com) +# Copyright 2020 Entgra Pvt. Ltd.. (http://entgra.io) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ # # -# This is the log4j configuration file used by WSO2 Carbon +# This is the log4j configuration file used by Entgra Pvt. Ltd. # # IMPORTANT : Please do not remove or change the names of any # of the Appenders defined here. The layout pattern & log file diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml index 2da3b26042..43b87672a2 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/test/resources/testng.xml @@ -1,18 +1,18 @@ diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index dc60f12880..d00863f18e 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -1,21 +1,21 @@ + ~ Copyright (c) 2020, Entgra (Pvt) Ltd. (http://entgra.io) All Rights Reserved. + ~ + ~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + ~ Version 2.0 (the "License"); you may not use this file except + ~ in compliance with the License. + ~ You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --> diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java index a85deab42c..b24e84f029 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -70,7 +70,7 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { try { devices = new ArrayList<>(); toBeNotified = new ArrayList<>(); - if(super.isDynamicTaskEligible()) { + if (super.isDynamicTaskEligible()) { devices.addAll(service.getAllocatedDevices(deviceType, super.getTaskContext().getActiveServerCount(), super.getTaskContext().getServerHashIndex())); @@ -79,11 +79,10 @@ public class DelegationTask extends DynamicPartitionedScheduleTask { } for (Device device : devices) { if (device != null && device.getEnrolmentInfo() != null - && device.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { + && device.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { toBeNotified.add(device); } - // } - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Adding policy operation to device : " + device.getDeviceIdentifier()); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index e539ad2c61..d51f283a8e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -139,7 +139,7 @@ public class MonitoringTask extends DynamicPartitionedScheduleTask { status.equals(EnrolmentInfo.Status.UNREACHABLE)) { notifiableDevices.add(device); } - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Adding monitoring operation to device : " + device.getDeviceIdentifier()); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java index aa8b517717..38d7dd0437 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TestHeartBeatManagementService.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2020, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved. + * + * Entgra Pvt Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.policy.mgt.core.mock; import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent; diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml index 7f6d79f526..fd079f6619 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/pom.xml @@ -1,19 +1,18 @@ diff --git a/features/heartbeat-management/pom.xml b/features/heartbeat-management/pom.xml index 049bf35a50..a56f5f9cd1 100644 --- a/features/heartbeat-management/pom.xml +++ b/features/heartbeat-management/pom.xml @@ -1,21 +1,21 @@ + ~ Copyright (c) 2020, Entgra (Pvt) Ltd. (http://entgra.io) All Rights Reserved. + ~ + ~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License, + ~ Version 2.0 (the "License"); you may not use this file except + ~ in compliance with the License. + ~ You may obtain a copy of the License at + ~ + ~ http://www.apache.org/licenses/LICENSE-2.0 + ~ + ~ Unless required by applicable law or agreed to in writing, + ~ software distributed under the License is distributed on an + ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + ~ KIND, either express or implied. See the License for the + ~ specific language governing permissions and limitations + ~ under the License. + --> @@ -32,7 +32,7 @@ 4.1.11-SNAPSHOT pom Entgra - Heart Beat Feature - http://wso2.org + http://entgra.io io.entgra.server.heart.beat.feature From 5531bc014098b961d460717058525fd9323db637 Mon Sep 17 00:00:00 2001 From: Ace Date: Mon, 7 Dec 2020 13:19:46 +0530 Subject: [PATCH 19/21] Addressing review comments --- .../mgt/dao/impl/OperationMappingDAOImpl.java | 6 +++-- .../dao/util/HeartBeatBeaconDAOUtil.java | 23 ------------------- .../HeartBeatManagementServiceImpl.java | 5 ++++ 3 files changed, 9 insertions(+), 25 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java index df1ebd7b64..5cc7b773dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java @@ -264,8 +264,10 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } } } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while fetching pending operation mappings for " + - "active devices of type '" + deviceTypeId + "'", e); + String msg = "Error occurred while fetching pending operation mappings for " + + "active devices of type '" + deviceTypeId + "'"; + log.error(msg, e); + throw new OperationManagementDAOException(msg, e); } return enrolmentOperationMappingList; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java index c131c3d43b..67b91df517 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dao/util/HeartBeatBeaconDAOUtil.java @@ -62,29 +62,6 @@ public final class HeartBeatBeaconDAOUtil { } } - /** - * Cleanup resources used to transaction - * - * @param stmt Statement used - * @param rs Obtained results set - */ - public static void cleanupResources(Statement stmt, ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing result set", e); - } - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing prepared statement", e); - } - } - } - /** * Lookup datasource using name and jndi properties * diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 5c742a984e..4281a6bc58 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -85,6 +85,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } else { String msg = "Heart Beat Configuration Disabled. Server Context Information Not available."; + log.error(msg); throw new HeartBeatManagementException(msg); } return serverCtxInfo; @@ -129,6 +130,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } else { String msg = "Heart Beat Configuration Disabled. Updating Server Context Failed."; + log.error(msg); throw new HeartBeatManagementException(msg); } return uuid; @@ -161,6 +163,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } else { String msg = "Heart Beat Configuration Disabled. Error occurred while checking if server is qualified to execute randomly designated task."; + log.error(msg); throw new HeartBeatManagementException(msg); } return isQualified; @@ -204,6 +207,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } else { String msg = "Heart Beat Configuration Disabled. Updating acknowledged task list failed."; + log.error(msg); throw new HeartBeatManagementException(msg); } return result; @@ -245,6 +249,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } else { String msg = "Heart Beat Configuration Disabled. Error electing candidate for dynamic task execution."; + log.error(msg); throw new HeartBeatManagementException(msg); } } From ceab2566acb5f61e631dca08993734cbb86f3806 Mon Sep 17 00:00:00 2001 From: Ace Date: Mon, 7 Dec 2020 13:27:57 +0530 Subject: [PATCH 20/21] Addressing review comments --- .../core/dao/impl/AbstractDeviceDAOImpl.java | 18 +++++++++++------- .../HeartBeatManagementServiceImpl.java | 1 + components/heartbeat-management/pom.xml | 2 +- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 996dca889e..29ce88f342 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -788,7 +788,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + String msg = "Error occurred while listing devices for type '" + type + "'"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -846,15 +848,17 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } } catch (Exception e) { - log.error("Error encountered while populating allocated active devices for server with index : " + serverIndex + - " active-server-count " + activeServerCount + " device-type " + type + " tenant-id " + tenantId); - throw new DeviceManagementDAOException("Error occurred while populating active devices '" + type + "'", e); + String msg = "Error encountered while populating allocated active devices for server with index : " + serverIndex + + " active-server-count " + activeServerCount + " device-type " + type + " tenant-id " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } } } catch (SQLException e) { - log.error("Error encountered while retrieving allocated devices for server with index : " + serverIndex + - " active-server-count " + activeServerCount + " device-type " + type + " tenant-id " + tenantId); - throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e); + String msg = "Error encountered while retrieving allocated devices for server with index : " + serverIndex + + " active-server-count " + activeServerCount + " device-type " + type + " tenant-id " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } return devices; } diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java index 4281a6bc58..1c312e5368 100644 --- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java +++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/service/HeartBeatManagementServiceImpl.java @@ -283,6 +283,7 @@ public class HeartBeatManagementServiceImpl implements HeartBeatManagementServic } } catch (HeartBeatDAOException e) { String msg = "Error occurred while recording heart beat."; + log.error(msg); throw new HeartBeatManagementException(msg, e); } catch (TransactionManagementException e) { HeartBeatBeaconDAOFactory.rollbackTransaction(); diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml index d00863f18e..1143f7e4d7 100644 --- a/components/heartbeat-management/pom.xml +++ b/components/heartbeat-management/pom.xml @@ -30,7 +30,7 @@ heartbeat-management pom Entgra - Task Allocation Framework - http://wso2.org + http://entgra.io io.entgra.server.bootup.heartbeat.beacon From 76c933254108f2e6637c9b5706e6033ad262887d Mon Sep 17 00:00:00 2001 From: Ace Date: Mon, 7 Dec 2020 14:00:26 +0530 Subject: [PATCH 21/21] Added disclaimer to heart-beat-config --- .../main/resources/conf/heart-beat-config.xml | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml index 814f2f1163..59b17614de 100644 --- a/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml +++ b/features/heartbeat-management/io.entgra.server.heart.beat.feature/src/main/resources/conf/heart-beat-config.xml @@ -19,7 +19,28 @@ --> + false + jdbc/HeartBeat_DS