Skip to content
This repository has been archived by the owner on Jan 21, 2021. It is now read-only.

Commit

Permalink
Implement update settings functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
ndegwamartin committed Sep 24, 2018
1 parent d25bcfc commit a7c6463
Show file tree
Hide file tree
Showing 9 changed files with 185 additions and 18 deletions.
4 changes: 2 additions & 2 deletions assets/config/opensrp.properties
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ mcts-report-delay-in-days=10
mcts.poll.time.interval.in.minutes=10

# OpenMRS configuration
openmrs.url=https://openmrs.anc-stage.smartregister.org/openmrs
openmrs.url=https://openmrs.anc-stage.smartregister.org/openmrs/
openmrs.username=admin
openmrs.password=Admin123
openmrs.idgen.url=/module/idgen/exportIdentifiers.form
Expand Down Expand Up @@ -98,4 +98,4 @@ opensrp.authencation.cache.ttl=600
redis.host=localhost
redis.port=6379
redis.password=RedI$P@S5
redis.pool.max.connections=25
redis.pool.max.connections=25
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ public class SettingConfiguration extends BaseDataObject {
@JsonProperty
private String version;

@JsonProperty
private String type;

@JsonProperty
private List<Setting> settings;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.List;

import org.opensrp.domain.postgres.SettingsMetadata;
import org.opensrp.domain.setting.SettingConfiguration;

public interface SettingRepository extends BaseRepository<SettingConfiguration> {
Expand All @@ -10,5 +11,10 @@ public interface SettingRepository extends BaseRepository<SettingConfiguration>

List<SettingConfiguration> findAllSettingsByVersion(Long lastSyncedServerVersion);

List<SettingConfiguration> findAllLatestSettingsByVersion(Long lastSyncedServerVersion);

List<SettingConfiguration> findByEmptyServerVersion();

SettingsMetadata saveSetting(SettingConfiguration settingConfiguration);

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.ektorp.support.CouchDbRepositorySupport;
import org.ektorp.support.View;
import org.opensrp.common.AllConstants;
import org.opensrp.domain.postgres.SettingsMetadata;
import org.opensrp.domain.setting.SettingConfiguration;
import org.opensrp.repository.SettingRepository;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -33,8 +34,8 @@ public List<SettingConfiguration> findAllSettings() {
public List<SettingConfiguration> findAllSettingsByVersion(Long lastSyncedServerVersion) {
ComplexKey startKey = ComplexKey.of(lastSyncedServerVersion);
ComplexKey endKey = ComplexKey.of(Long.MAX_VALUE);
return db.queryView(
createQuery("settings_by_version").includeDocs(true).startKey(startKey).endKey(endKey), SettingConfiguration.class);
return db.queryView(createQuery("settings_by_version").includeDocs(true).startKey(startKey).endKey(endKey),
SettingConfiguration.class);
}

/**
Expand All @@ -44,12 +45,19 @@ public List<SettingConfiguration> findAllSettingsByVersion(Long lastSyncedServer
*/
@View(name = "settings_by_empty_server_version", map = "function(doc) { if ( doc.type == 'Setting' && !doc.serverVersion) { emit(doc._id, doc); } }")
public List<SettingConfiguration> findByEmptyServerVersion() {
return db.queryView(createQuery("settings_by_empty_server_version").limit(200).includeDocs(true), SettingConfiguration.class);
return db.queryView(createQuery("settings_by_empty_server_version").limit(200).includeDocs(true),
SettingConfiguration.class);
}

@Override
public void safeRemove(SettingConfiguration entity) {
remove(entity);
}

@Override
public SettingsMetadata saveSetting(SettingConfiguration settingConfiguration) {
//To Be Implemented
return null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.List;
import java.util.UUID;

import org.opensrp.domain.postgres.Settings;
import org.opensrp.domain.postgres.SettingsMetadata;
import org.opensrp.domain.postgres.SettingsMetadataExample;
import org.opensrp.domain.setting.SettingConfiguration;
Expand All @@ -27,34 +28,37 @@ public SettingConfiguration get(String id) {
return convert(settingMetadataMapper.selectByDocumentId(id));
}

@Override
public void add(SettingConfiguration entity) {
public Settings addSetting(SettingConfiguration entity) {
org.opensrp.domain.postgres.Settings pgSetting = null;

if (entity == null || entity.getIdentifier() == null) {
return;
return pgSetting;
}

if (retrievePrimaryKey(entity) != null) { //Setting already added
return;
return pgSetting;
}

if (entity.getId() == null)
entity.setId(UUID.randomUUID().toString());
setRevision(entity);

org.opensrp.domain.postgres.Settings pgSetting = convert(entity, null);
pgSetting = convert(entity, null);
if (pgSetting == null) {
return;
return pgSetting;
}

int rowsAffected = settingMapper.insertSelectiveAndSetId(pgSetting);
if (rowsAffected < 1 || pgSetting.getId() == null) {
return;
return pgSetting;
}

SettingsMetadata metadata = createMetadata(entity, pgSetting.getId());
if (metadata != null) {
settingMetadataMapper.insertSelective(metadata);
}

return pgSetting;
}

@Override
Expand Down Expand Up @@ -133,6 +137,15 @@ public List<SettingConfiguration> findAllSettingsByVersion(Long lastSyncedServer
return convert(settingMetadataMapper.selectMany(metadataExample, 0, DEFAULT_FETCH_SIZE));
}

@Override
public List<SettingConfiguration> findAllLatestSettingsByVersion(Long lastSyncedServerVersion) {
SettingsMetadataExample metadataExample = new SettingsMetadataExample();
metadataExample.createCriteria().andServerVersionGreaterThanOrEqualTo(lastSyncedServerVersion);
metadataExample.setOrderByClause("server_version DESC");
metadataExample.gr("server_version DESC");
return convert(settingMetadataMapper.selectMany(metadataExample, 0, DEFAULT_FETCH_SIZE));
}

@Override
public List<SettingConfiguration> findByEmptyServerVersion() {
SettingsMetadataExample metadataExample = new SettingsMetadataExample();
Expand Down Expand Up @@ -207,4 +220,67 @@ private SettingsMetadata createMetadata(SettingConfiguration entity, Long id) {
return metadata;
}

@Override
public SettingsMetadata saveSetting(SettingConfiguration entity) {
if (entity == null || entity.getIdentifier() == null) {
return null;
}

if (retrievePrimaryKey(entity) != null) { //Event already added
return null;
}

if (entity.getId() == null)
entity.setId(UUID.randomUUID().toString());
setRevision(entity);

Settings settings = convert(entity, null);
if (settings == null) {
return null;
}

int rowsAffected = settingMapper.insertSelectiveAndSetId(settings);
if (rowsAffected < 1 || settings.getId() == null) {
return null;
}

SettingsMetadata settingsMetadata = createMetadata(entity, settings.getId());
if (settingsMetadata != null) {
settingMetadataMapper.insertSelective(settingsMetadata);
}

return settingsMetadata;

}

@Override
public void add(SettingConfiguration entity) {
if (entity == null || entity.getIdentifier() == null) {
return;
}

if (retrievePrimaryKey(entity) != null) { //Event already added
return;
}

if (entity.getId() == null)
entity.setId(UUID.randomUUID().toString());
setRevision(entity);

Settings settings = convert(entity, null);
if (settings == null) {
return;
}

int rowsAffected = settingMapper.insertSelectiveAndSetId(settings);
if (rowsAffected < 1 || settings.getId() == null) {
return;
}

SettingsMetadata settingsMetadata = createMetadata(entity, settings.getId());
if (settingsMetadata != null) {
settingMetadataMapper.insertSelective(settingsMetadata);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@

public interface CustomSettingMapper extends SettingsMapper {

int insertSelectiveAndSetId(Settings viewConfiguration);
int insertSelectiveAndSetId(Settings setting);
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
#{id,jdbcType=BIGINT},
</if>
<if test="json != null">
#{json,jdbcType=OTHER,typeHandler=org.opensrp.repository.postgres.handler.SettingsTypeHandler},
#{json,jdbcType=OTHER,typeHandler=org.opensrp.repository.postgres.handler.SettingTypeHandler},
</if>
</trim>
</insert>
Expand Down
16 changes: 16 additions & 0 deletions opensrp-core/src/main/java/org/opensrp/service/SettingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.List;

import org.opensrp.domain.postgres.SettingsMetadata;
import org.opensrp.domain.setting.SettingConfiguration;
import org.opensrp.repository.SettingRepository;
import org.slf4j.Logger;
Expand All @@ -25,6 +26,10 @@ public List<SettingConfiguration> findSettingsByVersion(Long lastSyncedServerVer
return settingRepository.findAllSettingsByVersion(lastSyncedServerVersion);
}

public List<SettingConfiguration> findLatestSettingsByVersion(Long lastSyncedServerVersion) {
return settingRepository.findAllLatestSettingsByVersion(lastSyncedServerVersion);
}

public void addServerVersion() {
try {
List<SettingConfiguration> settingConfigurations = settingRepository.findByEmptyServerVersion();
Expand All @@ -47,4 +52,15 @@ public void addServerVersion() {
}
}

public synchronized SettingsMetadata saveSetting(SettingConfiguration settingConfiguration) {

if (settingConfiguration.getIdentifier() == null) {
throw new IllegalArgumentException(
"An event already exists with given baseEntity and formSubmission combination. Consider updating");

}

return settingRepository.saveSetting(settingConfiguration);
}

}
Original file line number Diff line number Diff line change
@@ -1,26 +1,48 @@
package org.opensrp.web.rest;

import static java.text.MessageFormat.format;
import static org.opensrp.web.rest.RestUtils.getStringFilter;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import org.opensrp.common.AllConstants.BaseEntity;
import org.opensrp.domain.postgres.SettingsMetadata;
import org.opensrp.domain.setting.SettingConfiguration;
import org.opensrp.service.SettingService;
import org.opensrp.util.DateTimeTypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

@Controller
@RequestMapping(value = "/rest/settings")
public class SettingResource {

private SettingService settingService;

private static Logger logger = LoggerFactory.getLogger(EventResource.class.toString());

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).create();

@Autowired
public void setSettingService(SettingService settingService) {
this.settingService = settingService;
Expand All @@ -34,6 +56,48 @@ public List<SettingConfiguration> findSettingsByVersion(HttpServletRequest reque
if (serverVersion != null) {
lastSyncedServerVersion = Long.valueOf(serverVersion) + 1;
}
return settingService.findSettingsByVersion(lastSyncedServerVersion);
return settingService.findLatestSettingsByVersion(lastSyncedServerVersion);
}

@SuppressWarnings("unchecked")
@RequestMapping(headers = { "Accept=application/json" }, method = POST, value = "/sync")
public ResponseEntity<JSONObject> saveSetting(@RequestBody String data) {
JSONObject response = new JSONObject();

try {
JSONObject syncData = new JSONObject(data);

if (!syncData.has("settingConfigurations")) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} else {

ArrayList<SettingConfiguration> settingConfigurations = (ArrayList<SettingConfiguration>) gson.fromJson(
syncData.getString("settingConfigurations"),
new TypeToken<ArrayList<SettingConfiguration>>() {}.getType());
SettingsMetadata dbSettingMetadata = null;
JSONArray dbSettingsArray = new JSONArray();

for (SettingConfiguration settingConfiguration : settingConfigurations) {
try {
dbSettingMetadata = settingService.saveSetting(settingConfiguration);
dbSettingsArray.put(dbSettingMetadata.getIdentifier());
}
catch (Exception e) {
logger.error("Setting " + settingConfiguration.getIdentifier() == null ? ""
: settingConfiguration.getIdentifier() + " failed to sync",
e);
}
}

}

}

catch (Exception e) {
logger.error(format("Sync data processing failed with exception {0}.- ", e));
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}

return new ResponseEntity<JSONObject>(response, HttpStatus.OK);
}
}

0 comments on commit a7c6463

Please sign in to comment.