target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testIsUserInValidGroupShouldReturnFalseOnError() throws Exception { Whitebox.setInternalState(userService, "keyStore", keyStore); Whitebox.setInternalState(keyStore, "initialized", true); Whitebox.setInternalState(keyStore, "keyStoreSpi", keyStoreSpi); String user = "johndoe"; when(keyStore.containsAlias(user)).thenReturn(true); KeyStore.PrivateKeyEntry privateKeyEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class); when(keyStore.getEntry(user, null)).thenReturn(privateKeyEntry); String password = UUID.randomUUID().toString(); assertFalse(userService.isUserInValidGroup(user, password.toCharArray())); verify(allSharedPreferences, never()).fetchEncryptedGroupId(user); verifyZeroInteractions(repository); } | public boolean isUserInValidGroup(final String userName, final char[] password) { if (keyStore != null && userName != null && password != null && !allSharedPreferences.fetchForceRemoteLogin(userName)) { byte[] storedHash = null; byte[] passwordHash = null; try { storedHash = getLocalAuthenticationCredentials(userName); passwordHash = generatePasswordHash(userName, password); if (storedHash != null && Arrays.equals(storedHash, passwordHash)) { return isValidDBPassword(getDBAuthenticationCredentials(userName)); } } catch (Exception e) { Timber.e(e); } finally { SecurityHelper.clearArray(password); SecurityHelper.clearArray(passwordHash); SecurityHelper.clearArray(storedHash); } } return false; } | UserService { public boolean isUserInValidGroup(final String userName, final char[] password) { if (keyStore != null && userName != null && password != null && !allSharedPreferences.fetchForceRemoteLogin(userName)) { byte[] storedHash = null; byte[] passwordHash = null; try { storedHash = getLocalAuthenticationCredentials(userName); passwordHash = generatePasswordHash(userName, password); if (storedHash != null && Arrays.equals(storedHash, passwordHash)) { return isValidDBPassword(getDBAuthenticationCredentials(userName)); } } catch (Exception e) { Timber.e(e); } finally { SecurityHelper.clearArray(password); SecurityHelper.clearArray(passwordHash); SecurityHelper.clearArray(storedHash); } } return false; } } | UserService { public boolean isUserInValidGroup(final String userName, final char[] password) { if (keyStore != null && userName != null && password != null && !allSharedPreferences.fetchForceRemoteLogin(userName)) { byte[] storedHash = null; byte[] passwordHash = null; try { storedHash = getLocalAuthenticationCredentials(userName); passwordHash = generatePasswordHash(userName, password); if (storedHash != null && Arrays.equals(storedHash, passwordHash)) { return isValidDBPassword(getDBAuthenticationCredentials(userName)); } } catch (Exception e) { Timber.e(e); } finally { SecurityHelper.clearArray(password); SecurityHelper.clearArray(passwordHash); SecurityHelper.clearArray(storedHash); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); } | UserService { public boolean isUserInValidGroup(final String userName, final char[] password) { if (keyStore != null && userName != null && password != null && !allSharedPreferences.fetchForceRemoteLogin(userName)) { byte[] storedHash = null; byte[] passwordHash = null; try { storedHash = getLocalAuthenticationCredentials(userName); passwordHash = generatePasswordHash(userName, password); if (storedHash != null && Arrays.equals(storedHash, passwordHash)) { return isValidDBPassword(getDBAuthenticationCredentials(userName)); } } catch (Exception e) { Timber.e(e); } finally { SecurityHelper.clearArray(password); SecurityHelper.clearArray(passwordHash); SecurityHelper.clearArray(storedHash); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | UserService { public boolean isUserInValidGroup(final String userName, final char[] password) { if (keyStore != null && userName != null && password != null && !allSharedPreferences.fetchForceRemoteLogin(userName)) { byte[] storedHash = null; byte[] passwordHash = null; try { storedHash = getLocalAuthenticationCredentials(userName); passwordHash = generatePasswordHash(userName, password); if (storedHash != null && Arrays.equals(storedHash, passwordHash)) { return isValidDBPassword(getDBAuthenticationCredentials(userName)); } } catch (Exception e) { Timber.e(e); } finally { SecurityHelper.clearArray(password); SecurityHelper.clearArray(passwordHash); SecurityHelper.clearArray(storedHash); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } |
@Test public void testIsUserInPioneerGroupShouldReturnTrueForPioneerUser() throws Exception { userService = spy(userService); Whitebox.setInternalState(userService, "keyStore", keyStore); Whitebox.setInternalState(keyStore, "initialized", true); Whitebox.setInternalState(keyStore, "keyStoreSpi", keyStoreSpi); String user = "johndoe"; when(keyStore.containsAlias(user)).thenReturn(true); KeyStore.PrivateKeyEntry privateKeyEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class); when(keyStore.getEntry(user, null)).thenReturn(privateKeyEntry); when(allSharedPreferences.fetchPioneerUser()).thenReturn(user); assertTrue(userService.isUserInPioneerGroup(user)); } | public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } |
@Test public void testIsUserInPioneerGroupShouldReturnFalseForOthers() throws Exception { when(allSharedPreferences.fetchPioneerUser()).thenReturn("user"); assertFalse(userService.isUserInPioneerGroup("john")); } | public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } | UserService { public boolean isUserInPioneerGroup(String userName) { String pioneerUser = allSharedPreferences.fetchPioneerUser(); if (userName.equals(pioneerUser)) { return true; } else { byte[] currentUserSecretKey = getDecryptedPassphraseValue(userName); byte[] pioneerUserSecretKey = getDecryptedPassphraseValue(pioneerUser); if (currentUserSecretKey != null && Arrays.equals(pioneerUserSecretKey, currentUserSecretKey)) { return isValidDBPassword(currentUserSecretKey); } } return false; } UserService(AllSettings allSettingsArg, AllSharedPreferences
allSharedPreferencesArg, HTTPAgent httpAgentArg, Session sessionArg,
DristhiConfiguration configurationArg, SaveANMLocationTask
saveANMLocationTaskArg, SaveUserInfoTask saveUserInfoTaskArg, SaveANMTeamTask saveANMTeamTaskArg); static TimeZone getServerTimeZone(LoginResponseData userInfo); void initKeyStore(); TimeStatus validateStoredServerTimeZone(); TimeStatus validateDeviceTime(LoginResponseData userInfo, long serverTimeThreshold); boolean isValidLocalLogin(String userName, byte[] password); boolean isUserInValidGroup(final String userName, final char[] password); byte[] getDecryptedAccountValue(String userName, String key); byte[] getDecryptedPassphraseValue(String userName); boolean isUserInPioneerGroup(String userName); LoginResponse fetchUserDetails(String accessToken); AllSharedPreferences getAllSharedPreferences(); Response<String> getLocationInformation(); boolean localLoginWith(String userName); void processLoginResponseDataForUser(String userName, LoginResponseData userInfo); void forceRemoteLogin(String userName); User getUserData(LoginResponseData userInfo); LocationTree getUserLocation(LoginResponseData userInfo); TeamMember getUserTeam(LoginResponseData userInfo); void saveDefaultLocationId(String userName, String locationId); String getUserDefaultTeam(LoginResponseData userInfo); void saveDefaultTeam(String userName, String team); String getUserDefaultTeamId(LoginResponseData userInfo); void saveDefaultTeamId(String userName, String teamId); String getUserDefaultLocationId(LoginResponseData userInfo); String getUserLocationId(LoginResponseData userInfo); void saveUserLocationId(String userName, String locationId); void saveAnmLocation(LocationTree anmLocation); void saveAnmTeam(TeamMember anmTeam); void saveJurisdictions(List<String> jurisdictions); void saveJurisdictionIds(Set<String> jurisdictionIds); Set<String> fetchJurisdictionIds(); void saveOrganizations(TeamMember teamMember); void saveOrganizations(List<Long> organizations); Set<Long> fetchOrganizations(); void saveUserInfo(User user); Bundle saveUserCredentials(String userName, char[] password, LoginResponseData userInfo); boolean hasARegisteredUser(); void logout(); void logoutSession(); boolean hasSessionExpired(); String switchLanguagePreference(); KeyStore getKeyStore(); @Deprecated byte[] getGroupId(String userName); @Deprecated byte[] getGroupId(String userName, KeyStore.PrivateKeyEntry privateKeyEntry); } |
@Test public void testSaveEventAndClientsWithNullEC() { recreateECUtil.saveEventAndClients(null, database); verifyZeroInteractions(database); } | public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag); void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase); } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag); void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase); } |
@Test public void shouldUpdateEveryOnlyNewlyBornChildrenWhileRegistering() throws Exception { Child firstChild = new Child("Child X", "Mother X", "female", EasyMap.create("weight", "3").put("immunizationsGiven", "bcg opv_0").map()); Child secondChild = new Child("Child Y", "Mother X", "female", EasyMap.create("weight", "4").put("immunizationsGiven", "bcg").map()); FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(motherRepository.findById("Mother X")).thenReturn(new Mother("Mother X", "EC 1", "TC 1", "2012-01-01")); Mockito.when(childRepository.find("Child X")).thenReturn(firstChild); Mockito.when(childRepository.find("Child Y")).thenReturn(secondChild); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getSubFormByName("child_registration")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"), EasyMap.mapOf("id", "Child Y"))); service.register(submission); Mockito.verify(childRepository).find("Child X"); Mockito.verify(childRepository).find("Child Y"); Mockito.verify(childRepository).update(firstChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(childRepository).update(secondChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child X", "2012-01-01", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child Y", "2012-01-01", "4", "bcg")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInMotherProfile("Mother X", "2012-01-01", "female", "2012-01-01", "phc")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInECProfile("EC 1", "2012-01-01", "female", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "bcg", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "opv_0", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child Y", "bcg", "2012-01-01")); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); } | public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldDeleteRegisteredChildWhenDeliveryOutcomeIsStillBirth() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_registration")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"))); service.register(submission); Mockito.verify(childRepository).delete("Child X"); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); Mockito.verifyNoMoreInteractions(serviceProvidedService); } | public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void register(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.DeliveryOutcomeFields.CHILD_REGISTRATION_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findById(submission.entityId()); for (Map<String, String> childInstance : subForm.instances()) { Child child = childRepository.find(childInstance.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.ChildRegistrationFields.WEIGHT), child.getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldUpdateNewlyRegisteredChildrenDuringPNCRegistrationOA() throws Exception { Child firstChild = new Child("Child X", "Mother X", "female", EasyMap.create("weight", "3").put("immunizationsGiven", "bcg opv_0").map()); Child secondChild = new Child("Child Y", "Mother X", "female", EasyMap.create("weight", "4").put("immunizationsGiven", "bcg").map()); Mother mother = new Mother("Mother X", "EC X", "TC 1", "2012-01-02"); Mockito.when(motherRepository.findAllCasesForEC("EC X")).thenReturn(Arrays.asList(mother)); Mockito.when(childRepository.find("Child X")).thenReturn(firstChild); Mockito.when(childRepository.find("Child Y")).thenReturn(secondChild); FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("EC X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("subcenter"); Mockito.when(submission.getSubFormByName("child_registration_oa")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"), EasyMap.mapOf("id", "Child Y"))); service.pncRegistrationOA(submission); Mockito.verify(childRepository).find("Child X"); Mockito.verify(childRepository).find("Child Y"); Mockito.verify(childRepository).update(firstChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(childRepository).update(secondChild.setIsClosed(false).setDateOfBirth("2012-01-01").setThayiCardNumber("TC 1")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child X", "2012-01-01", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("Child Y", "2012-01-01", "4", "bcg")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInMotherProfile("Mother X", "2012-01-01", "female", "2012-01-01", "subcenter")); Mockito.verify(allTimelineEvents, Mockito.times(2)).add(TimelineEvent.forChildBirthInECProfile("EC X", "2012-01-01", "female", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "bcg", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child X", "opv_0", "2012-01-01")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("Child Y", "bcg", "2012-01-01")); Mockito.verifyNoMoreInteractions(childRepository); } | public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldDeleteRegisteredChildWhenPNCRegistrationOAIsHandledAndDeliveryOutcomeIsStillBirth() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_registration_oa")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.mapOf("id", "Child X"))); service.pncRegistrationOA(submission); Mockito.verify(childRepository).delete("Child X"); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); Mockito.verifyNoMoreInteractions(serviceProvidedService); } | public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldCheckForEmptyInstanceInTheCaseOfStillBirth() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("Mother X"); Mockito.when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryPlace")).thenReturn("phc"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_registration_oa")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(new ArrayList<Map<String, String>>()); service.pncRegistrationOA(submission); Mockito.verifyNoMoreInteractions(childRepository); Mockito.verifyNoMoreInteractions(allTimelineEvents); Mockito.verifyNoMoreInteractions(serviceProvidedService); } | public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void pncRegistrationOA(FormSubmission submission) { SubForm subForm = submission.getSubFormByName( AllConstants.PNCRegistrationOAFields.CHILD_REGISTRATION_OA_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } String referenceDate = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.REFERENCE_DATE); String deliveryPlace = submission .getFieldValue(AllConstants.DeliveryOutcomeFields.DELIVERY_PLACE); Mother mother = motherRepository.findAllCasesForEC(submission.entityId()).get(0); for (Map<String, String> childInstances : subForm.instances()) { Child child = childRepository.find(childInstances.get(ENTITY_ID_FIELD_NAME)); childRepository .update(child.setIsClosed(false).setThayiCardNumber(mother.thayiCardNumber()) .setDateOfBirth(referenceDate)); allTimelines.add(forChildBirthInChildProfile(child.caseId(), referenceDate, child.getDetail(AllConstants.PNCRegistrationOAFields.WEIGHT), child.getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile(mother.caseId(), referenceDate, child.gender(), referenceDate, deliveryPlace)); allTimelines .add(forChildBirthInECProfile(mother.ecCaseId(), referenceDate, child.gender(), referenceDate)); String immunizationsGiven = child .getDetail(AllConstants.PNCRegistrationOAFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(child.caseId(), immunization, referenceDate)); } } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldAddTimelineEventsWhenChildImmunizationsAreUpdated() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("previousImmunizations")).thenReturn("bcg"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0 pentavalent_0"); Mockito.when(submission.getFieldValue("immunizationDate")).thenReturn("2013-01-01"); service.updateImmunizations(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildImmunization("child id 1", "opv_0", "2013-01-01")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildImmunization("child id 1", "pentavalent_0", "2013-01-01")); Mockito.verifyNoMoreInteractions(allTimelineEvents); } | public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldAddServiceProvidedWhenChildImmunizationsAreUpdated() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("previousImmunizations")).thenReturn("bcg"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0 pentavalent_0"); Mockito.when(submission.getFieldValue("immunizationDate")).thenReturn("2013-01-01"); service.updateImmunizations(submission); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 1", "opv_0", "2013-01-01", null)); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 1", "pentavalent_0", "2013-01-01", null)); Mockito.verifyNoMoreInteractions(serviceProvidedService); } | public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldMarkRemindersAsInProcessWhenImmunizationsAreProvided() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("previousImmunizations")).thenReturn("bcg"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0 pentavalent_0"); Mockito.when(submission.getFieldValue("immunizationDate")).thenReturn("2013-01-01"); service.updateImmunizations(submission); Mockito.verify(allAlerts).changeAlertStatusToInProcess("child id 1", "opv_0"); Mockito.verify(allAlerts).changeAlertStatusToInProcess("child id 1", "pentavalent_0"); Mockito.verifyNoMoreInteractions(allAlerts); } | public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void updateImmunizations(FormSubmission submission) { String immunizationDate = submission .getFieldValue(AllConstants.ChildImmunizationsFields.IMMUNIZATION_DATE); List<String> immunizationsGivenList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.IMMUNIZATIONS_GIVEN); List<String> previousImmunizationsList = splitFieldValueBySpace(submission, AllConstants.ChildImmunizationsFields.PREVIOUS_IMMUNIZATIONS_GIVEN); immunizationsGivenList.removeAll(previousImmunizationsList); for (String immunization : immunizationsGivenList) { allTimelines.add(forChildImmunization(submission.entityId(), immunization, immunizationDate)); serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, immunizationDate)); allAlerts.changeAlertStatusToInProcess(submission.entityId(), immunization); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldAddTimelineEventWhenChildIsRegisteredForEC() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mother mother = new Mother("mother id 1", "ec id 1", "thayi card number", "2013-01-01"); Mockito.when(submission.entityId()).thenReturn("ec id 1"); Mockito.when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("childId")).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("dateOfBirth")).thenReturn("2013-01-02"); Mockito.when(submission.getFieldValue("gender")).thenReturn("female"); Mockito.when(submission.getFieldValue("weight")).thenReturn("3"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0"); Mockito.when(submission.getFieldValue("bcgDate")).thenReturn("2012-01-06"); Mockito.when(submission.getFieldValue("opv0Date")).thenReturn("2012-01-07"); Mockito.when(submission.getFieldValue("shouldCloseMother")).thenReturn(""); Mockito.when(allBeneficiaries.findMother("mother id 1")).thenReturn(mother); service.registerForEC(submission); Mockito.verify(allBeneficiaries).updateMother(mother.setIsClosed(true)); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("child id 1", "2013-01-02", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInMotherProfile("mother id 1", "2013-01-02", "female", null, null)); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInECProfile("ec id 1", "2013-01-02", "female", null)); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "bcg", "2012-01-06")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "opv_0", "2012-01-07")); } | public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldNotCloseMotherWhenAnOpenANCAlreadyExistWhileRegisteringAChildForEC() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("ec id 1"); Mockito.when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("childId")).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("dateOfBirth")).thenReturn("2013-01-02"); Mockito.when(submission.getFieldValue("gender")).thenReturn("female"); Mockito.when(submission.getFieldValue("weight")).thenReturn("3"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0"); Mockito.when(submission.getFieldValue("bcgDate")).thenReturn("2012-01-06"); Mockito.when(submission.getFieldValue("opv0Date")).thenReturn("2012-01-07"); Mockito.when(submission.getFieldValue("shouldCloseMother")).thenReturn("false"); service.registerForEC(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("child id 1", "2013-01-02", "3", "bcg opv_0")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInMotherProfile("mother id 1", "2013-01-02", "female", null, null)); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInECProfile("ec id 1", "2013-01-02", "female", null)); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "bcg", "2012-01-06")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("child id 1", "opv_0", "2012-01-07")); } | public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void registerForEC(FormSubmission submission) { if (shouldCloseMother(submission.getFieldValue(SHOULD_CLOSE_MOTHER))) { closeMother(submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID)); } Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); allTimelines.add(forChildBirthInChildProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.WEIGHT), submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN))); allTimelines.add(forChildBirthInMotherProfile( submission.getFieldValue(AllConstants.ChildRegistrationFields.MOTHER_ID), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null, null)); allTimelines.add(forChildBirthInECProfile(submission.entityId(), submission.getFieldValue(AllConstants.ChildRegistrationFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationFields.GENDER), null)); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationFields.IMMUNIZATIONS_GIVEN); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided.forChildImmunization( submission.getFieldValue(AllConstants.ChildRegistrationFields.CHILD_ID), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void testSaveEventAndClients() throws IOException { when(database.rawQuery(query, params)).thenReturn(getECCursor()); when(clientProcessor.getColumnMappings(tableName)).thenReturn(getEcConfig()); Whitebox.setInternalState(recreateECUtil, "eventClientRepository", eventClientRepository); Pair<List<Event>, List<Client>> eventsAndClients = recreateECUtil.createEventAndClients(database, tableName, query, params, "FamilyRegistration", "Family", formTag); eventsAndClients.first.get(0).addDetails("opearational_area1", "123"); eventsAndClients.first.get(0).addDetails("task_business_status", "Completed"); recreateECUtil.saveEventAndClients(eventsAndClients, database); verify(eventClientRepository).batchInsertClients(jsonArrayArgumentCaptor.capture(), eq(database)); verify(eventClientRepository).batchInsertEvents(jsonArrayArgumentCaptor.capture(), eq(0l), eq(database)); Gson gson = JsonFormUtils.gson; assertEquals(gson.toJson(eventsAndClients.second), jsonArrayArgumentCaptor.getAllValues().get(0).toString()); assertEquals(gson.toJson(eventsAndClients.first), jsonArrayArgumentCaptor.getAllValues().get(1).toString()); } | public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag); void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase); } | RecreateECUtil { public void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase) { if (eventClients == null) { return; } if (eventClients.first != null) { JSONArray events; try { events = new JSONArray(gson.toJson(eventClients.first)); Timber.d("saving %d events, %s ", eventClients.first.size(), events); eventClientRepository.batchInsertEvents(events, 0, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } if (eventClients.second != null) { JSONArray clients; try { clients = new JSONArray(gson.toJson(eventClients.second)); Timber.d("saving %d clients, %s", eventClients.second.size(), clients); eventClientRepository.batchInsertClients(clients, sqLiteDatabase); } catch (JSONException e) { Timber.e(e); } } } Pair<List<Event>, List<Client>> createEventAndClients(SQLiteDatabase database, String tablename, String query, String[] params, String eventType, String entityType, FormTag formTag); void saveEventAndClients(Pair<List<Event>, List<Client>> eventClients, SQLiteDatabase sqLiteDatabase); } |
@Test public void assertTryParseWithValidValue() { Assert.assertEquals(FloatUtil.tryParse("1", 1.0f), 1.0f); Assert.assertEquals(FloatUtil.tryParse("1", "1"), "1.0"); } | public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } | FloatUtil { public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } } | FloatUtil { public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } } | FloatUtil { public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } static Float tryParse(String value, Float defaultValue); static String tryParse(String value, String defaultValue); } | FloatUtil { public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } static Float tryParse(String value, Float defaultValue); static String tryParse(String value, String defaultValue); } |
@Test public void shouldAddPNCVisitTimelineEventWhenPNCVisitHappens() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); Mockito.when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getSubFormByName("child_pnc_visit")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn( Arrays.asList( EasyMap.create("id", "child id 1") .put("weight", "3") .put("temperature", "98") .map(), EasyMap.create("id", "child id 2") .put("weight", "4") .put("temperature", "98.1") .map())); service.pncVisitHappened(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildPNCVisit("child id 1", "2", "2012-01-01", "3", "98")); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildPNCVisit("child id 2", "2", "2012-01-01", "4", "98.1")); } | public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldHandleStillBirthWhenPNCVisitHappens() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); Mockito.when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("deliveryOutcome")).thenReturn("still_birth"); Mockito.when(submission.getSubFormByName("child_pnc_visit")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn(Arrays.asList(EasyMap.create("id", "child id 1").map())); service.pncVisitHappened(submission); Mockito.verify(childRepository).delete("child id 1"); Mockito.verifyNoMoreInteractions(allTimelineEvents); } | public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldAddPNCVisitServiceProvidedWhenPNCVisitHappens() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); SubForm subForm = Mockito.mock(SubForm.class); Mockito.when(submission.entityId()).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); Mockito.when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getSubFormByName("child_pnc_visit")).thenReturn(subForm); Mockito.when(subForm.instances()).thenReturn( Arrays.asList(EasyMap.mapOf("id", "child id 1"), EasyMap.mapOf("id", "child id 2"))); service.pncVisitHappened(submission); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 1", "PNC", "2012-01-01", EasyMap.mapOf("day", "2"))); Mockito.verify(serviceProvidedService).add(new ServiceProvided("child id 2", "PNC", "2012-01-01", EasyMap.mapOf("day", "2"))); } | public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void pncVisitHappened(FormSubmission submission) { String pncVisitDate = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE); String pncVisitDay = submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY); SubForm subForm = submission .getSubFormByName(AllConstants.PNCVisitFields.CHILD_PNC_VISIT_SUB_FORM_NAME); if (handleStillBirth(submission, subForm)) { return; } for (Map<String, String> childInstances : subForm.instances()) { allTimelines.add(forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate, childInstances.get(AllConstants.PNCVisitFields.WEIGHT), childInstances.get(AllConstants.PNCVisitFields.TEMPERATURE))); serviceProvidedService.add(ServiceProvided .forChildPNCVisit(childInstances.get(ENTITY_ID_FIELD_NAME), pncVisitDay, pncVisitDate)); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldCloseChildRecordForDeleteChildAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); service.close(submission); Mockito.verify(allBeneficiaries).closeChild("child id 1"); } | public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } | ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } } | ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldUpdateIllnessForUpdateIllnessAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-02"); Mockito.when(submission.getFieldValue("sickVisitDate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("childSigns")).thenReturn("child signs"); Mockito.when(submission.getFieldValue("childSignsOther")).thenReturn("child signs other"); Mockito.when(submission.getFieldValue("reportChildDisease")).thenReturn("report child disease"); Mockito.when(submission.getFieldValue("reportChildDiseaseOther")).thenReturn("report child disease other"); Mockito.when(submission.getFieldValue("reportChildDiseaseDate")).thenReturn(null); Mockito.when(submission.getFieldValue("reportChildDiseasePlace")).thenReturn("report child disease place"); Mockito.when(submission.getFieldValue("childReferral")).thenReturn("child referral"); service.updateIllnessStatus(submission); Map<String, String> map = EasyMap.create("sickVisitDate", "2012-01-01") .put("childSignsOther", "child signs other") .put("childSigns", "child signs") .put("reportChildDisease", "report child disease") .put("reportChildDiseaseOther", "report child disease other") .put("reportChildDiseaseDate", null) .put("reportChildDiseasePlace", "report child disease place") .put("childReferral", "child referral").map(); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildIllnessVisit("child id 1", "2012-01-01", map)); } | public void updateIllnessStatus(FormSubmission submission) { String sickVisitDate = submission.getFieldValue(SICK_VISIT_DATE); String date = sickVisitDate != null ? sickVisitDate : submission.getFieldValue(REPORT_CHILD_DISEASE_DATE); serviceProvidedService.add(ServiceProvided.forChildIllnessVisit(submission.entityId(), date, createChildIllnessMap(submission))); } | ChildService { public void updateIllnessStatus(FormSubmission submission) { String sickVisitDate = submission.getFieldValue(SICK_VISIT_DATE); String date = sickVisitDate != null ? sickVisitDate : submission.getFieldValue(REPORT_CHILD_DISEASE_DATE); serviceProvidedService.add(ServiceProvided.forChildIllnessVisit(submission.entityId(), date, createChildIllnessMap(submission))); } } | ChildService { public void updateIllnessStatus(FormSubmission submission) { String sickVisitDate = submission.getFieldValue(SICK_VISIT_DATE); String date = sickVisitDate != null ? sickVisitDate : submission.getFieldValue(REPORT_CHILD_DISEASE_DATE); serviceProvidedService.add(ServiceProvided.forChildIllnessVisit(submission.entityId(), date, createChildIllnessMap(submission))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void updateIllnessStatus(FormSubmission submission) { String sickVisitDate = submission.getFieldValue(SICK_VISIT_DATE); String date = sickVisitDate != null ? sickVisitDate : submission.getFieldValue(REPORT_CHILD_DISEASE_DATE); serviceProvidedService.add(ServiceProvided.forChildIllnessVisit(submission.entityId(), date, createChildIllnessMap(submission))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void updateIllnessStatus(FormSubmission submission) { String sickVisitDate = submission.getFieldValue(SICK_VISIT_DATE); String date = sickVisitDate != null ? sickVisitDate : submission.getFieldValue(REPORT_CHILD_DISEASE_DATE); serviceProvidedService.add(ServiceProvided.forChildIllnessVisit(submission.entityId(), date, createChildIllnessMap(submission))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldUpdateVitaminADosagesForUpdateVitaminAProvidedAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("vitaminADate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("vitaminADose")).thenReturn("1"); Mockito.when(submission.getFieldValue("vitaminAPlace")).thenReturn("PHC"); service.updateVitaminAProvided(submission); Mockito.verify(serviceProvidedService).add(ServiceProvided.forVitaminAProvided("child id 1", "2012-01-01", "1", "PHC")); } | public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } | ChildService { public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } } | ChildService { public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldAddTimelineEventWhenChildIsRegisteredForOA() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("ec id 1"); Mockito.when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); Mockito.when(submission.getFieldValue("id")).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("dateOfBirth")).thenReturn("2013-01-02"); Mockito.when(submission.getFieldValue("gender")).thenReturn("female"); Mockito.when(submission.getFieldValue("weight")).thenReturn("3"); Mockito.when(submission.getFieldValue("immunizationsGiven")).thenReturn("bcg opv_0"); Mockito.when(submission.getFieldValue("bcgDate")).thenReturn("2012-01-06"); Mockito.when(submission.getFieldValue("opv0Date")).thenReturn("2012-01-07"); Mockito.when(submission.getFieldValue("thayiCardNumber")).thenReturn("1234567"); Mockito.when(allBeneficiaries.findChild("child id 1")).thenReturn(child); service.registerForOA(submission); Mockito.verify(child).setThayiCardNumber("1234567"); Mockito.verify(allBeneficiaries).updateChild(child); Mockito.verify(allTimelineEvents).add(TimelineEvent.forChildBirthInChildProfile("child id 1", "2013-01-02", "3", "bcg opv_0")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("ec id 1", "bcg", "2012-01-06")); Mockito.verify(serviceProvidedService).add(ServiceProvided.forChildImmunization("ec id 1", "opv_0", "2012-01-07")); } | public void registerForOA(FormSubmission submission) { Child child = allBeneficiaries.findChild(submission.getFieldValue(CHILD_ID)); child.setThayiCardNumber(submission.getFieldValue(THAYI_CARD_NUMBER)); allBeneficiaries.updateChild(child); Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationOAFields.IMMUNIZATIONS_GIVEN); immunizationsGiven = isBlank(immunizationsGiven) ? "" : immunizationsGiven; allTimelines.add(forChildBirthInChildProfile(submission.getFieldValue(CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.WEIGHT), immunizationsGiven)); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } | ChildService { public void registerForOA(FormSubmission submission) { Child child = allBeneficiaries.findChild(submission.getFieldValue(CHILD_ID)); child.setThayiCardNumber(submission.getFieldValue(THAYI_CARD_NUMBER)); allBeneficiaries.updateChild(child); Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationOAFields.IMMUNIZATIONS_GIVEN); immunizationsGiven = isBlank(immunizationsGiven) ? "" : immunizationsGiven; allTimelines.add(forChildBirthInChildProfile(submission.getFieldValue(CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.WEIGHT), immunizationsGiven)); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } } | ChildService { public void registerForOA(FormSubmission submission) { Child child = allBeneficiaries.findChild(submission.getFieldValue(CHILD_ID)); child.setThayiCardNumber(submission.getFieldValue(THAYI_CARD_NUMBER)); allBeneficiaries.updateChild(child); Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationOAFields.IMMUNIZATIONS_GIVEN); immunizationsGiven = isBlank(immunizationsGiven) ? "" : immunizationsGiven; allTimelines.add(forChildBirthInChildProfile(submission.getFieldValue(CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.WEIGHT), immunizationsGiven)); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); } | ChildService { public void registerForOA(FormSubmission submission) { Child child = allBeneficiaries.findChild(submission.getFieldValue(CHILD_ID)); child.setThayiCardNumber(submission.getFieldValue(THAYI_CARD_NUMBER)); allBeneficiaries.updateChild(child); Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationOAFields.IMMUNIZATIONS_GIVEN); immunizationsGiven = isBlank(immunizationsGiven) ? "" : immunizationsGiven; allTimelines.add(forChildBirthInChildProfile(submission.getFieldValue(CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.WEIGHT), immunizationsGiven)); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } | ChildService { public void registerForOA(FormSubmission submission) { Child child = allBeneficiaries.findChild(submission.getFieldValue(CHILD_ID)); child.setThayiCardNumber(submission.getFieldValue(THAYI_CARD_NUMBER)); allBeneficiaries.updateChild(child); Map<String, String> immunizationDateFieldMap = createImmunizationDateFieldMap(); String immunizationsGiven = submission .getFieldValue(AllConstants.ChildRegistrationOAFields.IMMUNIZATIONS_GIVEN); immunizationsGiven = isBlank(immunizationsGiven) ? "" : immunizationsGiven; allTimelines.add(forChildBirthInChildProfile(submission.getFieldValue(CHILD_ID), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.DATE_OF_BIRTH), submission.getFieldValue(AllConstants.ChildRegistrationOAFields.WEIGHT), immunizationsGiven)); for (String immunization : immunizationsGiven.split(SPACE)) { serviceProvidedService.add(ServiceProvided .forChildImmunization(submission.entityId(), immunization, submission.getFieldValue(immunizationDateFieldMap.get(immunization)))); } } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository
motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents
allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts
allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); } |
@Test public void shouldFetchAlertActionsAndNotSaveAnythingIfThereIsNothingNewToSave() throws Exception { setupActions(ResponseStatus.success, new ArrayList<Action>()); Assert.assertEquals(FetchStatus.nothingFetched, service.fetchNewActions()); Mockito.verify(drishtiService).fetchNewActions("ANM X", "1234"); Mockito.verifyNoMoreInteractions(drishtiService); Mockito.verifyNoMoreInteractions(actionRouter); } | public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } |
@Test public void shouldNotSaveAnythingIfTheDrishtiResponseStatusIsFailure() throws Exception { setupActions(ResponseStatus.failure, Arrays.asList(ActionBuilder.actionForCloseAlert("Case X", "ANC 1", "2012-01-01", "0"))); Assert.assertEquals(FetchStatus.fetchedFailed, service.fetchNewActions()); Mockito.verify(drishtiService).fetchNewActions("ANM X", "1234"); Mockito.verifyNoMoreInteractions(drishtiService); Mockito.verifyNoMoreInteractions(actionRouter); } | public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } |
@Test public void shouldFetchAlertActionsAndSaveThemToRepository() throws Exception { Action action = ActionBuilder.actionForCreateAlert("Case X", "normal", "mother", "Ante Natal Care - Normal", "ANC 1", "2012-01-01", null, "0"); setupActions(ResponseStatus.success, Arrays.asList(action)); Assert.assertEquals(FetchStatus.fetched, service.fetchNewActions()); Mockito.verify(drishtiService).fetchNewActions("ANM X", "1234"); Mockito.verify(actionRouter).directAlertAction(action); } | public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } |
@Test public void assertretrieveValueForLinkedRecord() throws Exception { formUtils = new FormUtils(context_); Mockito.when(context_.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open(entityRelationShip)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, entityRelationShip)); } }); JSONObject mockobject = Mockito.mock(JSONObject.class); Mockito.when(mockobject.getString(Mockito.anyString())).thenReturn("val"); formUtils.retrieveValueForLinkedRecord("household.elco", mockobject); } | public String retrieveValueForLinkedRecord(String link, JSONObject entityJson) { try { String entityRelationships = readFileFromAssetsFolder( "www/form/entity_relationship" + AllConstants.JSON_FILE_EXTENSION); JSONArray json = new JSONArray(entityRelationships); Timber.i(json.toString()); JSONObject rJson; if ((rJson = retrieveRelationshipJsonForLink(link, json)) != null) { String[] path = link.split("\\."); String parentTable = path[0]; String childTable = path[1]; String joinValueKey = parentTable.equals(rJson.getString("parent")) ? rJson.getString("from") : rJson.getString("to"); joinValueKey = joinValueKey.contains(".") ? joinValueKey .substring(joinValueKey.lastIndexOf(".") + 1) : joinValueKey; String val = entityJson.getString(joinValueKey); String joinField = parentTable.equals(rJson.getString("parent")) ? rJson.getString("to") : rJson.getString("from"); String sql = "select * from " + childTable + " where " + joinField + "=?"; Timber.d(sql); String dbEntity = theAppContext.formDataRepository().queryUniqueResult(sql, new String[]{val}); JSONObject linkedEntityJson = new JSONObject(); if (dbEntity != null && !dbEntity.isEmpty()) { linkedEntityJson = new JSONObject(dbEntity); } String sourceKey = link.substring(link.lastIndexOf(".") + 1); if (linkedEntityJson.has(sourceKey)) { return linkedEntityJson.getString(sourceKey); } } } catch (Exception e) { Timber.e(e); } return null; } | FormUtils { public String retrieveValueForLinkedRecord(String link, JSONObject entityJson) { try { String entityRelationships = readFileFromAssetsFolder( "www/form/entity_relationship" + AllConstants.JSON_FILE_EXTENSION); JSONArray json = new JSONArray(entityRelationships); Timber.i(json.toString()); JSONObject rJson; if ((rJson = retrieveRelationshipJsonForLink(link, json)) != null) { String[] path = link.split("\\."); String parentTable = path[0]; String childTable = path[1]; String joinValueKey = parentTable.equals(rJson.getString("parent")) ? rJson.getString("from") : rJson.getString("to"); joinValueKey = joinValueKey.contains(".") ? joinValueKey .substring(joinValueKey.lastIndexOf(".") + 1) : joinValueKey; String val = entityJson.getString(joinValueKey); String joinField = parentTable.equals(rJson.getString("parent")) ? rJson.getString("to") : rJson.getString("from"); String sql = "select * from " + childTable + " where " + joinField + "=?"; Timber.d(sql); String dbEntity = theAppContext.formDataRepository().queryUniqueResult(sql, new String[]{val}); JSONObject linkedEntityJson = new JSONObject(); if (dbEntity != null && !dbEntity.isEmpty()) { linkedEntityJson = new JSONObject(dbEntity); } String sourceKey = link.substring(link.lastIndexOf(".") + 1); if (linkedEntityJson.has(sourceKey)) { return linkedEntityJson.getString(sourceKey); } } } catch (Exception e) { Timber.e(e); } return null; } } | FormUtils { public String retrieveValueForLinkedRecord(String link, JSONObject entityJson) { try { String entityRelationships = readFileFromAssetsFolder( "www/form/entity_relationship" + AllConstants.JSON_FILE_EXTENSION); JSONArray json = new JSONArray(entityRelationships); Timber.i(json.toString()); JSONObject rJson; if ((rJson = retrieveRelationshipJsonForLink(link, json)) != null) { String[] path = link.split("\\."); String parentTable = path[0]; String childTable = path[1]; String joinValueKey = parentTable.equals(rJson.getString("parent")) ? rJson.getString("from") : rJson.getString("to"); joinValueKey = joinValueKey.contains(".") ? joinValueKey .substring(joinValueKey.lastIndexOf(".") + 1) : joinValueKey; String val = entityJson.getString(joinValueKey); String joinField = parentTable.equals(rJson.getString("parent")) ? rJson.getString("to") : rJson.getString("from"); String sql = "select * from " + childTable + " where " + joinField + "=?"; Timber.d(sql); String dbEntity = theAppContext.formDataRepository().queryUniqueResult(sql, new String[]{val}); JSONObject linkedEntityJson = new JSONObject(); if (dbEntity != null && !dbEntity.isEmpty()) { linkedEntityJson = new JSONObject(dbEntity); } String sourceKey = link.substring(link.lastIndexOf(".") + 1); if (linkedEntityJson.has(sourceKey)) { return linkedEntityJson.getString(sourceKey); } } } catch (Exception e) { Timber.e(e); } return null; } FormUtils(Context context); } | FormUtils { public String retrieveValueForLinkedRecord(String link, JSONObject entityJson) { try { String entityRelationships = readFileFromAssetsFolder( "www/form/entity_relationship" + AllConstants.JSON_FILE_EXTENSION); JSONArray json = new JSONArray(entityRelationships); Timber.i(json.toString()); JSONObject rJson; if ((rJson = retrieveRelationshipJsonForLink(link, json)) != null) { String[] path = link.split("\\."); String parentTable = path[0]; String childTable = path[1]; String joinValueKey = parentTable.equals(rJson.getString("parent")) ? rJson.getString("from") : rJson.getString("to"); joinValueKey = joinValueKey.contains(".") ? joinValueKey .substring(joinValueKey.lastIndexOf(".") + 1) : joinValueKey; String val = entityJson.getString(joinValueKey); String joinField = parentTable.equals(rJson.getString("parent")) ? rJson.getString("to") : rJson.getString("from"); String sql = "select * from " + childTable + " where " + joinField + "=?"; Timber.d(sql); String dbEntity = theAppContext.formDataRepository().queryUniqueResult(sql, new String[]{val}); JSONObject linkedEntityJson = new JSONObject(); if (dbEntity != null && !dbEntity.isEmpty()) { linkedEntityJson = new JSONObject(dbEntity); } String sourceKey = link.substring(link.lastIndexOf(".") + 1); if (linkedEntityJson.has(sourceKey)) { return linkedEntityJson.getString(sourceKey); } } } catch (Exception e) { Timber.e(e); } return null; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); } | FormUtils { public String retrieveValueForLinkedRecord(String link, JSONObject entityJson) { try { String entityRelationships = readFileFromAssetsFolder( "www/form/entity_relationship" + AllConstants.JSON_FILE_EXTENSION); JSONArray json = new JSONArray(entityRelationships); Timber.i(json.toString()); JSONObject rJson; if ((rJson = retrieveRelationshipJsonForLink(link, json)) != null) { String[] path = link.split("\\."); String parentTable = path[0]; String childTable = path[1]; String joinValueKey = parentTable.equals(rJson.getString("parent")) ? rJson.getString("from") : rJson.getString("to"); joinValueKey = joinValueKey.contains(".") ? joinValueKey .substring(joinValueKey.lastIndexOf(".") + 1) : joinValueKey; String val = entityJson.getString(joinValueKey); String joinField = parentTable.equals(rJson.getString("parent")) ? rJson.getString("to") : rJson.getString("from"); String sql = "select * from " + childTable + " where " + joinField + "=?"; Timber.d(sql); String dbEntity = theAppContext.formDataRepository().queryUniqueResult(sql, new String[]{val}); JSONObject linkedEntityJson = new JSONObject(); if (dbEntity != null && !dbEntity.isEmpty()) { linkedEntityJson = new JSONObject(dbEntity); } String sourceKey = link.substring(link.lastIndexOf(".") + 1); if (linkedEntityJson.has(sourceKey)) { return linkedEntityJson.getString(sourceKey); } } } catch (Exception e) { Timber.e(e); } return null; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } |
@Test public void shouldUpdatePreviousIndexWithIndexOfEachActionThatIsHandled() throws Exception { Action firstAction = ActionBuilder.actionForCreateAlert("Case X", "normal", "mother", "Ante Natal Care - Normal", "ANC 1", "2012-01-01", "2012-01-22", "11111"); Action secondAction = ActionBuilder.actionForCreateAlert("Case Y", "normal", "mother", "Ante Natal Care - Normal", "ANC 2", "2012-01-01", "2012-01-11", "12345"); setupActions(ResponseStatus.success, Arrays.asList(firstAction, secondAction)); service.fetchNewActions(); InOrder inOrder = Mockito.inOrder(actionRouter, allSettings); inOrder.verify(actionRouter).directAlertAction(firstAction); inOrder.verify(allSettings).savePreviousFetchIndex("11111"); inOrder.verify(actionRouter).directAlertAction(secondAction); inOrder.verify(allSettings).savePreviousFetchIndex("12345"); } | public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } | ActionService { public FetchStatus fetchNewActions() { String previousFetchIndex = allSettings.fetchPreviousFetchIndex(); Response<List<Action>> response = drishtiService .fetchNewActions(allSharedPreference.fetchRegisteredANM(), previousFetchIndex); if (response.isFailure()) { return fetchedFailed; } if (response.payload().isEmpty()) { return nothingFetched; } handleActions(response); return FetchStatus.fetched; } ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports); ActionService(DrishtiService drishtiService, AllSettings allSettings,
AllSharedPreferences allSharedPreferences, AllReports allReports,
ActionRouter actionRouter); FetchStatus fetchNewActions(); } |
@Test public void assertReplicationIntentServiceInitializationTest() { ReplicationIntentService replicationIntentService = new ReplicationIntentService(); Assert.assertNotNull(replicationIntentService); replicationIntentService.onHandleIntent(null); } | @Override protected void onHandleIntent(Intent intent) { } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } |
@Test public void assertReplicationIntentServiceInitializationTest2() { ReplicationIntentService replicationIntentService = new ReplicationIntentService("service_name"); Assert.assertNotNull(replicationIntentService); replicationIntentService.onHandleIntent(null); } | @Override protected void onHandleIntent(Intent intent) { } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } | ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); } |
@Test public void shouldRegisterANC() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); when(submission.getFieldValue("thayiCardNumber")).thenReturn("thayi 1"); when(submission.getFieldValue("registrationDate")).thenReturn("2012-01-02"); when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); service.registerANC(submission); allTimelineEvents.add(TimelineEvent.forStartOfPregnancy("mother id 1", "2012-01-02", "2012-01-01")); allTimelineEvents.add(TimelineEvent.forStartOfPregnancyForEC("entity id 1", "thayi 1", "2012-01-02", "2012-01-01")); } | public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } | MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } } | MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldRegisterOutOfAreaANC() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); when(submission.getFieldValue("thayiCardNumber")).thenReturn("thayi 1"); when(submission.getFieldValue("registrationDate")).thenReturn("2012-01-02"); when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); service.registerOutOfAreaANC(submission); allTimelineEvents.add(TimelineEvent.forStartOfPregnancy("mother id 1", "2012-01-02", "2012-01-01")); allTimelineEvents.add(TimelineEvent.forStartOfPregnancyForEC("entity id 1", "thayi 1", "2012-01-02", "2012-01-01")); } | public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } | MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } } | MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldCreateTimelineEventsWhenANCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("ancVisitDate")).thenReturn("2013-01-01"); when(submission.getFieldValue("ancVisitNumber")).thenReturn("2"); when(submission.getFieldValue("weight")).thenReturn("21"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("bpSystolic")).thenReturn("90"); when(submission.getFieldValue("temperature")).thenReturn("98.5"); service.ancVisit(submission); verify(allTimelineEvents).add(TimelineEvent.forANCCareProvided("entity id 1", "2", "2013-01-01", create("bpDiastolic", "80").put("bpSystolic", "90").put("temperature", "98.5").put("weight", "21").map())); } | public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddServiceProvidedWhenANCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("ancVisitDate")).thenReturn("2013-01-01"); when(submission.getFieldValue("ancVisitNumber")).thenReturn("1"); when(submission.getFieldValue("weight")).thenReturn("21"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("bpSystolic")).thenReturn("90"); service.ancVisit(submission); verify(serviceProvidedService).add( new ServiceProvided("entity id 1", "ANC 1", "2013-01-01", create("bpDiastolic", "80").put("bpSystolic", "90").put("weight", "21").map())); } | public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void ancVisit(FormSubmission submission) { allTimelines.add(forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), create(BP_SYSTOLIC, submission.getFieldValue(BP_SYSTOLIC)) .put(BP_DIASTOLIC, submission.getFieldValue(BP_DIASTOLIC)) .put(TEMPERATURE, submission.getFieldValue(TEMPERATURE)) .put(WEIGHT, submission.getFieldValue(WEIGHT)).map())); serviceProvidedService.add(ServiceProvided.forANCCareProvided(submission.entityId(), submission.getFieldValue(ANC_VISIT_NUMBER), submission.getFieldValue(ANC_VISIT_DATE), submission.getFieldValue(BP_SYSTOLIC), submission.getFieldValue(BP_DIASTOLIC), submission.getFieldValue(WEIGHT))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldNotDoAnythingWhenANCIsClosedAndMotherDoesNotExist() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(null); service.close(submission); verify(allBeneficiaries, times(0)).closeMother("entity id 1"); verifyZeroInteractions(allEligibleCouples); } | public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldCloseECWhenMotherIsClosedAndReasonIsDeath() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("death_of_mother"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); } | public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldCloseECWhenWomanIsClosedAndReasonIsDeath() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("death_of_woman"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); } | public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void assertgenerateXMLInputForFormWithEntityId() throws Exception { formUtils = new FormUtils(context_); Mockito.when(context_.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open(formDefinition)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formDefinition)); } }); Mockito.when(assetManager.open(model)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, model)); } }); Mockito.when(assetManager.open(formJSON)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formJSON)); } }); FormDataRepository formDataRepository = Mockito.mock(FormDataRepository.class); Mockito.when(context.formDataRepository()).thenReturn(formDataRepository); Mockito.when(formDataRepository.getMapFromSQLQuery(Mockito.anyString(),Mockito.any(String[].class))).thenReturn(new HashMap<String, String>()); DetailsRepository detailsRepository = Mockito.mock(DetailsRepository.class); Mockito.when(context.detailsRepository()).thenReturn(detailsRepository); Mockito.when(detailsRepository.getAllDetailsForClient(Mockito.anyString())).thenReturn(new HashMap<String, String>()); PowerMockito.mockStatic(Xml.class); XmlSerializerMock xmlSerializer = new XmlSerializerMock(); PowerMockito.when(Xml.newSerializer()).thenReturn(xmlSerializer); Assert.assertNotNull(formUtils.generateXMLInputForFormWithEntityId("baseEntityId", FORMNAME, null)); } | public String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides) { try { JSONObject fieldOverrides = new JSONObject(); if (overrides != null) { fieldOverrides = new JSONObject(overrides); String overridesStr = fieldOverrides.getString("fieldOverrides"); fieldOverrides = new JSONObject(overridesStr); } String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String ec_bind_path = formDefinition.getJSONObject("form").getString("ec_bind_type"); String sql = "select * from " + ec_bind_path + " where base_entity_id =?"; Map<String, String> dbEntity = theAppContext.formDataRepository(). getMapFromSQLQuery(sql, new String[]{entityId}); Map<String, String> detailsMap = theAppContext.detailsRepository(). getAllDetailsForClient(entityId); detailsMap.putAll(dbEntity); JSONObject entityJson = new JSONObject(); if (detailsMap != null && !detailsMap.isEmpty()) { entityJson = new JSONObject(detailsMap); } String formModelString = readFileFromAssetsFolder( "www/form/" + formName + "/model" + ".xml").replaceAll("\n", " ") .replaceAll("\r", " "); InputStream is = new ByteArrayInputStream(formModelString.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.startDocument(CharEncoding.UTF_8, true); NodeList els = ((Element) document.getElementsByTagName("model").item(0)). getElementsByTagName("instance"); Element el = (Element) els.item(0); NodeList entries = el.getChildNodes(); int num = entries.getLength(); for (int i = 0; i < num; i++) { Node n = entries.item(i); if (n instanceof Element) { Element node = (Element) n; writeXML(node, serializer, fieldOverrides, formDefinition, entityJson, null); } } serializer.endDocument(); String xml = writer.toString(); xml = xml.substring(56); System.out.println(xml); return xml; } catch (Exception e) { Timber.e(e); } return ""; } | FormUtils { public String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides) { try { JSONObject fieldOverrides = new JSONObject(); if (overrides != null) { fieldOverrides = new JSONObject(overrides); String overridesStr = fieldOverrides.getString("fieldOverrides"); fieldOverrides = new JSONObject(overridesStr); } String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String ec_bind_path = formDefinition.getJSONObject("form").getString("ec_bind_type"); String sql = "select * from " + ec_bind_path + " where base_entity_id =?"; Map<String, String> dbEntity = theAppContext.formDataRepository(). getMapFromSQLQuery(sql, new String[]{entityId}); Map<String, String> detailsMap = theAppContext.detailsRepository(). getAllDetailsForClient(entityId); detailsMap.putAll(dbEntity); JSONObject entityJson = new JSONObject(); if (detailsMap != null && !detailsMap.isEmpty()) { entityJson = new JSONObject(detailsMap); } String formModelString = readFileFromAssetsFolder( "www/form/" + formName + "/model" + ".xml").replaceAll("\n", " ") .replaceAll("\r", " "); InputStream is = new ByteArrayInputStream(formModelString.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.startDocument(CharEncoding.UTF_8, true); NodeList els = ((Element) document.getElementsByTagName("model").item(0)). getElementsByTagName("instance"); Element el = (Element) els.item(0); NodeList entries = el.getChildNodes(); int num = entries.getLength(); for (int i = 0; i < num; i++) { Node n = entries.item(i); if (n instanceof Element) { Element node = (Element) n; writeXML(node, serializer, fieldOverrides, formDefinition, entityJson, null); } } serializer.endDocument(); String xml = writer.toString(); xml = xml.substring(56); System.out.println(xml); return xml; } catch (Exception e) { Timber.e(e); } return ""; } } | FormUtils { public String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides) { try { JSONObject fieldOverrides = new JSONObject(); if (overrides != null) { fieldOverrides = new JSONObject(overrides); String overridesStr = fieldOverrides.getString("fieldOverrides"); fieldOverrides = new JSONObject(overridesStr); } String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String ec_bind_path = formDefinition.getJSONObject("form").getString("ec_bind_type"); String sql = "select * from " + ec_bind_path + " where base_entity_id =?"; Map<String, String> dbEntity = theAppContext.formDataRepository(). getMapFromSQLQuery(sql, new String[]{entityId}); Map<String, String> detailsMap = theAppContext.detailsRepository(). getAllDetailsForClient(entityId); detailsMap.putAll(dbEntity); JSONObject entityJson = new JSONObject(); if (detailsMap != null && !detailsMap.isEmpty()) { entityJson = new JSONObject(detailsMap); } String formModelString = readFileFromAssetsFolder( "www/form/" + formName + "/model" + ".xml").replaceAll("\n", " ") .replaceAll("\r", " "); InputStream is = new ByteArrayInputStream(formModelString.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.startDocument(CharEncoding.UTF_8, true); NodeList els = ((Element) document.getElementsByTagName("model").item(0)). getElementsByTagName("instance"); Element el = (Element) els.item(0); NodeList entries = el.getChildNodes(); int num = entries.getLength(); for (int i = 0; i < num; i++) { Node n = entries.item(i); if (n instanceof Element) { Element node = (Element) n; writeXML(node, serializer, fieldOverrides, formDefinition, entityJson, null); } } serializer.endDocument(); String xml = writer.toString(); xml = xml.substring(56); System.out.println(xml); return xml; } catch (Exception e) { Timber.e(e); } return ""; } FormUtils(Context context); } | FormUtils { public String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides) { try { JSONObject fieldOverrides = new JSONObject(); if (overrides != null) { fieldOverrides = new JSONObject(overrides); String overridesStr = fieldOverrides.getString("fieldOverrides"); fieldOverrides = new JSONObject(overridesStr); } String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String ec_bind_path = formDefinition.getJSONObject("form").getString("ec_bind_type"); String sql = "select * from " + ec_bind_path + " where base_entity_id =?"; Map<String, String> dbEntity = theAppContext.formDataRepository(). getMapFromSQLQuery(sql, new String[]{entityId}); Map<String, String> detailsMap = theAppContext.detailsRepository(). getAllDetailsForClient(entityId); detailsMap.putAll(dbEntity); JSONObject entityJson = new JSONObject(); if (detailsMap != null && !detailsMap.isEmpty()) { entityJson = new JSONObject(detailsMap); } String formModelString = readFileFromAssetsFolder( "www/form/" + formName + "/model" + ".xml").replaceAll("\n", " ") .replaceAll("\r", " "); InputStream is = new ByteArrayInputStream(formModelString.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.startDocument(CharEncoding.UTF_8, true); NodeList els = ((Element) document.getElementsByTagName("model").item(0)). getElementsByTagName("instance"); Element el = (Element) els.item(0); NodeList entries = el.getChildNodes(); int num = entries.getLength(); for (int i = 0; i < num; i++) { Node n = entries.item(i); if (n instanceof Element) { Element node = (Element) n; writeXML(node, serializer, fieldOverrides, formDefinition, entityJson, null); } } serializer.endDocument(); String xml = writer.toString(); xml = xml.substring(56); System.out.println(xml); return xml; } catch (Exception e) { Timber.e(e); } return ""; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); } | FormUtils { public String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides) { try { JSONObject fieldOverrides = new JSONObject(); if (overrides != null) { fieldOverrides = new JSONObject(overrides); String overridesStr = fieldOverrides.getString("fieldOverrides"); fieldOverrides = new JSONObject(overridesStr); } String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String ec_bind_path = formDefinition.getJSONObject("form").getString("ec_bind_type"); String sql = "select * from " + ec_bind_path + " where base_entity_id =?"; Map<String, String> dbEntity = theAppContext.formDataRepository(). getMapFromSQLQuery(sql, new String[]{entityId}); Map<String, String> detailsMap = theAppContext.detailsRepository(). getAllDetailsForClient(entityId); detailsMap.putAll(dbEntity); JSONObject entityJson = new JSONObject(); if (detailsMap != null && !detailsMap.isEmpty()) { entityJson = new JSONObject(detailsMap); } String formModelString = readFileFromAssetsFolder( "www/form/" + formName + "/model" + ".xml").replaceAll("\n", " ") .replaceAll("\r", " "); InputStream is = new ByteArrayInputStream(formModelString.getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(is); XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.startDocument(CharEncoding.UTF_8, true); NodeList els = ((Element) document.getElementsByTagName("model").item(0)). getElementsByTagName("instance"); Element el = (Element) els.item(0); NodeList entries = el.getChildNodes(); int num = entries.getLength(); for (int i = 0; i < num; i++) { Node n = entries.item(i); if (n instanceof Element) { Element node = (Element) n; writeXML(node, serializer, fieldOverrides, formDefinition, entityJson, null); } } serializer.endDocument(); String xml = writer.toString(); xml = xml.substring(56); System.out.println(xml); return xml; } catch (Exception e) { Timber.e(e); } return ""; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } |
@Test public void shouldCloseECWhenMotherIsClosedAndReasonIsPermanentRelocation() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("relocation_permanent"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); } | public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldCloseECWhenMotherIsClosedUsingPNCCloseAndReasonIsPermanentRelocation() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("permanent_relocation"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verify(allEligibleCouples).close("ec entity id 1"); } | public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldNotCloseECWhenMotherIsClosedForOtherReasons() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("closeReason")).thenReturn("other_reason"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec entity id 1", "thayi 1", "2013-01-01")); service.close(submission); verifyZeroInteractions(allEligibleCouples); } | public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void close(FormSubmission submission) { close(submission.entityId(), submission.getFieldValue(CLOSE_REASON_FIELD_NAME)); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldHandleTTProvided() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("ttDose")).thenReturn("ttbooster"); when(submission.getFieldValue("ttDate")).thenReturn("2013-01-01"); service.ttProvided(submission); verify(allTimelineEvents).add(forTTShotProvided("entity id 1", "ttbooster", "2013-01-01")); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "TT Booster", "2013-01-01", mapOf("dose", "TT Booster"))); } | public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); } | MotherService { public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); } } | MotherService { public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddTimelineEventWhenIFATabletsAreGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("ifaTabletsDate")).thenReturn("2013-02-01"); service.ifaTabletsGiven(submission); verify(allTimelineEvents).add(forIFATabletsGiven("entity id 1", "100", "2013-02-01")); } | public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddServiceProvidedWhenIFATabletsAreGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("ifaTabletsDate")).thenReturn("2013-02-01"); service.ifaTabletsGiven(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "IFA", "2013-02-01", mapOf("dose", "100"))); } | public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldDoNothingWhenIFATabletsAreNotGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("0"); when(submission.getFieldValue("ifaTabletsDate")).thenReturn("2013-02-01"); service.ifaTabletsGiven(submission); verifyZeroInteractions(allTimelineEvents); verifyZeroInteractions(serviceProvidedService); } | public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void ifaTabletsGiven(FormSubmission submission) { String numberOfIFATabletsGiven = submission.getFieldValue(NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); serviceProvidedService.add(ServiceProvided .forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(IFA_TABLETS_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldHandleHBTest() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("hbLevel")).thenReturn("11"); when(submission.getFieldValue("hbTestDate")).thenReturn("2013-01-01"); service.hbTest(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "Hb Test", "2013-01-01", mapOf("hbLevel", "11"))); } | public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } | MotherService { public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } } | MotherService { public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldHandleDeliveryOutcome() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("didWomanSurvive")).thenReturn("yes"); when(allBeneficiaries.findMotherWithOpenStatus("entity id 1")).thenReturn(new Mother("entity id 1", "ec id 1", "1234567", "2014-01-01")); service.deliveryOutcome(submission); verify(allBeneficiaries).switchMotherToPNC("entity id 1"); } | public void deliveryOutcome(FormSubmission submission) { Mother mother = allBeneficiaries.findMotherWithOpenStatus(submission.entityId()); if (mother == null) { logWarn("Failed to handle delivery outcome for mother. Entity ID: " + submission .entityId()); return; } if (BOOLEAN_FALSE.equals(submission.getFieldValue(DID_WOMAN_SURVIVE)) || BOOLEAN_FALSE .equals(submission.getFieldValue(DID_MOTHER_SURVIVE))) { allBeneficiaries.closeMother(submission.entityId()); allEligibleCouples.close(mother.ecCaseId()); return; } allBeneficiaries.switchMotherToPNC(submission.entityId()); } | MotherService { public void deliveryOutcome(FormSubmission submission) { Mother mother = allBeneficiaries.findMotherWithOpenStatus(submission.entityId()); if (mother == null) { logWarn("Failed to handle delivery outcome for mother. Entity ID: " + submission .entityId()); return; } if (BOOLEAN_FALSE.equals(submission.getFieldValue(DID_WOMAN_SURVIVE)) || BOOLEAN_FALSE .equals(submission.getFieldValue(DID_MOTHER_SURVIVE))) { allBeneficiaries.closeMother(submission.entityId()); allEligibleCouples.close(mother.ecCaseId()); return; } allBeneficiaries.switchMotherToPNC(submission.entityId()); } } | MotherService { public void deliveryOutcome(FormSubmission submission) { Mother mother = allBeneficiaries.findMotherWithOpenStatus(submission.entityId()); if (mother == null) { logWarn("Failed to handle delivery outcome for mother. Entity ID: " + submission .entityId()); return; } if (BOOLEAN_FALSE.equals(submission.getFieldValue(DID_WOMAN_SURVIVE)) || BOOLEAN_FALSE .equals(submission.getFieldValue(DID_MOTHER_SURVIVE))) { allBeneficiaries.closeMother(submission.entityId()); allEligibleCouples.close(mother.ecCaseId()); return; } allBeneficiaries.switchMotherToPNC(submission.entityId()); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void deliveryOutcome(FormSubmission submission) { Mother mother = allBeneficiaries.findMotherWithOpenStatus(submission.entityId()); if (mother == null) { logWarn("Failed to handle delivery outcome for mother. Entity ID: " + submission .entityId()); return; } if (BOOLEAN_FALSE.equals(submission.getFieldValue(DID_WOMAN_SURVIVE)) || BOOLEAN_FALSE .equals(submission.getFieldValue(DID_MOTHER_SURVIVE))) { allBeneficiaries.closeMother(submission.entityId()); allEligibleCouples.close(mother.ecCaseId()); return; } allBeneficiaries.switchMotherToPNC(submission.entityId()); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void deliveryOutcome(FormSubmission submission) { Mother mother = allBeneficiaries.findMotherWithOpenStatus(submission.entityId()); if (mother == null) { logWarn("Failed to handle delivery outcome for mother. Entity ID: " + submission .entityId()); return; } if (BOOLEAN_FALSE.equals(submission.getFieldValue(DID_WOMAN_SURVIVE)) || BOOLEAN_FALSE .equals(submission.getFieldValue(DID_MOTHER_SURVIVE))) { allBeneficiaries.closeMother(submission.entityId()); allEligibleCouples.close(mother.ecCaseId()); return; } allBeneficiaries.switchMotherToPNC(submission.entityId()); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddPNCVisitTimelineEventWhenPNCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); when(submission.getFieldValue("submissionDate")).thenReturn("2013-01-01"); service.pncVisitHappened(submission); verify(allTimelineEvents).add(TimelineEvent.forMotherPNCVisit("entity id 1", "2", "2012-01-01", "120", "80", "98.1", "10.0")); } | public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void assertgenerateFormSubmisionFromXMLString() throws Exception { formUtils = new FormUtils(context_); String formData = getStringFromStream(new FileInputStream(getFileFromPath(this, formSubmissionXML))); Mockito.when(context_.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open(formDefinition)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formDefinition)); } }); Mockito.when(assetManager.open(model)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, model)); } }); Mockito.when(assetManager.open(formJSON)).thenAnswer(new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock invocation) throws Throwable { return new FileInputStream(getFileFromPath(this, formJSON)); } }); FormDataRepository formDataRepository = Mockito.mock(FormDataRepository.class); Mockito.when(context.formDataRepository()).thenReturn(formDataRepository); Mockito.when(formDataRepository.queryUniqueResult(Mockito.anyString(),Mockito.any(String[].class))).thenReturn(null); Assert.assertNotNull(formUtils.generateFormSubmisionFromXMLString("baseEntityId", formData, FORMNAME, new JSONObject())); } | public FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides) throws Exception { JSONObject formSubmission = XML.toJSONObject(formData); System.out.println(formSubmission); String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String rootNodeKey = formSubmission.keys().next(); entity_id = formSubmission.getJSONObject(rootNodeKey).has(databaseIdKey) ? formSubmission .getJSONObject(rootNodeKey).getString(databaseIdKey) : generateRandomUUIDString(); JSONObject fieldsDefinition = formDefinition.getJSONObject("form"); JSONArray populatedFieldsArray = getPopulatedFieldsForArray(fieldsDefinition, entity_id, formSubmission, overrides); formDefinition.getJSONObject("form").put("fields", populatedFieldsArray); if (formDefinition.getJSONObject("form").has("sub_forms")) { JSONObject subFormDefinition = formDefinition.getJSONObject("form"). getJSONArray("sub_forms").getJSONObject(0); String bindPath = subFormDefinition.getString("default_bind_path"); JSONArray subFormDataArray = new JSONArray(); Object subFormDataObject = getObjectAtPath(bindPath.split("/"), formSubmission); if (subFormDataObject instanceof JSONObject) { JSONObject subFormData = (JSONObject) subFormDataObject; subFormDataArray.put(0, subFormData); } else if (subFormDataObject instanceof JSONArray) { subFormDataArray = (JSONArray) subFormDataObject; } JSONArray subForms = getSubForms(subFormDataArray, entity_id, subFormDefinition, overrides); formDefinition.getJSONObject("form").put("sub_forms", subForms); } String instanceId = generateRandomUUIDString(); String entityId = retrieveIdForSubmission(formDefinition); String formDefinitionVersionString = formDefinition .getString("form_data_definition_version"); String clientVersion = String.valueOf(new Date().getTime()); String instance = formDefinition.toString(); FormSubmission fs = new FormSubmission(instanceId, entityId, formName, instance, clientVersion, SyncStatus.PENDING, formDefinitionVersionString); generateClientAndEventModelsForFormSubmission(fs, formName); return fs; } | FormUtils { public FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides) throws Exception { JSONObject formSubmission = XML.toJSONObject(formData); System.out.println(formSubmission); String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String rootNodeKey = formSubmission.keys().next(); entity_id = formSubmission.getJSONObject(rootNodeKey).has(databaseIdKey) ? formSubmission .getJSONObject(rootNodeKey).getString(databaseIdKey) : generateRandomUUIDString(); JSONObject fieldsDefinition = formDefinition.getJSONObject("form"); JSONArray populatedFieldsArray = getPopulatedFieldsForArray(fieldsDefinition, entity_id, formSubmission, overrides); formDefinition.getJSONObject("form").put("fields", populatedFieldsArray); if (formDefinition.getJSONObject("form").has("sub_forms")) { JSONObject subFormDefinition = formDefinition.getJSONObject("form"). getJSONArray("sub_forms").getJSONObject(0); String bindPath = subFormDefinition.getString("default_bind_path"); JSONArray subFormDataArray = new JSONArray(); Object subFormDataObject = getObjectAtPath(bindPath.split("/"), formSubmission); if (subFormDataObject instanceof JSONObject) { JSONObject subFormData = (JSONObject) subFormDataObject; subFormDataArray.put(0, subFormData); } else if (subFormDataObject instanceof JSONArray) { subFormDataArray = (JSONArray) subFormDataObject; } JSONArray subForms = getSubForms(subFormDataArray, entity_id, subFormDefinition, overrides); formDefinition.getJSONObject("form").put("sub_forms", subForms); } String instanceId = generateRandomUUIDString(); String entityId = retrieveIdForSubmission(formDefinition); String formDefinitionVersionString = formDefinition .getString("form_data_definition_version"); String clientVersion = String.valueOf(new Date().getTime()); String instance = formDefinition.toString(); FormSubmission fs = new FormSubmission(instanceId, entityId, formName, instance, clientVersion, SyncStatus.PENDING, formDefinitionVersionString); generateClientAndEventModelsForFormSubmission(fs, formName); return fs; } } | FormUtils { public FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides) throws Exception { JSONObject formSubmission = XML.toJSONObject(formData); System.out.println(formSubmission); String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String rootNodeKey = formSubmission.keys().next(); entity_id = formSubmission.getJSONObject(rootNodeKey).has(databaseIdKey) ? formSubmission .getJSONObject(rootNodeKey).getString(databaseIdKey) : generateRandomUUIDString(); JSONObject fieldsDefinition = formDefinition.getJSONObject("form"); JSONArray populatedFieldsArray = getPopulatedFieldsForArray(fieldsDefinition, entity_id, formSubmission, overrides); formDefinition.getJSONObject("form").put("fields", populatedFieldsArray); if (formDefinition.getJSONObject("form").has("sub_forms")) { JSONObject subFormDefinition = formDefinition.getJSONObject("form"). getJSONArray("sub_forms").getJSONObject(0); String bindPath = subFormDefinition.getString("default_bind_path"); JSONArray subFormDataArray = new JSONArray(); Object subFormDataObject = getObjectAtPath(bindPath.split("/"), formSubmission); if (subFormDataObject instanceof JSONObject) { JSONObject subFormData = (JSONObject) subFormDataObject; subFormDataArray.put(0, subFormData); } else if (subFormDataObject instanceof JSONArray) { subFormDataArray = (JSONArray) subFormDataObject; } JSONArray subForms = getSubForms(subFormDataArray, entity_id, subFormDefinition, overrides); formDefinition.getJSONObject("form").put("sub_forms", subForms); } String instanceId = generateRandomUUIDString(); String entityId = retrieveIdForSubmission(formDefinition); String formDefinitionVersionString = formDefinition .getString("form_data_definition_version"); String clientVersion = String.valueOf(new Date().getTime()); String instance = formDefinition.toString(); FormSubmission fs = new FormSubmission(instanceId, entityId, formName, instance, clientVersion, SyncStatus.PENDING, formDefinitionVersionString); generateClientAndEventModelsForFormSubmission(fs, formName); return fs; } FormUtils(Context context); } | FormUtils { public FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides) throws Exception { JSONObject formSubmission = XML.toJSONObject(formData); System.out.println(formSubmission); String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String rootNodeKey = formSubmission.keys().next(); entity_id = formSubmission.getJSONObject(rootNodeKey).has(databaseIdKey) ? formSubmission .getJSONObject(rootNodeKey).getString(databaseIdKey) : generateRandomUUIDString(); JSONObject fieldsDefinition = formDefinition.getJSONObject("form"); JSONArray populatedFieldsArray = getPopulatedFieldsForArray(fieldsDefinition, entity_id, formSubmission, overrides); formDefinition.getJSONObject("form").put("fields", populatedFieldsArray); if (formDefinition.getJSONObject("form").has("sub_forms")) { JSONObject subFormDefinition = formDefinition.getJSONObject("form"). getJSONArray("sub_forms").getJSONObject(0); String bindPath = subFormDefinition.getString("default_bind_path"); JSONArray subFormDataArray = new JSONArray(); Object subFormDataObject = getObjectAtPath(bindPath.split("/"), formSubmission); if (subFormDataObject instanceof JSONObject) { JSONObject subFormData = (JSONObject) subFormDataObject; subFormDataArray.put(0, subFormData); } else if (subFormDataObject instanceof JSONArray) { subFormDataArray = (JSONArray) subFormDataObject; } JSONArray subForms = getSubForms(subFormDataArray, entity_id, subFormDefinition, overrides); formDefinition.getJSONObject("form").put("sub_forms", subForms); } String instanceId = generateRandomUUIDString(); String entityId = retrieveIdForSubmission(formDefinition); String formDefinitionVersionString = formDefinition .getString("form_data_definition_version"); String clientVersion = String.valueOf(new Date().getTime()); String instance = formDefinition.toString(); FormSubmission fs = new FormSubmission(instanceId, entityId, formName, instance, clientVersion, SyncStatus.PENDING, formDefinitionVersionString); generateClientAndEventModelsForFormSubmission(fs, formName); return fs; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); } | FormUtils { public FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides) throws Exception { JSONObject formSubmission = XML.toJSONObject(formData); System.out.println(formSubmission); String formDefinitionJson = readFileFromAssetsFolder( "www/form/" + formName + "/form_definition.json"); JSONObject formDefinition = new JSONObject(formDefinitionJson); String rootNodeKey = formSubmission.keys().next(); entity_id = formSubmission.getJSONObject(rootNodeKey).has(databaseIdKey) ? formSubmission .getJSONObject(rootNodeKey).getString(databaseIdKey) : generateRandomUUIDString(); JSONObject fieldsDefinition = formDefinition.getJSONObject("form"); JSONArray populatedFieldsArray = getPopulatedFieldsForArray(fieldsDefinition, entity_id, formSubmission, overrides); formDefinition.getJSONObject("form").put("fields", populatedFieldsArray); if (formDefinition.getJSONObject("form").has("sub_forms")) { JSONObject subFormDefinition = formDefinition.getJSONObject("form"). getJSONArray("sub_forms").getJSONObject(0); String bindPath = subFormDefinition.getString("default_bind_path"); JSONArray subFormDataArray = new JSONArray(); Object subFormDataObject = getObjectAtPath(bindPath.split("/"), formSubmission); if (subFormDataObject instanceof JSONObject) { JSONObject subFormData = (JSONObject) subFormDataObject; subFormDataArray.put(0, subFormData); } else if (subFormDataObject instanceof JSONArray) { subFormDataArray = (JSONArray) subFormDataObject; } JSONArray subForms = getSubForms(subFormDataArray, entity_id, subFormDefinition, overrides); formDefinition.getJSONObject("form").put("sub_forms", subForms); } String instanceId = generateRandomUUIDString(); String entityId = retrieveIdForSubmission(formDefinition); String formDefinitionVersionString = formDefinition .getString("form_data_definition_version"); String clientVersion = String.valueOf(new Date().getTime()); String instance = formDefinition.toString(); FormSubmission fs = new FormSubmission(instanceId, entityId, formName, instance, clientVersion, SyncStatus.PENDING, formDefinitionVersionString); generateClientAndEventModelsForFormSubmission(fs, formName); return fs; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } |
@Test public void shouldAddIFATabletsGivenTimelineEventWhenPNCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-02"); service.pncVisitHappened(submission); verify(allTimelineEvents).add(forIFATabletsGiven("entity id 1", "100", "2012-01-02")); } | public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddPNCVisitServiceProvidedWhenPNCVisitHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn("100"); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); when(submission.getFieldValue("submissionDate")).thenReturn("2013-01-01"); service.pncVisitHappened(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "PNC", "2012-01-01", mapOf("day", "2"))); } | public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldNotAddIFATabletsGivenTimelineEventWhenPNCVisitHappensAndNoIFATabletsWereGiven() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("pncVisitDay")).thenReturn("2"); when(submission.getFieldValue("pncVisitDate")).thenReturn("2012-01-01"); when(submission.getFieldValue("numberOfIFATabletsGiven")).thenReturn(""); when(submission.getFieldValue("ifaTabletsDate")).thenReturn(null); when(submission.getFieldValue("bpSystolic")).thenReturn("120"); when(submission.getFieldValue("bpDiastolic")).thenReturn("80"); when(submission.getFieldValue("temperature")).thenReturn("98.1"); when(submission.getFieldValue("hbLevel")).thenReturn("10.0"); service.pncVisitHappened(submission); verify(allTimelineEvents, times(0)).add(forIFATabletsGiven("entity id 1", "2012-01-01", "100")); } | public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void pncVisitHappened(FormSubmission submission) { allTimelines.add(forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE), submission.getFieldValue(AllConstants.PNCVisitFields.BP_SYSTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.BP_DIASTOLIC), submission.getFieldValue(AllConstants.PNCVisitFields.TEMPERATURE), submission.getFieldValue(AllConstants.PNCVisitFields.HB_LEVEL))); serviceProvidedService.add(ServiceProvided.forMotherPNCVisit(submission.entityId(), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DAY), submission.getFieldValue(AllConstants.PNCVisitFields.PNC_VISIT_DATE))); String numberOfIFATabletsGiven = submission .getFieldValue(AllConstants.PNCVisitFields.NUMBER_OF_IFA_TABLETS_GIVEN); if (tryParse(numberOfIFATabletsGiven, 0) > 0) { allTimelines.add(forIFATabletsGiven(submission.entityId(), numberOfIFATabletsGiven, submission.getFieldValue(SUBMISSION_DATE))); } } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddTimelineEventWhenDeliveryPlanHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("deliveryFacilityName")).thenReturn("Delivery Facility Name"); when(submission.getFieldValue("transportationPlan")).thenReturn("Transportation Plan"); when(submission.getFieldValue("birthCompanion")).thenReturn("Birth Companion"); when(submission.getFieldValue("ashaPhoneNumber")).thenReturn("Asha Phone"); when(submission.getFieldValue("phoneNumber")).thenReturn("1234567890"); when(submission.getFieldValue("reviewedHRPStatus")).thenReturn("HRP Status"); when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-01"); service.deliveryPlan(submission); verify(allTimelineEvents).add(forDeliveryPlan("entity id 1", "Delivery Facility Name", "Transportation Plan", "Birth Companion", "Asha Phone", "1234567890", "HRP Status", "2012-01-01")); } | public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void shouldAddServiceProvidedWhenDeliveryPlanHappens() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("deliveryFacilityName")).thenReturn("Delivery Facility Name"); when(submission.getFieldValue("transportationPlan")).thenReturn("Transportation Plan"); when(submission.getFieldValue("birthCompanion")).thenReturn("Birth Companion"); when(submission.getFieldValue("ashaPhoneNumber")).thenReturn("Asha Phone"); when(submission.getFieldValue("phoneNumber")).thenReturn("1234567890"); when(submission.getFieldValue("reviewedHRPStatus")).thenReturn("HRP Status"); when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-01"); service.deliveryPlan(submission); verify(serviceProvidedService).add(ServiceProvided.forDeliveryPlan("entity id 1", "Delivery Facility Name", "Transportation Plan", "Birth Companion", "Asha Phone", "1234567890", "HRP Status", "2012-01-01")); } | public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); } | MotherService { public void deliveryPlan(FormSubmission submission) { allTimelines.add(forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); serviceProvidedService.add(ServiceProvided.forDeliveryPlan(submission.entityId(), submission.getFieldValue(DELIVERY_FACILITY_NAME), submission.getFieldValue(TRANSPORTATION_PLAN), submission.getFieldValue(BIRTH_COMPANION), submission.getFieldValue(ASHA_PHONE_NUMBER), submission.getFieldValue(PHONE_NUMBER), submission.getFieldValue(REVIEWED_HRP_STATUS), submission.getFieldValue(SUBMISSION_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples
allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService
serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; } |
@Test public void testReadValueClearsEditableAfterReadingValue() { Mockito.doReturn(2).when(editable).length(); SecurityHelper.readValue(editable); ArgumentCaptor<Integer> lengthCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<char[]> charsCaptor = ArgumentCaptor.forClass(char[].class); ArgumentCaptor<Integer> firstArgCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> lastArgCaptor = ArgumentCaptor.forClass(Integer.class); Mockito.verify(editable).getChars(firstArgCaptor.capture(), lengthCaptor.capture(), charsCaptor.capture(), lastArgCaptor.capture()); Assert.assertEquals(2, lengthCaptor.getValue().intValue()); Assert.assertEquals(0, firstArgCaptor.getValue().intValue()); Assert.assertEquals(0, lastArgCaptor.getValue().intValue()); } | public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } | SecurityHelper { public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } } | SecurityHelper { public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } } | SecurityHelper { public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); } | SecurityHelper { public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } |
@Test public void clearArray() { byte[] sensitiveDataArray = SecurityHelper.toBytes(TEST_PASSWORD); SecurityHelper.clearArray(sensitiveDataArray); Assert.assertNotNull(sensitiveDataArray); for (byte c : sensitiveDataArray) { Assert.assertEquals((byte) 0, c); } } | public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } |
@Test public void testClearArrayOverwritesCharArrayValuesWithAsterisk() { char[] sensitiveDataArray = TEST_PASSWORD; SecurityHelper.clearArray(sensitiveDataArray); Assert.assertNotNull(sensitiveDataArray); for (char c : sensitiveDataArray) { Assert.assertEquals('*', c); } } | public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); } | SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } |
@Test public void testToBytes() throws CharacterCodingException { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(TEST_PASSWORD); byte[] testPasswordBytes = SecurityHelper.toBytes(stringBuffer); Assert.assertNotNull(testPasswordBytes); Assert.assertEquals(TEST_PASSWORD.length + 1, testPasswordBytes.length); } | public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()); clearStringBuffer(stringBuffer); return bytes; } | SecurityHelper { public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()); clearStringBuffer(stringBuffer); return bytes; } } | SecurityHelper { public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()); clearStringBuffer(stringBuffer); return bytes; } } | SecurityHelper { public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()); clearStringBuffer(stringBuffer); return bytes; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); } | SecurityHelper { public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()); clearStringBuffer(stringBuffer); return bytes; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } |
@Test public void nullSafeBase64DecodeDoesNotThrowExceptionIfParameterIsNull() { PowerMockito.mockStatic(Base64.class); PowerMockito.when(Base64.decode(ArgumentMatchers.anyString(), ArgumentMatchers.eq(Base64.DEFAULT))).thenReturn(new byte[]{0, 1}); byte[] decoded = SecurityHelper.nullSafeBase64Decode(null); Assert.assertNull(decoded); } | public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } | SecurityHelper { public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } } | SecurityHelper { public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } } | SecurityHelper { public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); } | SecurityHelper { public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } |
@Test public void getFormJsonShouldReturnCorrectFormWithSameLength() { Mockito.doReturn(RuntimeEnvironment.application.getResources()).when(context_).getResources(); Mockito.doReturn(RuntimeEnvironment.application.getApplicationContext()).when(context_).getApplicationContext(); Assert.assertEquals(10011, formUtils.getFormJson("test_basic_form").toString().length()); } | public JSONObject getFormJson(String formIdentity) { if (mContext != null) { try { String locale = mContext.getResources().getConfiguration().locale.getLanguage(); locale = locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage()) ? "" : "-" + locale; InputStream inputStream; try { inputStream = mContext.getApplicationContext().getAssets() .open("json.form" + locale + "/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } catch (FileNotFoundException e) { inputStream = mContext.getApplicationContext().getAssets() .open("json.form/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, CharEncoding.UTF_8)); String jsonString; StringBuilder stringBuilder = new StringBuilder(); while ((jsonString = reader.readLine()) != null) { stringBuilder.append(jsonString); } inputStream.close(); return new JSONObject(stringBuilder.toString()); } catch (IOException | JSONException e) { Timber.e(e); } } return null; } | FormUtils { public JSONObject getFormJson(String formIdentity) { if (mContext != null) { try { String locale = mContext.getResources().getConfiguration().locale.getLanguage(); locale = locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage()) ? "" : "-" + locale; InputStream inputStream; try { inputStream = mContext.getApplicationContext().getAssets() .open("json.form" + locale + "/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } catch (FileNotFoundException e) { inputStream = mContext.getApplicationContext().getAssets() .open("json.form/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, CharEncoding.UTF_8)); String jsonString; StringBuilder stringBuilder = new StringBuilder(); while ((jsonString = reader.readLine()) != null) { stringBuilder.append(jsonString); } inputStream.close(); return new JSONObject(stringBuilder.toString()); } catch (IOException | JSONException e) { Timber.e(e); } } return null; } } | FormUtils { public JSONObject getFormJson(String formIdentity) { if (mContext != null) { try { String locale = mContext.getResources().getConfiguration().locale.getLanguage(); locale = locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage()) ? "" : "-" + locale; InputStream inputStream; try { inputStream = mContext.getApplicationContext().getAssets() .open("json.form" + locale + "/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } catch (FileNotFoundException e) { inputStream = mContext.getApplicationContext().getAssets() .open("json.form/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, CharEncoding.UTF_8)); String jsonString; StringBuilder stringBuilder = new StringBuilder(); while ((jsonString = reader.readLine()) != null) { stringBuilder.append(jsonString); } inputStream.close(); return new JSONObject(stringBuilder.toString()); } catch (IOException | JSONException e) { Timber.e(e); } } return null; } FormUtils(Context context); } | FormUtils { public JSONObject getFormJson(String formIdentity) { if (mContext != null) { try { String locale = mContext.getResources().getConfiguration().locale.getLanguage(); locale = locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage()) ? "" : "-" + locale; InputStream inputStream; try { inputStream = mContext.getApplicationContext().getAssets() .open("json.form" + locale + "/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } catch (FileNotFoundException e) { inputStream = mContext.getApplicationContext().getAssets() .open("json.form/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, CharEncoding.UTF_8)); String jsonString; StringBuilder stringBuilder = new StringBuilder(); while ((jsonString = reader.readLine()) != null) { stringBuilder.append(jsonString); } inputStream.close(); return new JSONObject(stringBuilder.toString()); } catch (IOException | JSONException e) { Timber.e(e); } } return null; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); } | FormUtils { public JSONObject getFormJson(String formIdentity) { if (mContext != null) { try { String locale = mContext.getResources().getConfiguration().locale.getLanguage(); locale = locale.equalsIgnoreCase(Locale.ENGLISH.getLanguage()) ? "" : "-" + locale; InputStream inputStream; try { inputStream = mContext.getApplicationContext().getAssets() .open("json.form" + locale + "/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } catch (FileNotFoundException e) { inputStream = mContext.getApplicationContext().getAssets() .open("json.form/" + formIdentity + AllConstants.JSON_FILE_EXTENSION); } BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, CharEncoding.UTF_8)); String jsonString; StringBuilder stringBuilder = new StringBuilder(); while ((jsonString = reader.readLine()) != null) { stringBuilder.append(jsonString); } inputStream.close(); return new JSONObject(stringBuilder.toString()); } catch (IOException | JSONException e) { Timber.e(e); } } return null; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } |
@Test public void testGenerateRandomPassphraseGeneratesAlphanumericArray() { char[] value = SecurityHelper.generateRandomPassphrase(); Assert.assertNotNull(value); Assert.assertTrue(StringUtils.isAlphanumeric(new StringBuilder().append(value).toString())); Assert.assertEquals(32, value.length); } | public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } | SecurityHelper { public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } } | SecurityHelper { public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } } | SecurityHelper { public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); } | SecurityHelper { public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; } |
@Test public void initP2pLibrary() { String expectedUsername = "nurse1"; String expectedTeamIdPassword = "908980dslkjfljsdlf"; Mockito.doReturn(RuntimeEnvironment.application) .when(context) .applicationContext(); AllSharedPreferences allSharedPreferences = new AllSharedPreferences( PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application.getApplicationContext()) ); allSharedPreferences.updateANMUserName(expectedUsername); allSharedPreferences.saveDefaultTeamId(expectedUsername, expectedTeamIdPassword); P2PLibrary.Options p2POptions = new P2PLibrary.Options(context.applicationContext(), expectedTeamIdPassword, expectedUsername, p2PAuthorizationService, receiverTransferDao, senderTransferDao); P2PLibrary.init(p2POptions); P2PLibrary p2PLibrary = P2PLibrary.getInstance(); assertEquals(expectedUsername, p2PLibrary.getUsername()); } | public void initP2pLibrary(@Nullable String username) { if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { String p2pUsername = username; AllSharedPreferences allSharedPreferences = new AllSharedPreferences(getDefaultSharedPreferences(context.applicationContext())); if (p2pUsername == null) { p2pUsername = allSharedPreferences.fetchRegisteredANM(); } if (!TextUtils.isEmpty(p2pUsername)) { String teamId = allSharedPreferences.fetchDefaultTeamId(p2pUsername); if (p2POptions.getAuthorizationService() == null) { p2POptions.setAuthorizationService(new P2PSyncAuthorizationService(teamId)); } if (p2POptions.getReceiverTransferDao() == null) { p2POptions.setReceiverTransferDao(new P2PReceiverTransferDao()); } if (p2POptions.getSenderTransferDao() == null) { p2POptions.setSenderTransferDao(new P2PSenderTransferDao()); } if (p2POptions.getSyncFinishedCallback() == null) { p2POptions.setSyncFinishedCallback(new P2PSyncFinishCallback()); } P2PLibrary.Options options = new P2PLibrary.Options(context.applicationContext() , teamId, p2pUsername, p2POptions.getAuthorizationService(), p2POptions.getReceiverTransferDao() , p2POptions.getSenderTransferDao()); options.setBatchSize(p2POptions.getBatchSize()); options.setSyncFinishedCallback(p2POptions.getSyncFinishedCallback()); options.setRecalledIdentifier(p2POptions.getRecalledIdentifier()); P2PLibrary.init(options); } } } | CoreLibrary implements OnAccountsUpdateListener { public void initP2pLibrary(@Nullable String username) { if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { String p2pUsername = username; AllSharedPreferences allSharedPreferences = new AllSharedPreferences(getDefaultSharedPreferences(context.applicationContext())); if (p2pUsername == null) { p2pUsername = allSharedPreferences.fetchRegisteredANM(); } if (!TextUtils.isEmpty(p2pUsername)) { String teamId = allSharedPreferences.fetchDefaultTeamId(p2pUsername); if (p2POptions.getAuthorizationService() == null) { p2POptions.setAuthorizationService(new P2PSyncAuthorizationService(teamId)); } if (p2POptions.getReceiverTransferDao() == null) { p2POptions.setReceiverTransferDao(new P2PReceiverTransferDao()); } if (p2POptions.getSenderTransferDao() == null) { p2POptions.setSenderTransferDao(new P2PSenderTransferDao()); } if (p2POptions.getSyncFinishedCallback() == null) { p2POptions.setSyncFinishedCallback(new P2PSyncFinishCallback()); } P2PLibrary.Options options = new P2PLibrary.Options(context.applicationContext() , teamId, p2pUsername, p2POptions.getAuthorizationService(), p2POptions.getReceiverTransferDao() , p2POptions.getSenderTransferDao()); options.setBatchSize(p2POptions.getBatchSize()); options.setSyncFinishedCallback(p2POptions.getSyncFinishedCallback()); options.setRecalledIdentifier(p2POptions.getRecalledIdentifier()); P2PLibrary.init(options); } } } } | CoreLibrary implements OnAccountsUpdateListener { public void initP2pLibrary(@Nullable String username) { if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { String p2pUsername = username; AllSharedPreferences allSharedPreferences = new AllSharedPreferences(getDefaultSharedPreferences(context.applicationContext())); if (p2pUsername == null) { p2pUsername = allSharedPreferences.fetchRegisteredANM(); } if (!TextUtils.isEmpty(p2pUsername)) { String teamId = allSharedPreferences.fetchDefaultTeamId(p2pUsername); if (p2POptions.getAuthorizationService() == null) { p2POptions.setAuthorizationService(new P2PSyncAuthorizationService(teamId)); } if (p2POptions.getReceiverTransferDao() == null) { p2POptions.setReceiverTransferDao(new P2PReceiverTransferDao()); } if (p2POptions.getSenderTransferDao() == null) { p2POptions.setSenderTransferDao(new P2PSenderTransferDao()); } if (p2POptions.getSyncFinishedCallback() == null) { p2POptions.setSyncFinishedCallback(new P2PSyncFinishCallback()); } P2PLibrary.Options options = new P2PLibrary.Options(context.applicationContext() , teamId, p2pUsername, p2POptions.getAuthorizationService(), p2POptions.getReceiverTransferDao() , p2POptions.getSenderTransferDao()); options.setBatchSize(p2POptions.getBatchSize()); options.setSyncFinishedCallback(p2POptions.getSyncFinishedCallback()); options.setRecalledIdentifier(p2POptions.getRecalledIdentifier()); P2PLibrary.init(options); } } } protected CoreLibrary(Context contextArg, SyncConfiguration syncConfiguration, @Nullable P2POptions p2POptions); } | CoreLibrary implements OnAccountsUpdateListener { public void initP2pLibrary(@Nullable String username) { if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { String p2pUsername = username; AllSharedPreferences allSharedPreferences = new AllSharedPreferences(getDefaultSharedPreferences(context.applicationContext())); if (p2pUsername == null) { p2pUsername = allSharedPreferences.fetchRegisteredANM(); } if (!TextUtils.isEmpty(p2pUsername)) { String teamId = allSharedPreferences.fetchDefaultTeamId(p2pUsername); if (p2POptions.getAuthorizationService() == null) { p2POptions.setAuthorizationService(new P2PSyncAuthorizationService(teamId)); } if (p2POptions.getReceiverTransferDao() == null) { p2POptions.setReceiverTransferDao(new P2PReceiverTransferDao()); } if (p2POptions.getSenderTransferDao() == null) { p2POptions.setSenderTransferDao(new P2PSenderTransferDao()); } if (p2POptions.getSyncFinishedCallback() == null) { p2POptions.setSyncFinishedCallback(new P2PSyncFinishCallback()); } P2PLibrary.Options options = new P2PLibrary.Options(context.applicationContext() , teamId, p2pUsername, p2POptions.getAuthorizationService(), p2POptions.getReceiverTransferDao() , p2POptions.getSenderTransferDao()); options.setBatchSize(p2POptions.getBatchSize()); options.setSyncFinishedCallback(p2POptions.getSyncFinishedCallback()); options.setRecalledIdentifier(p2POptions.getRecalledIdentifier()); P2PLibrary.init(options); } } } protected CoreLibrary(Context contextArg, SyncConfiguration syncConfiguration, @Nullable P2POptions p2POptions); static void init(Context context); static void init(Context context, SyncConfiguration syncConfiguration); static void init(Context context, SyncConfiguration syncConfiguration, long buildTimestamp); static void init(Context context, SyncConfiguration syncConfiguration, long buildTimestamp, @NonNull P2POptions options); static CoreLibrary getInstance(); void initP2pLibrary(@Nullable String username); Context context(); static void reset(Context context); static void reset(Context context, SyncConfiguration syncConfiguration); SyncConfiguration getSyncConfiguration(); AccountManager getAccountManager(); AccountAuthenticatorXml getAccountAuthenticatorXml(); static long getBuildTimeStamp(); String getEcClientFieldsFile(); void setEcClientFieldsFile(String ecClientFieldsFile); @Nullable P2POptions getP2POptions(); boolean isPeerToPeerProcessing(); void setPeerToPeerProcessing(boolean peerToPeerProcessing); @Override void onAccountsUpdated(Account[] accounts); } | CoreLibrary implements OnAccountsUpdateListener { public void initP2pLibrary(@Nullable String username) { if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { String p2pUsername = username; AllSharedPreferences allSharedPreferences = new AllSharedPreferences(getDefaultSharedPreferences(context.applicationContext())); if (p2pUsername == null) { p2pUsername = allSharedPreferences.fetchRegisteredANM(); } if (!TextUtils.isEmpty(p2pUsername)) { String teamId = allSharedPreferences.fetchDefaultTeamId(p2pUsername); if (p2POptions.getAuthorizationService() == null) { p2POptions.setAuthorizationService(new P2PSyncAuthorizationService(teamId)); } if (p2POptions.getReceiverTransferDao() == null) { p2POptions.setReceiverTransferDao(new P2PReceiverTransferDao()); } if (p2POptions.getSenderTransferDao() == null) { p2POptions.setSenderTransferDao(new P2PSenderTransferDao()); } if (p2POptions.getSyncFinishedCallback() == null) { p2POptions.setSyncFinishedCallback(new P2PSyncFinishCallback()); } P2PLibrary.Options options = new P2PLibrary.Options(context.applicationContext() , teamId, p2pUsername, p2POptions.getAuthorizationService(), p2POptions.getReceiverTransferDao() , p2POptions.getSenderTransferDao()); options.setBatchSize(p2POptions.getBatchSize()); options.setSyncFinishedCallback(p2POptions.getSyncFinishedCallback()); options.setRecalledIdentifier(p2POptions.getRecalledIdentifier()); P2PLibrary.init(options); } } } protected CoreLibrary(Context contextArg, SyncConfiguration syncConfiguration, @Nullable P2POptions p2POptions); static void init(Context context); static void init(Context context, SyncConfiguration syncConfiguration); static void init(Context context, SyncConfiguration syncConfiguration, long buildTimestamp); static void init(Context context, SyncConfiguration syncConfiguration, long buildTimestamp, @NonNull P2POptions options); static CoreLibrary getInstance(); void initP2pLibrary(@Nullable String username); Context context(); static void reset(Context context); static void reset(Context context, SyncConfiguration syncConfiguration); SyncConfiguration getSyncConfiguration(); AccountManager getAccountManager(); AccountAuthenticatorXml getAccountAuthenticatorXml(); static long getBuildTimeStamp(); String getEcClientFieldsFile(); void setEcClientFieldsFile(String ecClientFieldsFile); @Nullable P2POptions getP2POptions(); boolean isPeerToPeerProcessing(); void setPeerToPeerProcessing(boolean peerToPeerProcessing); @Override void onAccountsUpdated(Account[] accounts); } |
@Test public void testAddOrUpdateShouldAdd() { Campaign campaign = gson.fromJson(campaignJson, Campaign.class); campaignRepository.addOrUpdate(campaign); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); assertEquals(2, stringArgumentCaptor.getAllValues().size()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(CAMPAIGN_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(10, contentValues.size()); assertEquals("IRS_2018_S1", contentValues.getAsString("_id")); assertEquals("2019 IRS Season 1", contentValues.getAsString("title")); assertEquals(IN_PROGRESS.name(), contentValues.getAsString("status")); } | public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } |
@Test(expected = IllegalArgumentException.class) public void testAddOrUpdateShouldThrowException() { Campaign campaign = new Campaign(); campaignRepository.addOrUpdate(campaign); } | public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | CampaignRepository extends BaseRepository { public void addOrUpdate(Campaign campaign) { if (StringUtils.isBlank(campaign.getIdentifier())) throw new IllegalArgumentException("Identifier must be specified"); ContentValues contentValues = new ContentValues(); contentValues.put(ID, campaign.getIdentifier()); contentValues.put(TITLE, campaign.getTitle()); contentValues.put(DESCRIPTION, campaign.getDescription()); if (campaign.getStatus() != null) { contentValues.put(STATUS, campaign.getStatus().name()); } if (campaign.getExecutionPeriod() != null) { contentValues.put(START, DateUtil.getMillis(campaign.getExecutionPeriod().getStart())); contentValues.put(END, DateUtil.getMillis(campaign.getExecutionPeriod().getEnd())); } contentValues.put(AUTHORED_ON, DateUtil.getMillis(campaign.getAuthoredOn())); contentValues.put(LAST_MODIFIED, DateUtil.getMillis(campaign.getLastModified())); contentValues.put(OWNER, campaign.getOwner()); contentValues.put(SERVER_VERSION, campaign.getServerVersion()); getWritableDatabase().replace(CAMPAIGN_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } |
@Test public void tesGetCampaignsAllCampaigns() { when(sqLiteDatabase.rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null)).thenReturn(getCursor()); List<Campaign> allCampaigns = campaignRepository.getAllCampaigns(); verify(sqLiteDatabase).rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); assertEquals(1, allCampaigns.size()); assertEquals(campaignJson, gson.toJson(allCampaigns.get(0))); } | public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } | CampaignRepository extends BaseRepository { public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } } | CampaignRepository extends BaseRepository { public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } } | CampaignRepository extends BaseRepository { public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | CampaignRepository extends BaseRepository { public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } |
@Test public void testGetCampaignByIdentifier() { when(sqLiteDatabase.rawQuery("SELECT * FROM campaign WHERE _id =?", new String[]{"IRS_2018_S1"})).thenReturn(getCursor()); Campaign campaign = campaignRepository.getCampaignByIdentifier("IRS_2018_S1"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals(1, argsCaptor.getValue().length); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("SELECT * FROM campaign WHERE _id =?", stringArgumentCaptor.getValue()); assertEquals(campaignJson, gson.toJson(campaign)); } | public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } | CampaignRepository extends BaseRepository { public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } } | CampaignRepository extends BaseRepository { public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } } | CampaignRepository extends BaseRepository { public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } | CampaignRepository extends BaseRepository { public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); } |
@Test public void testAddOrUpdateShouldAdd() { Note note = new Note(); note.setText("Should be completed by End of November"); Long now = System.currentTimeMillis(); note.setTime(new DateTime(now)); note.setAuthorString("jdoe"); taskNotesRepository.addOrUpdate(note, "task22132"); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); assertEquals(2, stringArgumentCaptor.getAllValues().size()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(TASK_NOTES_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(4, contentValues.size()); assertEquals("task22132", contentValues.getAsString("task_id")); assertEquals("Should be completed by End of November", contentValues.getAsString("text")); assertEquals("jdoe", contentValues.getAsString("author")); assertEquals(now, contentValues.getAsLong("time")); } | public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } | TaskNotesRepository extends BaseRepository { public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } } | TaskNotesRepository extends BaseRepository { public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } } | TaskNotesRepository extends BaseRepository { public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); } | TaskNotesRepository extends BaseRepository { public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); } |
@Test public void tesGetTasksAllTasks() { when(sqLiteDatabase.rawQuery("SELECT * FROM task_note WHERE task_id =?", new String[]{"task22132"})).thenReturn(getCursor()); List<Note> notes = taskNotesRepository.getNotesByTask("task22132"); verify(sqLiteDatabase).rawQuery("SELECT * FROM task_note WHERE task_id =?", new String[]{"task22132"}); assertEquals(1, notes.size()); assertEquals("Should be completed by End of November", notes.get(0).getText()); assertEquals("jdoe", notes.get(0).getAuthorString()); assertEquals(1543232476345l, notes.get(0).getTime().getMillis()); } | public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } | TaskNotesRepository extends BaseRepository { public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } } | TaskNotesRepository extends BaseRepository { public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } } | TaskNotesRepository extends BaseRepository { public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); } | TaskNotesRepository extends BaseRepository { public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); } |
@Test public void testAddOrUpdateShouldAdd() { Task task = gson.fromJson(taskJson, Task.class); taskRepository.addOrUpdate(task); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(TASK_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(21, contentValues.size()); assertEquals("tsk11231jh22", contentValues.getAsString("_id")); assertEquals("IRS_2018_S1", contentValues.getAsString("plan_id")); assertEquals("2018_IRS-3734", contentValues.getAsString("group_id")); verify(taskNotesRepository).addOrUpdate(task.getNotes().get(0), task.getIdentifier()); } | public void addOrUpdate(Task task) { addOrUpdate(task, false); } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test(expected = IllegalArgumentException.class) public void testAddOrUpdateShouldThrowException() { Task task = new Task(); taskRepository.addOrUpdate(task); } | public void addOrUpdate(Task task) { addOrUpdate(task, false); } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void addOrUpdate(Task task) { addOrUpdate(task, false); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void getIndexForFormNameShouldReturnCorrectIndex() { String[] formNames = new String[] {"Birth Reg", "Immunisation Reg", "Death Form"}; Assert.assertEquals(1, formUtils.getIndexForFormName("Immunisation Reg", formNames)); } | public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } | FormUtils { public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } } | FormUtils { public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } FormUtils(Context context); } | FormUtils { public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); } | FormUtils { public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData,
String formName, JSONObject
overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String
overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId,
JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String
relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; } |
@Test public void testGetTasksByPlanAndGroup() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE plan_id=? AND group_id =? AND status NOT IN (?,?)", new String[]{"IRS_2018_S1", "2018_IRS-3734", CANCELLED.name(), ARCHIVED.name()})).thenReturn(getCursor()); Map<String, Set<Task>> allTasks = taskRepository.getTasksByPlanAndGroup("IRS_2018_S1", "2018_IRS-3734"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM task WHERE plan_id=? AND group_id =? AND status NOT IN (?,?)", stringArgumentCaptor.getValue()); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("2018_IRS-3734", argsCaptor.getValue()[1]); assertEquals(CANCELLED.name(), argsCaptor.getValue()[2]); assertEquals(ARCHIVED.name(), argsCaptor.getValue()[3]); assertEquals(1, allTasks.size()); assertEquals(1, allTasks.get("structure._id.33efadf1-feda-4861-a979-ff4f7cec9ea7").size()); Task task = allTasks.get("structure._id.33efadf1-feda-4861-a979-ff4f7cec9ea7").iterator().next(); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } | public Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId) { Cursor cursor = null; Map<String, Set<Task>> tasks = new HashMap<>(); try { String[] params = new String[]{planId, groupId}; cursor = getReadableDatabase().rawQuery(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))), ArrayUtils.addAll(params, INACTIVE_TASK_STATUS)); while (cursor.moveToNext()) { Set<Task> taskSet; Task task = readCursor(cursor); if (tasks.containsKey(task.getStructureId())) taskSet = tasks.get(task.getStructureId()); else taskSet = new HashSet<>(); taskSet.add(task); tasks.put(task.getStructureId(), taskSet); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return tasks; } | TaskRepository extends BaseRepository { public Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId) { Cursor cursor = null; Map<String, Set<Task>> tasks = new HashMap<>(); try { String[] params = new String[]{planId, groupId}; cursor = getReadableDatabase().rawQuery(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))), ArrayUtils.addAll(params, INACTIVE_TASK_STATUS)); while (cursor.moveToNext()) { Set<Task> taskSet; Task task = readCursor(cursor); if (tasks.containsKey(task.getStructureId())) taskSet = tasks.get(task.getStructureId()); else taskSet = new HashSet<>(); taskSet.add(task); tasks.put(task.getStructureId(), taskSet); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return tasks; } } | TaskRepository extends BaseRepository { public Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId) { Cursor cursor = null; Map<String, Set<Task>> tasks = new HashMap<>(); try { String[] params = new String[]{planId, groupId}; cursor = getReadableDatabase().rawQuery(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))), ArrayUtils.addAll(params, INACTIVE_TASK_STATUS)); while (cursor.moveToNext()) { Set<Task> taskSet; Task task = readCursor(cursor); if (tasks.containsKey(task.getStructureId())) taskSet = tasks.get(task.getStructureId()); else taskSet = new HashSet<>(); taskSet.add(task); tasks.put(task.getStructureId(), taskSet); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return tasks; } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId) { Cursor cursor = null; Map<String, Set<Task>> tasks = new HashMap<>(); try { String[] params = new String[]{planId, groupId}; cursor = getReadableDatabase().rawQuery(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))), ArrayUtils.addAll(params, INACTIVE_TASK_STATUS)); while (cursor.moveToNext()) { Set<Task> taskSet; Task task = readCursor(cursor); if (tasks.containsKey(task.getStructureId())) taskSet = tasks.get(task.getStructureId()); else taskSet = new HashSet<>(); taskSet.add(task); tasks.put(task.getStructureId(), taskSet); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return tasks; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId) { Cursor cursor = null; Map<String, Set<Task>> tasks = new HashMap<>(); try { String[] params = new String[]{planId, groupId}; cursor = getReadableDatabase().rawQuery(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))), ArrayUtils.addAll(params, INACTIVE_TASK_STATUS)); while (cursor.moveToNext()) { Set<Task> taskSet; Task task = readCursor(cursor); if (tasks.containsKey(task.getStructureId())) taskSet = tasks.get(task.getStructureId()); else taskSet = new HashSet<>(); taskSet.add(task); tasks.put(task.getStructureId(), taskSet); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return tasks; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testGetTasksByEntityAndCode() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE plan_id=? AND group_id =? AND for =? AND code =? AND status NOT IN (?,?)", new String[]{"IRS_2018_S1", "2018_IRS-3734", "location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", "IRS", CANCELLED.name(), ARCHIVED.name()})).thenReturn(getCursor()); Set<Task> allTasks = taskRepository.getTasksByEntityAndCode("IRS_2018_S1", "2018_IRS-3734", "location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", "IRS"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM task WHERE plan_id=? AND group_id =? AND for =? AND code =? AND status NOT IN (?,?)", stringArgumentCaptor.getValue()); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("2018_IRS-3734", argsCaptor.getValue()[1]); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", argsCaptor.getValue()[2]); assertEquals("IRS", argsCaptor.getValue()[3]); assertEquals(CANCELLED.name(), argsCaptor.getValue()[4]); assertEquals(ARCHIVED.name(), argsCaptor.getValue()[5]); assertEquals(1, allTasks.size()); Task task = allTasks.iterator().next(); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } | public Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s =? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, FOR, CODE, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, groupId, forEntity, code}, INACTIVE_TASK_STATUS)); } | TaskRepository extends BaseRepository { public Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s =? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, FOR, CODE, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, groupId, forEntity, code}, INACTIVE_TASK_STATUS)); } } | TaskRepository extends BaseRepository { public Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s =? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, FOR, CODE, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, groupId, forEntity, code}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s =? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, FOR, CODE, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, groupId, forEntity, code}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s =? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, GROUP_ID, FOR, CODE, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, groupId, forEntity, code}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testGetTaskByIdentifier() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE _id =?", new String[]{"tsk11231jh22"})).thenReturn(getCursor()); Task task = taskRepository.getTaskByIdentifier("tsk11231jh22"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM task WHERE _id =?", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals("tsk11231jh22", argsCaptor.getValue()[0]); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } | public Task getTaskByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_TABLE + " WHERE " + ID + " =?", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } | TaskRepository extends BaseRepository { public Task getTaskByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_TABLE + " WHERE " + ID + " =?", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } } | TaskRepository extends BaseRepository { public Task getTaskByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_TABLE + " WHERE " + ID + " =?", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public Task getTaskByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_TABLE + " WHERE " + ID + " =?", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public Task getTaskByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_TABLE + " WHERE " + ID + " =?", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testGetUnSyncedTaskStatus() { taskRepository.getUnSyncedTaskStatus(); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertNotNull(taskRepository.getUnSyncedTaskStatus()); } | public List<TaskUpdate> getUnSyncedTaskStatus() { Cursor cursor = null; List<TaskUpdate> taskUpdates = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery(String.format("SELECT " + ID + "," + STATUS + "," + BUSINESS_STATUS + "," + SERVER_VERSION + " FROM %s WHERE %s =?", TASK_TABLE, SYNC_STATUS), new String[]{BaseRepository.TYPE_Unsynced}); while (cursor.moveToNext()) { taskUpdates.add(readUpdateCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return taskUpdates; } | TaskRepository extends BaseRepository { public List<TaskUpdate> getUnSyncedTaskStatus() { Cursor cursor = null; List<TaskUpdate> taskUpdates = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery(String.format("SELECT " + ID + "," + STATUS + "," + BUSINESS_STATUS + "," + SERVER_VERSION + " FROM %s WHERE %s =?", TASK_TABLE, SYNC_STATUS), new String[]{BaseRepository.TYPE_Unsynced}); while (cursor.moveToNext()) { taskUpdates.add(readUpdateCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return taskUpdates; } } | TaskRepository extends BaseRepository { public List<TaskUpdate> getUnSyncedTaskStatus() { Cursor cursor = null; List<TaskUpdate> taskUpdates = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery(String.format("SELECT " + ID + "," + STATUS + "," + BUSINESS_STATUS + "," + SERVER_VERSION + " FROM %s WHERE %s =?", TASK_TABLE, SYNC_STATUS), new String[]{BaseRepository.TYPE_Unsynced}); while (cursor.moveToNext()) { taskUpdates.add(readUpdateCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return taskUpdates; } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public List<TaskUpdate> getUnSyncedTaskStatus() { Cursor cursor = null; List<TaskUpdate> taskUpdates = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery(String.format("SELECT " + ID + "," + STATUS + "," + BUSINESS_STATUS + "," + SERVER_VERSION + " FROM %s WHERE %s =?", TASK_TABLE, SYNC_STATUS), new String[]{BaseRepository.TYPE_Unsynced}); while (cursor.moveToNext()) { taskUpdates.add(readUpdateCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return taskUpdates; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public List<TaskUpdate> getUnSyncedTaskStatus() { Cursor cursor = null; List<TaskUpdate> taskUpdates = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery(String.format("SELECT " + ID + "," + STATUS + "," + BUSINESS_STATUS + "," + SERVER_VERSION + " FROM %s WHERE %s =?", TASK_TABLE, SYNC_STATUS), new String[]{BaseRepository.TYPE_Unsynced}); while (cursor.moveToNext()) { taskUpdates.add(readUpdateCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return taskUpdates; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testUpdateTaskStructureIdFromClient() throws Exception { List<Client> clients = new ArrayList<>(); Client client = gson.fromJson(clientJson, Client.class); clients.add(client); taskRepository.updateTaskStructureIdFromClient(clients, ""); assertNotNull(taskRepository.getUnSyncedTaskStatus()); } | public boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute) { if (clients == null || clients.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Client client : clients) { String taskFor = client.getBaseEntityId(); if (client.getAttribute(attribute) == null) { continue; } String structureId = client.getAttribute(attribute).toString(); updateStatement.bindString(1, structureId); updateStatement.bindString(2, taskFor); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute) { if (clients == null || clients.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Client client : clients) { String taskFor = client.getBaseEntityId(); if (client.getAttribute(attribute) == null) { continue; } String structureId = client.getAttribute(attribute).toString(); updateStatement.bindString(1, structureId); updateStatement.bindString(2, taskFor); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute) { if (clients == null || clients.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Client client : clients) { String taskFor = client.getBaseEntityId(); if (client.getAttribute(attribute) == null) { continue; } String structureId = client.getAttribute(attribute).toString(); updateStatement.bindString(1, structureId); updateStatement.bindString(2, taskFor); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute) { if (clients == null || clients.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Client client : clients) { String taskFor = client.getBaseEntityId(); if (client.getAttribute(attribute) == null) { continue; } String structureId = client.getAttribute(attribute).toString(); updateStatement.bindString(1, structureId); updateStatement.bindString(2, taskFor); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute) { if (clients == null || clients.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Client client : clients) { String taskFor = client.getBaseEntityId(); if (client.getAttribute(attribute) == null) { continue; } String structureId = client.getAttribute(attribute).toString(); updateStatement.bindString(1, structureId); updateStatement.bindString(2, taskFor); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void updateTaskStructureIdFromStructure() throws Exception { List<Location> locations = new ArrayList<>(); Location location = gson.fromJson(structureJson, Location.class); locations.add(location); taskRepository.updateTaskStructureIdFromStructure(locations); assertTrue(taskRepository.updateTaskStructureIdFromStructure(locations)); } | public boolean updateTaskStructureIdFromStructure(List<Location> locations) { if (locations == null || locations.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Location location : locations) { updateStatement.bindString(1, location.getId()); updateStatement.bindString(2, location.getId()); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromStructure(List<Location> locations) { if (locations == null || locations.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Location location : locations) { updateStatement.bindString(1, location.getId()); updateStatement.bindString(2, location.getId()); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromStructure(List<Location> locations) { if (locations == null || locations.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Location location : locations) { updateStatement.bindString(1, location.getId()); updateStatement.bindString(2, location.getId()); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromStructure(List<Location> locations) { if (locations == null || locations.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Location location : locations) { updateStatement.bindString(1, location.getId()); updateStatement.bindString(2, location.getId()); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdFromStructure(List<Location> locations) { if (locations == null || locations.isEmpty()) { return false; } SQLiteStatement updateStatement = null; try { getWritableDatabase().beginTransaction(); String updateTaskSructureIdQuery = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s IS NULL", TASK_TABLE, STRUCTURE_ID, FOR, STRUCTURE_ID); updateStatement = getWritableDatabase().compileStatement(updateTaskSructureIdQuery); for (Location location : locations) { updateStatement.bindString(1, location.getId()); updateStatement.bindString(2, location.getId()); updateStatement.executeUpdateDelete(); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (SQLException e) { Timber.e(e); getWritableDatabase().endTransaction(); return false; } finally { if (updateStatement != null) updateStatement.close(); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testCancelTasksForEntity() { taskRepository.cancelTasksForEntity("id1"); verify(sqLiteDatabase).update(eq(TASK_TABLE), contentValuesArgumentCaptor.capture(), eq("for = ? AND status =?"), eq(new String[]{"id1", READY.name()})); assertEquals(BaseRepository.TYPE_Unsynced, contentValuesArgumentCaptor.getValue().getAsString("sync_status")); assertEquals(CANCELLED.name(), contentValuesArgumentCaptor.getValue().getAsString("status")); assertEquals(2, contentValuesArgumentCaptor.getValue().size()); } | public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testCancelTasksForEntityWithNullParams() { taskRepository.cancelTasksForEntity(null); verify(sqLiteDatabase, never()).update(any(), any(), any(), any()); verifyZeroInteractions(sqLiteDatabase); } | public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void cancelTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.CANCELLED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s =?", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testArchiveTasksForEntity() { taskRepository.archiveTasksForEntity("id1"); verify(sqLiteDatabase).update(eq(TASK_TABLE), contentValuesArgumentCaptor.capture(), eq("for = ? AND status NOT IN (?,?)"), eq(new String[]{"id1", READY.name(), CANCELLED.name()})); assertEquals(BaseRepository.TYPE_Unsynced, contentValuesArgumentCaptor.getValue().getAsString("sync_status")); assertEquals(ARCHIVED.name(), contentValuesArgumentCaptor.getValue().getAsString("status")); assertEquals(2, contentValuesArgumentCaptor.getValue().size()); } | public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testArchiveTasksForEntityWithNullParams() { taskRepository.archiveTasksForEntity(null); verifyZeroInteractions(sqLiteDatabase); } | public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void archiveTasksForEntity(@NonNull String entityId) { if (StringUtils.isBlank(entityId)) return; ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, TaskStatus.ARCHIVED.name()); contentValues.put(SYNC_STATUS, BaseRepository.TYPE_Unsynced); getWritableDatabase().update(TASK_TABLE, contentValues, String.format("%s = ? AND %s NOT IN (?,?)", FOR, STATUS), new String[]{entityId, TaskStatus.READY.name(), TaskStatus.CANCELLED.name()}); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void assertServiceConstructorInitializationNotNull() throws Exception { PowerMockito.mockStatic(Volley.class); PowerMockito.when(Volley.newRequestQueue(Mockito.any(android.content.Context.class), Mockito.any(HurlStack.class))).thenReturn(Mockito.mock(RequestQueue.class)); OpenSRPImageLoader openSRPImageLoader = new OpenSRPImageLoader(Mockito.mock(Service.class), -1); Assert.assertNotNull(openSRPImageLoader); } | private static RequestQueue newRequestQueue(Context context) { RequestQueue requestQueue; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { HurlStack stack = new HurlStack() { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } else { HttpClientStack stack = new HttpClientStack( AndroidHttpClient.newInstance(FileUtilities.getUserAgent(context))) { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } return requestQueue; } | OpenSRPImageLoader extends ImageLoader { private static RequestQueue newRequestQueue(Context context) { RequestQueue requestQueue; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { HurlStack stack = new HurlStack() { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } else { HttpClientStack stack = new HttpClientStack( AndroidHttpClient.newInstance(FileUtilities.getUserAgent(context))) { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } return requestQueue; } } | OpenSRPImageLoader extends ImageLoader { private static RequestQueue newRequestQueue(Context context) { RequestQueue requestQueue; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { HurlStack stack = new HurlStack() { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } else { HttpClientStack stack = new HttpClientStack( AndroidHttpClient.newInstance(FileUtilities.getUserAgent(context))) { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } return requestQueue; } OpenSRPImageLoader(FragmentActivity activity); OpenSRPImageLoader(Service service, int defaultPlaceHolderResId); OpenSRPImageLoader(Context context, int defaultPlaceHolderResId); OpenSRPImageLoader(FragmentActivity activity, int defaultPlaceHolderResId); OpenSRPImageLoader(FragmentActivity activity, ArrayList<Drawable> placeHolderDrawables); } | OpenSRPImageLoader extends ImageLoader { private static RequestQueue newRequestQueue(Context context) { RequestQueue requestQueue; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { HurlStack stack = new HurlStack() { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } else { HttpClientStack stack = new HttpClientStack( AndroidHttpClient.newInstance(FileUtilities.getUserAgent(context))) { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } return requestQueue; } OpenSRPImageLoader(FragmentActivity activity); OpenSRPImageLoader(Service service, int defaultPlaceHolderResId); OpenSRPImageLoader(Context context, int defaultPlaceHolderResId); OpenSRPImageLoader(FragmentActivity activity, int defaultPlaceHolderResId); OpenSRPImageLoader(FragmentActivity activity, ArrayList<Drawable> placeHolderDrawables); static File getDiskCacheDir(Context context, String uniqueName); static OpenSRPImageListener getStaticImageListener(ImageView view, int
defaultImageResId, int errorImageResId); static void saveStaticImageToDisk(String entityId, Bitmap image); static boolean moveSyncedImageAndSaveProfilePic(@NonNull String syncStatus, @NonNull String entityId, @NonNull File imageFile); static boolean copyFile(File src, File dst); OpenSRPImageLoader setFadeInImage(boolean fadeInImage); OpenSRPImageLoader setMaxImageSize(int maxImageWidth, int maxImageHeight); OpenSRPImageLoader setMaxImageSize(int maxImageSize); void getImageByClientId(String entityId, OpenSRPImageListener opensrpImageListener); void get(final ProfileImage image, final OpenSRPImageListener opensrpImageListener); ImageContainer get(String requestUrl, ImageView imageView); ImageContainer get(String requestUrl, ImageView imageView, int placeHolderIndex); ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder); ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder, int
maxWidth, int maxHeight); } | OpenSRPImageLoader extends ImageLoader { private static RequestQueue newRequestQueue(Context context) { RequestQueue requestQueue; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { HurlStack stack = new HurlStack() { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } else { HttpClientStack stack = new HttpClientStack( AndroidHttpClient.newInstance(FileUtilities.getUserAgent(context))) { @Override public HttpResponse performRequest(Request<?> request, Map<String, String> headers) throws IOException, AuthFailureError { addBearerTokenAuthorizationHeader(headers); return super.performRequest(request, headers); } }; requestQueue = Volley.newRequestQueue(context, stack); } return requestQueue; } OpenSRPImageLoader(FragmentActivity activity); OpenSRPImageLoader(Service service, int defaultPlaceHolderResId); OpenSRPImageLoader(Context context, int defaultPlaceHolderResId); OpenSRPImageLoader(FragmentActivity activity, int defaultPlaceHolderResId); OpenSRPImageLoader(FragmentActivity activity, ArrayList<Drawable> placeHolderDrawables); static File getDiskCacheDir(Context context, String uniqueName); static OpenSRPImageListener getStaticImageListener(ImageView view, int
defaultImageResId, int errorImageResId); static void saveStaticImageToDisk(String entityId, Bitmap image); static boolean moveSyncedImageAndSaveProfilePic(@NonNull String syncStatus, @NonNull String entityId, @NonNull File imageFile); static boolean copyFile(File src, File dst); OpenSRPImageLoader setFadeInImage(boolean fadeInImage); OpenSRPImageLoader setMaxImageSize(int maxImageWidth, int maxImageHeight); OpenSRPImageLoader setMaxImageSize(int maxImageSize); void getImageByClientId(String entityId, OpenSRPImageListener opensrpImageListener); void get(final ProfileImage image, final OpenSRPImageListener opensrpImageListener); ImageContainer get(String requestUrl, ImageView imageView); ImageContainer get(String requestUrl, ImageView imageView, int placeHolderIndex); ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder); ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder, int
maxWidth, int maxHeight); } |
@Test public void testReadUpdateCursor() { MatrixCursor cursor = getCursor(); cursor.moveToNext(); String expectedIdentifier = cursor.getString(cursor.getColumnIndex("_id")); String expectedStatus = cursor.getString(cursor.getColumnIndex("status")); String expectedBusinessStatus = cursor.getString(cursor.getColumnIndex("business_status")); String expectedServerVersion = cursor.getString(cursor.getColumnIndex("server_version")); TaskUpdate returnedTaskUpdate = taskRepository.readUpdateCursor(cursor); assertNotNull(returnedTaskUpdate); assertEquals(expectedIdentifier, returnedTaskUpdate.getIdentifier()); assertEquals(expectedStatus, returnedTaskUpdate.getStatus()); assertEquals(expectedBusinessStatus, returnedTaskUpdate.getBusinessStatus()); assertEquals(expectedServerVersion, returnedTaskUpdate.getServerVersion()); } | protected TaskUpdate readUpdateCursor(Cursor cursor) { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(cursor.getString(cursor.getColumnIndex(ID))); if (cursor.getString(cursor.getColumnIndex(STATUS)) != null) { taskUpdate.setStatus(cursor.getString(cursor.getColumnIndex(STATUS))); } if (cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS)) != null) { taskUpdate.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS))); } if (cursor.getString(cursor.getColumnIndex(SERVER_VERSION)) != null) { taskUpdate.setServerVersion(cursor.getString(cursor.getColumnIndex(SERVER_VERSION))); } return taskUpdate; } | TaskRepository extends BaseRepository { protected TaskUpdate readUpdateCursor(Cursor cursor) { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(cursor.getString(cursor.getColumnIndex(ID))); if (cursor.getString(cursor.getColumnIndex(STATUS)) != null) { taskUpdate.setStatus(cursor.getString(cursor.getColumnIndex(STATUS))); } if (cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS)) != null) { taskUpdate.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS))); } if (cursor.getString(cursor.getColumnIndex(SERVER_VERSION)) != null) { taskUpdate.setServerVersion(cursor.getString(cursor.getColumnIndex(SERVER_VERSION))); } return taskUpdate; } } | TaskRepository extends BaseRepository { protected TaskUpdate readUpdateCursor(Cursor cursor) { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(cursor.getString(cursor.getColumnIndex(ID))); if (cursor.getString(cursor.getColumnIndex(STATUS)) != null) { taskUpdate.setStatus(cursor.getString(cursor.getColumnIndex(STATUS))); } if (cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS)) != null) { taskUpdate.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS))); } if (cursor.getString(cursor.getColumnIndex(SERVER_VERSION)) != null) { taskUpdate.setServerVersion(cursor.getString(cursor.getColumnIndex(SERVER_VERSION))); } return taskUpdate; } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { protected TaskUpdate readUpdateCursor(Cursor cursor) { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(cursor.getString(cursor.getColumnIndex(ID))); if (cursor.getString(cursor.getColumnIndex(STATUS)) != null) { taskUpdate.setStatus(cursor.getString(cursor.getColumnIndex(STATUS))); } if (cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS)) != null) { taskUpdate.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS))); } if (cursor.getString(cursor.getColumnIndex(SERVER_VERSION)) != null) { taskUpdate.setServerVersion(cursor.getString(cursor.getColumnIndex(SERVER_VERSION))); } return taskUpdate; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { protected TaskUpdate readUpdateCursor(Cursor cursor) { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(cursor.getString(cursor.getColumnIndex(ID))); if (cursor.getString(cursor.getColumnIndex(STATUS)) != null) { taskUpdate.setStatus(cursor.getString(cursor.getColumnIndex(STATUS))); } if (cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS)) != null) { taskUpdate.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS))); } if (cursor.getString(cursor.getColumnIndex(SERVER_VERSION)) != null) { taskUpdate.setServerVersion(cursor.getString(cursor.getColumnIndex(SERVER_VERSION))); } return taskUpdate; } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testMarkTaskAsSynced() { String expectedTaskIdentifier = "id1"; taskRepository.markTaskAsSynced(expectedTaskIdentifier); verify(sqLiteDatabase).update(stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture(), stringArgumentCaptor.capture(), stringArrayArgumentCaptor.capture()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(TaskRepository.TASK_TABLE, iterator.next()); assertEquals("_id = ?", iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(3, contentValues.size()); assertEquals(expectedTaskIdentifier, contentValues.getAsString("_id")); assertEquals(BaseRepository.TYPE_Synced, contentValues.getAsString("sync_status")); assertEquals(0, contentValues.getAsInteger("server_version").intValue()); String actualTaskIdentifier = stringArrayArgumentCaptor.getAllValues().get(0)[0]; assertEquals(expectedTaskIdentifier, actualTaskIdentifier); } | public void markTaskAsSynced(String taskID) { try { ContentValues values = new ContentValues(); values.put(TaskRepository.ID, taskID); values.put(TaskRepository.SYNC_STATUS, BaseRepository.TYPE_Synced); values.put(TaskRepository.SERVER_VERSION, 0); getWritableDatabase().update(TaskRepository.TASK_TABLE, values, TaskRepository.ID + " = ?", new String[]{taskID}); } catch (Exception e) { Timber.e(e); } } | TaskRepository extends BaseRepository { public void markTaskAsSynced(String taskID) { try { ContentValues values = new ContentValues(); values.put(TaskRepository.ID, taskID); values.put(TaskRepository.SYNC_STATUS, BaseRepository.TYPE_Synced); values.put(TaskRepository.SERVER_VERSION, 0); getWritableDatabase().update(TaskRepository.TASK_TABLE, values, TaskRepository.ID + " = ?", new String[]{taskID}); } catch (Exception e) { Timber.e(e); } } } | TaskRepository extends BaseRepository { public void markTaskAsSynced(String taskID) { try { ContentValues values = new ContentValues(); values.put(TaskRepository.ID, taskID); values.put(TaskRepository.SYNC_STATUS, BaseRepository.TYPE_Synced); values.put(TaskRepository.SERVER_VERSION, 0); getWritableDatabase().update(TaskRepository.TASK_TABLE, values, TaskRepository.ID + " = ?", new String[]{taskID}); } catch (Exception e) { Timber.e(e); } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public void markTaskAsSynced(String taskID) { try { ContentValues values = new ContentValues(); values.put(TaskRepository.ID, taskID); values.put(TaskRepository.SYNC_STATUS, BaseRepository.TYPE_Synced); values.put(TaskRepository.SERVER_VERSION, 0); getWritableDatabase().update(TaskRepository.TASK_TABLE, values, TaskRepository.ID + " = ?", new String[]{taskID}); } catch (Exception e) { Timber.e(e); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public void markTaskAsSynced(String taskID) { try { ContentValues values = new ContentValues(); values.put(TaskRepository.ID, taskID); values.put(TaskRepository.SYNC_STATUS, BaseRepository.TYPE_Synced); values.put(TaskRepository.SERVER_VERSION, 0); getWritableDatabase().update(TaskRepository.TASK_TABLE, values, TaskRepository.ID + " = ?", new String[]{taskID}); } catch (Exception e) { Timber.e(e); } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testGetAllUnSyncedCreatedTasks() { when(sqLiteDatabase.rawQuery("SELECT * FROM task WHERE sync_status =? OR server_version IS NULL", new String[]{BaseRepository.TYPE_Created})).thenReturn(getCursor()); List<Task> unsyncedCreatedTasks = taskRepository.getAllUnsynchedCreatedTasks(); assertEquals(1, unsyncedCreatedTasks.size()); Task actualTask = unsyncedCreatedTasks.get(0); assertEquals("tsk11231jh22", actualTask.getIdentifier()); assertEquals("2018_IRS-3734", actualTask.getGroupIdentifier()); assertEquals(READY, actualTask.getStatus()); assertEquals("Not Visited", actualTask.getBusinessStatus()); assertEquals(3, actualTask.getPriority()); assertEquals("IRS", actualTask.getCode()); assertEquals("Spray House", actualTask.getDescription()); assertEquals("IRS Visit", actualTask.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", actualTask.getForEntity()); assertEquals("2018-11-10T2200", actualTask.getExecutionStartDate().toString(formatter)); assertNull(actualTask.getExecutionEndDate()); assertEquals("2018-10-31T0700", actualTask.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", actualTask.getLastModified().toString(formatter)); assertEquals("demouser", actualTask.getOwner()); } | public List<Task> getAllUnsynchedCreatedTasks() { return new ArrayList<>(getTasks(String.format("SELECT * FROM %s WHERE %s =? OR %s IS NULL", TASK_TABLE, SYNC_STATUS, SERVER_VERSION), new String[]{BaseRepository.TYPE_Created})); } | TaskRepository extends BaseRepository { public List<Task> getAllUnsynchedCreatedTasks() { return new ArrayList<>(getTasks(String.format("SELECT * FROM %s WHERE %s =? OR %s IS NULL", TASK_TABLE, SYNC_STATUS, SERVER_VERSION), new String[]{BaseRepository.TYPE_Created})); } } | TaskRepository extends BaseRepository { public List<Task> getAllUnsynchedCreatedTasks() { return new ArrayList<>(getTasks(String.format("SELECT * FROM %s WHERE %s =? OR %s IS NULL", TASK_TABLE, SYNC_STATUS, SERVER_VERSION), new String[]{BaseRepository.TYPE_Created})); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public List<Task> getAllUnsynchedCreatedTasks() { return new ArrayList<>(getTasks(String.format("SELECT * FROM %s WHERE %s =? OR %s IS NULL", TASK_TABLE, SYNC_STATUS, SERVER_VERSION), new String[]{BaseRepository.TYPE_Created})); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public List<Task> getAllUnsynchedCreatedTasks() { return new ArrayList<>(getTasks(String.format("SELECT * FROM %s WHERE %s =? OR %s IS NULL", TASK_TABLE, SYNC_STATUS, SERVER_VERSION), new String[]{BaseRepository.TYPE_Created})); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testUpdateTaskStructureIdsFromExistingStructures() { String expectedSql = "UPDATE task SET structure_id =(SELECT _id FROM structure WHERE _id = for) WHERE structure_id IS NULL"; boolean updated = taskRepository.updateTaskStructureIdsFromExistingStructures(); assertTrue(updated); verify(sqLiteDatabase).execSQL(stringArgumentCaptor.capture()); assertEquals(expectedSql, stringArgumentCaptor.getValue()); } | public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testUpdateTaskStructureIdsFromExistingStructuresFailure() { String expectedSql = "UPDATE task SET structure_id =(SELECT _id FROM structure WHERE _id = for) WHERE structure_id IS NULL"; doThrow(new SQLiteException()).when(sqLiteDatabase).execSQL(anyString()); boolean updated = taskRepository.updateTaskStructureIdsFromExistingStructures(); assertFalse(updated); verify(sqLiteDatabase).execSQL(stringArgumentCaptor.capture()); assertEquals(expectedSql, stringArgumentCaptor.getValue()); } | public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingStructures() { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM structure WHERE %s = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, ID, ID, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testUpdateTaskStructureIdsfromExistingClients() { String expectedSql = "UPDATE task SET structure_id =(SELECT structure_id FROM ec_family_member WHERE base_entity_id = for) WHERE structure_id IS NULL"; String clientTable = "ec_family_member"; boolean updated = taskRepository.updateTaskStructureIdsFromExistingClients(clientTable); assertTrue(updated); verify(sqLiteDatabase).execSQL(stringArgumentCaptor.capture()); assertEquals(expectedSql, stringArgumentCaptor.getValue()); } | public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testUpdateTaskStructureIdsfromExistingClientsFailure() { String expectedSql = "UPDATE task SET structure_id =(SELECT structure_id FROM ec_family_member WHERE base_entity_id = for) WHERE structure_id IS NULL"; String clientTable = "ec_family_member"; doThrow(new SQLiteException()).when(sqLiteDatabase).execSQL(anyString()); boolean updated = taskRepository.updateTaskStructureIdsFromExistingClients(clientTable); assertFalse(updated); verify(sqLiteDatabase).execSQL(stringArgumentCaptor.capture()); assertEquals(expectedSql, stringArgumentCaptor.getValue()); } | public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean updateTaskStructureIdsFromExistingClients(String clientTable) { try { getReadableDatabase().execSQL(String.format("UPDATE %s SET %s =(SELECT %s FROM %s WHERE base_entity_id = %s) WHERE %s IS NULL", TASK_TABLE, STRUCTURE_ID, STRUCTURE_ID, clientTable, FOR, STRUCTURE_ID)); return true; } catch (Exception e) { Timber.e(e); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testBatchInsertTasks() throws Exception { Task expectedTask = gson.fromJson(taskJson, Task.class); JSONArray taskArray = new JSONArray().put(new JSONObject(taskJson)); taskRepository = spy(taskRepository); boolean inserted = taskRepository.batchInsertTasks(taskArray); verify(sqLiteDatabase).beginTransaction(); verify(sqLiteDatabase).setTransactionSuccessful(); verify(sqLiteDatabase).endTransaction(); assertTrue(inserted); verify(taskRepository).addOrUpdate(taskArgumentCaptor.capture()); assertEquals(expectedTask.getIdentifier(), taskArgumentCaptor.getValue().getIdentifier()); assertEquals(expectedTask.getStatus(), taskArgumentCaptor.getValue().getStatus()); assertEquals(expectedTask.getBusinessStatus(), taskArgumentCaptor.getValue().getBusinessStatus()); assertEquals(expectedTask.getCode(), taskArgumentCaptor.getValue().getCode()); assertEquals(expectedTask.getForEntity(), taskArgumentCaptor.getValue().getForEntity()); } | public boolean batchInsertTasks(JSONArray array) { if (array == null || array.length() == 0) { return false; } try { getWritableDatabase().beginTransaction(); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); Task task = TaskServiceHelper.taskGson.fromJson(jsonObject.toString(), Task.class); addOrUpdate(task); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); getWritableDatabase().endTransaction(); return false; } } | TaskRepository extends BaseRepository { public boolean batchInsertTasks(JSONArray array) { if (array == null || array.length() == 0) { return false; } try { getWritableDatabase().beginTransaction(); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); Task task = TaskServiceHelper.taskGson.fromJson(jsonObject.toString(), Task.class); addOrUpdate(task); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); getWritableDatabase().endTransaction(); return false; } } } | TaskRepository extends BaseRepository { public boolean batchInsertTasks(JSONArray array) { if (array == null || array.length() == 0) { return false; } try { getWritableDatabase().beginTransaction(); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); Task task = TaskServiceHelper.taskGson.fromJson(jsonObject.toString(), Task.class); addOrUpdate(task); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); getWritableDatabase().endTransaction(); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public boolean batchInsertTasks(JSONArray array) { if (array == null || array.length() == 0) { return false; } try { getWritableDatabase().beginTransaction(); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); Task task = TaskServiceHelper.taskGson.fromJson(jsonObject.toString(), Task.class); addOrUpdate(task); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); getWritableDatabase().endTransaction(); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public boolean batchInsertTasks(JSONArray array) { if (array == null || array.length() == 0) { return false; } try { getWritableDatabase().beginTransaction(); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); Task task = TaskServiceHelper.taskGson.fromJson(jsonObject.toString(), Task.class); addOrUpdate(task); } getWritableDatabase().setTransactionSuccessful(); getWritableDatabase().endTransaction(); return true; } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); getWritableDatabase().endTransaction(); return false; } } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void testGetTasksByPlanAndEntity() { String query = "SELECT * FROM task WHERE plan_id=? AND for =? AND status NOT IN (?,?)"; when(sqLiteDatabase.rawQuery(query, new String[]{"IRS_2018_S1", "location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", CANCELLED.name(), ARCHIVED.name()})).thenReturn(getCursor()); Set<Task> allTasks = taskRepository.getTasksByPlanAndEntity("IRS_2018_S1", "location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals(query, stringArgumentCaptor.getValue()); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", argsCaptor.getValue()[1]); assertEquals(CANCELLED.name(), argsCaptor.getValue()[2]); assertEquals(ARCHIVED.name(), argsCaptor.getValue()[3]); assertEquals(1, allTasks.size()); Task task = allTasks.iterator().next(); assertEquals("tsk11231jh22", task.getIdentifier()); assertEquals("2018_IRS-3734", task.getGroupIdentifier()); assertEquals(READY, task.getStatus()); assertEquals("Not Visited", task.getBusinessStatus()); assertEquals(3, task.getPriority()); assertEquals("IRS", task.getCode()); assertEquals("Spray House", task.getDescription()); assertEquals("IRS Visit", task.getFocus()); assertEquals("location.properties.uid:41587456-b7c8-4c4e-b433-23a786f742fc", task.getForEntity()); assertEquals("2018-11-10T2200", task.getExecutionStartDate().toString(formatter)); assertNull(task.getExecutionEndDate()); assertEquals("2018-10-31T0700", task.getAuthoredOn().toString(formatter)); assertEquals("2018-10-31T0700", task.getLastModified().toString(formatter)); assertEquals("demouser", task.getOwner()); } | public Set<Task> getTasksByPlanAndEntity(String planId, String forEntity) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, FOR, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, forEntity}, INACTIVE_TASK_STATUS)); } | TaskRepository extends BaseRepository { public Set<Task> getTasksByPlanAndEntity(String planId, String forEntity) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, FOR, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, forEntity}, INACTIVE_TASK_STATUS)); } } | TaskRepository extends BaseRepository { public Set<Task> getTasksByPlanAndEntity(String planId, String forEntity) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, FOR, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, forEntity}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); } | TaskRepository extends BaseRepository { public Set<Task> getTasksByPlanAndEntity(String planId, String forEntity) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, FOR, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, forEntity}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } | TaskRepository extends BaseRepository { public Set<Task> getTasksByPlanAndEntity(String planId, String forEntity) { return getTasks(String.format("SELECT * FROM %s WHERE %s=? AND %s =? AND %s NOT IN (%s)", TASK_TABLE, PLAN_ID, FOR, STATUS, TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))) , ArrayUtils.addAll(new String[]{planId, forEntity}, INACTIVE_TASK_STATUS)); } TaskRepository(TaskNotesRepository taskNotesRepository); static void createTable(SQLiteDatabase database); void addOrUpdate(Task task); void addOrUpdate(Task task, boolean updateOnly); Map<String, Set<Task>> getTasksByPlanAndGroup(String planId, String groupId); Task getTaskByIdentifier(String identifier); Set<Task> getTasksByEntityAndCode(String planId, String groupId, String forEntity, String code); Set<Task> getTasksByPlanAndEntity(String planId, String forEntity); Set<Task> getTasksByEntity(String forEntity); Set<Task> getTasksByEntityAndStatus(String planId, String forEntity, TaskStatus taskStatus); Task readCursor(Cursor cursor); List<TaskUpdate> getUnSyncedTaskStatus(); void markTaskAsSynced(String taskID); List<Task> getAllUnsynchedCreatedTasks(); boolean updateTaskStructureIdFromClient(List<Client> clients, String attribute); boolean updateTaskStructureIdFromStructure(List<Location> locations); boolean updateTaskStructureIdsFromExistingStructures(); boolean updateTaskStructureIdsFromExistingClients(String clientTable); boolean batchInsertTasks(JSONArray array); @Nullable JsonData getTasks(long lastRowId, int limit, String jurisdictionId); void cancelTasksForEntity(@NonNull String entityId); void archiveTasksForEntity(@NonNull String entityId); int getUnsyncedCreatedTasksAndTaskStatusCount(); } |
@Test public void shouldSavePreviousFetchIndex() throws Exception { allSettings.savePreviousFetchIndex("1234"); Mockito.verify(settingsRepository).updateSetting("previousFetchIndex", "1234"); } | public void savePreviousFetchIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, value); } | AllSettings { public void savePreviousFetchIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, value); } } | AllSettings { public void savePreviousFetchIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public void savePreviousFetchIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public void savePreviousFetchIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void formatDateReturnsinRequiredFormat() throws Exception { Date date = new Date(); String dateInFormat = dd_MM_yyyy.format(date); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'"); String dateinFMT = fmt.format(dd_MM_yyyy.parse(dateInFormat)); String returnedDateinString = (JsonFormUtils.formatDate(dateInFormat)); Assert.assertEquals(dateinFMT, returnedDateinString); } | public static Date formatDate(String dateString, boolean startOfToday) { try { if (StringUtils.isBlank(dateString)) { return null; } if (dateString.matches("\\d{2}-\\d{2}-\\d{4}")) { return dd_MM_yyyy.parse(dateString); } else if (dateString.matches("\\d{4}-\\d{2}-\\d{2}") || dateString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) { return DateUtil.parseDate(dateString); } } catch (ParseException e) { Timber.e(e); } return null; } | JsonFormUtils { public static Date formatDate(String dateString, boolean startOfToday) { try { if (StringUtils.isBlank(dateString)) { return null; } if (dateString.matches("\\d{2}-\\d{2}-\\d{4}")) { return dd_MM_yyyy.parse(dateString); } else if (dateString.matches("\\d{4}-\\d{2}-\\d{2}") || dateString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) { return DateUtil.parseDate(dateString); } } catch (ParseException e) { Timber.e(e); } return null; } } | JsonFormUtils { public static Date formatDate(String dateString, boolean startOfToday) { try { if (StringUtils.isBlank(dateString)) { return null; } if (dateString.matches("\\d{2}-\\d{2}-\\d{4}")) { return dd_MM_yyyy.parse(dateString); } else if (dateString.matches("\\d{4}-\\d{2}-\\d{2}") || dateString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) { return DateUtil.parseDate(dateString); } } catch (ParseException e) { Timber.e(e); } return null; } } | JsonFormUtils { public static Date formatDate(String dateString, boolean startOfToday) { try { if (StringUtils.isBlank(dateString)) { return null; } if (dateString.matches("\\d{2}-\\d{2}-\\d{4}")) { return dd_MM_yyyy.parse(dateString); } else if (dateString.matches("\\d{4}-\\d{2}-\\d{2}") || dateString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) { return DateUtil.parseDate(dateString); } } catch (ParseException e) { Timber.e(e); } return null; } static Client createBaseClient(JSONArray fields, FormTag formTag, String entityId); static Event createEvent(JSONArray fields, JSONObject metadata, FormTag formTag, String entityId, String encounterType, String bindType); static void addObservation(Event e, JSONObject jsonObject); static Map<String, String> extractIdentifiers(JSONArray fields); static Map<String, Object> extractAttributes(JSONArray fields); static Map<String, Address> extractAddresses(JSONArray fields); static void fillIdentifiers(Map<String, String> pids, JSONObject jsonObject); static void fillAttributes(Map<String, Object> pattributes, JSONObject jsonObject); static void fillAddressFields(JSONObject jsonObject, Map<String, Address> addresses); static Map<String, String> extractIdentifiers(JSONArray fields, String bindType); static Map<String, Object> extractAttributes(JSONArray fields, String bindType); static Map<String, Address> extractAddresses(JSONArray fields, String bindType); static String getSubFormFieldValue(JSONArray jsonArray, FormEntityConstants.Person person, String bindType); static void fillSubFormIdentifiers(Map<String, String> pids, JSONObject jsonObject, String bindType); static void fillSubFormAttributes(Map<String, Object> pattributes, JSONObject jsonObject, String bindType); static void fillSubFormAddressFields(JSONObject jsonObject, Map<String, Address> addresses, String bindType); static JSONArray getSingleStepFormfields(JSONObject jsonForm); static JSONArray fields(JSONObject jsonForm); static JSONArray getMultiStepFormFields(JSONObject jsonForm); static Map<String, String> sectionFields(JSONObject jsonForm); static JSONObject toJSONObject(String jsonString); static String getFieldValue(JSONArray jsonArray, FormEntityConstants.Person person); static String getFieldValue(JSONArray jsonArray, FormEntityConstants.Encounter encounter); static String getFieldValue(String jsonString, String key); @Nullable static JSONObject getFieldJSONObject(JSONArray jsonArray, String key); @Nullable static String value(JSONArray jsonArray, String entity, String entityId); @Nullable static String getFieldValue(JSONArray jsonArray, String key); @Nullable static JSONObject getJSONObject(JSONArray jsonArray, int index); @Nullable static JSONArray getJSONArray(JSONObject jsonObject, String field); static JSONObject getJSONObject(JSONObject jsonObject, String field); static String getString(JSONObject jsonObject, String field); static String getString(String jsonString, String field); static Long getLong(JSONObject jsonObject, String field); static Date formatDate(String dateString, boolean startOfToday); static String generateRandomUUIDString(); static void addToJSONObject(JSONObject jsonObject, String key, String value); static String formatDate(String date); static JSONObject merge(JSONObject original, JSONObject updated); static String[] getNames(JSONObject jo); static String convertToOpenMRSDate(String value); static boolean isBlankJsonArray(JSONArray jsonArray); static boolean isBlankJsonObject(JSONObject jsonObject); } | JsonFormUtils { public static Date formatDate(String dateString, boolean startOfToday) { try { if (StringUtils.isBlank(dateString)) { return null; } if (dateString.matches("\\d{2}-\\d{2}-\\d{4}")) { return dd_MM_yyyy.parse(dateString); } else if (dateString.matches("\\d{4}-\\d{2}-\\d{2}") || dateString.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) { return DateUtil.parseDate(dateString); } } catch (ParseException e) { Timber.e(e); } return null; } static Client createBaseClient(JSONArray fields, FormTag formTag, String entityId); static Event createEvent(JSONArray fields, JSONObject metadata, FormTag formTag, String entityId, String encounterType, String bindType); static void addObservation(Event e, JSONObject jsonObject); static Map<String, String> extractIdentifiers(JSONArray fields); static Map<String, Object> extractAttributes(JSONArray fields); static Map<String, Address> extractAddresses(JSONArray fields); static void fillIdentifiers(Map<String, String> pids, JSONObject jsonObject); static void fillAttributes(Map<String, Object> pattributes, JSONObject jsonObject); static void fillAddressFields(JSONObject jsonObject, Map<String, Address> addresses); static Map<String, String> extractIdentifiers(JSONArray fields, String bindType); static Map<String, Object> extractAttributes(JSONArray fields, String bindType); static Map<String, Address> extractAddresses(JSONArray fields, String bindType); static String getSubFormFieldValue(JSONArray jsonArray, FormEntityConstants.Person person, String bindType); static void fillSubFormIdentifiers(Map<String, String> pids, JSONObject jsonObject, String bindType); static void fillSubFormAttributes(Map<String, Object> pattributes, JSONObject jsonObject, String bindType); static void fillSubFormAddressFields(JSONObject jsonObject, Map<String, Address> addresses, String bindType); static JSONArray getSingleStepFormfields(JSONObject jsonForm); static JSONArray fields(JSONObject jsonForm); static JSONArray getMultiStepFormFields(JSONObject jsonForm); static Map<String, String> sectionFields(JSONObject jsonForm); static JSONObject toJSONObject(String jsonString); static String getFieldValue(JSONArray jsonArray, FormEntityConstants.Person person); static String getFieldValue(JSONArray jsonArray, FormEntityConstants.Encounter encounter); static String getFieldValue(String jsonString, String key); @Nullable static JSONObject getFieldJSONObject(JSONArray jsonArray, String key); @Nullable static String value(JSONArray jsonArray, String entity, String entityId); @Nullable static String getFieldValue(JSONArray jsonArray, String key); @Nullable static JSONObject getJSONObject(JSONArray jsonArray, int index); @Nullable static JSONArray getJSONArray(JSONObject jsonObject, String field); static JSONObject getJSONObject(JSONObject jsonObject, String field); static String getString(JSONObject jsonObject, String field); static String getString(String jsonString, String field); static Long getLong(JSONObject jsonObject, String field); static Date formatDate(String dateString, boolean startOfToday); static String generateRandomUUIDString(); static void addToJSONObject(JSONObject jsonObject, String key, String value); static String formatDate(String date); static JSONObject merge(JSONObject original, JSONObject updated); static String[] getNames(JSONObject jo); static String convertToOpenMRSDate(String value); static boolean isBlankJsonArray(JSONArray jsonArray); static boolean isBlankJsonObject(JSONObject jsonObject); static final String TAG; static final String OPENMRS_ENTITY; static final String OPENMRS_ENTITY_ID; static final String OPENMRS_ENTITY_PARENT; static final String OPENMRS_CHOICE_IDS; static final String OPENMRS_DATA_TYPE; static final String PERSON_ATTRIBUTE; static final String PERSON_INDENTIFIER; static final String PERSON_ADDRESS; static final String SIMPRINTS_GUID; static final String FINGERPRINT_KEY; static final String FINGERPRINT_OPTION; static final String FINGERPRINT_OPTION_REGISTER; static final String CONCEPT; static final String VALUE; static final String VALUES; static final String FIELDS; static final String KEY; static final String ENTITY_ID; static final String STEP1; static final String SECTIONS; static final String attributes; static final String ENCOUNTER; static final String ENCOUNTER_LOCATION; static final String SAVE_OBS_AS_ARRAY; static final String SAVE_ALL_CHECKBOX_OBS_AS_ARRAY; static final SimpleDateFormat dd_MM_yyyy; static Gson gson; } |
@Test public void shouldFetchPreviousFetchIndex() throws Exception { Mockito.when(settingsRepository.querySetting("previousFetchIndex", "0")).thenReturn("1234"); String actual = allSettings.fetchPreviousFetchIndex(); Mockito.verify(settingsRepository).querySetting("previousFetchIndex", "0"); Assert.assertEquals("1234", actual); } | public String fetchPreviousFetchIndex() { return settingsRepository.querySetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, "0"); } | AllSettings { public String fetchPreviousFetchIndex() { return settingsRepository.querySetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, "0"); } } | AllSettings { public String fetchPreviousFetchIndex() { return settingsRepository.querySetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public String fetchPreviousFetchIndex() { return settingsRepository.querySetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public String fetchPreviousFetchIndex() { return settingsRepository.querySetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void shouldSavePreviousFormSyncIndex() throws Exception { allSettings.savePreviousFormSyncIndex("1234"); Mockito.verify(settingsRepository).updateSetting("previousFormSyncIndex", "1234"); } | public void savePreviousFormSyncIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, value); } | AllSettings { public void savePreviousFormSyncIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, value); } } | AllSettings { public void savePreviousFormSyncIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public void savePreviousFormSyncIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public void savePreviousFormSyncIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void shouldFetchPreviousFormSyncIndex() throws Exception { Mockito.when(settingsRepository.querySetting("previousFormSyncIndex", "0")).thenReturn("1234"); String actual = allSettings.fetchPreviousFormSyncIndex(); Mockito.verify(settingsRepository).querySetting("previousFormSyncIndex", "0"); Assert.assertEquals("1234", actual); } | public String fetchPreviousFormSyncIndex() { return settingsRepository.querySetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, "0"); } | AllSettings { public String fetchPreviousFormSyncIndex() { return settingsRepository.querySetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, "0"); } } | AllSettings { public String fetchPreviousFormSyncIndex() { return settingsRepository.querySetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public String fetchPreviousFormSyncIndex() { return settingsRepository.querySetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public String fetchPreviousFormSyncIndex() { return settingsRepository.querySetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void shouldSaveAppliedVillageFilter() throws Exception { allSettings.saveAppliedVillageFilter("munjanahalli"); Mockito.verify(settingsRepository).updateSetting("appliedVillageFilter", "munjanahalli"); } | public void saveAppliedVillageFilter(String village) { settingsRepository.updateSetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, village); } | AllSettings { public void saveAppliedVillageFilter(String village) { settingsRepository.updateSetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, village); } } | AllSettings { public void saveAppliedVillageFilter(String village) { settingsRepository.updateSetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, village); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public void saveAppliedVillageFilter(String village) { settingsRepository.updateSetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, village); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public void saveAppliedVillageFilter(String village) { settingsRepository.updateSetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, village); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void shouldGetAppliedVillageFilter() throws Exception { allSettings.appliedVillageFilter("All"); Mockito.verify(settingsRepository).querySetting("appliedVillageFilter", "All"); } | public String appliedVillageFilter(String defaultFilterValue) { return settingsRepository .querySetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, defaultFilterValue); } | AllSettings { public String appliedVillageFilter(String defaultFilterValue) { return settingsRepository .querySetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, defaultFilterValue); } } | AllSettings { public String appliedVillageFilter(String defaultFilterValue) { return settingsRepository .querySetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, defaultFilterValue); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public String appliedVillageFilter(String defaultFilterValue) { return settingsRepository .querySetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, defaultFilterValue); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public String appliedVillageFilter(String defaultFilterValue) { return settingsRepository .querySetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, defaultFilterValue); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void assertRegisterANMCallsPreferenceAndRepositoryUpdate() throws Exception { Mockito.doNothing().when(allSharedPreferences).updateANMUserName(Mockito.anyString()); allSettings.registerANM(""); Mockito.verify(allSharedPreferences, Mockito.times(1)).updateANMUserName(Mockito.anyString()); } | public void registerANM(String userName) { preferences.updateANMUserName(userName); } | AllSettings { public void registerANM(String userName) { preferences.updateANMUserName(userName); } } | AllSettings { public void registerANM(String userName) { preferences.updateANMUserName(userName); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public void registerANM(String userName) { preferences.updateANMUserName(userName); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public void registerANM(String userName) { preferences.updateANMUserName(userName); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
@Test public void assertSaveANMLocationCallsRepositoryUpdate() { Mockito.doNothing().doNothing().when(settingsRepository).updateSetting(Mockito.anyString(), Mockito.anyString()); allSettings.saveANMLocation(""); Mockito.verify(settingsRepository, Mockito.times(1)).updateSetting(Mockito.anyString(), Mockito.anyString()); } | public void saveANMLocation(String anmLocation) { settingsRepository.updateSetting(ANM_LOCATION, anmLocation); } | AllSettings { public void saveANMLocation(String anmLocation) { settingsRepository.updateSetting(ANM_LOCATION, anmLocation); } } | AllSettings { public void saveANMLocation(String anmLocation) { settingsRepository.updateSetting(ANM_LOCATION, anmLocation); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); } | AllSettings { public void saveANMLocation(String anmLocation) { settingsRepository.updateSetting(ANM_LOCATION, anmLocation); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); } | AllSettings { public void saveANMLocation(String anmLocation) { settingsRepository.updateSetting(ANM_LOCATION, anmLocation); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.