Defining interfaces and other adjustments

revert-70ac1926
Ace 4 years ago
parent eadc1a1992
commit 7b28665135

@ -0,0 +1,10 @@
package org.wso2.carbon.device.mgt.common.dynamic.task.allocation;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.ntask.core.Task;
import java.util.List;
public abstract class DynamicPartitionedScheduleTask implements Task {
}

@ -325,6 +325,18 @@ public interface DeviceDAO {
*/
List<Device> getDevices(String type, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the list of devices attributed to a specific node
* when using dynamic partitioning to allocate tasks given the tenant and device type
* along with activeServerCount and serverIndex
*
* @param type device type.
* @param tenantId tenant id.
* @return returns list of devices of provided type.
* @throws DeviceManagementDAOException
*/
List<Device> getDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException;
List<Device> getDevices(long timestamp, int tenantId) throws DeviceManagementDAOException;
/**

@ -800,6 +800,65 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
return devices;
}
@Override
public List<Device> getDevices(String type, int tenantId, int activeServerCount, int serverIndex) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null;
try {
conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID," +
" d1.DESCRIPTION," +
" d1.NAME AS DEVICE_NAME," +
" d1.DEVICE_TYPE," +
" d1.DEVICE_IDENTIFICATION," +
" e.OWNER," +
" e.OWNERSHIP," +
" e.STATUS," +
" e.IS_TRANSFERRED," +
" e.DATE_OF_LAST_UPDATE," +
" e.DATE_OF_ENROLMENT," +
" e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e," +
" (SELECT d.ID," +
" d.DESCRIPTION," +
" d.NAME," +
" d.DEVICE_IDENTIFICATION," +
" t.NAME AS DEVICE_TYPE" +
" FROM DM_DEVICE d, DM_DEVICE_TYPE t" +
" WHERE DEVICE_TYPE_ID = t.ID" +
" AND t.NAME = ?" +
" AND t.ID = d.DEVICE_TYPE_ID" +
" AND d.TENANT_ID = ?) d1" +
"WHERE d1.ID = e.DEVICE_ID" +
" AND TENANT_ID = ?" +
" AND MOD(d1.ID, 3) = 2" +
"ORDER BY e.DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql);
stmt.setString(1, type);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
stmt.setInt(4, activeServerCount);
stmt.setInt(5, serverIndex);
rs = stmt.executeQuery();
devices = new ArrayList<>();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadActiveDevice(rs, false);
if (device != null) {
devices.add(device);
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while listing devices for type '" + type + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return devices;
}
@Override
public List<Device> getDevicesOfUser(String username, int tenantId) throws DeviceManagementDAOException {
Connection conn;

@ -107,6 +107,17 @@ public interface DeviceManagementProviderService {
*/
List<Device> getAllDevices(String deviceType, boolean requireDeviceInfo) throws DeviceManagementException;
/**
* Method returns a list of devices allocated to a specific node of the server, given the serverIndex and active server count
* @param deviceType
* @param activeServerCount
* @param serverIndex
* @return
* @throws DeviceManagementException
*/
List<Device> getAllocatedDevices(String deviceType, int activeServerCount, int serverIndex) throws DeviceManagementException;
/**
* Method to retrieve all the devices registered in the system.
*

@ -765,6 +765,46 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return allDevices;
}
@Override
public List<Device> getAllocatedDevices(String deviceType, int activeServerCount, int serverIndex) throws DeviceManagementException {
if (deviceType == null) {
String msg = "Device type is empty for method getAllDevices";
log.error(msg);
throw new DeviceManagementException(msg);
}
if (log.isDebugEnabled()) {
log.debug("Getting allocated Devices for Server with index "+ serverIndex + " and" +
" type '" + deviceType);
}
List<Device> allocatedDevices;
try {
DeviceManagementDAOFactory.openConnection();
allocatedDevices = deviceDAO.getDevices(deviceType, this.getTenantId(), activeServerCount, serverIndex);
if (allocatedDevices == null) {
if (log.isDebugEnabled()) {
log.debug("No device is found upon the type '" + deviceType + "'");
}
return null;
}
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving all devices of type '" +
deviceType + "' that are being managed within the scope of current tenant";
log.error(msg);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred while getting all devices of device type '" + deviceType + "'";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return allocatedDevices;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
return this.getAllDevices(true);

@ -1,180 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>task-allocation</artifactId>
<version>4.1.11-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.dynamic.task.allocation.framework</artifactId>
<packaging>bundle</packaging>
<name>Entgra - Task Allocation Framework</name>
<description>Entgra - Framework for partitioning tasks evenly amongst multiple nodes</description>
<url>http://entgra.io</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>Entgra - Task Allocation Framework Bundle</Bundle-Description>
<Private-Package>io.entgra.dynamic.task.allocation.framework.internal</Private-Package>
<Import-Package>
org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.apache.axiom.*; version="${axiom.osgi.version.range}",
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
org.wso2.carbon.context,
org.wso2.carbon.utils.*,
org.wso2.carbon.registry.api,
org.w3c.dom,
org.apache.velocity;version="${velocity.version}",
org.apache.velocity.app;version="${velocity.version}",
org.apache.velocity.context;version="${velocity.version}",
org.apache.velocity.exception;version="${velocity.version}",
org.apache.velocity.runtime.resource;version="${velocity.version}",
org.apache.velocity.runtime.resource.loader;version="${velocity.version}",
org.apache.commons.io,
org.apache.axis2.transport.mail,
org.wso2.carbon.registry.core.service,
org.wso2.carbon.registry.core.session,
org.apache.commons.collections
</Import-Package>
<Export-Package>
!io.entgra.dynamic.task.allocation.framework.internal,
io.entgra.dynamic.task.allocation.framework.*
</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<log4j.configuration>file:src/test/resources/log4j.properties</log4j.configuration>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<dependency>
<groupId>commons-io.wso2</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.transport</groupId>
<artifactId>axis2-transport-mail</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<dependency>
<groupId>commons-collections.wso2</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
</dependencies>
</project>

@ -1,45 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
public class ContentProcessingInterruptedException extends Exception {
private static final long serialVersionUID = -3151279311929070298L;
public ContentProcessingInterruptedException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public ContentProcessingInterruptedException(String message, Throwable cause) {
super(message, cause);
}
public ContentProcessingInterruptedException(String msg) {
super(msg);
}
public ContentProcessingInterruptedException() {
super();
}
public ContentProcessingInterruptedException(Throwable cause) {
super(cause);
}
}

@ -1,55 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import java.util.Map;
public class ContentProviderInfo {
private String template;
private Map<String, TypedValue<Class<?>, Object>> params;
public ContentProviderInfo(final String template, final Map<String, TypedValue<Class<?>, 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<String, TypedValue<Class<?>, Object>> getParams() {
return params;
}
public void addParam(String name, TypedValue<Class<?>, Object> param) {
params.put(name, param);
}
public TypedValue<Class<?>, Object> getParam(String name) {
return params.get(name);
}
}

@ -1,28 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import java.util.Map;
public interface EmailContentProvider {
EmailData getContent(String path,
Map<String, TypedValue<Class<?>, Object>> params) throws ContentProcessingInterruptedException;
}

@ -1,27 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
public class EmailContentProviderFactory {
public static EmailContentProvider getContentProvider() {
return new VelocityBasedEmailContentProvider();
}
}

@ -1,138 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import java.util.*;
public class EmailContext {
private Set<String> recipients;
private Properties properties;
private ContentProviderInfo contentProviderInfo;
private EmailContext(final ContentProviderInfo contentProviderInfo, final Set<String> 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<String>() {{
add(recipient);
}};
if (properties == null) {
throw new IllegalArgumentException("Email Context property bag cannot be null");
}
this.properties = properties;
}
public Set<String> 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<String> recipients;
private ContentProviderInfo contentProviderInfo;
private Properties properties;
public EmailContextBuilder(final ContentProviderInfo contentProviderInfo, Set<String> 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<String>() {{
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);
}
}
}

@ -1,48 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "EmailConfig")
public class EmailData {
private String subject;
private String body;
@XmlElement(name = "Subject", required = true)
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@XmlElement(name = "Body", required = true)
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}

@ -1,106 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import org.w3c.dom.Document;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
@XmlRootElement(name = "EmailSenderConfig")
public class EmailSenderConfig {
private int minThreads;
private int maxThreads;
private int keepAliveDuration;
private int threadQueueCapacity;
private static EmailSenderConfig config;
private static final String EMAIL_SENDER_CONFIG_PATH =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "email-sender-config.xml";
private EmailSenderConfig() {
}
public static EmailSenderConfig getInstance() {
if (config == null) {
throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " +
"initialized properly");
}
return config;
}
@XmlElement(name = "MinThreads", required = true)
public int getMinThreads() {
return minThreads;
}
public void setMinThreads(int minThreads) {
this.minThreads = minThreads;
}
@XmlElement(name = "MaxThreads", required = true)
public int getMaxThreads() {
return maxThreads;
}
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
@XmlElement(name = "KeepAliveDuration", required = true)
public int getKeepAliveDuration() {
return keepAliveDuration;
}
public void setKeepAliveDuration(int keepAliveDuration) {
this.keepAliveDuration = keepAliveDuration;
}
@XmlElement(name = "ThreadQueueCapacity", required = true)
public int getThreadQueueCapacity() {
return threadQueueCapacity;
}
public void setThreadQueueCapacity(int threadQueueCapacity) {
this.threadQueueCapacity = threadQueueCapacity;
}
public static void init() throws EmailSenderConfigurationFailedException {
try {
File emailSenderConfig = new File(EMAIL_SENDER_CONFIG_PATH);
Document doc = EmailSenderUtil.convertToDocument(emailSenderConfig);
/* Un-marshaling Email Sender configuration */
JAXBContext ctx = JAXBContext.newInstance(EmailSenderConfig.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
//unmarshaller.setSchema(getSchema());
config = (EmailSenderConfig) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while un-marshalling Email " +
"Sender Config", e);
}
}
}

