• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

opensrp / opensrp-client-core / #172

pending completion
#172

push

github-actions

web-flow
Merge pull request #918 from opensrp/crashFixonFailure

updated SyncSettingsServiceHelper to Exception Handling

18240 of 26785 relevant lines covered (68.1%)

0.68 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.33
opensrp-core/src/main/java/org/smartregister/sync/helper/SyncSettingsServiceHelper.java
1
package org.smartregister.sync.helper;
2

3
import androidx.annotation.VisibleForTesting;
4

5
import org.json.JSONArray;
6
import org.json.JSONException;
7
import org.json.JSONObject;
8
import org.smartregister.AllConstants;
9
import org.smartregister.CoreLibrary;
10
import org.smartregister.SyncFilter;
11
import org.smartregister.account.AccountAuthenticatorXml;
12
import org.smartregister.account.AccountHelper;
13
import org.smartregister.domain.Response;
14
import org.smartregister.domain.Setting;
15
import org.smartregister.domain.SyncStatus;
16
import org.smartregister.repository.AllSharedPreferences;
17
import org.smartregister.service.HTTPAgent;
18
import org.smartregister.sync.intent.BaseSyncIntentService;
19
import org.smartregister.sync.intent.SettingsSyncIntentService;
20
import org.smartregister.util.JsonFormUtils;
21
import org.smartregister.util.Utils;
22

23
import java.text.MessageFormat;
24
import java.util.List;
25

26
import timber.log.Timber;
27

28
/**
29
 * Created by ndegwamartin on 14/09/2018.
30
 */
31
public class SyncSettingsServiceHelper {
32

33
    private HTTPAgent httpAgent;
34
    private String baseUrl;
35
    private AllSharedPreferences sharedPreferences;
36

37
    public SyncSettingsServiceHelper(String baseUrl, HTTPAgent httpAgent) {
1✔
38

39
        this.httpAgent = httpAgent;
1✔
40
        this.baseUrl = baseUrl;
1✔
41
        sharedPreferences = getInstance().context().allSharedPreferences();
1✔
42
    }
1✔
43

44

45
    public int processIntent() throws JSONException {
46

47
        try {
48
            JSONObject response = pushSettingsToServer();
1✔
49
            if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) {
1✔
50
                JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS);
×
51
                Setting setting;
52
                for (int i = 0; i < records.length(); i++) {
×
53
                    setting = getInstance().context().allSettings().getSetting(records.getString(0));
×
54
                    setting.setSyncStatus(SyncStatus.SYNCED.name());
×
55
                    getInstance().context().allSettings().putSetting(setting);
×
56
                }
57
            }
58

59
        } catch (JSONException e) {
×
60
            Timber.e(e);
×
61
        } catch (NullPointerException e) {
×
62
            Timber.e(e);
×
63
        }
1✔
64

65
        JSONArray settings = getSettings();
1✔
66
        if (settings != null && settings.length() > 0) {
1✔
67
            ServerSettingsHelper.saveSetting(settings);
1✔
68
        }
69

70
        return settings == null ? 0 : settings.length();
1✔
71
    }
72

73
    private JSONArray getSettings() throws JSONException {
74

75
        String authToken = getAccessToken();
1✔
76

77
        JSONArray settings = pullSettingsFromServer(getInstance().getSyncConfiguration().getSettingsSyncFilterValue(), authToken);
1✔
78
        getGlobalSettings(settings, authToken);
1✔
79
        getExtraSettings(settings, authToken);
1✔
80
        return settings;
1✔
81
    }
82

83
    @VisibleForTesting
84
    protected String getAccessToken() {
85
        AccountAuthenticatorXml authenticatorXml = CoreLibrary.getInstance().getAccountAuthenticatorXml();
×
86
        return AccountHelper.getCachedOAuthToken(sharedPreferences.fetchRegisteredANM(), authenticatorXml.getAccountType(), AccountHelper.TOKEN_TYPE.PROVIDER);
×
87
    }
88

89
    @VisibleForTesting
90
    protected CoreLibrary getInstance() {
91
        return CoreLibrary.getInstance();
1✔
92
    }
93

94
    // will automatically use the resolve check
95

96
    private void getExtraSettings(JSONArray settings, String accessToken) throws JSONException {
97
        JSONArray completeExtraSettings = new JSONArray();
1✔
98
        if (getInstance().getSyncConfiguration() != null && getInstance().getSyncConfiguration().hasExtraSettingsSync()) {
1✔
99
            String syncParams = getInstance().getSyncConfiguration().getExtraStringSettingsParameters();
1✔
100
            BaseSyncIntentService.RequestParamsBuilder builder = new BaseSyncIntentService.RequestParamsBuilder().addParam(AllConstants.SERVER_VERSION, "0").addParam(AllConstants.RESOLVE, getInstance().getSyncConfiguration().resolveSettings());
1✔
101
            String url = SettingsSyncIntentService.SETTINGS_URL + "?" + syncParams + "&" + builder.toString();
1✔
102
            JSONArray extraSettings = pullSettings(url, accessToken);
1✔
103
            if (extraSettings != null) {
1✔
104
                aggregateSettings(completeExtraSettings, extraSettings);
1✔
105
            }
106
        }
107

108
        aggregateSettings(settings, completeExtraSettings);
1✔
109
    }
1✔
110

111

