MIFOSX-2135: Create new endpoints and the User interface for managing credentials to external services.

This commit is contained in:
shahrahul1985
2015-08-14 12:27:22 +05:30
parent fb8eb4a977
commit e4f260bd69
27 changed files with 1235 additions and 47 deletions
+98
View File
@@ -2395,6 +2395,16 @@
<td></td>
<td></td>
</tr>
<tr>
<td><a href="#external_services">External Services</a></td>
<td>externalservice/{servicename}</td>
<td></td>
<td><a href="#configs_externalService_retrieve">Retrieve
a external service configuration</a></td>
<td><a href="#configs_externalService_update">Update
external service Configuration</a></td>
<td></td>
</tr>
</table>
</div>
</div>
@@ -16556,6 +16566,94 @@ POST scheduler?command=stop
</code>
</div>
</div>
<a id="external_services" name="external_services" class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h3>External Services</h3>
<p>External Services Configuration related to set of supported configurations for third party services like Amazon S3 and SMTP:</p>
<ol>
<li><b>S3 (Amazon S3):</b></li>
<li><b>s3_access_key</b> - </li>
<li><b>s3_bucket_name</b> - </li>
<li><b>s3_secret_key</b> - </li>
<br><br>
<li><b>SMTP (Email Service):</b></li>
<li><b>username</b> - </li>
<li><b>password</b> - </li>
<li><b>host</b> - </li>
<li><b>port</b> - </li>
<li><b>useTLS</b> - </li>
</ol>
</div>
</div>
<a id="configs_externalService_retrieve" name="configs_externalService_retrieve" class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h4>Retrieve External Services Configuration</h4>
<p>Returns a external Service configurations based on the Service Name.</p>
<p>Service Names supported are S3 and SMTP.</p>
<p>Example Requests:</p>
<div class=apiClick>externalservice/SMTP</div>
</div>
<div class="method-example">
<code class="method-declaration">
GET https://DomainName/api/v1/externalservice/{serviceName}
</code>
<code class="method-response">
[
{
"name": "username",
"value": "test@mifos.com"
},
{
"name": "password",
"value": "XXXX"
},
{
"name": "host",
"value": "smtp.gmail.com"
},
{
"name": "port",
"value": "25"
},
{
"name": "useTLS",
"value": "true"
}
]
</code>
</div>
</div>
<a id="config_externalService_update" name="config_externalService_update"
class="old-syle-anchor">&nbsp;</a>
<div class="method-section">
<div class="method-description">
<h4>Update External Service</h4>
<p>Updates the external Service Configuration for a Service Name.</p>
</div>
<div class="method-example">
<code class="method-declaration">
PUT https://DomainName/api/v1/externalservice/{serviceName}
</code>
<code class="method-request">
PUT externalservice/S3
Content-Type: application/json
{
"username" : "test@mifos.org"
"password" : "XXXX"
}
</code>
</div>
</div>
<!-- Fund starts here -->
<a id="funds" name="funds" class="old-syle-anchor">&nbsp;</a>
@@ -0,0 +1,96 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.integrationtests;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mifosplatform.integrationtests.common.ExternalServicesConfigurationHelper;
import org.mifosplatform.integrationtests.common.Utils;
import com.jayway.restassured.builder.RequestSpecBuilder;
import com.jayway.restassured.builder.ResponseSpecBuilder;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
public class ExternalServicesConfigurationTest {
private ResponseSpecification responseSpec;
private RequestSpecification requestSpec;
private ExternalServicesConfigurationHelper externalServicesConfigurationHelper;
private ResponseSpecification httpStatusForidden;
@Before
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
this.httpStatusForidden = new ResponseSpecBuilder().expectStatusCode(403).build();
}
@Test
public void testExternalServicesConfiguration() {
this.externalServicesConfigurationHelper = new ExternalServicesConfigurationHelper(this.requestSpec, this.responseSpec);
// Checking for S3
String configName = "s3_access_key";
ArrayList<HashMap> externalServicesConfig = this.externalServicesConfigurationHelper
.getExternalServicesConfigurationByServiceName(requestSpec, responseSpec, "S3");
Assert.assertNotNull(externalServicesConfig);
for (Integer configIndex = 0; configIndex < (externalServicesConfig.size()); configIndex++) {
String name = (String) externalServicesConfig.get(configIndex).get("name");
String value = null;
if (name.equals(configName)) {
value = (String) externalServicesConfig.get(configIndex).get("value");
String newValue = "test";
System.out.println(name + ":" + value);
HashMap arrayListValue = this.externalServicesConfigurationHelper.updateValueForExternaServicesConfiguration(requestSpec,
responseSpec, "S3", name, newValue);
Assert.assertNotNull(arrayListValue.get("value"));
Assert.assertEquals(arrayListValue.get("value"), newValue);
HashMap arrayListValue1 = this.externalServicesConfigurationHelper.updateValueForExternaServicesConfiguration(requestSpec,
responseSpec, "S3", name, value);
Assert.assertNotNull(arrayListValue1.get("value"));
Assert.assertEquals(arrayListValue1.get("value"), value);
}
}
// Checking for SMTP:
configName = "username";
externalServicesConfig = this.externalServicesConfigurationHelper.getExternalServicesConfigurationByServiceName(requestSpec,
responseSpec, "SMTP");
Assert.assertNotNull(externalServicesConfig);
for (Integer configIndex = 0; configIndex < (externalServicesConfig.size()); configIndex++) {
String name = (String) externalServicesConfig.get(configIndex).get("name");
String value = null;
if (name.equals(configName)) {
value = (String) externalServicesConfig.get(configIndex).get("value");
String newValue = "test";
System.out.println(name + ":" + value);
HashMap arrayListValue = this.externalServicesConfigurationHelper.updateValueForExternaServicesConfiguration(requestSpec,
responseSpec, "SMTP", name, newValue);
Assert.assertNotNull(arrayListValue.get("value"));
Assert.assertEquals(arrayListValue.get("value"), newValue);
HashMap arrayListValue1 = this.externalServicesConfigurationHelper.updateValueForExternaServicesConfiguration(requestSpec,
responseSpec, "SMTP", name, value);
Assert.assertNotNull(arrayListValue1.get("value"));
Assert.assertEquals(arrayListValue1.get("value"), value);
}
}
}
}
@@ -0,0 +1,51 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.integrationtests.common;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.Gson;
import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
public class ExternalServicesConfigurationHelper {
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
public ExternalServicesConfigurationHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) {
this.requestSpec = requestSpec;
this.responseSpec = responseSpec;
}
public static ArrayList<HashMap> getExternalServicesConfigurationByServiceName(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String serviceName) {
final String GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL = "/mifosng-provider/api/v1/externalservice/" + serviceName + "?"
+ Utils.TENANT_IDENTIFIER;
System.out.println("------------------------ RETRIEVING GLOBAL CONFIGURATION BY ID -------------------------");
return Utils.performServerGet(requestSpec, responseSpec, GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL, "");
}
public static HashMap updateValueForExternaServicesConfiguration(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String serviceName, final String name, final String value) {
final String EXTERNAL_SERVICES_CONFIG_UPDATE_URL = "/mifosng-provider/api/v1/externalservice/" + serviceName + "?"
+ Utils.TENANT_IDENTIFIER;
System.out.println("---------------------------------UPDATE VALUE FOR GLOBAL CONFIG---------------------------------------------");
HashMap map = Utils.performServerPut(requestSpec, responseSpec, EXTERNAL_SERVICES_CONFIG_UPDATE_URL,
updateExternalServicesConfigUpdateValueAsJSON(name, value), "");
return (HashMap) map.get("changes");
}
public static String updateExternalServicesConfigUpdateValueAsJSON(final String name, final String value) {
final HashMap<String, String> map = new HashMap<>();
map.put(name, value);
System.out.println("map : " + map);
return new Gson().toJson(map);
}
}
@@ -29,8 +29,8 @@ public class CommandWrapperBuilder {
private Long templateId;
public CommandWrapper build() {
return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, this.actionName,
this.entityName, this.entityId, this.subentityId, this.href, this.json, this.transactionId, this.productId, this.templateId);
return new CommandWrapper(this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, this.actionName, this.entityName,
this.entityId, this.subentityId, this.href, this.json, this.transactionId, this.productId, this.templateId);
}
public CommandWrapperBuilder withLoanId(final Long withLoanId) {
@@ -1813,7 +1813,8 @@ public class CommandWrapperBuilder {
return this;
}
public CommandWrapperBuilder saveOrUpdateAttendance(final Long entityId, final String supportedEntityType, final Long supportedEntityId) {
public CommandWrapperBuilder saveOrUpdateAttendance(final Long entityId, final String supportedEntityType,
final Long supportedEntityId) {
this.actionName = "SAVEORUPDATEATTENDANCE";
this.entityName = "MEETING";
this.entityId = entityId;
@@ -2394,4 +2395,13 @@ public class CommandWrapperBuilder {
return this;
}
public CommandWrapperBuilder updateExternalServiceProperties(final String externalServiceName) {
this.actionName = "UPDATE";
this.entityName = "EXTERNALSERVICES";
this.transactionId = externalServiceName;
this.href = "/externalservices/" + externalServiceName;
return this;
}
}
@@ -0,0 +1,19 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.api;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ExternalServiceConfigurationApiConstant {
public static final String NAME = "name";
public static final String VALUE = "value";
public static final String EXTERNAL_SERVICE_RESOURCE_NAME = "externalServiceConfiguration";
public static final Set<String> EXTERNAL_SERVICE_CONFIGURATION_DATA_PARAMETERS = new HashSet<>(Arrays.asList(NAME, VALUE));
}
@@ -0,0 +1,93 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.api;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import org.mifosplatform.commands.domain.CommandWrapper;
import org.mifosplatform.commands.service.CommandWrapperBuilder;
import org.mifosplatform.commands.service.PortfolioCommandSourceWritePlatformService;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesData;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesPropertiesData;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesPropertiesReadPlatformService;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesReadPlatformService;
import org.mifosplatform.infrastructure.core.api.ApiRequestParameterHelper;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.ToApiJsonSerializer;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Path("/externalservice")
@Component
@Scope("singleton")
public class ExternalServicesConfigurationApiResource {
private final PlatformSecurityContext context;
private final ExternalServicesPropertiesReadPlatformService externalServicePropertiesReadPlatformService;
private final ExternalServicesReadPlatformService externalServiceReadPlatformService;
private final ToApiJsonSerializer<ExternalServicesPropertiesData> toApiJsonSerializer;
// private final ToApiJsonSerializer<S3CredentialsData>
// s3ToApiJsonSerializer;
private final ApiRequestParameterHelper apiRequestParameterHelper;
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
@Autowired
public ExternalServicesConfigurationApiResource(final PlatformSecurityContext context,
final ExternalServicesPropertiesReadPlatformService readPlatformService,
final ExternalServicesReadPlatformService externalServicesReadPlatformService,
final ToApiJsonSerializer<ExternalServicesPropertiesData> toApiJsonSerializer,
final ApiRequestParameterHelper apiRequestParameterHelper,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
this.context = context;
this.externalServicePropertiesReadPlatformService = readPlatformService;
this.toApiJsonSerializer = toApiJsonSerializer;
this.externalServiceReadPlatformService = externalServicesReadPlatformService;
// this.s3ToApiJsonSerializer = s3ToApiJsonSerializer;
this.apiRequestParameterHelper = apiRequestParameterHelper;
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
}
@GET
@Path("{servicename}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String retrieveOne(@PathParam("servicename") final String serviceName, @Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(ExternalServiceConfigurationApiConstant.EXTERNAL_SERVICE_RESOURCE_NAME);
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
final Collection<ExternalServicesPropertiesData> externalServiceNVPs = this.externalServicePropertiesReadPlatformService
.retrieveOne(serviceName);
return this.toApiJsonSerializer.serialize(settings, externalServiceNVPs,
ExternalServiceConfigurationApiConstant.EXTERNAL_SERVICE_CONFIGURATION_DATA_PARAMETERS);
}
@PUT
@Path("{servicename}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public String updateExternalServiceProperties(@PathParam("servicename") final String serviceName, final String apiRequestBodyAsJson) {
// ExternalServicesData external =
// this.externalServiceReadPlatformService.getExternalServiceDetailsByServiceName(serviceName);
final CommandWrapper commandRequest = new CommandWrapperBuilder().updateExternalServiceProperties(serviceName)
.withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
}
}
@@ -0,0 +1,26 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.data;
public class ExternalServicesData {
private final Long id;
private final String name;
public ExternalServicesData(final Long id, final String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
@@ -0,0 +1,28 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.data;
import java.io.Serializable;
public class ExternalServicesPropertiesData implements Serializable {
private final String name;
private final String value;
public ExternalServicesPropertiesData(final String name, final String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
@@ -0,0 +1,44 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.data;
public class SMTPCredentialsData {
private final String username;
private final String password;
private final String host;
private final String port;
private final boolean useTLS;
public SMTPCredentialsData(final String username, final String password, final String host, final String port, final boolean useTLS) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
this.useTLS = useTLS;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getHost() {
return host;
}
public String getPort() {
return port;
}
public boolean isUseTLS() {
return useTLS;
}
}
@@ -1,5 +1,11 @@
package org.mifosplatform.infrastructure.configuration.domain;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType;
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
@@ -8,29 +14,39 @@ package org.mifosplatform.infrastructure.configuration.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "c_external_service", uniqueConstraints = { @UniqueConstraint(columnNames = "name") })
@Table(name = "c_external_service", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "name_UNIQUE") })
public class ExternalService extends AbstractPersistable<Long> {
@Column(name = "name", nullable = false)
@Column(name = "name", length = 50)
private String name;
@Column(name = "value", nullable = false)
private String value;
// @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy =
// "externalServicePropertiesPK.externalService", orphanRemoval = true)
// private Set<ExternalServicesProperties> values;
public ExternalService(final String name, final String value) {
public static ExternalService fromJson(final JsonCommand command) {
final String name = command.stringValueOfParameterNamed("name");
return new ExternalService(name);
}
private ExternalService(final String name) {
this.name = name;
this.value = value;
}
protected ExternalService() {}
public String getValue() {
return this.value;
public String name() {
return this.name;
}
}
@@ -0,0 +1,43 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.data.annotation.Id;
@Embeddable
public class ExternalServicePropertiesPK implements Serializable {
@Column(name = "name", length = 150)
private String name;
@Column(name = "external_service_id")
private Long externalServiceId;
public ExternalServicePropertiesPK() {
}
public ExternalServicePropertiesPK(Long externalServiceId, String name) {
this.externalServiceId = externalServiceId;
this.name = name;
}
public String getName() {
return name;
}
public Long getExternalService() {
return externalServiceId;
}
}
@@ -0,0 +1,76 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.domain;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesPropertiesData;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesConstants.EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesConstants.SMTP_JSON_INPUT_PARAMS;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.springframework.data.annotation.Id;
@Entity
@Table(name = "c_external_service_properties")
public class ExternalServicesProperties {
@EmbeddedId
ExternalServicePropertiesPK externalServicePropertiesPK;
@Column(name = "value", length = 250)
private String value;
protected ExternalServicesProperties() {
}
private ExternalServicesProperties(final ExternalServicePropertiesPK externalServicePropertiesPK, final String value) {
this.externalServicePropertiesPK = externalServicePropertiesPK;
this.value = value;
}
public static ExternalServicesProperties fromJson(final ExternalService externalService, final JsonCommand command) {
final String name = command.stringValueOfParameterNamed(EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS.NAME.getValue());
final String value = command.stringValueOfParameterNamed(EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS.VALUE.getValue());
return new ExternalServicesProperties(new ExternalServicePropertiesPK(externalService.getId(), name), value);
}
public Map<String, Object> update(final JsonCommand command, String paramName) {
final Map<String, Object> actualChanges = new LinkedHashMap<>(2);
final String valueParamName = EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS.VALUE.getValue();
if (command.isChangeInStringParameterNamed(paramName, this.value)) {
final String newValue = command.stringValueOfParameterNamed(paramName);
if (paramName.equals(SMTP_JSON_INPUT_PARAMS.PASSWORD.getValue()) && newValue.equals("XXXX")) {
// If Param Name is Password and ParamValue is XXXX that means
// the password has not been changed.
} else {
actualChanges.put(valueParamName, newValue);
}
this.value = StringUtils.defaultIfEmpty(newValue, null);
}
return actualChanges;
}
public ExternalServicesPropertiesData toData() {
return new ExternalServicesPropertiesData(this.externalServicePropertiesPK.getName(), this.value);
}
}
@@ -8,7 +8,8 @@ package org.mifosplatform.infrastructure.configuration.domain;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ExternalServiceRepository extends JpaRepository<ExternalService, Long>, JpaSpecificationExecutor<ExternalService> {
public interface ExternalServicesPropertiesRepository extends JpaRepository<ExternalServicesProperties, ExternalServicePropertiesPK>,
JpaSpecificationExecutor<ExternalServicesProperties> {
ExternalService findOneByName(String name);
ExternalServicesProperties findOneByExternalServicePropertiesPK(ExternalServicePropertiesPK externalServicesProptiesPK);
}
@@ -0,0 +1,28 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.domain;
import org.mifosplatform.infrastructure.configuration.exception.ExternalServiceConfigurationNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExternalServicesPropertiesRepositoryWrapper {
private final ExternalServicesPropertiesRepository repository;
@Autowired
public ExternalServicesPropertiesRepositoryWrapper(final ExternalServicesPropertiesRepository repository) {
this.repository = repository;
}
public ExternalServicesProperties findOneByIdAndName(Long id, String name, String externalServiceName) {
final ExternalServicesProperties externalServicesProperties = this.repository
.findOneByExternalServicePropertiesPK(new ExternalServicePropertiesPK(id, name));
if (externalServicesProperties == null) throw new ExternalServiceConfigurationNotFoundException(externalServiceName, name);
return externalServicesProperties;
}
}
@@ -0,0 +1,20 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.exception;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException;
public class ExternalServiceConfigurationNotFoundException extends AbstractPlatformResourceNotFoundException {
public ExternalServiceConfigurationNotFoundException(final String serviceName) {
super("error.msg.externalservice.servicename.invalid", "Service Name`" + serviceName + "` does not exist", serviceName);
}
public ExternalServiceConfigurationNotFoundException(final String externalServiceName, final String name) {
super("error.msg.externalservice.property.invalid",
"Parameter`" + name + "` does not exist for the ServiceName `" + externalServiceName + "`", name, externalServiceName);
}
}
@@ -0,0 +1,34 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.handler;
import org.mifosplatform.commands.annotation.CommandType;
import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.configuration.service.ExternalServiceWritePlatformService;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@CommandType(entity = "EXTERNALSERVICES", action = "UPDATE")
public class UpdateExternalServiceConfigurationCommandHandler implements NewCommandSourceHandler {
private final ExternalServiceWritePlatformService writePlatformService;
@Autowired
public UpdateExternalServiceConfigurationCommandHandler(final ExternalServiceWritePlatformService writePlatformService) {
this.writePlatformService = writePlatformService;
}
@Transactional
@Override
public CommandProcessingResult processCommand(final JsonCommand command) {
return this.writePlatformService.updateExternalServicesProperties(command.getTransactionId(), command);
}
}
@@ -0,0 +1,72 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.serialization;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.configuration.exception.ExternalServiceConfigurationNotFoundException;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesConstants;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesConstants.EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesConstants.S3_JSON_INPUT_PARAMS;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesConstants.SMTP_JSON_INPUT_PARAMS;
import org.mifosplatform.infrastructure.core.data.ApiParameterError;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.mifosplatform.infrastructure.core.exception.InvalidJsonException;
import org.mifosplatform.infrastructure.core.serialization.FromJsonHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
@Component
public class ExternalServicesPropertiesCommandFromApiJsonDeserializer {
private final Set<String> supportedParameters = EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS.getAllValues();
private final Set<String> S3SupportedParameters = S3_JSON_INPUT_PARAMS.getAllValues();
private final Set<String> SMTPSupportedParameters = SMTP_JSON_INPUT_PARAMS.getAllValues();
private final FromJsonHelper fromApiJsonHelper;
@Autowired
public ExternalServicesPropertiesCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) {
this.fromApiJsonHelper = fromApiJsonHelper;
}
public void validateForUpdate(final String json, final String externalServiceName) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
switch (externalServiceName) {
case "S3":
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.S3SupportedParameters);
break;
case "SMTP":
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.SMTPSupportedParameters);
break;
default:
throw new ExternalServiceConfigurationNotFoundException(externalServiceName);
}
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("external.service");
final JsonElement element = this.fromApiJsonHelper.parse(json);
}
public Set<String> getNameKeys(final String json) {
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, String> jsonMap = this.fromApiJsonHelper.extractDataMap(typeOfMap, json);
Set<String> keyNames = jsonMap.keySet();
return keyNames;
}
}
@@ -0,0 +1,15 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.service;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
public interface ExternalServiceWritePlatformService {
CommandProcessingResult updateExternalServicesProperties(String externalServiceName, JsonCommand command);
}
@@ -0,0 +1,79 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.service;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesData;
import org.mifosplatform.infrastructure.configuration.domain.ExternalServicesProperties;
import org.mifosplatform.infrastructure.configuration.domain.ExternalServicesPropertiesRepository;
import org.mifosplatform.infrastructure.configuration.domain.ExternalServicesPropertiesRepositoryWrapper;
import org.mifosplatform.infrastructure.configuration.serialization.ExternalServicesPropertiesCommandFromApiJsonDeserializer;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ExternalServiceWritePlatformServiceJpaRepositoryImpl implements ExternalServiceWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(ExternalServiceWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context;
private final ExternalServicesPropertiesRepositoryWrapper repositoryWrapper;
private final ExternalServicesPropertiesRepository repository;
private final ExternalServicesPropertiesCommandFromApiJsonDeserializer fromApiJsonDeserializer;
private final ExternalServicesReadPlatformService readPlatformService;
@Autowired
public ExternalServiceWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context,
final ExternalServicesPropertiesRepositoryWrapper repositoryWrapper, final ExternalServicesPropertiesRepository repository,
final ExternalServicesPropertiesCommandFromApiJsonDeserializer fromApiJsonDeserializer,
final ExternalServicesReadPlatformService readPlatformService) {
this.context = context;
this.repositoryWrapper = repositoryWrapper;
this.repository = repository;
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.readPlatformService = readPlatformService;
}
@Transactional
@Override
public CommandProcessingResult updateExternalServicesProperties(String externalServiceName, JsonCommand command) {
// TODO Auto-generated method stub
this.context.authenticatedUser();
this.fromApiJsonDeserializer.validateForUpdate(command.json(), externalServiceName);
Set<String> keyName = this.fromApiJsonDeserializer.getNameKeys(command.json());
ExternalServicesData external = this.readPlatformService.getExternalServiceDetailsByServiceName(externalServiceName);
Long externalServiceId = external.getId();
Iterator<String> it = keyName.iterator();
Map<String, Object> changesList = new LinkedHashMap<>();
while (it.hasNext()) {
String name = it.next();
final ExternalServicesProperties externalServicesProperties = this.repositoryWrapper.findOneByIdAndName(externalServiceId, name,
externalServiceName);
final Map<String, Object> changes = externalServicesProperties.update(command, name);
changesList.putAll(changes);
if (!changes.isEmpty()) {
this.repository.saveAndFlush(externalServicesProperties);
}
}
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()).withEntityId(externalServiceId).with(changesList).build();
//
}
}
@@ -5,10 +5,116 @@
*/
package org.mifosplatform.infrastructure.configuration.service;
import java.util.HashSet;
import java.util.Set;
import org.mifosplatform.infrastructure.codes.CodeConstants.CODEVALUE_JSON_INPUT_PARAMS;
public class ExternalServicesConstants {
public static final String S3_SERVICE_NAME = "S3";
public static final String S3_BUCKET_NAME = "s3_bucket_name";
public static final String S3_ACCESS_KEY = "s3_access_key";
public static final String S3_SECRET_KEY = "s3_secret_key";
public static final String SMTP_SERVICE_NAME = "SMTP_Email_Account";
public static final String SMTP_USERNAME = "username";
public static final String SMTP_PASSWORD = "password";
public static final String SMTP_HOST = "host";
public static final String SMTP_PORT = "port";
public static final String SMTP_USE_TLS = "useTLS";
public static enum EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS {
EXTERNAL_SERVICE_ID("external_service_id"), NAME("name"), VALUE("value");
private final String value;
private EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS(final String value) {
this.value = value;
}
private static final Set<String> values = new HashSet<>();
static {
for (final EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS type : EXTERNALSERVICEPROPERTIES_JSON_INPUT_PARAMS.values()) {
values.add(type.value);
}
}
public static Set<String> getAllValues() {
return values;
}
@Override
public String toString() {
return name().toString().replaceAll("_", " ");
}
public String getValue() {
return this.value;
}
}
public static enum SMTP_JSON_INPUT_PARAMS {
USERNAME("username"), PASSWORD("password"), HOST("host"), PORT("port"), USETLS("useTLS");
private final String value;
private SMTP_JSON_INPUT_PARAMS(final String value) {
this.value = value;
}
private static final Set<String> values = new HashSet<>();
static {
for (final SMTP_JSON_INPUT_PARAMS type : SMTP_JSON_INPUT_PARAMS.values()) {
values.add(type.value);
}
}
public static Set<String> getAllValues() {
return values;
}
@Override
public String toString() {
return name().toString().replaceAll("_", " ");
}
public String getValue() {
return this.value;
}
}
public static enum S3_JSON_INPUT_PARAMS {
S3_ACCESS_KEY("s3_access_key"), S3_BUCKET_NAME("s3_bucket_name"), S3_SECRET_KEY("s3_secret_key");
private final String value;
private S3_JSON_INPUT_PARAMS(final String value) {
this.value = value;
}
private static final Set<String> values = new HashSet<>();
static {
for (final S3_JSON_INPUT_PARAMS type : S3_JSON_INPUT_PARAMS.values()) {
values.add(type.value);
}
}
public static Set<String> getAllValues() {
return values;
}
@Override
public String toString() {
return name().toString().replaceAll("_", " ");
}
public String getValue() {
return this.value;
}
}
}
@@ -0,0 +1,22 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.service;
import java.util.Collection;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesPropertiesData;
import org.mifosplatform.infrastructure.configuration.data.S3CredentialsData;
import org.mifosplatform.infrastructure.configuration.data.SMTPCredentialsData;
public interface ExternalServicesPropertiesReadPlatformService {
S3CredentialsData getS3Credentials();
SMTPCredentialsData getSMTPCredentials();
Collection<ExternalServicesPropertiesData> retrieveOne(String serviceName);
}
@@ -0,0 +1,137 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.configuration.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesPropertiesData;
import org.mifosplatform.infrastructure.configuration.data.S3CredentialsData;
import org.mifosplatform.infrastructure.configuration.data.SMTPCredentialsData;
import org.mifosplatform.infrastructure.configuration.exception.ExternalServiceConfigurationNotFoundException;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.infrastructure.documentmanagement.data.DocumentData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
@Service
public class ExternalServicesPropertiesReadPlatformServiceImpl implements ExternalServicesPropertiesReadPlatformService {
private final JdbcTemplate jdbcTemplate;
@Autowired
public ExternalServicesPropertiesReadPlatformServiceImpl(final RoutingDataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final class S3CredentialsDataExtractor implements ResultSetExtractor<S3CredentialsData> {
@Override
public S3CredentialsData extractData(final ResultSet rs) throws SQLException, DataAccessException {
String accessKey = null;
String bucketName = null;
String secretKey = null;
while (rs.next()) {
if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.S3_ACCESS_KEY)) {
accessKey = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.S3_BUCKET_NAME)) {
bucketName = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.S3_SECRET_KEY)) {
secretKey = rs.getString("value");
}
}
return new S3CredentialsData(bucketName, accessKey, secretKey);
}
}
private static final class SMTPCredentialsDataExtractor implements ResultSetExtractor<SMTPCredentialsData> {
@Override
public SMTPCredentialsData extractData(final ResultSet rs) throws SQLException, DataAccessException {
String username = null;
String password = null;
String host = null;
String port = "25";
boolean useTLS = false;
while (rs.next()) {
if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.SMTP_USERNAME)) {
username = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.SMTP_PASSWORD)) {
password = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.SMTP_HOST)) {
host = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.SMTP_PORT)) {
port = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.SMTP_USE_TLS)) {
useTLS = Boolean.parseBoolean(rs.getString("value"));
}
}
return new SMTPCredentialsData(username, password, host, port, useTLS);
}
}
private static final class ExternalServiceMapper implements RowMapper<ExternalServicesPropertiesData> {
@Override
public ExternalServicesPropertiesData mapRow(ResultSet rs, int rowNum) throws SQLException {
// TODO Auto-generated method stub
final String name = rs.getString("name");
String value = rs.getString("value");
// Masking the password as we should not send the password back
if (name != null && "password".equalsIgnoreCase(name)) {
value = "XXXX";
}
return new ExternalServicesPropertiesData(name, value);
}
}
@Override
public S3CredentialsData getS3Credentials() {
final ResultSetExtractor<S3CredentialsData> resultSetExtractor = new S3CredentialsDataExtractor();
final String sql = "SELECT esp.name, esp.value FROM c_external_service_properties esp inner join c_external_service es on esp.external_service_id = es.id where es.name = '"
+ ExternalServicesConstants.S3_SERVICE_NAME + "'";
final S3CredentialsData s3CredentialsData = this.jdbcTemplate.query(sql, resultSetExtractor, new Object[] {});
return s3CredentialsData;
}
@Override
public SMTPCredentialsData getSMTPCredentials() {
// TODO Auto-generated method stub
final ResultSetExtractor<SMTPCredentialsData> resultSetExtractor = new SMTPCredentialsDataExtractor();
final String sql = "SELECT esp.name, esp.value FROM c_external_service_properties esp inner join c_external_service es on esp.external_service_id = es.id where es.name = '"
+ ExternalServicesConstants.SMTP_SERVICE_NAME + "'";
final SMTPCredentialsData smtpCredentialsData = this.jdbcTemplate.query(sql, resultSetExtractor, new Object[] {});
return smtpCredentialsData;
}
public Collection<ExternalServicesPropertiesData> retrieveOne(String serviceName) {
String serviceNameToUse = null;
switch (serviceName) {
case "S3":
serviceNameToUse = ExternalServicesConstants.S3_SERVICE_NAME;
break;
case "SMTP":
serviceNameToUse = ExternalServicesConstants.SMTP_SERVICE_NAME;
break;
default:
throw new ExternalServiceConfigurationNotFoundException(serviceName);
}
final ExternalServiceMapper mapper = new ExternalServiceMapper();
final String sql = "SELECT esp.name, esp.value FROM c_external_service_properties esp inner join c_external_service es on esp.external_service_id = es.id where es.name = '"
+ serviceNameToUse + "'";
return this.jdbcTemplate.query(sql, mapper, new Object[] {});
}
}
@@ -5,10 +5,10 @@
*/
package org.mifosplatform.infrastructure.configuration.service;
import org.mifosplatform.infrastructure.configuration.data.S3CredentialsData;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesData;
public interface ExternalServicesReadPlatformService {
S3CredentialsData getS3Credentials();
ExternalServicesData getExternalServiceDetailsByServiceName(String serviceName);
}
}
@@ -8,7 +8,8 @@ package org.mifosplatform.infrastructure.configuration.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.mifosplatform.infrastructure.configuration.data.S3CredentialsData;
import org.mifosplatform.infrastructure.configuration.data.ExternalServicesData;
import org.mifosplatform.infrastructure.configuration.exception.ExternalServiceConfigurationNotFoundException;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
@@ -26,31 +27,43 @@ public class ExternalServicesReadPlatformServiceImpl implements ExternalServices
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final class S3CredentialsDataExtractor implements ResultSetExtractor<S3CredentialsData> {
@Override
public ExternalServicesData getExternalServiceDetailsByServiceName(String serviceName) {
// TODO Auto-generated method stub
final ResultSetExtractor<ExternalServicesData> resultSetExtractor = new ExternalServicesDetailsDataExtractor();
String serviceNameToUse = null;
switch (serviceName) {
case "S3":
serviceNameToUse = ExternalServicesConstants.S3_SERVICE_NAME;
break;
case "SMTP":
serviceNameToUse = ExternalServicesConstants.SMTP_SERVICE_NAME;
break;
default:
throw new ExternalServiceConfigurationNotFoundException(serviceName);
}
final String sql = "SELECT es.name as name, es.id as id FROM c_external_service es where es.name='" + serviceNameToUse + "'";
final ExternalServicesData externalServicesData = this.jdbcTemplate.query(sql, resultSetExtractor, new Object[] {});
return externalServicesData;
}
private static final class ExternalServicesDetailsDataExtractor implements ResultSetExtractor<ExternalServicesData> {
@Override
public S3CredentialsData extractData(final ResultSet rs) throws SQLException, DataAccessException {
String accessKey = null;
String bucketName = null;
String secretKey = null;
public ExternalServicesData extractData(ResultSet rs) throws SQLException, DataAccessException {
// TODO Auto-generated method stub
Long id = (long) 0;
String name = null;
while (rs.next()) {
if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.S3_ACCESS_KEY)) {
accessKey = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.S3_BUCKET_NAME)) {
bucketName = rs.getString("value");
} else if (rs.getString("name").equalsIgnoreCase(ExternalServicesConstants.S3_SECRET_KEY)) {
secretKey = rs.getString("value");
}
name = rs.getString("name");
id = rs.getLong("id");
}
return new S3CredentialsData(bucketName, accessKey, secretKey);
return new ExternalServicesData(id, name);
}
}
@Override
public S3CredentialsData getS3Credentials() {
final ResultSetExtractor<S3CredentialsData> resultSetExtractor = new S3CredentialsDataExtractor();
final String sql = "SELECT es.name, es.value FROM c_external_service es where es.name in('s3_bucket_name','s3_access_key','s3_secret_key')";
final S3CredentialsData s3CredentialsData = this.jdbcTemplate.query(sql, resultSetExtractor, new Object[] {});
return s3CredentialsData;
}
}
@@ -9,28 +9,41 @@ import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.mifosplatform.infrastructure.configuration.data.S3CredentialsData;
import org.mifosplatform.infrastructure.configuration.data.SMTPCredentialsData;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesPropertiesReadPlatformService;
import org.mifosplatform.infrastructure.core.domain.EmailDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GmailBackedPlatformEmailService implements PlatformEmailService {
private final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService;
@Autowired
public GmailBackedPlatformEmailService(final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService){
this.externalServicesReadPlatformService = externalServicesReadPlatformService;
}
@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
final Email email = new SimpleEmail();
final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService.getSMTPCredentials();
final String authuserName = smtpCredentialsData.getUsername();
final String authuserName = "support@cloudmicrofinance.com";
final String authuser = "support@cloudmicrofinance.com";
final String authpwd = "support80";
final String authuser = smtpCredentialsData.getUsername();
final String authpwd = smtpCredentialsData.getPassword();
// Very Important, Don't use email.setAuthentication()
email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
email.setDebug(false); // true if you want to debug
email.setHostName("smtp.gmail.com");
email.setHostName(smtpCredentialsData.getHost());
try {
email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
email.setFrom(authuser, authuserName);
if(smtpCredentialsData.isUseTLS()){
email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
}
email.setFrom(authuser, authuserName);
final StringBuilder subjectBuilder = new StringBuilder().append("MifosX Prototype Demo: ").append(emailDetail.getContactName())
.append(" user account creation.");
@@ -7,7 +7,7 @@ package org.mifosplatform.infrastructure.documentmanagement.contentrepository;
import org.mifosplatform.infrastructure.configuration.data.S3CredentialsData;
import org.mifosplatform.infrastructure.configuration.domain.ConfigurationDomainService;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesReadPlatformService;
import org.mifosplatform.infrastructure.configuration.service.ExternalServicesPropertiesReadPlatformService;
import org.mifosplatform.infrastructure.documentmanagement.domain.StorageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
@@ -17,11 +17,11 @@ import org.springframework.stereotype.Component;
public class ContentRepositoryFactory {
private final ApplicationContext applicationContext;
private final ExternalServicesReadPlatformService externalServicesReadPlatformService;
private final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService;
@Autowired
public ContentRepositoryFactory(final ApplicationContext applicationContext,
final ExternalServicesReadPlatformService externalServicesReadPlatformService) {
final ExternalServicesPropertiesReadPlatformService externalServicesReadPlatformService) {
this.applicationContext = applicationContext;
this.externalServicesReadPlatformService = externalServicesReadPlatformService;
}
@@ -0,0 +1,48 @@
alter table c_external_service drop index name;
Rename table c_external_service to c_external_service_properties;
CREATE TABLE `c_external_service` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name_UNIQUE` (`name`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
insert into `c_external_service` ( `name`) values( 'S3');
Alter table c_external_service_properties
ADD COLUMN `external_service_id` BIGINT(20) NULL DEFAULT NULL;
update c_external_service_properties set external_service_id = (select id from c_external_service where name = 'S3');
ALTER TABLE `c_external_service_properties`
CHANGE COLUMN `external_service_id` `external_service_id` BIGINT(20) NOT NULL;
ALTER TABLE `c_external_service_properties`
ADD CONSTRAINT `FK_c_external_service_properties_c_external_service` FOREIGN KEY (`external_service_id`) REFERENCES `c_external_service` (`id`);
insert into `c_external_service` ( `name`) values( 'SMTP_Email_Account');
insert into c_external_service_properties (`name`, `value`, `external_service_id`) values('username', 'support@cloudmicrofinance.com', (select id from c_external_service where name = 'Gmail_Email_Account'));
insert into c_external_service_properties (`name`, `value`, `external_service_id`) values('password', 'support80', (select id from c_external_service where name = 'Gmail_Email_Account'));
insert into c_external_service_properties (`name`, `value`, `external_service_id`) values('host', 'smtp.gmail.com', (select id from c_external_service where name = 'Gmail_Email_Account'));
insert into c_external_service_properties (`name`, `value`, `external_service_id`) values('port', '25', (select id from c_external_service where name = 'Gmail_Email_Account'));
insert into c_external_service_properties (`name`, `value`, `external_service_id`) values('useTLS', 'true', (select id from c_external_service where name = 'Gmail_Email_Account'));
insert into m_permission(grouping, code, entity_name, action_name, can_maker_checker) values('externalservices', 'UPDATE_EXTERNALSERVICES', 'EXTERNALSERVICES', 'UPDATE', 0);
commit;