@ -1,45 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
public class EmailSenderConfigurationFailedException extends Exception {
private static final long serialVersionUID = -3151279312929070298L;
public EmailSenderConfigurationFailedException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EmailSenderConfigurationFailedException(String message, Throwable cause) {
super(message, cause);
}
public EmailSenderConfigurationFailedException(String msg) {
super(msg);
}
public EmailSenderConfigurationFailedException() {
super();
}
public EmailSenderConfigurationFailedException(Throwable cause) {
super(cause);
}
}

@ -1,44 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class EmailSenderUtil {
public static Document convertToDocument(File file) throws EmailSenderConfigurationFailedException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new EmailSenderConfigurationFailedException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
}

@ -1,45 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
public class EmailSendingFailedException extends Exception {
private static final long serialVersionUID = -3151279311929070294L;
public EmailSendingFailedException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EmailSendingFailedException(String message, Throwable cause) {
super(message, cause);
}
public EmailSendingFailedException(String msg) {
super(msg);
}
public EmailSendingFailedException() {
super();
}
public EmailSendingFailedException(Throwable cause) {
super(cause);
}
}

@ -1,44 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.dynamic.task.allocation.framework;
public class EmailTransportNotConfiguredException extends Exception {
private static final long serialVersionUID = -3151279311929070294L;
public EmailTransportNotConfiguredException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EmailTransportNotConfiguredException(String message, Throwable cause) {
super(message, cause);
}
public EmailTransportNotConfiguredException(String msg) {
super(msg);
}
public EmailTransportNotConfiguredException() {
super();
}
public EmailTransportNotConfiguredException(Throwable cause) {
super(cause);
}
}