112
    private void getGlobalSettings(JSONArray settings, String accessToken) throws JSONException {
113
        JSONArray globalSettings = new JSONArray();
1✔
114
        if (getInstance().getSyncConfiguration().hasGlobalSettings()) {
1✔
115
            globalSettings = pullGlobalSettingsFromServer(accessToken);
1✔
116
        }
117

118
        aggregateSettings(settings, globalSettings);
1✔
119
    }
1✔
120

121
    private void aggregateSettings(JSONArray settings, JSONArray globalSettings) throws JSONException {
122
        if (!JsonFormUtils.isBlankJsonArray(globalSettings) && settings != null) {
1✔
123
            for (int i = 0; i < globalSettings.length(); i++) {
1✔
124
                JSONObject global = globalSettings.getJSONObject(i);
1✔
125
                settings.put(global);
1✔
126
            }
127
        }
128
    }
1✔
129

130
    private JSONObject pushSettingsToServer() throws JSONException {
131
        String endString = "/";
1✔
132
        if (baseUrl.endsWith(endString)) {
1✔
133
            baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(endString));
1✔
134
        }
135

136
        String url = MessageFormat.format("{0}/{1}", baseUrl, SettingsSyncIntentService.SETTINGS_URL);
1✔
137
        Timber.i("URL: %s", url);
1✔
138

139
        if (httpAgent == null) {
1✔
140
            Timber.e("%s http agent is null", url);
×
141
            return null;
×
142
        }
143

144
        JSONObject payload = createSettingsConfigurationPayload();
1✔
145

146
        if (payload.getJSONArray(AllConstants.INTENT_KEY.SETTING_CONFIGURATIONS).length() > 0) {
1✔
147

148
            Response<String> response = httpAgent.postWithJsonResponse(url, payload.toString());
×
149

150
            return new JSONObject(response.payload());
×
151

152
        } else return null;
1✔
153
    }
154

155
    /**
156
     * Create a sync setting url that allows the users to get non adapted settings from the server
157
     * Get the resolved settings from the server.
158
     *
159
     * @param syncFilterValue {@link String} -- the set sync filter value
160
     * @return settings {@link JSONArray} -- a JSON array of all the settings
161
     * @throws JSONException
162
     */
163
    public JSONArray pullSettingsFromServer(String syncFilterValue, String accessToken) throws JSONException {
164
        String url = SettingsSyncIntentService.SETTINGS_URL + "?" + getSettingsSyncFilterParam().value() + "=" + syncFilterValue + "&" + AllConstants.SERVER_VERSION + "=" + sharedPreferences.fetchLastSettingsSyncTimeStamp();
1✔
165
        return pullSettings(url, accessToken);
1✔
166
    }
167

168
    @VisibleForTesting
169
    protected SyncFilter getSettingsSyncFilterParam() {
170
        return getInstance().getSyncConfiguration().getSettingsSyncFilterParam();
×
171
    }
172

173
    @VisibleForTesting
174
    protected String getGlobalSettingsQueryParams() {
175
        return Utils.composeApiCallParamsString(getInstance().getSyncConfiguration().getGlobalSettingsQueryParams());
1✔
176
    }
177

178
    /**
179
     * Gets settings that are not tied to team,teamid,location,provider
180
     *
181
     * @return settings {@link JSONArray} -- a JSON array of all the settings
182
     * @throws JSONException
183
     */
184
    public JSONArray pullGlobalSettingsFromServer(String accessToken) throws JSONException {
185
        String url = SettingsSyncIntentService.SETTINGS_URL + "?" + AllConstants.SERVER_VERSION + "=" + sharedPreferences.fetchLastSettingsSyncTimeStamp() + getGlobalSettingsQueryParams();
1✔
186
        return pullSettings(url, accessToken);
1✔
187
    }
188

189

190
    private JSONObject createSettingsConfigurationPayload() throws JSONException {
191
        JSONObject siteSettingsPayload = new JSONObject();
1✔
192
        JSONArray settingsArray = new JSONArray();
1✔
193
        List<Setting> unsyncedSettings = getInstance().context().allSettings().getUnsyncedSettings();
1✔
194

195
        for (int i = 0; i < unsyncedSettings.size(); i++) {
1✔
196
            SyncableJSONObject settingsWrapper = new SyncableJSONObject(unsyncedSettings.get(i).getValue());
×
197
            settingsArray.put(settingsWrapper);
×
198
        }
199

200
        siteSettingsPayload.put(AllConstants.INTENT_KEY.SETTING_CONFIGURATIONS, settingsArray);
1✔
201
        return siteSettingsPayload;
1✔
202
    }
203

204
    private JSONArray pullSettings(String directoryUrl, String accessToken) throws JSONException {
205
        String endString = "/";
1✔
206
        if (baseUrl.endsWith(endString)) {
1✔
207
            baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(endString));
×
208
        }
209

210
        String completeUrl = baseUrl + directoryUrl;
1✔
211

212
        Timber.i("URL: %s", completeUrl);
1✔
213

214
        if (httpAgent == null) {
1✔
215
            Timber.e("%s http agent is null", completeUrl);
×
216
            return null;
×
217
        }
218

219
        Response resp = getResponse(completeUrl, accessToken);
1✔
220

221
        if (resp == null || resp.isFailure()) {
1✔
222
            Timber.e(" %s  not returned data ", completeUrl);
×
223
            return null;
×
224
        }
225

226
        return new JSONArray((String) resp.payload());
1✔
227
    }
228

229
    @VisibleForTesting
230
    protected Response<String> getResponse(String completeUrl, String accessToken) {
231
        return httpAgent.fetchWithCredentials(completeUrl, accessToken);
×
232
    }
233
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc