diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EmailMessageProperties.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EmailMessageProperties.java deleted file mode 100644 index 7bac7098cc..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EmailMessageProperties.java +++ /dev/null @@ -1,137 +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 org.wso2.carbon.device.mgt.common; - -import java.util.Arrays; - -public class EmailMessageProperties { - - private String messageBody; - private String[] mailTo; - private String[] ccList; - private String[] bccList; - private String subject; - private String firstName; - private String enrolmentUrl; - private String title; - private String password; - private String userName; - private String domainName; - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getDomainName() { - return domainName; - } - - public void setDomainName(String domainName) { - this.domainName = domainName; - } - - public String getMessageBody() { - return messageBody; - } - - public void setMessageBody(String messageBody) { - this.messageBody = messageBody; - } - - public String[] getMailTo() { - return mailTo; - } - - public void setMailTo(String[] mailTo) { - this.mailTo = mailTo; - } - - public String[] getCcList() { - return ccList; - } - - public void setCcList(String[] ccList) { - this.ccList = ccList; - } - - public String[] getBccList() { - return bccList; - } - - public void setBccList(String[] bccList) { - this.bccList = bccList; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getEnrolmentUrl() { - return enrolmentUrl; - } - - public void setEnrolmentUrl(String enrolmentUrl) { - this.enrolmentUrl = enrolmentUrl; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public String toString() { - return "EmailMessageProperties{" + - "messageBody='" + messageBody + '\'' + - ", mailTo=" + Arrays.toString(mailTo) + - ", ccList=" + Arrays.toString(ccList) + - ", bccList=" + Arrays.toString(bccList) + - ", subject='" + subject + '\'' + - ", firstName='" + firstName + '\'' + - ", enrolmentUrl='" + enrolmentUrl + '\'' + - ", title='" + title + '\'' + - '}'; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java index 6a53d75c08..cdcba75a72 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java @@ -23,6 +23,8 @@ import java.util.Properties; public class Application implements Serializable { + private static final long serialVersionUID = 1998101711L; + private int id; private String platform; private String category; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java new file mode 100644 index 0000000000..454608b915 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java @@ -0,0 +1,233 @@ +/* + * 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 org.wso2.carbon.device.mgt.common.device.details; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +public class DeviceInfo implements Serializable{ + + private static final long serialVersionUID = 1998101733L; + + private int deviceId; + private String deviceType; + private DeviceIdentifier deviceIdentifier; + + private String IMEI; + private String IMSI; + private String deviceModel; + private String vendor; + private String osVersion; + private Double batteryLevel; + private Double internalTotalMemory; + private Double internalAvailableMemory; + private Double externalTotalMemory; + private Double externalAvailableMemory; + private String operator; + private String connectionType; + private Double mobileSignalStrength; + private String ssid; + private Double cpuUsage; + private Double totalRAMMemory; + private Double availableRAMMemory; + private boolean pluggedIn; + + private Map deviceDetailsMap = new HashMap<>(); + + public int getDeviceId() { + return deviceId; + } + + public void setDeviceId(int deviceId) { + this.deviceId = deviceId; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + + public DeviceIdentifier getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getIMEI() { + return IMEI; + } + + public void setIMEI(String IMEI) { + this.IMEI = IMEI; + } + + public String getIMSI() { + return IMSI; + } + + public void setIMSI(String IMSI) { + this.IMSI = IMSI; + } + + public String getDeviceModel() { + return deviceModel; + } + + public void setDeviceModel(String deviceModel) { + this.deviceModel = deviceModel; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public String getOsVersion() { + return osVersion; + } + + public void setOsVersion(String osVersion) { + this.osVersion = osVersion; + } + + public Double getBatteryLevel() { + return batteryLevel; + } + + public void setBatteryLevel(Double batteryLevel) { + this.batteryLevel = batteryLevel; + } + + public Double getInternalTotalMemory() { + return internalTotalMemory; + } + + public void setInternalTotalMemory(Double internalTotalMemory) { + this.internalTotalMemory = internalTotalMemory; + } + + public Double getInternalAvailableMemory() { + return internalAvailableMemory; + } + + public void setInternalAvailableMemory(Double internalAvailableMemory) { + this.internalAvailableMemory = internalAvailableMemory; + } + + public Double getExternalTotalMemory() { + return externalTotalMemory; + } + + public void setExternalTotalMemory(Double externalTotalMemory) { + this.externalTotalMemory = externalTotalMemory; + } + + public Double getExternalAvailableMemory() { + return externalAvailableMemory; + } + + public void setExternalAvailableMemory(Double externalAvailableMemory) { + this.externalAvailableMemory = externalAvailableMemory; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } + + public String getConnectionType() { + return connectionType; + } + + public void setConnectionType(String connectionType) { + this.connectionType = connectionType; + } + + public Double getMobileSignalStrength() { + return mobileSignalStrength; + } + + public void setMobileSignalStrength(Double mobileSignalStrength) { + this.mobileSignalStrength = mobileSignalStrength; + } + + public String getSsid() { + return ssid; + } + + public void setSsid(String ssid) { + this.ssid = ssid; + } + + public Double getCpuUsage() { + return cpuUsage; + } + + public void setCpuUsage(Double cpuUsage) { + this.cpuUsage = cpuUsage; + } + + public Double getTotalRAMMemory() { + return totalRAMMemory; + } + + public void setTotalRAMMemory(Double totalRAMMemory) { + this.totalRAMMemory = totalRAMMemory; + } + + public Double getAvailableRAMMemory() { + return availableRAMMemory; + } + + public void setAvailableRAMMemory(Double availableRAMMemory) { + this.availableRAMMemory = availableRAMMemory; + } + + public boolean isPluggedIn() { + return pluggedIn; + } + + public void setPluggedIn(boolean pluggedIn) { + this.pluggedIn = pluggedIn; + } + + public void setDeviceDetailsMap(Map deviceDetailsMap) { + this.deviceDetailsMap = deviceDetailsMap; + } + + public Map getDeviceDetailsMap() { + return deviceDetailsMap; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java new file mode 100644 index 0000000000..0b05406522 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java @@ -0,0 +1,123 @@ +/* + * 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 org.wso2.carbon.device.mgt.common.device.details; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.io.Serializable; + +public class DeviceLocation implements Serializable { + + private static final long serialVersionUID = 1998101722L; + + private int deviceId; + private DeviceIdentifier deviceIdentifier; + private Double latitude; + private Double longitude; + + private String street1; + private String street2; + + private String city; + private String state; + private String zip; + private String country; + + public int getDeviceId() { + return deviceId; + } + + public void setDeviceId(int deviceId) { + this.deviceId = deviceId; + } + + public DeviceIdentifier getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public String getStreet1() { + return street1; + } + + public void setStreet1(String street1) { + this.street1 = street1; + } + + public String getStreet2() { + return street2; + } + + public void setStreet2(String street2) { + this.street2 = street2; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java index 0273a42213..5a4b45dd1e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/Condition.java @@ -23,7 +23,7 @@ public class Condition { private String key; private String value; - public String mark; + public String operator; private State state; @@ -38,5 +38,29 @@ public class Condition { public void setState(State state){ this.state = state; } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java index b8e5e7b3d1..9f4a8bb7da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/search/SearchContext.java @@ -19,6 +19,36 @@ package org.wso2.carbon.device.mgt.common.search; +import java.util.List; + public class SearchContext { + + private List conditions; + private int start; + private int end; + + public List getConditions() { + return conditions; + } + + public void setConditions(List conditions) { + this.conditions = conditions; + } + + public int getStart() { + return start; + } + + public void setStart(int start) { + this.start = start; + } + + public int getEnd() { + return end; + } + + public void setEnd(int end) { + this.end = end; + } } 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 8d77d48888..2e9d83547f 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 @@ -83,9 +83,10 @@ org.wso2.carbon.ntask.core.*, org.wso2.carbon.ntask.common, org.wso2.carbon.ndatasource.core, - org.apache.axis2.transport.mail, org.apache.catalina, - org.apache.catalina.core + org.apache.catalina.core, + org.apache.commons.collections, + org.wso2.carbon.email.sender.* !org.wso2.carbon.device.mgt.core.internal, @@ -225,11 +226,23 @@ org.wso2.carbon.ntask.core - - - - - + + + commons-collections.wso2 + commons-collections + + + org.wso2.carbon.devicemgt + org.wso2.carbon.email.sender.core + + + + mysql + mysql-connector-java + 5.1.34 + test + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index 1b0cf9ee10..ad4a8e64ee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -58,4 +58,21 @@ public final class DeviceManagementConstants { public static final String MONITOR_OPERATION_CODE = "MONITOR"; public static final String POLICY_OPERATION_CODE = PolicyOperation.POLICY_OPERATION_CODE; } + + public static final class EmailAttributes { + private EmailAttributes() { + throw new AssertionError(); + } + + public static final String ENCODED_SCHEME = "UTF-8"; + public static final String FIRST_NAME = "first-name"; + public static final String USERNAME = "username"; + public static final String PASSWORD = "password"; + public static final String DOMAIN = "domain-name"; + + public static final String SERVER_BASE_URL_HTTPS = "base-url-https"; + public static final String SERVER_BASE_URL_HTTP = "base-url-http"; + public static final String DOWNLOAD_URL = "download-url"; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java index 0c735ba1ff..51b6b63f2e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceConfigurationManager.java @@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.core.config; import org.w3c.dom.Document; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.config.email.NotificationMessagesConfig; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.utils.CarbonUtils; import org.xml.sax.SAXException; @@ -35,21 +34,17 @@ import javax.xml.validation.SchemaFactory; import java.io.File; /** - * Class responsible for the cdm manager configuration initialization. + * Class responsible for the cdm configuration initialization. */ public class DeviceConfigurationManager { private DeviceManagementConfig currentDeviceConfig; - private NotificationMessagesConfig notificationMessagesConfig; private static DeviceConfigurationManager deviceConfigManager; private static final String DEVICE_MGT_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator + DeviceManagementConstants.DataSourceProperties.DEVICE_CONFIG_XML_NAME; private static final String DEVICE_MGT_CONFIG_SCHEMA_PATH = "resources/config/schema/device-mgt-config-schema.xsd"; - private static final String NOTIFICATION_MSG_CONFIG_PATH = - CarbonUtils.getCarbonConfigDirPath() + File.separator + - DeviceManagementConstants.NotificationProperties.NOTIFICATION_CONFIG_FILE; public static DeviceConfigurationManager getInstance() { if (deviceConfigManager == null) { @@ -63,7 +58,6 @@ public class DeviceConfigurationManager { } public synchronized void initConfig() throws DeviceManagementException { - try { File deviceMgtConfig = new File(DeviceConfigurationManager.DEVICE_MGT_CONFIG_PATH); Document doc = DeviceManagerUtil.convertToDocument(deviceMgtConfig); @@ -76,18 +70,6 @@ public class DeviceConfigurationManager { } catch (JAXBException e) { throw new DeviceManagementException("Error occurred while initializing Data Source config", e); } - - try { - File notificationConfig = new File(DeviceConfigurationManager.NOTIFICATION_MSG_CONFIG_PATH); - Document doc = DeviceManagerUtil.convertToDocument(notificationConfig); - - /* Un-marshaling Notifications Management configuration */ - JAXBContext notificationContext = JAXBContext.newInstance(NotificationMessagesConfig.class); - Unmarshaller unmarshaller = notificationContext.createUnmarshaller(); - this.notificationMessagesConfig = (NotificationMessagesConfig) unmarshaller.unmarshal(doc); - } catch(JAXBException e){ - throw new DeviceManagementException("Error occurred while initializing Notification settings config", e); - } } private static Schema getSchema() throws DeviceManagementException { @@ -105,8 +87,4 @@ public class DeviceConfigurationManager { return currentDeviceConfig; } - public NotificationMessagesConfig getNotificationMessagesConfig() { - return notificationMessagesConfig; - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java index 6434a5d0e5..2ae0b77436 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfigRepository.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.core.config; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; -import org.wso2.carbon.device.mgt.core.config.email.EmailConfigurations; import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; @@ -32,11 +31,12 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "ManagementRepository") public class DeviceManagementConfigRepository { - private DataSourceConfig dataSourceConfig; - private EmailConfigurations emailConfigurations; - private IdentityConfigurations identityConfigurations; - private PolicyConfiguration policyConfiguration; + +// private EmailConfigurations emailConfigurations; private TaskConfiguration taskConfiguration; + private DataSourceConfig dataSourceConfig; + private IdentityConfigurations identityConfigurations; + private PolicyConfiguration policyConfiguration; @XmlElement(name = "DataSourceConfiguration", required = true) public DataSourceConfig getDataSourceConfig() { @@ -47,20 +47,21 @@ public class DeviceManagementConfigRepository { this.dataSourceConfig = dataSourceConfig; } - @XmlElement(name = "EmailClientConfiguration", required = true) - public EmailConfigurations getEmailConfigurations() { - return emailConfigurations; - } - - public void setEmailConfigurations(EmailConfigurations emailConfigurations) { - this.emailConfigurations = emailConfigurations; - } +// @XmlElement(name = "EmailClientConfiguration", required = true) +// public EmailConfigurations getEmailConfigurations() { +// return emailConfigurations; +// } +// +// public void setEmailConfigurations(EmailConfigurations emailConfigurations) { +// this.emailConfigurations = emailConfigurations; +// } @XmlElement(name = "IdentityConfiguration", required = true) public IdentityConfigurations getIdentityConfigurations() { return identityConfigurations; } + public void setIdentityConfigurations(IdentityConfigurations identityConfigurations) { this.identityConfigurations = identityConfigurations; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/EmailConfigurations.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/EmailConfigurations.java deleted file mode 100644 index b0e3a9009a..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/EmailConfigurations.java +++ /dev/null @@ -1,85 +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 org.wso2.carbon.device.mgt.core.config.email; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "EmailClientConfiguration") -public class EmailConfigurations { - - private int minNumOfThread; - private int maxNumOfThread; - private int keepAliveTime; - private int threadQueueCapacity; - private String lBHostPortPrefix; - private String enrollmentContextPath; - - @XmlElement(name = "minimumThread", required = true) - public int getMinNumOfThread() { - return minNumOfThread; - } - - public void setMinNumOfThread(int minNumOfThread) { - this.minNumOfThread = minNumOfThread; - } - @XmlElement(name = "maximumThread", required = true) - public int getMaxNumOfThread() { - return maxNumOfThread; - } - - public void setMaxNumOfThread(int maxNumOfThread) { - this.maxNumOfThread = maxNumOfThread; - } - - @XmlElement(name = "keepAliveTime", required = true) - public int getKeepAliveTime() { - return keepAliveTime; - } - - public void setKeepAliveTime(int keepAliveTime) { - this.keepAliveTime = keepAliveTime; - } - @XmlElement(name = "ThreadQueueCapacity", required = true) - public int getThreadQueueCapacity() { - return threadQueueCapacity; - } - - public void setThreadQueueCapacity(int threadQueueCapacity) { - this.threadQueueCapacity = threadQueueCapacity; - } - - @XmlElement(name = "LBHostPortPrefix", required = true) - public String getlBHostPortPrefix() { - return lBHostPortPrefix; - } - - public void setlBHostPortPrefix(String lBHostPortPrefix) { - this.lBHostPortPrefix = lBHostPortPrefix; - } - - @XmlElement(name = "enrollmentContextPath", required = true) - public String getEnrollmentContextPath() { - return enrollmentContextPath; - } - - public void setEnrollmentContextPath(String enrollmentContextPath) { - this.enrollmentContextPath = enrollmentContextPath; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/NotificationMessages.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/NotificationMessages.java deleted file mode 100644 index 961497030b..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/NotificationMessages.java +++ /dev/null @@ -1,110 +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 org.wso2.carbon.device.mgt.core.config.email; - -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "NotificationMessage") -public class NotificationMessages { - - private String header; - private String body; - private String footerLine1; - private String footerLine2; - private String footerLine3; - private String subject; - private String url; - - @XmlAttribute(name = "type") - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - private String type; - - @XmlElement(name = "Header", required = true) - public String getHeader() { - return header; - } - - public void setHeader(String header) { - this.header = header; - } - - @XmlElement(name = "Body", required = true) - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - - @XmlElement(name = "Subject", required = true) - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - @XmlElement(name = "Url", required = true) - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - @XmlElement(name = "Footer1") - public String getFooterLine1() { - return footerLine1; - } - - public void setFooterLine1(String footerLine1) { - this.footerLine1 = footerLine1; - } - - @XmlElement(name = "Footer2") - public String getFooterLine2() { - return footerLine2; - } - - public void setFooterLine2(String footerLine2) { - this.footerLine2 = footerLine2; - } - - @XmlElement(name = "Footer3") - public String getFooterLine3() { - return footerLine3; - } - - public void setFooterLine3(String footerLine3) { - this.footerLine3 = footerLine3; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/NotificationMessagesConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/NotificationMessagesConfig.java deleted file mode 100644 index 97aefeaa0f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/email/NotificationMessagesConfig.java +++ /dev/null @@ -1,39 +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 org.wso2.carbon.device.mgt.core.config.email; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -@XmlRootElement(name = "Notifications") -public class NotificationMessagesConfig { - - private List notificationMessagesList; - - @XmlElement(name = "NotificationMessage") - public List getNotificationMessagesList() { - return notificationMessagesList; - } - - public void setNotificationMessagesList(List notificationMessagesList) { - this.notificationMessagesList = notificationMessagesList; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/task/TaskConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/task/TaskConfiguration.java new file mode 100644 index 0000000000..8b099b1b24 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/task/TaskConfiguration.java @@ -0,0 +1,101 @@ +/* + * 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. + */ + + +/** + * This class will read the configurations related to task. This task will be responsible for adding the operations. + */ +package org.wso2.carbon.device.mgt.core.config.task; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "TaskConfiguration") +public class TaskConfiguration { + + + private boolean enabled; + private int frequency; + private String taskClazz; + private List operations; + + @XmlElement(name = "Enable", required = true) + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @XmlElement(name = "Frequency", required = true) + public int getFrequency() { + return frequency; + } + + public void setFrequency(int frequency) { + this.frequency = frequency; + } + + @XmlElement(name = "TaskClass", required = true) + public String getTaskClazz() { + return taskClazz; + } + + public void setTaskClazz(String taskClazz) { + this.taskClazz = taskClazz; + } + + @XmlElementWrapper(name="Operations") + @XmlElement(name = "Operation", required = true) + public List getOperations() { + return operations; + } + + public void setOperations(List operations) { + this.operations = operations; + } + + @XmlRootElement(name = "Operation") + public static class Operation { + + + private String operationName; + private int recurrency; + + @XmlElement(name = "Name", required = true) + public String getOperationName() { + return operationName; + } + + public void setOperationName(String operationName) { + this.operationName = operationName; + } + + @XmlElement(name = "RecurrentTimes", required = true) + public int getRecurrency() { + return recurrency; + } + + public void setRecurrency(int recurrency) { + this.recurrency = recurrency; + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index 10f14fc3b6..4f98359104 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -32,6 +32,10 @@ import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.SQLServerDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; +import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl; +import org.wso2.carbon.device.mgt.core.search.mgt.dao.SearchDAO; +import org.wso2.carbon.device.mgt.core.search.mgt.dao.impl.SearchDAOImpl; import javax.sql.DataSource; import java.sql.Connection; @@ -127,6 +131,14 @@ public class DeviceManagementDAOFactory { return new ApplicationMappingDAOImpl(); } + public static DeviceDetailsDAO getDeviceDetailsDAO() { + return new DeviceDetailsDAOImpl(); + } + + public static SearchDAO getSearchDAO() { + return new SearchDAOImpl(); + } + public static void init(DataSourceConfig config) { dataSource = resolveDataSource(config); try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceDetailsMgtException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceDetailsMgtException.java index ac61dcb615..afa7a12cb3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceDetailsMgtException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceDetailsMgtException.java @@ -19,6 +19,40 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt; -public class DeviceDetailsMgtException { +public class DeviceDetailsMgtException extends Exception{ + private static final long serialVersionUID = -315127931137777499L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public DeviceDetailsMgtException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public DeviceDetailsMgtException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public DeviceDetailsMgtException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public DeviceDetailsMgtException() { + super(); + } + + public DeviceDetailsMgtException(Throwable cause) { + super(cause); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java index 3189844424..a8dc8e3950 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/DeviceDetailsDAO.java @@ -19,14 +19,16 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt.dao; -import org.wso2.carbon.device.mgt.common.device.details.DeviceApplication; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtDAOException; + +import java.util.Map; /** * This class will store device details related generic information such as cpu/memory utilization, battery level, * plugged in to a power source or operation on battery. + * In CDM framework, we only keep the snapshot of the device information. So previous details are deleted as soon as new + * data is arrived. */ public interface DeviceDetailsDAO { @@ -38,6 +40,13 @@ public interface DeviceDetailsDAO { */ void addDeviceInformation(DeviceInfo deviceInfo) throws DeviceDetailsMgtDAOException; + /** + * This method will add the device properties to the database. + * @param propertyMap - device properties. + * @throws DeviceDetailsMgtDAOException + */ + void addDeviceProperties(Map propertyMap, int deviceId) throws DeviceDetailsMgtDAOException; + /** * This method will return the device information when device id is provided. * @param deviceId - device Id @@ -46,6 +55,28 @@ public interface DeviceDetailsDAO { */ DeviceInfo getDeviceInformation(int deviceId) throws DeviceDetailsMgtDAOException; + /** + * This method will return the device properties from database. + * @param deviceId + * @return - device properties map. + * @throws DeviceDetailsMgtDAOException + */ + Map getDeviceProperties(int deviceId) throws DeviceDetailsMgtDAOException; + + /** + * This method will delete the device information from the database. + * @param deviceId - Integer. + * @throws DeviceDetailsMgtDAOException + */ + void deleteDeviceInformation(int deviceId) throws DeviceDetailsMgtDAOException; + + /** + * This method will delete the device properties from database. + * @param deviceId - Integer. + * @throws DeviceDetailsMgtDAOException + */ + void deleteDeviceProperties(int deviceId) throws DeviceDetailsMgtDAOException; + /** * This method will add device location to database. * @param deviceLocation - Device location with latitude and longitude. @@ -62,17 +93,31 @@ public interface DeviceDetailsDAO { DeviceLocation getDeviceLocation(int deviceId) throws DeviceDetailsMgtDAOException; /** - * This method will add device application to database. - * @param deviceApplication - Device application - * @throws DeviceDetailsMgtDAOException - */ - void addDeviceApplications(DeviceApplication deviceApplication) throws DeviceDetailsMgtDAOException; - - /** - * This method will return the device application list once device id is provided. + * This method will delete the device location from the database. * @param deviceId - * @return * @throws DeviceDetailsMgtDAOException */ - DeviceApplication getDeviceApplications(int deviceId) throws DeviceDetailsMgtDAOException; + void deleteDeviceLocation(int deviceId) throws DeviceDetailsMgtDAOException; + +// /** +// * This method will add device application to database. +// * @param deviceApplication - Device application +// * @throws DeviceDetailsMgtDAOException +// */ +// void addDeviceApplications(DeviceApplication deviceApplication) throws DeviceDetailsMgtDAOException; +// +// /** +// * This method will return the device application list once device id is provided. +// * @param deviceId +// * @return +// * @throws DeviceDetailsMgtDAOException +// */ +// DeviceApplication getDeviceApplications(int deviceId) throws DeviceDetailsMgtDAOException; +// +// /** +// * This method will delete the application list from the database. +// * @param deviceId - Integer +// * @throws DeviceDetailsMgtDAOException +// */ +// void deleteDeviceApplications(int deviceId) throws DeviceDetailsMgtDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index 23fa39ba3b..6ca1735035 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -19,6 +19,305 @@ package org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl; -public class DeviceDetailsDAOImpl { +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; +import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { + + private static Log log = LogFactory.getLog(DeviceDetailsDAOImpl.class); + + @Override + public void addDeviceInformation(DeviceInfo deviceInfo) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + + stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, IMEI, IMSI, DEVICE_MODEL, " + + "VENDOR, OS_VERSION, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " + + "EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, OPERATOR, CONNECTION_TYPE, " + + "MOBILE_SIGNAL_STRENGTH, SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?,? ); "); + + stmt.setInt(1, deviceInfo.getDeviceId()); + stmt.setString(2, deviceInfo.getIMEI()); + stmt.setString(3, deviceInfo.getIMSI()); + stmt.setString(4, deviceInfo.getDeviceModel()); + stmt.setString(5, deviceInfo.getVendor()); + stmt.setString(6, deviceInfo.getOsVersion()); + stmt.setDouble(7, deviceInfo.getBatteryLevel()); + stmt.setDouble(8, deviceInfo.getInternalTotalMemory()); + stmt.setDouble(9, deviceInfo.getInternalAvailableMemory()); + stmt.setDouble(10, deviceInfo.getExternalTotalMemory()); + stmt.setDouble(11, deviceInfo.getExternalAvailableMemory()); + stmt.setString(12, deviceInfo.getOperator()); + stmt.setString(13, deviceInfo.getConnectionType()); + stmt.setDouble(14, deviceInfo.getMobileSignalStrength()); + stmt.setString(15, deviceInfo.getSsid()); + stmt.setDouble(16, deviceInfo.getCpuUsage()); + stmt.setDouble(17, deviceInfo.getTotalRAMMemory()); + stmt.setDouble(18, deviceInfo.getAvailableRAMMemory()); + stmt.setBoolean(19, deviceInfo.isPluggedIn()); + + stmt.execute(); + + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while inserting device details to database.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + + } + + @Override + public void addDeviceProperties(Map propertyMap, int deviceId) throws DeviceDetailsMgtDAOException { + + if(propertyMap.isEmpty()){ + log.warn("Property map of device id :" + deviceId + " is empty."); + return; + } + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_INFO (DEVICE_ID, KEY_FIELD, VALUE_FIELD) VALUES (?, ?, ?)"); + + for (Map.Entry entry : propertyMap.entrySet()) { + stmt.setInt(1, deviceId); + stmt.setString(2, entry.getKey()); + stmt.setString(3, entry.getValue()); + stmt.addBatch(); + } + stmt.executeBatch(); + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while inserting device properties to database.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + + } + + @Override + public DeviceInfo getDeviceInformation(int deviceId) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + DeviceInfo deviceInfo = new DeviceInfo(); + try { + conn = this.getConnection(); + + String sql = "SELECT * FROM DM_DEVICE_DETAIL WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + rs = stmt.executeQuery(); + + while (rs.next()) { + deviceInfo.setDeviceId(rs.getInt("DEVICE_ID")); + deviceInfo.setIMEI(rs.getString("IMEI")); + deviceInfo.setIMSI(rs.getString("IMSI")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setVendor(rs.getString("VENDOR")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setInternalTotalMemory(rs.getDouble("INTERNAL_TOTAL_MEMORY")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setOperator(rs.getString("OPERATOR")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + } + + deviceInfo.setDeviceId(deviceId); + return deviceInfo; + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while fetching the details of the registered devices.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public Map getDeviceProperties(int deviceId) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Map map = new HashMap<>(); + try { + conn = this.getConnection(); + String sql = "SELECT * FROM DM_DEVICE_INFO WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + rs = stmt.executeQuery(); + + while (rs.next()) { + map.put(rs.getString("KEY_FIELD"), rs.getString("VALUE_FIELD")); + } + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while fetching the properties of the registered devices.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return map; + } + + @Override + public void deleteDeviceInformation(int deviceId) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String query = "DELETE FROM DM_DEVICE_DETAIL WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, deviceId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while deleting the device information from the data base.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void deleteDeviceProperties(int deviceId) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String query = "DELETE FROM DM_DEVICE_INFO WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, deviceId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while deleting the device properties from the data base.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_LOCATION (DEVICE_ID, LATITUDE, LONGITUDE, STREET1, " + + "STREET2, CITY, ZIP, STATE, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); + stmt.setInt(1, deviceLocation.getDeviceId()); + stmt.setDouble(2, deviceLocation.getLatitude()); + stmt.setDouble(3, deviceLocation.getLongitude()); + stmt.setString(4, deviceLocation.getStreet1()); + stmt.setString(5, deviceLocation.getStreet2()); + stmt.setString(6, deviceLocation.getCity()); + stmt.setString(7, deviceLocation.getZip()); + stmt.setString(8, deviceLocation.getState()); + stmt.setString(9, deviceLocation.getCountry()); + stmt.execute(); + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while adding the device location to database.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public DeviceLocation getDeviceLocation(int deviceId) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + DeviceLocation location = new DeviceLocation(); + try { + conn = this.getConnection(); + String sql = "SELECT * FROM DM_DEVICE_LOCATION WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + rs = stmt.executeQuery(); + + while (rs.next()) { + location.setDeviceId(deviceId); + location.setLatitude(rs.getDouble("LATITUDE")); + location.setLongitude(rs.getDouble("LONGITUDE")); + location.setStreet1(rs.getString("STREET1")); + location.setStreet2(rs.getString("STREET2")); + location.setCity(rs.getString("CITY")); + location.setZip(rs.getString("ZIP")); + location.setState(rs.getString("STATE")); + location.setCountry(rs.getString("COUNTRY")); + } + location.setDeviceId(deviceId); + + return location; + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while fetching the location of the registered devices.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public void deleteDeviceLocation(int deviceId) throws DeviceDetailsMgtDAOException { + + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String query = "DELETE FROM DM_DEVICE_LOCATION WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, deviceId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new DeviceDetailsMgtDAOException("Error occurred while deleting the device location from the data base.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + private Connection getConnection() throws SQLException { + return DeviceManagementDAOFactory.getConnection(); + } + + +// @Override +// public void addDeviceApplications(DeviceApplication deviceApplication) throws DeviceDetailsMgtDAOException { +// +// } +// +// @Override +// public DeviceApplication getDeviceApplications(int deviceId) throws DeviceDetailsMgtDAOException { +// return null; +// } +// +// @Override +// public void deleteDeviceApplications(int deviceId) throws DeviceDetailsMgtDAOException { +// +// } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 954e3fa218..cfd55a1b01 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -28,7 +28,7 @@ import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInfomationManager; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; @@ -36,7 +36,7 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import java.sql.SQLException; -public class DeviceInformationManagerImpl implements DeviceInfomationManager { +public class DeviceInformationManagerImpl implements DeviceInformationManager { private static Log log = LogFactory.getLog(DeviceInformationManagerImpl.class); @@ -50,6 +50,10 @@ public class DeviceInformationManagerImpl implements DeviceInfomationManager { public void addDeviceInfo(DeviceInfo deviceInfo) throws DeviceDetailsMgtException { try { + Device device = DeviceManagementDataHolder.getInstance(). + getDeviceManagementProvider().getDevice(deviceInfo.getDeviceIdentifier()); + deviceInfo.setDeviceId(device.getId()); + DeviceManagementDAOFactory.beginTransaction(); deviceDetailsDAO.deleteDeviceInformation(deviceInfo.getDeviceId()); deviceDetailsDAO.deleteDeviceProperties(deviceInfo.getDeviceId()); @@ -62,6 +66,9 @@ public class DeviceInformationManagerImpl implements DeviceInfomationManager { } catch (DeviceDetailsMgtDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while adding the device information."); + } catch (DeviceManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + throw new DeviceDetailsMgtException("Error occurred while retrieving the device information."); } finally { DeviceManagementDAOFactory.closeConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/email/EmailConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/email/EmailConstants.java deleted file mode 100644 index 139a845f85..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/email/EmailConstants.java +++ /dev/null @@ -1,31 +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 org.wso2.carbon.device.mgt.core.email; - -public final class EmailConstants { - - public static final class EnrolmentEmailConstants { - public static final String DOMAIN = "domain-name"; - public static final String USERNAME = "user-name"; - public static final String DOWNLOAD_URL = "downloadUrl"; - public static final String ENCODED_SCHEME = "UTF-8"; - public static final String PASSWORD = "password"; - public static final String FIRST_NAME = "first-name"; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/email/sender/EmailServiceProviderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/email/sender/EmailServiceProviderImpl.java deleted file mode 100644 index cd537f62a8..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/email/sender/EmailServiceProviderImpl.java +++ /dev/null @@ -1,116 +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 org.wso2.carbon.device.mgt.core.email.sender; - -import org.apache.axiom.om.OMAbstractFactory; -import org.apache.axiom.om.OMElement; -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.base.BaseConstants; -import org.apache.axis2.transport.mail.MailConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.EmailMessageProperties; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.email.EmailConfigurations; -import org.wso2.carbon.device.mgt.core.internal.EmailServiceDataHolder; -import org.wso2.carbon.device.mgt.core.service.EmailService; - -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 EmailServiceProviderImpl implements EmailService { - - private static ThreadPoolExecutor threadPoolExecutor; - - static { - EmailConfigurations emailConfig = - DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getEmailConfigurations(); - - threadPoolExecutor = new ThreadPoolExecutor(emailConfig.getMinNumOfThread(), - emailConfig.getMaxNumOfThread(), emailConfig.getKeepAliveTime(), TimeUnit.SECONDS, - new LinkedBlockingQueue(emailConfig.getThreadQueueCapacity())); - } - - private static final String EMAIL_URI_SCHEME = "mailto:"; - private static Log log = LogFactory.getLog(EmailServiceProviderImpl.class); - - @Override - public void sendEmail(EmailMessageProperties emailMessageProperties) throws DeviceManagementException { - for (String toAddr : emailMessageProperties.getMailTo()) { - threadPoolExecutor - .submit(new EmailSender(toAddr, emailMessageProperties.getSubject(), - emailMessageProperties.getMessageBody())); - } - } - - 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() { - Map headerMap = new HashMap(); - headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, subject); - OMElement payload = OMAbstractFactory.getOMFactory().createOMElement( - BaseConstants.DEFAULT_TEXT_WRAPPER, null); - payload.setText(body); - try { - ServiceClient serviceClient; - ConfigurationContext configContext = EmailServiceDataHolder.getInstance(). - getConfigurationContextService().getServerConfigContext(); - //Set configuration service client if available, else create new service client - if (configContext != null) { - serviceClient = new ServiceClient(configContext, null); - } else { - - serviceClient = new ServiceClient(); - } - Options options = new Options(); - options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); - options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); - options.setProperty(MailConstants.TRANSPORT_MAIL_FORMAT, - MailConstants.TRANSPORT_FORMAT_TEXT); - options.setTo(new EndpointReference(EMAIL_URI_SCHEME + to)); - serviceClient.setOptions(options); - serviceClient.fireAndForget(payload); - log.debug("Sending confirmation mail to " + to); - } catch (AxisFault e) { - log.error("Error in delivering the message, subject: '" + subject + "', to: '" + to + "'", e); - } - } - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementAxis2ConfigContextObserver.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementAxis2ConfigContextObserver.java index a973deacc9..3634164d33 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementAxis2ConfigContextObserver.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementAxis2ConfigContextObserver.java @@ -19,13 +19,31 @@ package org.wso2.carbon.device.mgt.core.internal; import org.apache.axis2.context.ConfigurationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.context.RegistryType; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +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.Axis2ConfigurationContextObserver; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; + +import java.io.File; +import java.io.FilenameFilter; public class DeviceManagementAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver { + private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "email-templates"; + private static final Log log = LogFactory.getLog(DeviceManagementAxis2ConfigContextObserver.class); + @Override public void creatingConfigurationContext(int tenantId) { - + } @Override 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 d0e18f017f..ee594bc657 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 @@ -47,7 +47,10 @@ public class DeviceManagementDataHolder { private ConfigurationContextService configurationContextService; private HashMap requireDeviceAuthorization = new HashMap<>(); private DeviceAccessAuthorizationService deviceAccessAuthorizationService; + private TaskService taskService; + //private EmailSenderService emailSenderService; + private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder(); @@ -167,6 +170,7 @@ public class DeviceManagementDataHolder { this.deviceAccessAuthorizationService = deviceAccessAuthorizationService; } + public TaskService getTaskService() { return taskService; } @@ -174,4 +178,13 @@ public class DeviceManagementDataHolder { public void setTaskService(TaskService taskService) { this.taskService = taskService; } +// +// public EmailSenderService getEmailSenderService() { +// return emailSenderService; +// } +// +// public void setEmailSenderService(EmailSenderService emailSenderService) { +// this.emailSenderService = emailSenderService; +// } + } 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 c01d740341..96d9e8d973 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 @@ -51,6 +51,7 @@ import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceIm import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; +import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.service.RealmService; @@ -181,9 +182,9 @@ public class DeviceManagementServiceComponent { bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); /* Registering Tenant Configuration Management Service */ - TenantConfigurationManagementService - tenantConfiguration = new TenantConfigurationManagementServiceImpl(); - bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null); + TenantConfigurationManagementService + tenantConfiguration = new TenantConfigurationManagementServiceImpl(); + bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null); /* Registering Notification Service */ NotificationManagementService notificationManagementService @@ -199,7 +200,7 @@ public class DeviceManagementServiceComponent { DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl(); DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService); bundleContext.registerService(DeviceAccessAuthorizationService.class.getName(), - deviceAccessAuthorizationService, null); + deviceAccessAuthorizationService, null); /* Registering App Management service */ try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.java new file mode 100644 index 0000000000..4d175bfa74 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceTaskManagerServiceComponent.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 org.wso2.carbon.device.mgt.core.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; +import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; +import org.wso2.carbon.device.mgt.core.task.impl.DeviceTaskManagerServiceImpl; +import org.wso2.carbon.ntask.core.service.TaskService; + +/** + * @scr.component name="org.wso2.carbon.device.task.manager" immediate="true" + * @scr.reference name="device.ntask.component" + * interface="org.wso2.carbon.ntask.core.service.TaskService" + * cardinality="1..1" + * policy="dynamic" + * bind="setTaskService" + * unbind="unsetTaskService" + */ + +public class DeviceTaskManagerServiceComponent { + + private static Log log = LogFactory.getLog(DeviceManagementServiceComponent.class); + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + try { + if (log.isDebugEnabled()) { + log.debug("Initializing device details retrieving task manager bundle."); + } + // This will start the device details retrieving task. + boolean taskEnable = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getTaskConfiguration().isEnabled(); + if (taskEnable) { + DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl(); + taskManagerService.startTask(); + } + componentContext.getBundleContext().registerService(DeviceInformationManager.class, + new DeviceInformationManagerImpl(), null); + + componentContext.getBundleContext().registerService(SearchManagerService.class, + new SearchManagerServiceImpl(), null); + } catch (Throwable e) { + log.error("Error occurred while initializing device details retrieving task manager service.", e); + } + } + + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { + + try { + DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl(); + taskManagerService.stopTask(); + } catch (Throwable e) { + log.error("Error occurred while destroying the device details retrieving task manager service.", e); + } + } + + + protected void setTaskService(TaskService taskService) { + if (log.isDebugEnabled()) { + log.debug("Setting the task service."); + } + DeviceManagementDataHolder.getInstance().setTaskService(taskService); + } + + protected void unsetTaskService(TaskService taskService) { + if (log.isDebugEnabled()) { + log.debug("Removing the task service."); + } + DeviceManagementDataHolder.getInstance().setTaskService(null); + } +} + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/EmailServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/EmailServiceComponent.java deleted file mode 100644 index 708198a0c4..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/EmailServiceComponent.java +++ /dev/null @@ -1,86 +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 org.wso2.carbon.device.mgt.core.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; -import org.wso2.carbon.device.mgt.core.email.sender.EmailServiceProviderImpl; -import org.wso2.carbon.device.mgt.core.service.EmailService; -import org.wso2.carbon.device.mgt.core.service.EmailServiceImpl; -import org.wso2.carbon.utils.ConfigurationContextService; - -/** - * @scr.component component.name="org.wso2.carbon.device.emailmanager" immediate="true" - * @scr.reference name="configurationcontext.service" - * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1" - * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService" - */ -public class EmailServiceComponent { - - private static Log log = LogFactory.getLog(EmailServiceComponent.class); - - /** - * initialize the email service here service here. - * - * @param context - */ - protected void activate(ComponentContext context) { - try { - if (log.isDebugEnabled()) { - log.debug("Initializing email service bundle"); - } - - DeviceConfigurationManager.getInstance().initConfig(); - DeviceManagementConfig config = - DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); - /* Initializing Email Service Configurations */ - - EmailService emailServiceProvider = new EmailServiceProviderImpl(); - EmailServiceDataHolder.getInstance().setEmailServiceProvider(emailServiceProvider); ; - - this.registerServices(context); - - if (log.isDebugEnabled()) { - log.debug("Email management core bundle has been successfully initialized"); - } - } catch (Throwable e) { - log.error("Error occurred while initializing device management core bundle", e); - } - } - protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { - EmailServiceDataHolder.getInstance().setConfigurationContextService(configurationContextService); - } - protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { - EmailServiceDataHolder.getInstance().setConfigurationContextService(null); - } - - private void registerServices(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("Registering OSGi service Email Service Impl"); - } - /* Registering Email Service */ - BundleContext bundleContext = componentContext.getBundleContext(); - bundleContext.registerService(EmailService.class.getName(), new EmailServiceImpl(), null); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/EmailServiceDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/EmailServiceDataHolder.java deleted file mode 100644 index e73b1d4e27..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/EmailServiceDataHolder.java +++ /dev/null @@ -1,61 +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 org.wso2.carbon.device.mgt.core.internal; - -import org.wso2.carbon.device.mgt.core.service.EmailService; -import org.wso2.carbon.utils.ConfigurationContextService; - -public class EmailServiceDataHolder { - - private static EmailServiceDataHolder thisInstance = new EmailServiceDataHolder(); - private ConfigurationContextService configurationContextService; - private EmailService emailServiceProvider; - - public static EmailServiceDataHolder getThisInstance() { - return thisInstance; - } - - public static void setThisInstance(EmailServiceDataHolder thisInstance) { - EmailServiceDataHolder.thisInstance = thisInstance; - } - - private EmailServiceDataHolder() { - } - - public static EmailServiceDataHolder getInstance() { - return thisInstance; - } - - 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 EmailService getEmailServiceProvider() { - return emailServiceProvider; - } - - public void setEmailServiceProvider(EmailService emailServiceProvider) { - this.emailServiceProvider = emailServiceProvider; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java index 99ef0a50ac..873dfa82ed 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Constants.java @@ -20,5 +20,8 @@ package org.wso2.carbon.device.mgt.core.search.mgt; public class Constants { -} + public static String GENERAL = "GENERAL"; + public static String PROP_AND = "PROP_AND"; + public static String PROP_OR = "PROP_OR"; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/InvalidOperatorException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/InvalidOperatorException.java index e713ae0d50..e85e9ed340 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/InvalidOperatorException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/InvalidOperatorException.java @@ -19,6 +19,41 @@ package org.wso2.carbon.device.mgt.core.search.mgt; -public class InvalidOperatorException { +public class InvalidOperatorException extends Exception { + + private static final long serialVersionUID = -3151279311388888499L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public InvalidOperatorException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public InvalidOperatorException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public InvalidOperatorException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public InvalidOperatorException() { + super(); + } + + public InvalidOperatorException(Throwable cause) { + super(cause); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java new file mode 100644 index 0000000000..88affab477 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java @@ -0,0 +1,31 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.search.mgt; + +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.common.search.Condition; +import org.wso2.carbon.device.mgt.common.search.SearchContext; + +import java.util.List; + +public interface Processor { + + List execute(SearchContext searchContext) throws SearchMgtException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java index 8297fc24aa..a6850ed1fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java @@ -20,19 +20,20 @@ package org.wso2.carbon.device.mgt.core.search.mgt; import org.wso2.carbon.device.mgt.common.search.Condition; -import org.wso2.carbon.device.mgt.core.search.mgt.InvalidOperatorException; import java.util.List; +import java.util.Map; public interface QueryBuilder { - void processAND(List conditions) throws InvalidOperatorException; + Map> buildQueries(List conditions) throws InvalidOperatorException; - void processOR(List conditions) throws InvalidOperatorException; + String processAND(List conditions) throws InvalidOperatorException; - void processEQUALS(List conditions) throws InvalidOperatorException; + String processOR(List conditions) throws InvalidOperatorException; - void processGREATERTHAN(List conditions) throws InvalidOperatorException; + List processANDProperties(List conditions) throws InvalidOperatorException; + + List processORProperties(List conditions) throws InvalidOperatorException; - void processLESSTHAN(List conditions) throws InvalidOperatorException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/ResultSetAggregator.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/ResultSetAggregator.java new file mode 100644 index 0000000000..9a5b9ab3f7 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/ResultSetAggregator.java @@ -0,0 +1,31 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.search.mgt; + +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; + +import java.util.List; +import java.util.Map; + +public interface ResultSetAggregator { + + List aggregate(Map> deviceWrappers); + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java new file mode 100644 index 0000000000..ad78ca171f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java @@ -0,0 +1,31 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.search.mgt; + +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.common.search.SearchContext; + +import java.util.List; + +public interface SearchManagerService { + + List search(SearchContext searchContext) throws SearchMgtException; +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchMgtException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchMgtException.java index 6cff277efc..96edd40399 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchMgtException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchMgtException.java @@ -19,6 +19,41 @@ package org.wso2.carbon.device.mgt.core.search.mgt; -public class SearchMgtException { +public class SearchMgtException extends Exception { + + private static final long serialVersionUID = -315127931137777499L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public SearchMgtException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public SearchMgtException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public SearchMgtException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public SearchMgtException() { + super(); + } + + public SearchMgtException(Throwable cause) { + super(cause); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAO.java index 80a95d1eb5..04379dae6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAO.java @@ -19,5 +19,13 @@ package org.wso2.carbon.device.mgt.core.search.mgt.dao; +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; + +import java.util.List; + public interface SearchDAO { + + List searchDeviceDetailsTable(String query) throws SearchDAOException; + + List searchDevicePropertyTable(String query) throws SearchDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAOException.java new file mode 100644 index 0000000000..cda8ae209f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/SearchDAOException.java @@ -0,0 +1,59 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.search.mgt.dao; + +public class SearchDAOException extends Exception { + + private static final long serialVersionUID = -315127931139999499L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public SearchDAOException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public SearchDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public SearchDAOException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public SearchDAOException() { + super(); + } + + public SearchDAOException(Throwable cause) { + super(cause); + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java index 11b2be53a0..5409091a67 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java @@ -19,6 +19,250 @@ package org.wso2.carbon.device.mgt.core.search.mgt.dao.impl; -public class SearchDAOImpl { +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.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.search.mgt.dao.SearchDAO; +import org.wso2.carbon.device.mgt.core.search.mgt.dao.SearchDAOException; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + + +public class SearchDAOImpl implements SearchDAO { + + private static final Log log = LogFactory.getLog(SearchDAOImpl.class); + + @Override + public List searchDeviceDetailsTable(String query) throws SearchDAOException { + + if (log.isDebugEnabled()) { + log.debug("Query : " + query); + } + + Connection conn; + PreparedStatement stmt = null; + ResultSet rs; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + stmt = conn.prepareStatement(query); + rs = stmt.executeQuery(); + while (rs.next()) { + + Device device = new Device(); + device.setId(rs.getInt("ID")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setName("NAME"); + device.setType(rs.getString("DEVICE_TYPE_NAME")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(rs.getString("DEVICE_TYPE_NAME")); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setDeviceId(rs.getInt("ID")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setIMEI(rs.getString("IMEI")); + deviceInfo.setIMSI(rs.getString("IMSI")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); + deviceInfo.setOperator(rs.getString("OPERATOR")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setVendor(rs.getString("VENDOR")); + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(rs.getDouble("LATITUDE")); + deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); + deviceLocation.setStreet1(rs.getString("STREET1")); + deviceLocation.setStreet2(rs.getString("STREET2")); + deviceLocation.setCity(rs.getString("CITY")); + deviceLocation.setState(rs.getString("STATE")); + deviceLocation.setZip(rs.getString("ZIP")); + deviceLocation.setCountry(rs.getString("COUNTRY")); + deviceLocation.setDeviceId(rs.getInt("ID")); + + DeviceWrapper wrapper = new DeviceWrapper(); + wrapper.setDevice(device); + wrapper.setDeviceInfo(deviceInfo); + wrapper.setDeviceLocation(deviceLocation); + wrapper.setDeviceIdentifier(identifier); + devices.add(wrapper); + + } + } catch (SQLException e) { + throw new SearchDAOException("Error occurred while acquiring the device details.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + + this.fillPropertiesOfDevices(devices); + + if (log.isDebugEnabled()) { + log.debug("Number of the device returned from the query : " + devices.size()); + } + return devices; + } + + @Override + public List searchDevicePropertyTable(String query) throws SearchDAOException { + + if (log.isDebugEnabled()) { + log.debug("Query : " + query); + } + + Connection conn; + PreparedStatement stmt = null; + ResultSet rs; + List devices = new ArrayList<>(); + try { + conn = this.getConnection(); + stmt = conn.prepareStatement(query); + rs = stmt.executeQuery(); + while (rs.next()) { + + Device device = new Device(); + device.setId(rs.getInt("ID")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setName("NAME"); + device.setType(rs.getString("DEVICE_TYPE_NAME")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(rs.getString("DEVICE_TYPE_NAME")); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setDeviceId(rs.getInt("ID")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setIMEI(rs.getString("IMEI")); + deviceInfo.setIMSI(rs.getString("IMSI")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); + deviceInfo.setOperator(rs.getString("OPERATOR")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setVendor(rs.getString("VENDOR")); + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(rs.getDouble("LATITUDE")); + deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); + deviceLocation.setStreet1(rs.getString("STREET1")); + deviceLocation.setStreet2(rs.getString("STREET2")); + deviceLocation.setCity(rs.getString("CITY")); + deviceLocation.setState(rs.getString("STATE")); + deviceLocation.setZip(rs.getString("ZIP")); + deviceLocation.setCountry(rs.getString("COUNTRY")); + deviceLocation.setDeviceId(rs.getInt("ID")); + + DeviceWrapper wrapper = new DeviceWrapper(); + wrapper.setDevice(device); + wrapper.setDeviceInfo(deviceInfo); + wrapper.setDeviceLocation(deviceLocation); + wrapper.setDeviceIdentifier(identifier); + devices.add(wrapper); + + } + } catch (SQLException e) { + throw new SearchDAOException("Error occurred while aquiring the device details.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + + this.fillPropertiesOfDevices(devices); + + if (log.isDebugEnabled()) { + log.debug("Number of the device returned from the query : " + devices.size()); + } + + return devices; + } + + + private Connection getConnection() throws SQLException { + return DeviceManagementDAOFactory.getConnection(); + } + + private List fillPropertiesOfDevices(List devices) throws SearchDAOException { + + if (devices.isEmpty()) { + return null; + } + + Connection conn; + PreparedStatement stmt; + ResultSet rs; + + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_DEVICE_INFO WHERE DEVICE_ID IN (?) ORDER BY DEVICE_ID ;"; + stmt = conn.prepareStatement(query); + if (conn.getMetaData().getDatabaseProductName().contains("H2")) { + String inData = Utils.getDeviceIdsAsString(devices); + stmt.setString(1, inData); + } else { + Array array = conn.createArrayOf("INT", Utils.getArrayOfDeviceIds(devices)); + stmt.setArray(1, array); + } + rs = stmt.executeQuery(); + + int deviceId = 0; + while (rs.next()) { + DeviceInfo dInfo = new DeviceInfo(); + + if (deviceId != rs.getInt("DEVICE_ID")) { + deviceId = rs.getInt("DEVICE_ID"); + dInfo = this.getDeviceInfo(devices, deviceId); + if (dInfo != null) { + dInfo.getDeviceDetailsMap().put(rs.getString("KEY_FIELD"), rs.getString("VALUE_FIELD")); + } + } else { + dInfo.getDeviceDetailsMap().put(rs.getString("KEY_FIELD"), rs.getString("VALUE_FIELD")); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + return devices; + } + + private DeviceInfo getDeviceInfo(List devices, int deviceId) { + + for (DeviceWrapper dw : devices) { + if (dw.getDevice().getId() == deviceId) { + return dw.getDeviceInfo(); + } + } + return null; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java index 5cdfb57a66..9dc4e85059 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -19,6 +19,143 @@ package org.wso2.carbon.device.mgt.core.search.mgt.impl; -public class ProcessorImpl { +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.search.mgt.*; +import org.wso2.carbon.device.mgt.core.search.mgt.dao.SearchDAO; +import org.wso2.carbon.device.mgt.core.search.mgt.dao.SearchDAOException; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ProcessorImpl implements Processor { + + private SearchDAO searchDAO; + + public ProcessorImpl() { + searchDAO = DeviceManagementDAOFactory.getSearchDAO(); + } + + @Override + public List execute(SearchContext searchContext) throws SearchMgtException { + + QueryBuilder queryBuilder = new QueryBuilderImpl(); + List generalDevices = new ArrayList<>(); + List> allANDDevices = new ArrayList<>(); + List> allORDevices = new ArrayList<>(); + try { + Map> queries = queryBuilder.buildQueries(searchContext.getConditions()); + DeviceManagementDAOFactory.openConnection(); + + if (queries.containsKey(Constants.GENERAL)) { + generalDevices = searchDAO.searchDeviceDetailsTable(queries.get(Constants.GENERAL).get(0)); + } + if (queries.containsKey(Constants.PROP_AND)) { + for (String query : queries.get(Constants.PROP_AND)) { + List andDevices = searchDAO.searchDevicePropertyTable(query); + allANDDevices.add(andDevices); + } + } + if (queries.containsKey(Constants.PROP_OR)) { + for (String query : queries.get(Constants.PROP_OR)) { + List orDevices = searchDAO.searchDevicePropertyTable(query); + allORDevices.add(orDevices); + } + } + } catch (InvalidOperatorException e) { + throw new SearchMgtException("Invalid operator was provided, so cannot execute the search.", e); + } catch (SQLException e) { + throw new SearchMgtException("Error occurred while managing database transactions.", e); + } catch (SearchDAOException e) { + throw new SearchMgtException("Error occurred while running the search operations.", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + + ResultSetAggregator aggregator = new ResultSetAggregatorImpl(); + + Map> deviceWrappers = new HashMap<>(); + + deviceWrappers.put(Constants.GENERAL, generalDevices); + deviceWrappers.put(Constants.PROP_AND, this.processANDSearch(allANDDevices)); + deviceWrappers.put(Constants.PROP_OR, this.processORSearch(allORDevices)); + + return aggregator.aggregate(deviceWrappers); + } + + + private List processANDSearch(List> deLists) { + + List devices = new ArrayList<>(); + List smallestDeviceList = this.findListWithLowestItems(deLists); + List> maps = this.convertDeviceListToMap(deLists); + boolean valueExist = false; + for (DeviceWrapper dw : smallestDeviceList) { + for (Map deviceWrapperMap : maps) { + if (deviceWrapperMap.containsKey(dw.getDevice().getId())) { + valueExist = true; + } else { + valueExist = false; + break; + } + } + if (valueExist) { + devices.add(dw); + } + } + return devices; + } + + private List processORSearch(List> deLists) { + List devices = new ArrayList<>(); + Map map = new HashMap<>(); + + for (List list : deLists) { + for (DeviceWrapper dw : list) { + if (!map.containsKey(dw.getDevice().getId())) { + map.put(dw.getDevice().getId(), dw); + devices.add(dw); + } + } + } + return devices; + } + + private List findListWithLowestItems(List> deLists) { + + int size = 0; + List deviceWrappers = new ArrayList<>(); + for (List list : deLists) { + if (size == 0) { + size = list.size(); + deviceWrappers = list; + continue; + } else { + if (list.size() < size) { + deviceWrappers = list; + } + } + } + return deviceWrappers; + } + + private List> convertDeviceListToMap(List> deLists) { + + List> maps = new ArrayList<>(); + for (List deviceWrapperList : deLists) { + Map deviceWrapperMap = new HashMap<>(); + + for (DeviceWrapper dw : deviceWrapperList) { + deviceWrapperMap.put(dw.getDevice().getId(), dw); + } + maps.add(deviceWrapperMap); + } + return maps; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java new file mode 100644 index 0000000000..98ecc2d8fd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -0,0 +1,193 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.search.mgt.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.search.Condition; +import org.wso2.carbon.device.mgt.core.search.mgt.Constants; +import org.wso2.carbon.device.mgt.core.search.mgt.InvalidOperatorException; +import org.wso2.carbon.device.mgt.core.search.mgt.QueryBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class QueryBuilderImpl implements QueryBuilder { + + + private static final Log log = LogFactory.getLog(QueryBuilderImpl.class); + + @Override + public Map> buildQueries(List conditions) throws InvalidOperatorException { + + List andColumns = new ArrayList<>(); + List orColumns = new ArrayList<>(); + List otherANDColumns = new ArrayList<>(); + List otherORColumns = new ArrayList<>(); + + if (conditions.size() == 1) { + if (Utils.getDeviceDetailsColumnNames().containsKey(conditions.get(0)) || + Utils.getDeviceLocationColumnNames().containsKey(conditions.get(0))) { + andColumns.add(conditions.get(0)); + } else { + otherANDColumns.add(conditions.get(0)); + } + } else { + for (Condition con : conditions) { + if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey()) || + Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) { + if (con.getState().equals(Condition.State.AND)) { + andColumns.add(con); + } else if (con.getState().equals(Condition.State.OR)) { + orColumns.add(con); + } else { + throw new InvalidOperatorException(con.getState() + " is not a valid operator."); + } + } else { + if (con.getState().equals(Condition.State.AND)) { + otherANDColumns.add(con); + } else if (con.getState().equals(Condition.State.OR)) { + otherORColumns.add(con); + } else { + throw new InvalidOperatorException(con.getState() + " is not a valid operator."); + } + } + } + } + + Map> queries = new HashMap<>(); + queries.put(Constants.GENERAL, Utils.convertStringToList(this.getGenericQueryPart() + this.processAND(andColumns) + + this.processOR(orColumns))); + queries.put(Constants.PROP_AND, this.processANDProperties(otherANDColumns)); + queries.put(Constants.PROP_OR, this.processORProperties(otherORColumns)); + + if (log.isDebugEnabled()) { + log.debug("General Query : " + queries.get(Constants.GENERAL)); + log.debug("Property with AND Query : " + queries.get(Constants.PROP_AND)); + log.debug("Property with OR Query : " + queries.get(Constants.PROP_OR)); + } + + return queries; + } + + @Override + public String processAND(List conditions) throws InvalidOperatorException { + + String querySuffix = ""; + + for (Condition con : conditions) { + if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey())) { + querySuffix = querySuffix + " AND DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + + con.getOperator() + con.getValue(); + } else if (Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) { + querySuffix = querySuffix + " AND DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + + con.getOperator() + con.getValue(); + } + } + + return querySuffix; + } + + @Override + public String processOR(List conditions) throws InvalidOperatorException { + + String querySuffix = ""; + + for (Condition con : conditions) { + if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey())) { + querySuffix = querySuffix + " OR DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + + con.getOperator() + con.getValue(); + } else if (Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) { + querySuffix = querySuffix + " OR DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + + con.getOperator() + con.getValue(); + } + } + return querySuffix; + } + + @Override + public List processANDProperties(List conditions) throws InvalidOperatorException { + return this.getQueryList(conditions); + } + + @Override + public List processORProperties(List conditions) throws InvalidOperatorException { + return this.getQueryList(conditions); + } + + private List getQueryList(List conditions) { + List queryList = new ArrayList<>(); + for (Condition con : conditions) { + + String querySuffix = this.getPropertyQueryPart() + " AND DI.KEY_FIELD = " + "\'" + con.getKey() + "\'" + + " AND DI.VALUE_FIELD " + con.getOperator() + "\'" + con.getValue() + "\'"; + queryList.add(querySuffix); + } + return queryList; + } + + private String getGenericQueryPart() { + + return "SELECT D.ID, D.DESCRIPTION, D.NAME, \n" + + " D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION, DT.ID AS DEVICE_TYPE_ID, \n" + + "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.IMEI, DD.IMSI, DD.DEVICE_MODEL, DD.VENDOR, \n" + + "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.OPERATOR, DD.CONNECTION_TYPE, \n" + + "DD.MOBILE_SIGNAL_STRENGTH, DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + + "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + + "DL.STATE, DL.COUNTRY FROM DM_DEVICE_DETAIL AS DD, DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, " + + "DM_DEVICE_TYPE AS DT WHERE D.TENANT_ID = " + + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + +// CREATE TABLE IF NOT EXISTS DM_DEVICE ( +// ID INTEGER auto_increment NOT NULL, +// DESCRIPTION TEXT DEFAULT NULL, +// NAME VARCHAR(100) DEFAULT NULL, +// DEVICE_TYPE_ID INT(11) DEFAULT NULL, +// DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, +// TENANT_ID INTEGER DEFAULT 0, +// PRIMARY KEY (ID), +// CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) +// REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +// ); + + + } + + private String getPropertyQueryPart() { + + return "SELECT D.ID, D.DESCRIPTION, D.NAME, \n" + + " D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION, DT.ID AS DEVICE_TYPE_ID, \n" + + "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.IMEI, DD.IMSI, DD.DEVICE_MODEL, DD.VENDOR, \n" + + "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.OPERATOR, DD.CONNECTION_TYPE, \n" + + "DD.MOBILE_SIGNAL_STRENGTH, DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + + "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + + "DL.STATE, DL.COUNTRY, DI.KEY_FIELD, DI.VALUE_FIELD FROM DM_DEVICE_DETAIL AS DD, " + + "DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, \n" + + "DM_DEVICE_INFO AS DI, DM_DEVICE_TYPE AS DT WHERE D.TENANT_ID = " + + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java index 3de2fd73cc..468a9cba80 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ResultSetAggregatorImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.search.mgt.impl; import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.core.search.mgt.Constants; import org.wso2.carbon.device.mgt.core.search.mgt.ResultSetAggregator; import java.util.ArrayList; @@ -28,26 +29,22 @@ import java.util.List; import java.util.Map; public class ResultSetAggregatorImpl implements ResultSetAggregator { + @Override public List aggregate(Map> deviceWrappers) { - Map generalQueryMap = this.convertToMap(deviceWrappers.get("GENERAL")); - Map andMap = this.convertToMap(deviceWrappers.get("PROP_AND")); - Map orMap = this.convertToMap(deviceWrappers.get("PROP_OR")); - - + Map generalQueryMap = this.convertToMap(deviceWrappers.get(Constants.GENERAL)); + Map andMap = this.convertToMap(deviceWrappers.get(Constants.PROP_AND)); + Map orMap = this.convertToMap(deviceWrappers.get(Constants.PROP_OR)); List finalResult = new ArrayList<>(); - for (Integer a : andMap.keySet()) { - if(generalQueryMap.containsKey(a)) { + if (generalQueryMap.containsKey(a)) { finalResult.add(andMap.get(a)); } } - for (Integer a : orMap.keySet()) { finalResult.add(orMap.get(a)); } - return finalResult; } @@ -63,4 +60,3 @@ public class ResultSetAggregatorImpl implements ResultSetAggregator { return deviceWrapperMap; } } - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java new file mode 100644 index 0000000000..888f3edc36 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.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 org.wso2.carbon.device.mgt.core.search.mgt.impl; + +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.search.mgt.Processor; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; + +import java.util.List; + +public class SearchManagerServiceImpl implements SearchManagerService { + + + private Processor processor; + + public SearchManagerServiceImpl() { + processor = new ProcessorImpl(); + } + + @Override + public List search(SearchContext searchContext) throws SearchMgtException { + return processor.execute(searchContext); + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java index 5997c9ffd2..bd0b7a816a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java @@ -19,6 +19,86 @@ package org.wso2.carbon.device.mgt.core.search.mgt.impl; +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public class Utils { + + public static Map getDeviceDetailsColumnNames() { + + Map colonmsMap = new HashMap<>(); + + colonmsMap.put("IMEI", "IMEI"); + colonmsMap.put("IMSI", "IMSI"); + colonmsMap.put("deviceModel", "DEVICE_MODEL"); + colonmsMap.put("vendor", "VENDOR"); + colonmsMap.put("osVersion", "OS_VERSION"); + colonmsMap.put("batteryLevel", "BATTERY_LEVEL"); + colonmsMap.put("internalTotalMemory", "INTERNAL_TOTAL_MEMORY"); + colonmsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY"); + colonmsMap.put("externalTotalMemory", "EXTERNAL_TOTAL_MEMORY"); + colonmsMap.put("externalAvailableMemory", "EXTERNAL_AVAILABLE_MEMORY"); + colonmsMap.put("operator", "OPERATOR"); + colonmsMap.put("connectionType", "CONNECTION_TYPE"); + colonmsMap.put("mobileSignalStrength", "MOBILE_SIGNAL_STRENGTH"); + colonmsMap.put("ssid", "SSID"); + colonmsMap.put("cpuUsage", "CPU_USAGE"); + colonmsMap.put("totalRAMMemory", "TOTAL_RAM_MEMORY"); + colonmsMap.put("availableRAMMemory", "AVAILABLE_RAM_MEMORY"); + colonmsMap.put("pluggedIn", "PLUGGED_IN"); + + return colonmsMap; + } + + public static Map getDeviceLocationColumnNames() { + Map colonmsMap = new HashMap<>(); + + colonmsMap.put("latitude", "LATITUDE"); + colonmsMap.put("longitude", "LONGITUDE"); + colonmsMap.put("street1", "STREET1"); + colonmsMap.put("street2", "STREET2"); + colonmsMap.put("city", "CITY"); + colonmsMap.put("state", "ZIP"); + colonmsMap.put("zip", "STATE"); + colonmsMap.put("country", "COUNTRY"); + + return colonmsMap; + } + + + public static List convertStringToList(String str) { + + List stList = new ArrayList<>(); + stList.add(str); + return stList; + } + + public static Integer[] getArrayOfDeviceIds(List deviceWrappers) { + + Integer[] arr = new Integer[deviceWrappers.size()]; + int x = 0; + for (DeviceWrapper dw : deviceWrappers) { + arr[x] = dw.getDevice().getId(); + x++; + } + return arr; + } + + + public static String getDeviceIdsAsString(List deviceWrappers) { + + String str = ""; + for (DeviceWrapper dw : deviceWrappers) { + str += dw.getDevice().getId() + ","; + } + if (deviceWrappers.isEmpty()) { + return null; + } + return str.substring(0, str.length() - 1); + } } 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 7538844755..0c307f6e0e 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 @@ -18,11 +18,8 @@ package org.wso2.carbon.device.mgt.core.service; import org.wso2.carbon.device.mgt.common.*; -import org.wso2.carbon.device.mgt.common.DeviceManager; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.license.mgt.License; -import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -42,94 +39,95 @@ public interface DeviceManagementProviderService extends OperationManager { /** * Method to retrieve all the devices with pagination support. * - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination * @return PaginationResult - Result including the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * devices. + * devices. */ PaginationResult getDevicesByType(PaginationRequest request) throws DeviceManagementException; /** * Method to retrieve all the devices with pagination support. * - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination * @return PaginationResult - Result including the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * devices. + * devices. */ PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException; - void sendEnrolmentInvitation(EmailMessageProperties config) throws DeviceManagementException; + void sendEnrolmentInvitation(EmailMetaInfo metaInfo) throws DeviceManagementException; - void sendRegistrationEmail(EmailMessageProperties config) throws DeviceManagementException; + void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException; FeatureManager getFeatureManager(String deviceType) throws DeviceManagementException; /** * Proxy method to get the tenant configuration of a given platform. * - * @param deviceType Device platform + * @param deviceType Device platform * @return Tenant configuration settings of the particular tenant and platform. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * configuration. + * configuration. */ TenantConfiguration getConfiguration(String deviceType) throws DeviceManagementException; /** * Method to get the list of devices owned by an user with paging information. * - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ PaginationResult getDevicesOfUser(PaginationRequest request) throws DeviceManagementException; /** * Method to get the list of devices filtered by the ownership with paging information. * - * @param request PaginationRequest object holding the data for pagination + * @param request PaginationRequest object holding the data for pagination * @return List of devices owned by a particular user along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ PaginationResult getDevicesByOwnership(PaginationRequest request) throws DeviceManagementException; /** * Method to get the list of devices owned by an user. * - * @param userName Username of the user + * @param userName Username of the user * @return List of devices owned by a particular user * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ List getDevicesOfUser(String userName) throws DeviceManagementException; /** * Method to get the list of devices owned by users of a particular user-role. * - * @param roleName Role name of the users + * @param roleName Role name of the users * @return List of devices owned by users of a particular role * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ List getAllDevicesOfRole(String roleName) throws DeviceManagementException; /** * Method to get the count of all types of devices. + * * @return device count * @throws DeviceManagementException If some unusual behaviour is observed while counting - * the devices + * the devices */ int getDeviceCount() throws DeviceManagementException; /** * Method to get the list of devices that matches with the given device name. * - * @param deviceName name of the device + * @param deviceName name of the device * @return List of devices that matches with the given device name. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ List getDevicesByName(String deviceName) throws DeviceManagementException; @@ -139,7 +137,7 @@ public interface DeviceManagementProviderService extends OperationManager { * @param request PaginationRequest object holding the data for pagination * @return List of devices in given status along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ PaginationResult getDevicesByName(PaginationRequest request) throws DeviceManagementException; @@ -160,7 +158,7 @@ public interface DeviceManagementProviderService extends OperationManager { * @param request PaginationRequest object holding the data for pagination * @return List of devices in given status along with the required parameters necessary to do pagination. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the - * device list + * device list */ PaginationResult getDevicesByStatus(PaginationRequest request) throws DeviceManagementException; @@ -188,7 +186,7 @@ public interface DeviceManagementProviderService extends OperationManager { Device getDevice(DeviceIdentifier deviceId, EnrolmentInfo.Status status) throws DeviceManagementException; - List getAvailableDeviceTypes() throws DeviceManagementException; + List getAvailableDeviceTypes() throws DeviceManagementException; boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException; @@ -199,6 +197,6 @@ public interface DeviceManagementProviderService extends OperationManager { boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException; - void notifyOperationToDevices(Operation operation, List deviceIds)throws DeviceManagementException; + void notifyOperationToDevices(Operation operation, List deviceIds) throws DeviceManagementException; } 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 80a1ae57d5..f70eb5dca5 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 @@ -28,26 +28,17 @@ 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.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.email.EmailConfigurations; -import org.wso2.carbon.device.mgt.core.config.email.NotificationMessages; import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.device.mgt.core.email.EmailConstants; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; -import org.wso2.carbon.device.mgt.core.internal.EmailServiceDataHolder; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +import org.wso2.carbon.email.sender.core.TypedValue; import org.wso2.carbon.user.api.UserStoreException; -import java.io.IOException; -import java.net.URLDecoder; -import java.net.URLEncoder; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; +import java.util.*; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -517,130 +508,47 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public void sendEnrolmentInvitation(EmailMessageProperties emailMessageProperties) - throws DeviceManagementException { - List notificationMessages = - DeviceConfigurationManager.getInstance().getNotificationMessagesConfig().getNotificationMessagesList(); - String messageHeader = ""; - String messageBody = ""; - String messageFooter1 = ""; - String messageFooter2 = ""; - String messageFooter3 = ""; - String url = ""; - String subject = ""; - - for (NotificationMessages notificationMessage : notificationMessages) { - if (org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailNotifications.ENROL_NOTIFICATION_TYPE - .equals(notificationMessage.getType())) { - messageHeader = notificationMessage.getHeader(); - messageBody = notificationMessage.getBody(); - messageFooter1 = notificationMessage.getFooterLine1(); - messageFooter2 = notificationMessage.getFooterLine2(); - messageFooter3 = notificationMessage.getFooterLine3(); - url = notificationMessage.getUrl(); - subject = notificationMessage.getSubject(); - break; - } - } - - StringBuilder messageBuilder = new StringBuilder(); - - try { - - // Reading the download url from the cdm-config.xml file - EmailConfigurations emailConfig = - DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getEmailConfigurations(); - emailMessageProperties.setEnrolmentUrl(emailConfig.getlBHostPortPrefix() + - emailConfig.getEnrollmentContextPath()); - messageHeader = messageHeader.replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants.FIRST_NAME + "\\}", - URLEncoder.encode(emailMessageProperties.getFirstName(), - EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); - messageBody = messageBody.trim() + System.getProperty("line.separator") + url.replaceAll("\\{" - + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}", - URLDecoder.decode(emailMessageProperties.getEnrolmentUrl(), - EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); - messageBuilder.append(messageHeader).append(System.getProperty("line.separator")) - .append(System.getProperty("line.separator")); - messageBuilder.append(messageBody); - messageBuilder.append(System.getProperty("line.separator")).append(System.getProperty("line.separator")); - messageBuilder.append(messageFooter1.trim()) - .append(System.getProperty("line.separator")).append(messageFooter2.trim()).append(System - .getProperty("line.separator")).append(messageFooter3.trim()); - } catch (IOException e) { - throw new DeviceManagementException("Error replacing tags in email template '" + - emailMessageProperties.getSubject() + "'", e); - } - emailMessageProperties.setMessageBody(messageBuilder.toString()); - emailMessageProperties.setSubject(subject); - EmailServiceDataHolder.getInstance().getEmailServiceProvider().sendEmail(emailMessageProperties); + public void sendEnrolmentInvitation(EmailMetaInfo metaInfo) throws DeviceManagementException { + Map, Object>> params = new HashMap<>(); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.FIRST_NAME, + new TypedValue, Object>(String.class, metaInfo.getProperty("first-name"))); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS, + new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP, + new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); +// try { +// EmailContext ctx = +// new EmailContext.EmailContextBuilder(new ContentProviderInfo("user-enrollment", params), +// metaInfo.getRecipients()).build(); +//// DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx); +// } catch (EmailSendingFailedException e) { +// throw new DeviceManagementException("Error occurred while sending enrollment invitation", e); +// } } @Override - public void sendRegistrationEmail(EmailMessageProperties emailMessageProperties) throws DeviceManagementException { - List notificationMessages = - DeviceConfigurationManager.getInstance().getNotificationMessagesConfig().getNotificationMessagesList(); - String messageHeader = ""; - String messageBody = ""; - String messageFooter1 = ""; - String messageFooter2 = ""; - String messageFooter3 = ""; - String url = ""; - String subject = ""; - - for (NotificationMessages notificationMessage : notificationMessages) { - if (org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailNotifications. - USER_REGISTRATION_NOTIFICATION_TYPE.equals(notificationMessage.getType())) { - messageHeader = notificationMessage.getHeader(); - messageBody = notificationMessage.getBody(); - messageFooter1 = notificationMessage.getFooterLine1(); - messageFooter2 = notificationMessage.getFooterLine2(); - messageFooter3 = notificationMessage.getFooterLine3(); - url = notificationMessage.getUrl(); - subject = notificationMessage.getSubject(); - break; - } - } - StringBuilder messageBuilder = new StringBuilder(); - try { - // Reading the download url from the cdm-config.xml file - EmailConfigurations emailConfig = - DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getDeviceManagementConfigRepository().getEmailConfigurations(); - emailMessageProperties.setEnrolmentUrl(emailConfig.getlBHostPortPrefix() + - emailConfig.getEnrollmentContextPath()); - messageHeader = messageHeader.replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants.FIRST_NAME + "\\}", - URLEncoder.encode(emailMessageProperties.getFirstName(), - EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); - messageBody = messageBody.trim().replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants - .USERNAME - + "\\}", - URLEncoder.encode(emailMessageProperties.getUserName(), EmailConstants.EnrolmentEmailConstants - .ENCODED_SCHEME)); - messageBody = messageBody.trim().replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants.DOMAIN - + "\\}", - URLEncoder.encode(emailMessageProperties.getDomainName(), EmailConstants.EnrolmentEmailConstants - .ENCODED_SCHEME)); - messageBody = messageBody.replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants.PASSWORD + "\\}", - URLEncoder.encode(emailMessageProperties.getPassword(), EmailConstants.EnrolmentEmailConstants - .ENCODED_SCHEME)); - messageBody = messageBody + System.getProperty("line.separator") + url.replaceAll("\\{" - + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}", - URLDecoder.decode(emailMessageProperties.getEnrolmentUrl(), - EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME)); - messageBuilder.append(messageHeader).append(System.getProperty("line.separator")); - messageBuilder.append(messageBody).append(System.getProperty("line.separator")).append( - messageFooter1.trim()); - messageBuilder.append(System.getProperty("line.separator")).append(messageFooter2.trim()); - messageBuilder.append(System.getProperty("line.separator")).append(messageFooter3.trim()); - - } catch (IOException e) { - throw new DeviceManagementException("Error replacing tags in email template '" + - emailMessageProperties.getSubject() + "'", e); - } - emailMessageProperties.setMessageBody(messageBuilder.toString()); - emailMessageProperties.setSubject(subject); - EmailServiceDataHolder.getInstance().getEmailServiceProvider().sendEmail(emailMessageProperties); + public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException { + Map, Object>> params = new HashMap<>(); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.FIRST_NAME, + new TypedValue, Object>(String.class, metaInfo.getProperty("first-name"))); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.USERNAME, + new TypedValue, Object>(String.class, metaInfo.getProperty("username"))); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.PASSWORD, + new TypedValue, Object>(String.class, metaInfo.getProperty("password"))); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.DOMAIN, + new TypedValue, Object>(String.class, metaInfo.getProperty("domain"))); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS, + new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl())); + params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP, + new TypedValue, Object>(String.class, DeviceManagerUtil.getServerBaseHttpUrl())); +// try { +// EmailContext ctx = +// new EmailContext.EmailContextBuilder(new ContentProviderInfo("user-registration", params), +// metaInfo.getRecipients()).build(); +// DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx); +// } catch (EmailSendingFailedException e) { +// throw new DeviceManagementException("Error occurred while sending user registration notification", e); +// } } @Override @@ -721,11 +629,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Map registeredTypes = pluginRepository.getAllDeviceManagementServices(); DeviceType deviceType; if (registeredTypes != null && deviceTypesInDatabase != null) { - for (int x = 0; x < deviceTypesInDatabase.size(); x++) { - if (registeredTypes.get(deviceTypesInDatabase.get(x).getName()) != null) { + for (DeviceType aDeviceTypesInDatabase : deviceTypesInDatabase) { + if (registeredTypes.get(aDeviceTypesInDatabase.getName()) != null) { deviceType = new DeviceType(); - deviceType.setId(deviceTypesInDatabase.get(x).getId()); - deviceType.setName(deviceTypesInDatabase.get(x).getName()); + deviceType.setId(aDeviceTypesInDatabase.getId()); + deviceType.setName(aDeviceTypesInDatabase.getName()); deviceTypesResponse.add(deviceType); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailMetaInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailMetaInfo.java new file mode 100644 index 0000000000..c5ac4af267 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailMetaInfo.java @@ -0,0 +1,75 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.service; + +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +public class EmailMetaInfo { + + private Set recipients; + private Properties properties; + + public EmailMetaInfo(final Set recipients, final Properties properties) { + 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; + } + + public EmailMetaInfo(final String recipient, final Properties properties) { + 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); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailServiceImpl.java deleted file mode 100644 index 807c511659..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailServiceImpl.java +++ /dev/null @@ -1,31 +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 org.wso2.carbon.device.mgt.core.service; - -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.EmailMessageProperties; -import org.wso2.carbon.device.mgt.core.internal.EmailServiceDataHolder; - -public class EmailServiceImpl implements EmailService{ - - @Override - public void sendEmail(EmailMessageProperties emailMessageProperties) throws DeviceManagementException { - EmailServiceDataHolder.getInstance().getEmailServiceProvider().sendEmail(emailMessageProperties); - } -} 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 2fce1e38e9..cc8ff8515f 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 @@ -24,10 +24,48 @@ import java.util.List; public interface DeviceTaskManager { /** - * This method will get the operation list from - * @return + * This method will get the operation list from configurations. + * + * @return - list of Task Operations. * @throws DeviceMgtTaskException */ List getOperationList() throws DeviceMgtTaskException; + + /** + * This method will take the monitoring frequency. + * @return - integer + * @throws DeviceMgtTaskException + */ + int getTaskFrequency() throws DeviceMgtTaskException; + + /** + * This method will return the task clazz from configurations. + * @return - Fully qualified class name. + * @throws DeviceMgtTaskException + */ + String getTaskImplementedClazz() throws DeviceMgtTaskException; + + /** + * This method checks wheather task is enabled in config file. + * @return - return true or false + * @throws DeviceMgtTaskException + */ + boolean isTaskEnabled() throws DeviceMgtTaskException; + + + /** + * This method will add the operations to devices + * @throws DeviceMgtTaskException + */ + void addOperations() throws DeviceMgtTaskException; + + + /** + * This method will return the operation names which should be added in each iterations. + * @return + * @throws DeviceMgtTaskException + */ + List getValidOperationNames() throws DeviceMgtTaskException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerService.java new file mode 100644 index 0000000000..c327f0af38 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/DeviceTaskManagerService.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 org.wso2.carbon.device.mgt.core.task; + +public interface DeviceTaskManagerService { + + /** + * This method will stop the task. + * @throws DeviceMgtTaskException + */ + void startTask() throws DeviceMgtTaskException; + + /** + * This method will start the task. + * @throws DeviceMgtTaskException + */ + void stopTask() throws DeviceMgtTaskException; + + /** + * This will update the task frequency which it runs. + * @param frequency - integer + * @throws DeviceMgtTaskException + */ + void updateTask(int frequency) throws DeviceMgtTaskException; + + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java new file mode 100644 index 0000000000..e7dc35b1bd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java @@ -0,0 +1,47 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.task; + + +/** + * This is the bean for the operations added by the task. + */ +public class TaskOperation { + + private String taskName; + private int recurrentTimes; + + public String getTaskName() { + return taskName; + } + + public void setTaskName(String taskName) { + this.taskName = taskName; + } + + public int getRecurrentTimes() { + return recurrentTimes; + } + + public void setRecurrentTimes(int recurrentTimes) { + this.recurrentTimes = recurrentTimes; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java new file mode 100644 index 0000000000..7f4537fa5c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java @@ -0,0 +1,43 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.task; + +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.util.HashMap; + +public class Utils { + + + public static HashMap getTenantedTaskOperationMap(HashMap> map) { + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + if (map.containsKey(tenantId)) { + return map.get(tenantId); + } else { + HashMap mp = new HashMap<>(); + map.put(tenantId, mp); + return mp; + } + } + +} + 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 88da514554..bba13ca307 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 @@ -30,7 +30,7 @@ import java.util.Map; public class DeviceDetailsRetrieverTask implements Task { private static Log log = LogFactory.getLog(DeviceDetailsRetrieverTask.class); - private DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(); +// private DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(); @Override public void setProperties(Map map) { @@ -48,6 +48,9 @@ public class DeviceDetailsRetrieverTask implements Task { if (log.isDebugEnabled()) { log.debug("Device details retrieving task started to run."); } + + DeviceTaskManager deviceTaskManager = new DeviceTaskManagerImpl(); + try { deviceTaskManager.addOperations(); } catch (DeviceMgtTaskException e) { 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 new file mode 100644 index 0000000000..813caf7f3b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java @@ -0,0 +1,151 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.task.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.DeviceManagementException; +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.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; +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.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; +import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; +import org.wso2.carbon.device.mgt.core.task.TaskOperation; +import org.wso2.carbon.device.mgt.core.task.Utils; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class DeviceTaskManagerImpl implements DeviceTaskManager { + + private static Log log = LogFactory.getLog(DeviceTaskManagerImpl.class); + + private static HashMap> map = new HashMap<>(); + + + @Override + public List getOperationList() throws DeviceMgtTaskException { + + TaskConfiguration taskConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getTaskConfiguration(); + + List ops = taskConfiguration.getOperations(); + List taskOperations = new ArrayList<>(); + + for (TaskConfiguration.Operation op : ops) { + TaskOperation taskOperation = new TaskOperation(); + taskOperation.setTaskName(op.getOperationName()); + taskOperation.setRecurrentTimes(op.getRecurrency()); + taskOperations.add(taskOperation); + } + return taskOperations; + } + + @Override + public int getTaskFrequency() throws DeviceMgtTaskException { + + return DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getTaskConfiguration().getFrequency(); + } + + @Override + public String getTaskImplementedClazz() throws DeviceMgtTaskException { + + return DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getTaskConfiguration().getTaskClazz(); + } + + @Override + public boolean isTaskEnabled() throws DeviceMgtTaskException { + + return DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getTaskConfiguration().isEnabled(); + } + + + @Override + public void addOperations() throws DeviceMgtTaskException { + + DeviceManagementProviderService deviceManagementProviderService = + DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(); + try { + List devices = deviceManagementProviderService.getAllDevices(); + List operations = this.getValidOperationNames(); + + if(!devices.isEmpty()) { + + for (String str : operations) { + CommandOperation operation = new CommandOperation(); + operation.setEnabled(true); + operation.setType(Operation.Type.COMMAND); + operation.setCode(str); + deviceManagementProviderService.addOperation(operation, DeviceManagerUtil.convertDevices(devices)); + } + } else { + if(log.isDebugEnabled()){ + log.debug("No devices are available to perform the operations."); + } + } + } catch (DeviceManagementException e) { + throw new DeviceMgtTaskException("Error occurred while retrieving the device list.", e); + } catch (OperationManagementException e) { + throw new DeviceMgtTaskException("Error occurred while adding the operations to devices", e); + } + + } + + @Override + public List getValidOperationNames() throws DeviceMgtTaskException { + + List taskOperations = this.getOperationList(); + List opNames = new ArrayList<>(); + Long milliseconds = System.currentTimeMillis(); + int frequency = this.getTaskFrequency(); + HashMap mp = Utils.getTenantedTaskOperationMap(map); + + for (TaskOperation top : taskOperations) { + if (!mp.containsKey(top.getTaskName())) { + opNames.add(top.getTaskName()); + mp.put(top.getTaskName(), milliseconds); + } else { + Long lastExecutedTime = mp.get(top.getTaskName()); + Long evalTime = lastExecutedTime + (frequency * top.getRecurrentTimes()); + if (evalTime <= milliseconds) { + opNames.add(top.getTaskName()); + mp.put(top.getTaskName(), milliseconds); + } + } + } + + if(log.isDebugEnabled()){ + log.debug("Valid operation names are : " + Arrays.toString(opNames.toArray())); + } + return opNames; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java new file mode 100644 index 0000000000..9a0b1b630f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerServiceImpl.java @@ -0,0 +1,150 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.task.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.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; +import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; +import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskManager; +import org.wso2.carbon.ntask.core.service.TaskService; + +import java.util.HashMap; +import java.util.Map; + +public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService { + + public static final String TASK_TYPE = "DEVICE_DETAILS"; + public static final String TASK_NAME = "DEVICE_DETAILS_TASK"; + public static final String TENANT_ID = "TENANT_ID"; + + private DeviceTaskManager deviceTaskManager; + + private static Log log = LogFactory.getLog(DeviceTaskManagerServiceImpl.class); + + @Override + public void startTask() throws DeviceMgtTaskException { + + deviceTaskManager = new DeviceTaskManagerImpl(); + if (!deviceTaskManager.isTaskEnabled()) { + throw new DeviceMgtTaskException("Task cannot be started, Please enable the task in cdm-config.xml file."); + } + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + taskService.registerTaskType(TASK_TYPE); + + if (log.isDebugEnabled()) { + log.debug("Device details retrieving task is started for the tenant id " + tenantId); + log.debug("Device details retrieving task is at frequency of : " + deviceTaskManager.getTaskFrequency()); + } + + TaskManager taskManager = taskService.getTaskManager(TASK_TYPE); + + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + triggerInfo.setIntervalMillis(deviceTaskManager.getTaskFrequency()); + triggerInfo.setRepeatCount(-1); + + Map properties = new HashMap<>(); + properties.put(TENANT_ID, String.valueOf(tenantId)); + + + if (!taskManager.isTaskScheduled(TASK_NAME)) { + + TaskInfo taskInfo = new TaskInfo(TASK_NAME, deviceTaskManager.getTaskImplementedClazz(), + properties, triggerInfo); + + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new DeviceMgtTaskException("Device details retrieving task is already started for this tenant " + + tenantId); + } + + } catch (TaskException e) { + throw new DeviceMgtTaskException("Error occurred while creating the task for tenant " + tenantId, e); + } + + } + + @Override + public void stopTask() throws DeviceMgtTaskException { + + try { + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + if (taskService.isServerInit()) { + TaskManager taskManager = taskService.getTaskManager(TASK_TYPE); + taskManager.deleteTask(TASK_NAME); + } + } catch (TaskException e) { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + throw new DeviceMgtTaskException("Error occurred while deleting the task for tenant " + tenantId, e); + } + + } + + @Override + public void updateTask(int frequency) throws DeviceMgtTaskException { + + if (!deviceTaskManager.isTaskEnabled()) { + throw new DeviceMgtTaskException("Task cannot be updated, Please enable the task in cdm-config.xml file."); + } + + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + deviceTaskManager = new DeviceTaskManagerImpl(); + try { + TaskService taskService = DeviceManagementDataHolder.getInstance().getTaskService(); + TaskManager taskManager = taskService.getTaskManager(TASK_TYPE); + + if (taskManager.isTaskScheduled(TASK_NAME)) { + + taskManager.deleteTask(TASK_NAME); + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); + triggerInfo.setIntervalMillis(frequency); + triggerInfo.setRepeatCount(-1); + + Map properties = new HashMap<>(); + properties.put(TENANT_ID, String.valueOf(tenantId)); + + TaskInfo taskInfo = new TaskInfo(TASK_NAME, deviceTaskManager.getTaskImplementedClazz(), properties, + triggerInfo); + + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + } else { + throw new DeviceMgtTaskException("Device details retrieving task has not been started for this tenant " + + tenantId + ". Please start the task first."); + } + + } catch (TaskException e) { + throw new DeviceMgtTaskException("Error occurred while updating the task for tenant " + tenantId, e); + } + + + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index b03e9d3350..dd68cf7a85 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -32,13 +32,21 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.ConfigurationContextService; +import org.wso2.carbon.utils.NetworkUtils; import javax.sql.DataSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; -import java.sql.SQLException; import java.util.*; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + public final class DeviceManagerUtil { @@ -178,4 +186,41 @@ public final class DeviceManagerUtil { return deviceIdentifiers; } + public static String getServerBaseHttpsUrl() { + String hostName = "localhost"; + try { + hostName = NetworkUtils.getMgtHostName(); + } catch (Exception ignored) { + } + String mgtConsoleTransport = CarbonUtils.getManagementTransport(); + ConfigurationContextService configContextService = + DeviceManagementDataHolder.getInstance().getConfigurationContextService(); + int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); + int httpsProxyPort = + CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), + mgtConsoleTransport); + if (httpsProxyPort > 0) { + port = httpsProxyPort; + } + return "https://" + hostName + ":" + port; + } + + public static String getServerBaseHttpUrl() { + String hostName = "localhost"; + try { + hostName = NetworkUtils.getMgtHostName(); + } catch (Exception ignored) { + } + ConfigurationContextService configContextService = + DeviceManagementDataHolder.getInstance().getConfigurationContextService(); + int port = CarbonUtils.getTransportPort(configContextService, "http"); + int httpProxyPort = + CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), + "http"); + if (httpProxyPort > 0) { + port = httpProxyPort; + } + return "http://" + hostName + ":" + port; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/DeviceDetails.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/DeviceDetails.java index 903b7ec40f..0160cde286 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/DeviceDetails.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/DeviceDetails.java @@ -17,8 +17,42 @@ */ -package org.wso2.carbon.device.mgt.core.Search; +package org.wso2.carbon.device.mgt.core.search; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.device.mgt.core.search.util.Utils; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; + +public class DeviceDetails extends BaseDeviceManagementTest { + + private static final Log log = LogFactory.getLog(DeviceDetails.class); + + @BeforeClass + @Override + public void init() throws Exception { + + DeviceManagementProviderService deviceManagementProviderService = new DeviceManagementProviderServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProviderService); + + } + + @Test + public void addDeviceDetails() throws Exception { + + log.debug("Adding the device details to database.....!"); + DeviceInformationManager deviceInformationManager = new DeviceInformationManagerImpl(); + deviceInformationManager.addDeviceInfo(Utils.getDeviceInfo()); + deviceInformationManager.addDeviceLocation(Utils.getSampleDeviceLocation()); + log.debug("Device details added to database.....!"); + } -public class DeviceDetails { } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java new file mode 100644 index 0000000000..63932998ff --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java @@ -0,0 +1,70 @@ +/* + * 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 org.wso2.carbon.device.mgt.core.search; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper; +import org.wso2.carbon.device.mgt.common.search.Condition; +import org.wso2.carbon.device.mgt.common.search.SearchContext; +import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; +import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; + +import java.util.ArrayList; +import java.util.List; + +public class SearchDevice extends BaseDeviceManagementTest { + + private static final Log log = LogFactory.getLog(DeviceDetails.class); + + @BeforeClass + @Override + public void init() throws Exception { + + } + + @Test + public void searchDeviceDetails() throws Exception { + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + Condition cond = new Condition(); + + cond.setKey("BATTERY_VOLTAGE"); + cond.setOperator("="); + cond.setValue("40"); + cond.setState(Condition.State.AND); + conditions.add(cond); + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java index 29b190c973..4a21cf9637 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java @@ -19,6 +19,88 @@ package org.wso2.carbon.device.mgt.core.search.util; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.core.common.TestDataHolder; + +import java.util.HashMap; +import java.util.Map; + public class Utils { + + public static DeviceInfo getDeviceInfo() { + + DeviceInfo deviceInfo = new DeviceInfo(); + + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(TestDataHolder.TEST_DEVICE_TYPE); + deviceIdentifier.setId("12345"); + + + deviceInfo.setDeviceIdentifier(deviceIdentifier); + + deviceInfo.setDeviceId(1); + deviceInfo.setIMSI("e6f236ac82537a8e"); + deviceInfo.setSsid("FAFDA"); + + + deviceInfo.setDeviceId(1); + deviceInfo.setAvailableRAMMemory(1.24); + deviceInfo.setBatteryLevel(27.3); + deviceInfo.setConnectionType("GSM"); + deviceInfo.setCpuUsage(82.34); + deviceInfo.setDeviceModel("SM-T520"); + deviceInfo.setExternalAvailableMemory(2.45); + deviceInfo.setExternalTotalMemory(16.23); + deviceInfo.setIMEI("e6f236ac82537a8e"); + deviceInfo.setIMSI("GT-0WDA"); + deviceInfo.setInternalAvailableMemory(3.56); + deviceInfo.setInternalTotalMemory(7.89); + deviceInfo.setMobileSignalStrength(0.67); + deviceInfo.setOperator("Dialog"); + deviceInfo.setOsVersion("Lolipop"); + deviceInfo.setPluggedIn(true); + deviceInfo.setSsid("SSSSSS"); + deviceInfo.setTotalRAMMemory(4.00); + deviceInfo.setVendor("SAMSUNG"); + + + Map propertyMap = new HashMap<>(); + + propertyMap.put("BATTERY_VOLTAGE", "40"); + propertyMap.put("BATTERY_HEALTH", "Good"); + propertyMap.put("BATTERY_STATUS", "SWElLED"); + propertyMap.put("LOW_MEMORY", "false"); + propertyMap.put("MEMORY_THRESHOLD", "100663296"); + propertyMap.put("CPU_IOW", "12"); + propertyMap.put("CPU_IRQ", "1"); + + deviceInfo.setDeviceDetailsMap(propertyMap); + + return deviceInfo; + } + + + public static DeviceLocation getSampleDeviceLocation(){ + + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(76.2422); + deviceLocation.setLongitude(81.43); + deviceLocation.setStreet1("4"); + deviceLocation.setStreet2("Isuru Uyana"); + deviceLocation.setCity("Karanadeniya"); + deviceLocation.setState("Karandeniya"); + deviceLocation.setZip("80360"); + deviceLocation.setCountry("Sri Lanka"); + deviceLocation.setDeviceId(1); + + return deviceLocation; + } } + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml index 750b8fffa8..8561fca040 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/datasource/data-source-config.xml @@ -22,4 +22,12 @@ org.h2.Driver wso2carbon wso2carbon + + + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index 0eaa54a00f..d172e2f5d2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -1,15 +1,22 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT AUTO_INCREMENT NOT NULL, - NAME VARCHAR(300) NULL DEFAULT NULL, + ID INT auto_increment NOT NULL, + NAME VARCHAR(300) DEFAULT NULL, PRIMARY KEY (ID) ); +CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( + ID INTEGER auto_increment NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, + PRIMARY KEY (ID) +); + CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, - DESCRIPTION TEXT NULL DEFAULT NULL, - NAME VARCHAR(100) NULL DEFAULT NULL, - DEVICE_TYPE_ID INT(11) NULL DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + NAME VARCHAR(100) DEFAULT NULL, + DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) @@ -21,13 +28,13 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION ( TYPE VARCHAR(50) NOT NULL, CREATED_TIMESTAMP TIMESTAMP NOT NULL, RECEIVED_TIMESTAMP TIMESTAMP NULL, - STATUS VARCHAR(50) NULL, OPERATION_CODE VARCHAR(1000) NOT NULL, PRIMARY KEY (ID) ); CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( OPERATION_ID INTEGER NOT NULL, + OPERATION_CONFIG BLOB DEFAULT NULL, PRIMARY KEY (OPERATION_ID), CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION @@ -41,6 +48,15 @@ CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( + OPERATION_ID INTEGER NOT NULL, + ENABLED INTEGER NOT NULL DEFAULT 0, + OPERATION_DETAILS BLOB DEFAULT NULL, + PRIMARY KEY (OPERATION_ID), + CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( OPERATION_ID INTEGER NOT NULL, ENABLED INTEGER NOT NULL DEFAULT 0, @@ -54,10 +70,10 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, OWNER VARCHAR(50) NOT NULL, - OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES @@ -76,17 +92,273 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( + ID INTEGER AUTO_INCREMENT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + OPERATION_RESPONSE BLOB DEFAULT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +-- POLICY RELATED TABLES -- + +CREATE TABLE IF NOT EXISTS DM_PROFILE ( + ID INT NOT NULL AUTO_INCREMENT , + PROFILE_NAME VARCHAR(45) NOT NULL , + TENANT_ID INT NOT NULL , + DEVICE_TYPE_ID INT NOT NULL , + CREATED_TIME DATETIME NOT NULL , + UPDATED_TIME DATETIME NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT DM_PROFILE_DEVICE_TYPE + FOREIGN KEY (DEVICE_TYPE_ID ) + REFERENCES DM_DEVICE_TYPE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + + + +CREATE TABLE IF NOT EXISTS DM_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT , + NAME VARCHAR(45) DEFAULT NULL , + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INT(11) NOT NULL , + PROFILE_ID INT(11) NOT NULL , + OWNERSHIP_TYPE VARCHAR(45) NULL, + COMPLIANCE VARCHAR(100) NULL, + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, + PRIMARY KEY (ID) , + CONSTRAINT FK_DM_PROFILE_DM_POLICY + FOREIGN KEY (PROFILE_ID ) + REFERENCES DM_PROFILE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT , + DEVICE_ID INT(11) NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, + DEVICE BLOB NOT NULL, + POLICY_ID INT(11) NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_POLICY_DEVICE_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DEVICE_DEVICE_POLICY + FOREIGN KEY (DEVICE_ID ) + REFERENCES DM_DEVICE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( + ID INT(11) NOT NULL , + DEVICE_TYPE_ID INT(11) NOT NULL , + POLICY_ID INT(11) NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_DEVICE_TYPE_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE + FOREIGN KEY (DEVICE_TYPE_ID ) + REFERENCES DM_DEVICE_TYPE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + + + +CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( + ID INT(11) NOT NULL AUTO_INCREMENT, + PROFILE_ID INT(11) NOT NULL, + FEATURE_CODE VARCHAR(30) NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL , + CONTENT BLOB NULL DEFAULT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES + FOREIGN KEY (PROFILE_ID) + REFERENCES DM_PROFILE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + + +CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT , + ROLE_NAME VARCHAR(45) NOT NULL , + POLICY_ID INT(11) NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_ROLE_POLICY_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + + +CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( + ID INT NOT NULL AUTO_INCREMENT , + POLICY_ID INT NOT NULL , + USERNAME VARCHAR(45) NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT DM_POLICY_USER_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL , + POLICY_CONTENT BLOB NULL , + TENANT_ID INT NOT NULL, + APPLIED TINYINT(1) NULL , + CREATED_TIME TIMESTAMP NULL , + UPDATED_TIME TIMESTAMP NULL , + APPLIED_TIME TIMESTAMP NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED + FOREIGN KEY (DEVICE_ID ) + REFERENCES DM_DEVICE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + +CREATE TABLE IF NOT EXISTS DM_CRITERIA ( + ID INT NOT NULL AUTO_INCREMENT, + TENANT_ID INT NOT NULL, + NAME VARCHAR(50) NULL, + PRIMARY KEY (ID) +); + + + +CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( + ID INT NOT NULL AUTO_INCREMENT, + CRITERIA_ID INT NOT NULL, + POLICY_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_CRITERIA_POLICY_CRITERIA + FOREIGN KEY (CRITERIA_ID) + REFERENCES DM_CRITERIA (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_POLICY_POLICY_CRITERIA + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_CRITERION_ID INT NOT NULL, + PROP_KEY VARCHAR(45) NULL, + PROP_VALUE VARCHAR(100) NULL, + CONTENT BLOB NULL COMMENT 'This is used to ', + PRIMARY KEY (ID), + CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES + FOREIGN KEY (POLICY_CRITERION_ID) + REFERENCES DM_POLICY_CRITERIA (ID) + ON DELETE CASCADE + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT NULL, + LAST_SUCCESS_TIME TIMESTAMP NULL, + LAST_REQUESTED_TIME TIMESTAMP NULL, + LAST_FAILED_TIME TIMESTAMP NULL, + ATTEMPTS INT NULL, + PRIMARY KEY (ID) +); + + +CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, + PRIMARY KEY (ID) +); + + +CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( + ID INT NOT NULL AUTO_INCREMENT, + COMPLIANCE_STATUS_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + FEATURE_CODE VARCHAR(15) NOT NULL, + STATUS INT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS + FOREIGN KEY (COMPLIANCE_STATUS_ID) + REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); CREATE TABLE IF NOT EXISTS DM_APPLICATION ( ID INTEGER AUTO_INCREMENT NOT NULL, - NAME VARCHAR(50) NOT NULL, - APP_IDENTIFIER VARCHAR(50) NOT NULL, - PLATFORM VARCHAR(50) NULL DEFAULT NULL, + NAME VARCHAR(150) NOT NULL, + APP_IDENTIFIER VARCHAR(150) NOT NULL, + PLATFORM VARCHAR(50) DEFAULT NULL, CATEGORY VARCHAR(50) NULL, VERSION VARCHAR(50) NULL, TYPE VARCHAR(50) NULL, - LOCATION_URL VARCHAR(100) NULL DEFAULT NULL, - IMAGE_URL VARCHAR(100) NULL DEFAULT NULL, + LOCATION_URL VARCHAR(100) DEFAULT NULL, + IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) @@ -104,3 +376,88 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +-- POLICY RELATED TABLES FINISHED -- + +-- NOTIFICATION TABLE -- +CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( + NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(100) NULL, + PRIMARY KEY (NOTIFICATION_ID), + CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); +-- NOTIFICATION TABLE END -- + +DROP TABLE IF EXISTS DM_DEVICE_INFO; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_DEVICE_INFO_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_DEVICE_LOCATION_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + IMEI VARCHAR(100) NULL, + IMSI VARCHAR(100) NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + OPERATOR VARCHAR(45) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(5) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + PLUGGED_IN INT(1) NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml index 4da53d1247..5195f7e39c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml @@ -23,6 +23,7 @@ + @@ -30,6 +31,8 @@ + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java index fb777f6176..0c5b6707ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/license/mgt/registry/RegistryBasedLicenseManager.java @@ -44,7 +44,6 @@ import java.util.Locale; @SuppressWarnings("unused") public class RegistryBasedLicenseManager implements LicenseManager { - private Registry registry; private GenericArtifactManager artifactManager; private static final Log log = LogFactory.getLog(RegistryBasedLicenseManager.class); @@ -54,7 +53,6 @@ public class RegistryBasedLicenseManager implements LicenseManager { throw new IllegalArgumentException("Registry instance retrieved is null. Hence, " + "'Registry based license manager cannot be initialized'"); } - this.registry = registry; try { this.artifactManager = GenericArtifactManagerFactory.getTenantAwareGovernanceArtifactManager(registry); } catch (LicenseManagementException e) { diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml b/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml new file mode 100644 index 0000000000..910238f0ec --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/pom.xml @@ -0,0 +1,159 @@ + + + + + + org.wso2.carbon.devicemgt + email-sender + 1.0.4-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.devicemgt + org.wso2.carbon.email.sender.core + 1.0.4-SNAPSHOT + bundle + WSO2 Carbon - Email Sender Core + WSO2 Carbon - Email Sender Core + http://wso2.org + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + Email Management Core Bundle + org.wso2.carbon.email.sender.core.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.*, + org.wso2.carbon.context, + org.wso2.carbon.utils.*, + org.wso2.carbon.registry.api, + org.w3c.dom, + org.apache.velocity, + org.apache.velocity.app, + org.apache.velocity.context, + org.apache.velocity.exception, + org.apache.velocity.runtime.resource, + org.apache.velocity.runtime.resource.loader, + 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.email.sender.core.internal, + org.wso2.carbon.email.sender.core.* + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18 + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + + + + + + + + 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.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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/ContentProcessingInterruptedException.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/ContentProcessingInterruptedException.java new file mode 100644 index 0000000000..db54398a46 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/ContentProviderInfo.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/ContentProviderInfo.java new file mode 100644 index 0000000000..534f3f963d --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailContentProvider.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailContentProvider.java new file mode 100644 index 0000000000..2f3ce81e54 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +import java.util.Map; + +public interface EmailContentProvider { + + EmailData getContent(String path, + Map, Object>> params) throws ContentProcessingInterruptedException; + +} diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailContentProviderFactory.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailContentProviderFactory.java new file mode 100644 index 0000000000..c9e13cf4d5 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +public class EmailContentProviderFactory { + + public static EmailContentProvider getContentProvider() { + return new VelocityBasedEmailContentProvider(); + } + +} diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailContext.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailContext.java new file mode 100644 index 0000000000..d6faede2f1 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailData.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailData.java new file mode 100644 index 0000000000..128d400a57 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderConfig.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderConfig.java new file mode 100644 index 0000000000..5c2104fb89 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderConfigurationFailedException.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderConfigurationFailedException.java new file mode 100644 index 0000000000..448ed2b64e --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.java new file mode 100644 index 0000000000..c1f03a02bc --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSenderUtil.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 org.wso2.carbon.email.sender.core; + +import org.w3c.dom.Document; +import org.wso2.carbon.email.sender.core.internal.EmailSenderDataHolder; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.ConfigurationContextService; +import org.wso2.carbon.utils.NetworkUtils; + +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 { + 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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSendingFailedException.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/EmailSendingFailedException.java new file mode 100644 index 0000000000..1f9fd9bef1 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/InvalidConfigurationStateException.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/InvalidConfigurationStateException.java new file mode 100644 index 0000000000..606503acfb --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/RegistryBasedResourceLoader.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/RegistryBasedResourceLoader.java new file mode 100644 index 0000000000..7ba350e07c --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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.*; + +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 + ".vm")) { + throw new ResourceNotFoundException("Resource '" + name + "' does not exist"); + } + org.wso2.carbon.registry.api.Resource resource = + registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name + ".vm"); + + 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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/TypedValue.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/TypedValue.java new file mode 100644 index 0000000000..616ff44188 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/VelocityBasedEmailContentProvider.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/VelocityBasedEmailContentProvider.java new file mode 100644 index 0000000000..156dc4dae6 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core; + +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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java new file mode 100644 index 0000000000..19a7349596 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderAxis2ConfigContextObserver.java @@ -0,0 +1,111 @@ +/* + * 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 org.wso2.carbon.email.sender.core.internal; + +import org.apache.axis2.context.ConfigurationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.RegistryType; +import org.wso2.carbon.email.sender.core.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.Axis2ConfigurationContextObserver; +import org.wso2.carbon.utils.CarbonUtils; + +import java.io.File; +import java.io.FilenameFilter; + +public class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver { + + private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "email-templates"; + private static final Log log = LogFactory.getLog(EmailSenderAxis2ConfigContextObserver.class); + + @Override + public void creatingConfigurationContext(int tenantId) { + + } + + @Override + public void createdConfigurationContext(ConfigurationContext configurationContext) { + try { + this.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) { + + } + + private void setupEmailTemplates() throws EmailSenderConfigurationFailedException { + File templateDir = + new File(CarbonUtils.getCarbonRepository() + "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 { + Registry registry = + CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION); + 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.setContent(template); + registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource); + } + } else { + for (File template : templates) { + if (!registry.resourceExists( + EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName())) { + Resource resource = registry.newResource(); + resource.setContent(template); + registry.put( + EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource); + } + } + } + } catch (RegistryException e) { + throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e); + } + } + } + +} diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderDataHolder.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderDataHolder.java new file mode 100644 index 0000000000..fa7c4ee451 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/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 org.wso2.carbon.email.sender.core.internal; + +import org.wso2.carbon.email.sender.core.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/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderServiceComponent.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderServiceComponent.java new file mode 100644 index 0000000000..b166c5861b --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/internal/EmailSenderServiceComponent.java @@ -0,0 +1,195 @@ +/* + * 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 org.wso2.carbon.email.sender.core.internal; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.email.sender.core.EmailSenderConfig; +import org.wso2.carbon.email.sender.core.EmailSenderConfigurationFailedException; +import org.wso2.carbon.email.sender.core.service.EmailSenderService; +import org.wso2.carbon.email.sender.core.service.EmailSenderServiceImpl; +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.registry.core.service.RegistryService; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.ConfigurationContextService; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.io.IOException; + +/** + * @scr.component name="org.wso2.carbon.email.sender.EmailSenderServiceComponent" 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); + + private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "/email-templates"; + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + try { + if (log.isDebugEnabled()) { + log.debug("Initializing email sender core bundle"); + } + /* Initializing email sende configuration */ + EmailSenderConfig.init(); + + /* Setting up default email templates */ + this.setupEmailTemplates(); + + /* Registering declarative service instances exposed by EmailSenderServiceComponent */ + this.registerServices(componentContext); + + 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 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); + } + + private 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 { + Registry registry = + EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(); + 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(); + String contents = FileUtils.readFileToString(template); + resource.setContent(contents.getBytes()); + registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), resource); + } + } else { + /* Existence of a given resource is not checked consciously, before performing registry.put() below. + * The rationale is that, the only less expensive way that one can check if a resource exists is + * that through registry.resourceExists(), which only checks if 'some' resource exists at the given + * registry path. However, this does not capture scenarios where there can be updated contents to + * the same resource of which the path hasn't changed after it has been initialized for the first + * time. Therefore, whenever the server starts-up, all email templates are updated just to avoid + * the aforementioned problem */ + for (File template : templates) { + Resource resource = registry.newResource(); + String contents = FileUtils.readFileToString(template); + resource.setContent(contents.getBytes()); + registry.put( + EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/" + template.getName(), 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); + } + } + } + + /** + * 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/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailService.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/service/EmailSenderService.java similarity index 67% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailService.java rename to components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/service/EmailSenderService.java index 2fb995ecc8..8bde6c3bdf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/EmailService.java +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/service/EmailSenderService.java @@ -15,13 +15,13 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.core.service; +package org.wso2.carbon.email.sender.core.service; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.EmailMessageProperties; +import org.wso2.carbon.email.sender.core.EmailContext; +import org.wso2.carbon.email.sender.core.EmailSendingFailedException; -public interface EmailService { +public interface EmailSenderService { - public void sendEmail(EmailMessageProperties emailMessageProperties) throws DeviceManagementException; + void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException; } diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/service/EmailSenderServiceImpl.java b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/service/EmailSenderServiceImpl.java new file mode 100644 index 0000000000..393350445f --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/main/java/org/wso2/carbon/email/sender/core/service/EmailSenderServiceImpl.java @@ -0,0 +1,129 @@ +/* + * 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 org.wso2.carbon.email.sender.core.service; + +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.email.sender.core.internal.EmailSenderDataHolder; +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; + + 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(); + } + + @Override + public void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException { + for (String recipient : emailCtx.getRecipients()) { + ContentProviderInfo info = emailCtx.getContentProviderInfo(); + EmailData emailData; + try { + emailData = contentProvider.getContent(info.getTemplate(), info.getParams()); + } catch (ContentProcessingInterruptedException e) { + throw new EmailSendingFailedException("Error occurred while retrieving email content to be " + + "sent for recipient '" + recipient + "'", e); + } + threadPoolExecutor.submit(new EmailSender(recipient, emailData.getSubject(), emailData.getBody())); + } + } + + 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, "text/html"); + 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/email-sender/org.wso2.carbon.email.sender.core/src/test/resources/log4j.properties b/components/email-sender/org.wso2.carbon.email.sender.core/src/test/resources/log4j.properties new file mode 100644 index 0000000000..dc3d465fc0 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/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/email-sender/org.wso2.carbon.email.sender.core/src/test/resources/testng.xml b/components/email-sender/org.wso2.carbon.email.sender.core/src/test/resources/testng.xml new file mode 100644 index 0000000000..7b13a25f89 --- /dev/null +++ b/components/email-sender/org.wso2.carbon.email.sender.core/src/test/resources/testng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + diff --git a/components/email-sender/org.wso2.carbon.email.sender.core/velocity.log b/components/email-sender/org.wso2.carbon.email.sender.core/velocity.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/components/email-sender/pom.xml b/components/email-sender/pom.xml new file mode 100644 index 0000000000..b1cbb67385 --- /dev/null +++ b/components/email-sender/pom.xml @@ -0,0 +1,60 @@ + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 1.0.4-SNAPSHOT + ../../pom.xml + + + 4.0.0 + org.wso2.carbon.devicemgt + email-sender + 1.0.4-SNAPSHOT + pom + WSO2 Carbon - Email Sender Component + http://wso2.org + + + org.wso2.carbon.email.sender.core + + + + + + + org.apache.felix + maven-scr-plugin + 1.7.2 + + + generate-scr-scrdescriptor + + scr + + + + + + + + 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 63b3a666c7..3ecbab54c3 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 @@ -24,31 +24,93 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import java.util.List; +/** + * This interface for manage caching for policies. This is using the cache implementation comes in kernel, which will + * automatically sync with the cluster. So all the nodes will receive the updated policies. + */ public interface PolicyCacheManager { + /** + * This method add policies to cache. + * @param policies - List of policies + */ void addAllPolicies(List policies); + /** + * This method will update the policies in the cache. + * @param policies - List of policies + */ void updateAllPolicies(List policies); + /** + * This method will return the all policies. + * @return - list of policies + * @throws PolicyManagementException + */ List getAllPolicies() throws PolicyManagementException; + /** + * This method will repopulate the cache, this will be called when there is a change of the policies. + * @throws PolicyManagementException + */ void rePopulateCache() throws PolicyManagementException; + /** + * This will remove all the policies from the cache. + */ void removeAllPolicies(); + /** + * This method will the policy to the cache. + * @param policy - policy to add + */ void addPolicy(Policy policy); + /** + * This method will update the policy in the cache. + * @param policy - policy to be updated. + */ void updatePolicy(Policy policy); + /** + * This method will update the policy by reading the cache. If it is not available it will read from policy manager. + * @param policyId - integer, policy id. + * @throws PolicyManagementException + */ void updatePolicy(int policyId) throws PolicyManagementException; + /** + * Remove policy from the cache. + * @param policyId - Id of the policy to be removed. + */ void removePolicy(int policyId); + /** + * This will return the policy from cache. If it not available in the cache, it will get from the policy manager. + * @param policyId - Id of the policy to be returned. + * @return - Policy + * @throws PolicyManagementException + */ Policy getPolicy(int policyId) throws PolicyManagementException; + /** + * This method will add a policy id against a device id. + * @param deviceId - Id of the device. + * @param policyId - Id of the policy + */ void addPolicyToDevice(int deviceId, int policyId); + /** + * This method will return the device ids, a certain policy is applied. + * @param policyId - Id of the policu. + * @return - List of device ids. + */ List getPolicyAppliedDeviceIds(int policyId); + /** + * This method will return the applied policy id of the device. + * @param deviceId - Id of the device + * @return - Id of the policy. + */ int getPolicyIdOfDevice(int deviceId); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java index c7fb6a3251..b8c72b619a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -101,6 +101,20 @@ public class PolicyManagementServiceComponent { } } + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { + try { + PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getDeviceManagementConfigRepository().getPolicyConfiguration(); + if (policyConfiguration.getMonitoringEnable()) { + TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl(); + taskScheduleService.stopTask(); + } + } catch (Throwable t) { + log.error("Error occurred while destroying the Policy management core.", t); + } + } + /** * Sets Realm Service diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java index a41edcf6ec..04fac4505c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java @@ -103,8 +103,10 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { try { String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); - taskManager.deleteTask(taskName); + if (taskService.isServerInit()) { + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); + taskManager.deleteTask(taskName); + } } catch (TaskException e) { throw new PolicyMonitoringTaskException("Error occurred while deleting the task for tenant " + tenantId, e); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml index fec4d783f6..3b8968bb27 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/pom.xml @@ -115,6 +115,7 @@ org.wso2.carbon.core.server:${carbon.kernel.version} org.wso2.carbon.apimgt.core:${carbon.api.mgt.version} org.wso2.carbon.device.mgt.extensions:${carbon.device.mgt.version} + org.wso2.carbon.email.sender:${carbon.device.mgt.version} diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml index a05f7c09cd..8bee53c0bb 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml @@ -24,14 +24,6 @@ jdbc/DM_DS - - 8 - 100 - 20 - 1000 - https://localhost:9443 - /emm-web-agent/enrollment - https://localhost:9443 admin diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/notification-messages.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/notification-messages.xml deleted file mode 100644 index eabecf785b..0000000000 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/notification-messages.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - Enroll your Device with WSO2 MDM -
Dear {first-name},
- - You have been registered to the WSO2 MDM. Below is the link to enroll. - - {downloadUrl} - - Best Regards, - - - WSO2 MDM Team. - - - http://www.wso2.com - -
- - Enroll your Device with WSO2 MDM -
Dear {first-name},
- -You have been registered to WSO2 MDM with following credentials. -Domain: {domain-name} -Username: {user-name} -Password: {password} -Below is the link to enroll. - - {downloadUrl} - - Best Regards, - - - WSO2 MDM Team. - - - http://www.wso2.com - -
-
\ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 87e8b13527..d172e2f5d2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -394,3 +394,70 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( ); -- NOTIFICATION TABLE END -- +DROP TABLE IF EXISTS DM_DEVICE_INFO; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_DEVICE_INFO_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_DEVICE_LOCATION_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + IMEI VARCHAR(100) NULL, + IMSI VARCHAR(100) NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + OPERATOR VARCHAR(45) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(5) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + PLUGGED_IN INT(1) NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index b2f954f69e..bb55d05862 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -382,3 +382,78 @@ CREATE TABLE DM_NOTIFICATION ( DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- NOTIFICATION TABLE END -- + + +DROP TABLE IF EXISTS DM_DEVICE_INFO; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, + PRIMARY KEY (ID), + INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC), + CONSTRAINT DM_DEVICE_INFO_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, + PRIMARY KEY (ID), + INDEX DM_DEVICE_LOCATION_DEVICE_idx (DEVICE_ID ASC), + CONSTRAINT DM_DEVICE_LOCATION_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +DROP TABLE IF EXISTS DM_DEVICE_DETAIL ; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + IMEI VARCHAR(100) NULL, + IMSI VARCHAR(100) NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + OPERATOR VARCHAR(45) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(5) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + PLUGGED_IN INT(1) NULL, + PRIMARY KEY (ID), + INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx (DEVICE_ID ASC), + CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 2c0fa84624..545f939108 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -393,3 +393,80 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( -- END NOTIFICATION TABLES -- + +DROP TABLE IF EXISTS DM_DEVICE_INFO; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, + PRIMARY KEY (ID), + INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC), + CONSTRAINT DM_DEVICE_INFO_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +) +ENGINE = InnoDB; + + + +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, + PRIMARY KEY (ID), + INDEX DM_DEVICE_LOCATION_DEVICE_idx (DEVICE_ID ASC), + CONSTRAINT DM_DEVICE_LOCATION_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +) +ENGINE = InnoDB; + + + +DROP TABLE IF EXISTS DM_DEVICE_DETAIL ; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + IMEI VARCHAR(100) NULL, + IMSI VARCHAR(100) NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(5) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(5) NULL, + OPERATOR VARCHAR(45) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + MOBILE_SIGNAL_STRENGTH DECIMAL(5) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(5) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(5) NULL, + PLUGGED_IN INT(1) NULL, + PRIMARY KEY (ID), + INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx (DEVICE_ID ASC), + CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION) +ENGINE = InnoDB; + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/email/templates/user-enrollment.vm b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/email/templates/user-enrollment.vm new file mode 100644 index 0000000000..25b3b26a0c --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/email/templates/user-enrollment.vm @@ -0,0 +1,72 @@ +#* + 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. +*# + + You have been invited to enroll your device in WSO2 EMM + + + + WSO2 Enterprise Mobility Manager + + +
+
+
+
+ WSO2 +
+
+
+

+ Hi $first-name, +

+ +

+ You have been invited to enrol your device in WSO2 Enterprise Mobility Manager. + Click here to download the WSO2 EMM client application to begin device + enrolment.

+ +

+ Should you need assistance, please contact your administrator. +

+ +

+ Regards, +

+ +

+ WSO2 EMM Administrator +

+
+
+ + + + +
WSO2
+
+
+
+ + + ]]> + +
diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/email/templates/user-registration.vm b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/email/templates/user-registration.vm new file mode 100644 index 0000000000..56e95625e0 --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/email/templates/user-registration.vm @@ -0,0 +1,82 @@ +#* + 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. +*# + + You have successfully been registered in WSO2 EMM + + + + WSO2 Enterprise Mobility Manager + + +
+
+
+
+ WSO2 +
+
+
+

+ Hi $first-name, +

+ +

+ You have been registered in WSO2 Enterprise Mobility Manager and invited to enrol your device. + Click here to download the WSO2 EMM client application to begin device + enrolment.

+ +

+ Use following credentials to log in to WSO2 EMM client application. +

+ +

+ Username: $username +
+ Password: $password +

+ +

+ Should you need assistance, please contact your administrator. +

+ +

+ Regards, +

+ +

+ WSO2 EMM Administrator +

+
+
+ + + + +
WSO2
+
+
+
+ + + ]]> + +
diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/p2.inf index 3d7d4ba5b6..63d198338f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/p2.inf @@ -1,7 +1,7 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/cdm-config.xml,target:${installFolder}/../../conf/cdm-config.xml,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/notification-messages.xml,target:${installFolder}/../../conf/notification-messages.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/license-config.xml,target:${installFolder}/../../conf/etc/license-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/conf/remote-appmanager-config.xml,target:${installFolder}/../../conf/etc/remote-appmanager-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/dbscripts/cdm,target:${installFolder}/../../../dbscripts/cdm,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/rxts/license.rxt,target:${installFolder}/../../../repository/resources/rxts/license.rxt,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/rxts/license.rxt,target:${installFolder}/../../../repository/resources/rxts/license.rxt,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.server_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ \ No newline at end of file diff --git a/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml b/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml new file mode 100644 index 0000000000..d368589daf --- /dev/null +++ b/features/email-sender/org.wso2.carbon.email.sender.feature/pom.xml @@ -0,0 +1,107 @@ + + + + + + + org.wso2.carbon.devicemgt + email-sender-feature + 1.0.4-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.email.sender.feature + pom + 1.0.4-SNAPSHOT + WSO2 Carbon - Email Sender Feature + http://wso2.org + This feature contains the core bundles required for email sender related functionality + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.email.sender.core + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + org.wso2.maven + carbon-p2-plugin + ${carbon.p2.plugin.version} + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.carbon.email.sender + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:false + + + + + org.wso2.carbon.devicemgt:org.wso2.carbon.email.sender.core:${carbon.device.mgt.version} + + + + org.wso2.carbon.core.server:${carbon.kernel.version} + + + + + + + + diff --git a/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/build.properties b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..9c86577d76 --- /dev/null +++ b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/build.properties @@ -0,0 +1 @@ +custom = true diff --git a/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/conf/email-sender-config.xml b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/conf/email-sender-config.xml new file mode 100644 index 0000000000..996cfacc2c --- /dev/null +++ b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/conf/email-sender-config.xml @@ -0,0 +1,30 @@ + + + + + 8 + + 100 + + 20 + + 1000 + + + diff --git a/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/email/templates/default.vm b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/email/templates/default.vm new file mode 100644 index 0000000000..25e3f880ca --- /dev/null +++ b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/email/templates/default.vm @@ -0,0 +1,34 @@ +#* + 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. +*# + + Hi There! + + + + Default Email Sender Template + + +
+ This template has to be customized to fit into any target context +
+ + + ]]> + +
diff --git a/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf new file mode 100644 index 0000000000..d4dadf6a1e --- /dev/null +++ b/features/email-sender/org.wso2.carbon.email.sender.feature/src/main/resources/p2.inf @@ -0,0 +1,3 @@ +instructions.configure = \ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.email.sender_${feature.version}/conf/email-sender-config.xml,target:${installFolder}/../../conf/etc/email-sender-config.xml,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.email.sender_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ \ No newline at end of file diff --git a/features/email-sender/pom.xml b/features/email-sender/pom.xml new file mode 100644 index 0000000000..c404dced59 --- /dev/null +++ b/features/email-sender/pom.xml @@ -0,0 +1,41 @@ + + + + + + + org.wso2.carbon.devicemgt + carbon-devicemgt + 1.0.4-SNAPSHOT + ../../pom.xml + + + 4.0.0 + org.wso2.carbon.devicemgt + email-sender-feature + 1.0.4-SNAPSHOT + pom + WSO2 Carbon - Email Sender Feature + http://wso2.org + + + org.wso2.carbon.email.sender.feature + + + diff --git a/pom.xml b/pom.xml index 096e604193..49634a1dd4 100644 --- a/pom.xml +++ b/pom.xml @@ -41,6 +41,7 @@ components/certificate-mgt components/webapp-authenticator-framework components/identity-extensions + components/email-sender features/device-mgt features/apimgt-extensions features/policy-mgt @@ -48,6 +49,7 @@ features/certificate-mgt features/dynamic-client-registration features/oauth-extensions + features/email-sender @@ -251,6 +253,11 @@ org.wso2.carbon.identity.authenticator.backend.oauth ${carbon.device.mgt.version} + + org.wso2.carbon.devicemgt + org.wso2.carbon.email.sender.core + ${carbon.device.mgt.version} + @@ -1225,12 +1232,6 @@ ${version.commons.codec} - - commons-io.wso2 - commons-io - ${version.commons.io} - - commons-lang.wso2 commons-lang @@ -1278,6 +1279,30 @@ commons-httpclient ${commons.httpclient.version} + + org.apache.velocity + velocity + ${velocity.version} + + + commons-io.wso2 + commons-io + ${commons-io.version} + + + commons-collections.wso2 + commons-collections + ${commons-collections.version} + + + + + + mysql + mysql-connector-java + ${tomcat.version} + test + @@ -1395,6 +1420,11 @@ maven-surefire-plugin 2.18 + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + @@ -1581,7 +1611,12 @@ 1.5.6.wso2v1 4.2.3.wso2v1 3.1.0.wso2v2 + 1.7 + 2.4.0.wso2v1 + 3.2.0.wso2v1 + + 5.1.34