@ -1,74 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
public class InvalidConfigurationStateException extends RuntimeException {
private static final long serialVersionUID = -3151279311329070297L;
private String errorMessage;
private int errorCode;
public InvalidConfigurationStateException(int errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public InvalidConfigurationStateException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public InvalidConfigurationStateException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public InvalidConfigurationStateException(String msg) {
super(msg);
setErrorMessage(msg);
}
public InvalidConfigurationStateException() {
super();
}
public InvalidConfigurationStateException(Throwable cause) {
super(cause);
}
}

@ -1,71 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import java.io.InputStream;
public class RegistryBasedResourceLoader extends ResourceLoader {
private static final String EMAIL_CONFIG_BASE_LOCATION = "email-templates";
@Override
public void init(ExtendedProperties extendedProperties) {
}
@Override
public InputStream getResourceStream(String name) throws ResourceNotFoundException {
try {
Registry registry =
CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
if (registry == null) {
throw new IllegalStateException("No valid registry instance is attached to the current carbon context");
}
if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) {
throw new ResourceNotFoundException("Resource '" + name + "' does not exist");
}
org.wso2.carbon.registry.api.Resource resource =
registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name);
resource.setMediaType("text/plain");
return resource.getContentStream();
} catch (RegistryException e) {
throw new ResourceNotFoundException("Error occurred while retrieving resource", e);
}
}
@Override
public boolean isSourceModified(Resource resource) {
return false;
}
@Override
public long getLastModified(Resource resource) {
return 0;
}
}

@ -1,50 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
public class TypedValue<T, V> {
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());
}
}

@ -1,87 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.registry.api.Registry;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;
public class VelocityBasedEmailContentProvider implements EmailContentProvider {
private VelocityEngine engine;
private static final Log log = LogFactory.getLog(VelocityBasedEmailContentProvider.class);
public VelocityBasedEmailContentProvider() {
engine = new VelocityEngine();
engine.setProperty("resource.loader", "registry");
engine.setProperty("velocimacro.library", "");
engine.setProperty("registry.resource.loader.class",
"org.wso2.carbon.email.sender.core.RegistryBasedResourceLoader");
engine.init();
}
@Override
public EmailData getContent(String name, Map<String,
TypedValue<Class<?>, Object>> params) throws ContentProcessingInterruptedException {
VelocityContext ctx = new VelocityContext();
for (Map.Entry<String, TypedValue<Class<?>, 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);
}
}
}
}
}

@ -1,55 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package io.entgra.dynamic.task.allocation.framework.internal;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.dynamic.task.allocation.framework.EmailSenderConfigurationFailedException;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
class EmailSenderAxis2ConfigContextObserver implements Axis2ConfigurationContextObserver {
private static final Log log = LogFactory.getLog(EmailSenderAxis2ConfigContextObserver.class);
@Override
public void creatingConfigurationContext(int tenantId) {
}
@Override
public void createdConfigurationContext(ConfigurationContext configurationContext) {
try {
EmailUtils.setupEmailTemplates();
} catch (EmailSenderConfigurationFailedException e) {
log.error("Error occurred while setting up email templates", e);
}
}
@Override
public void terminatingConfigurationContext(ConfigurationContext configurationContext) {
}
@Override
public void terminatedConfigurationContext(ConfigurationContext configurationContext) {
}
}

@ -1,69 +0,0 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.dynamic.task.allocation.framework.internal;
import io.entgra.dynamic.task.allocation.framework.service.EmailSenderService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.utils.ConfigurationContextService;
public class EmailSenderDataHolder {
private RegistryService registryService;
private ConfigurationContextService configurationContextService;
private EmailSenderService emailServiceProvider;
private static EmailSenderDataHolder thisInstance = new EmailSenderDataHolder();
private EmailSenderDataHolder() {}
public static EmailSenderDataHolder getInstance() {
return thisInstance;
}
public RegistryService getRegistryService() {
if (registryService == null) {
throw new IllegalStateException("Registry service is not initialized properly");
}
return registryService;
}
public void setRegistryService(RegistryService registryService) {
this.registryService = registryService;
}
public ConfigurationContextService getConfigurationContextService() {
if (configurationContextService == null) {
throw new IllegalStateException("ConfigurationContext service is not initialized properly");
}
return configurationContextService;
}
public void setConfigurationContextService(ConfigurationContextService configurationContextService) {
this.configurationContextService = configurationContextService;
}
public EmailSenderService getEmailServiceProvider() {
return emailServiceProvider;
}
public void setEmailServiceProvider(EmailSenderService emailServiceProvider) {
this.emailServiceProvider = emailServiceProvider;
}
}

@ -1,127 +0,0 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.dynamic.task.allocation.framework.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import io.entgra.dynamic.task.allocation.framework.EmailSenderConfig;
import io.entgra.dynamic.task.allocation.framework.service.EmailSenderService;
import io.entgra.dynamic.task.allocation.framework.service.EmailSenderServiceImpl;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.ConfigurationContextService;
/**
* @scr.component name="org.wso2.carbon.email.sender.emailsendereervicecomponent"
* immediate="true"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1"
* policy="dynamic"
* bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService"
* cardinality="0..1"
* policy="dynamic"
* bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
*/
public class EmailSenderServiceComponent {
private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class);
@SuppressWarnings("unused")
protected void activate(ComponentContext componentContext) {
try {
if (log.isDebugEnabled()) {
log.debug("Initializing email sender core bundle");
}
/* Initializing email sender configuration */
EmailSenderConfig.init();
/* Setting up default email templates */
EmailUtils.setupEmailTemplates();
/* Registering declarative service instances exposed by EmailSenderServiceComponent */
this.registerServices(componentContext);
if (log.isDebugEnabled()) {
log.debug("Email sender core bundle has been successfully initialized");
}
componentContext.getBundleContext().registerService(Axis2ConfigurationContextObserver.class.getName(),
new EmailSenderAxis2ConfigContextObserver(), null);
} catch (Throwable e) {
log.error("Error occurred while initializing email sender core bundle", e);
}
}
@SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) {
//do nothing
}
private void registerServices(ComponentContext componentContext) {
if (log.isDebugEnabled()) {
log.debug("Registering email sender service");
}
EmailSenderService emailServiceProvider = new EmailSenderServiceImpl();
EmailSenderDataHolder.getInstance().setEmailServiceProvider(emailServiceProvider);
componentContext.getBundleContext().registerService(EmailSenderService.class, emailServiceProvider, null);
}
/**
* Sets Registry Service.
*
* @param registryService An instance of RegistryService
*/
protected void setRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.debug("Setting Registry Service");
}
EmailSenderDataHolder.getInstance().setRegistryService(registryService);
}
/**
* Unsets Registry Service.
*
* @param registryService An instance of RegistryService
*/
protected void unsetRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.debug("Un setting Registry Service");
}
EmailSenderDataHolder.getInstance().setRegistryService(null);
}
protected void setConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Setting ConfigurationContextService");
}
EmailSenderDataHolder.getInstance().setConfigurationContextService(configurationContextService);
}
protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) {
if (log.isDebugEnabled()) {
log.debug("Un-setting ConfigurationContextService");
}
EmailSenderDataHolder.getInstance().setConfigurationContextService(null);
}
}

@ -1,87 +0,0 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.dynamic.task.allocation.framework.internal;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import io.entgra.dynamic.task.allocation.framework.EmailSenderConfigurationFailedException;
import org.wso2.carbon.registry.api.Collection;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
class EmailUtils {
private static final String EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH = "/email-templates";
private static Log log = LogFactory.getLog(EmailSenderServiceComponent.class);
static void setupEmailTemplates() throws EmailSenderConfigurationFailedException {
File templateDir =
new File(CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator +
"resources" + File.separator + "email-templates");
if (!templateDir.exists()) {
if (log.isDebugEnabled()) {
log.debug("The directory that is expected to use as the container for all email templates is not " +
"available. Therefore, no template is uploaded to the registry");
}
}
if (templateDir.canRead()) {
File[] templates = templateDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
name = name.toLowerCase();
return name.endsWith(".vm");
}
});
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
Registry registry =
EmailSenderDataHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
if (!registry.resourceExists(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH)) {
Collection collection = registry.newCollection();
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH, collection);
for (File template : templates) {
Resource resource = registry.newResource();
resource.setMediaType("text/plain");
String contents = FileUtils.readFileToString(template);
resource.setContent(contents);
registry.put(EMAIL_TEMPLATE_DIR_RELATIVE_REGISTRY_PATH + "/"
+ template.getName().replace(".vm", ""), resource);
}
}
} catch (RegistryException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while setting up email templates", e);
} catch (FileNotFoundException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while writing template file " +
"contents as an input stream of a resource", e);
} catch (IOException e) {
throw new EmailSenderConfigurationFailedException("Error occurred while serializing file " +
"contents to a string", e);
}
}
}
}

@ -1,28 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.dynamic.task.allocation.framework.service;
import io.entgra.dynamic.task.allocation.framework.EmailContext;
import io.entgra.dynamic.task.allocation.framework.EmailSendingFailedException;
import io.entgra.dynamic.task.allocation.framework.EmailTransportNotConfiguredException;
public interface EmailSenderService {
void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException, EmailTransportNotConfiguredException;
}

@ -1,150 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.dynamic.task.allocation.framework.service;
import io.entgra.dynamic.task.allocation.framework.ContentProcessingInterruptedException;
import io.entgra.dynamic.task.allocation.framework.ContentProviderInfo;
import io.entgra.dynamic.task.allocation.framework.EmailContentProvider;
import io.entgra.dynamic.task.allocation.framework.EmailContentProviderFactory;
import io.entgra.dynamic.task.allocation.framework.EmailContext;
import io.entgra.dynamic.task.allocation.framework.EmailData;
import io.entgra.dynamic.task.allocation.framework.EmailSenderConfig;
import io.entgra.dynamic.task.allocation.framework.EmailSendingFailedException;
import io.entgra.dynamic.task.allocation.framework.EmailTransportNotConfiguredException;
import io.entgra.dynamic.task.allocation.framework.internal.EmailSenderDataHolder;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.llom.util.AXIOMUtil;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.mail.MailConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.email.sender.core.*;
import org.wso2.carbon.utils.ConfigurationContextService;
import javax.xml.stream.XMLStreamException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class EmailSenderServiceImpl implements EmailSenderService {
private static ThreadPoolExecutor threadPoolExecutor;
private EmailContentProvider contentProvider;
private static final String TRANSPORT_SENDER_NAME = "mailto";
static {
EmailSenderConfig config = EmailSenderConfig.getInstance();
threadPoolExecutor = new ThreadPoolExecutor(config.getMinThreads(), config.getMaxThreads(),
config.getKeepAliveDuration(), TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(config.getThreadQueueCapacity()));
}
private static final String EMAIL_URI_SCHEME = "mailto:";
private static Log log = LogFactory.getLog(EmailSenderServiceImpl.class);
public EmailSenderServiceImpl() {
this.contentProvider = EmailContentProviderFactory.getContentProvider();
}
private boolean isMailServerConfigured() {
return (EmailSenderDataHolder.getInstance().getConfigurationContextService().getServerConfigContext().
getAxisConfiguration().getTransportOut(TRANSPORT_SENDER_NAME) != null);
}
@Override
public void sendEmail(EmailContext emailCtx) throws EmailSendingFailedException,
EmailTransportNotConfiguredException {
if (this.isMailServerConfigured()) {
for (String recipient : emailCtx.getRecipients()) {
ContentProviderInfo info = emailCtx.getContentProviderInfo();
EmailData emailData;
try {
emailData = contentProvider.getContent(info.getTemplate(), info.getParams());
threadPoolExecutor.submit(new EmailSender(recipient, emailData.getSubject(), emailData.getBody()));
} catch (ContentProcessingInterruptedException e) {
throw new EmailSendingFailedException("Error occurred while retrieving email content to be " +
"sent for recipient '" + recipient + "'", e);
}
}
} else {
String msg = "Email sender transport is not configured. Please configure the 'mailto' sender" +
" transport in axis2.xml.";
log.warn(msg);
throw new EmailTransportNotConfiguredException(msg);
}
}
public static class EmailSender implements Runnable {
String to;
String subject;
String body;
EmailSender(String to, String subject, String body) {
this.to = to;
this.subject = subject;
this.body = body;
}
public void run() {
OMElement payload = null;
try {
payload = AXIOMUtil.stringToOM(body);
} catch (XMLStreamException e) {
log.error("Error occurred while converting email body contents to an XML", e);
}
try {
ConfigurationContextService configCtxService =
EmailSenderDataHolder.getInstance().getConfigurationContextService();
if (configCtxService == null) {
throw new IllegalStateException("Configuration Context Service is not available");
}
ConfigurationContext configCtx = configCtxService.getServerConfigContext();
ServiceClient serviceClient = new ServiceClient(configCtx, null);
Map<String, String> headerMap = new HashMap<>();
headerMap.put(MailConstants.MAIL_HEADER_SUBJECT, subject);
Options options = new Options();
options.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
options.setProperty("FORCE_CONTENT_TYPE_BASED_FORMATTER", "true");
options.setProperty(Constants.Configuration.MESSAGE_TYPE, "application/xml");
options.setProperty(Constants.Configuration.CONTENT_TYPE, "text/html");
options.setTo(new EndpointReference(EMAIL_URI_SCHEME + to));
serviceClient.setOptions(options);
serviceClient.fireAndForget(payload);
if (log.isDebugEnabled()) {
log.debug("Email has been successfully sent to '" + to + "'");
}
} catch (AxisFault e) {
log.error("Error occurred while delivering the message, subject: '" + subject + "', to: '" + to +
"'", e);
}
}
}
}

@ -1,32 +0,0 @@
#
# Copyright 2009 WSO2, Inc. (http://wso2.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This is the log4j configuration file used by WSO2 Carbon
#
# IMPORTANT : Please do not remove or change the names of any
# of the Appenders defined here. The layout pattern & log file
# can be changed using the WSO2 Carbon Management Console, and those
# settings will override the settings in this file.
#
log4j.rootLogger=INFO, STD_OUT
# Redirect log messages to console
log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
log4j.appender.STD_OUT.Target=System.out
log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

@ -1,29 +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.
-->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="DeviceManagementCore">
<parameter name="useDefaultListeners" value="false"/>
<test name="EmailSenderTests" preserve-order="true">
<classes>
</classes>
</test>
</suite>

@ -59,7 +59,6 @@
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
org.wso2.carbon.context,
org.wso2.carbon.utils.*,
org.wso2.carbon.registry.api,
org.w3c.dom,
org.apache.velocity;version="${velocity.version}",
org.apache.velocity.app;version="${velocity.version}",
@ -69,8 +68,6 @@
org.apache.velocity.runtime.resource.loader;version="${velocity.version}",
org.apache.commons.io,
org.apache.axis2.transport.mail,
org.wso2.carbon.registry.core.service,
org.wso2.carbon.registry.core.session,
org.apache.commons.collections,
org.wso2.carbon.device.mgt.common.*
</Import-Package>
@ -143,10 +140,6 @@
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
@ -167,10 +160,6 @@
<groupId>org.apache.axis2.transport</groupId>
<artifactId>axis2-transport-mail</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<dependency>
<groupId>commons-collections.wso2</groupId>
<artifactId>commons-collections</artifactId>

@ -145,11 +145,11 @@ public class GenericHeartBeatDAOImpl implements HeartBeatDAO {
try {
Connection conn = HeartBeatBeaconDAOFactory.getConnection();
String sql = "SELECT (@row_number:=@row_number + 1) AS IDX, UUID, HOST_NAME, MAC from " +
"SERVER_HEART_BEAT_EVENTS WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " +
"SERVER_HEART_BEAT_EVENTS, (SELECT @row_number:=-1) AS TEMP " +
"WHERE LAST_UPDATED_TIMESTAMP > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL ? SECOND) " +
"ORDER BY UUID";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, elapsedTimeInSeconds);
stmt.execute("SET @row_number = 0");
resultSet = stmt.executeQuery();
while (resultSet.next()) {
ctxList.add(HeartBeatBeaconDAOUtil.populateContext(resultSet));

@ -17,7 +17,6 @@
*/
package io.entgra.server.bootup.heartbeat.beacon.internal;
import com.sun.security.ntlm.Server;
import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfig;
import io.entgra.server.bootup.heartbeat.beacon.HeartBeatBeaconConfigurationException;
import io.entgra.server.bootup.heartbeat.beacon.dto.HeartBeatEvent;

@ -33,7 +33,6 @@
<url>http://wso2.org</url>
<modules>
<module>io.entgra.dynamic.task.allocation.framework</module>
<module>io.entgra.server.bootup.heartbeat.beacon</module>
</modules>

Loading…
Cancel
Save