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 testGetParentLocationIdForNsaloGirlsSchool() throws Exception { ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn(anmLocation2) .when(anmLocationController).get(); Pair<String, String> parentAndChildLocationIds = Whitebox.invokeMethod(locationHelper, "getParentAndChildLocationIds", "Nsalo Secondary School"); assertEquals("44de66fb-e6c6-4bae-92bb-386dfe626eba", parentAndChildLocationIds.first); } | public static LocationHelper getInstance() { return instance; } | LocationHelper { public static LocationHelper getInstance() { return instance; } } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGetParentLocationIdForJambulaGirlsSchool() throws Exception { ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn(anmLocation2) .when(anmLocationController).get(); Pair<String, String> parentAndChildLocationIds = Whitebox.invokeMethod(locationHelper, "getParentAndChildLocationIds", "Jambula Girls School"); assertEquals("44de66fb-e6c6-4bae-92bb-386dfe626eba", parentAndChildLocationIds.first); } | public static LocationHelper getInstance() { return instance; } | LocationHelper { public static LocationHelper getInstance() { return instance; } } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGetParentLocationIdForBukesaUrbanHealthCentre() throws Exception { ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn(anmLocation2) .when(anmLocationController).get(); Pair<String, String> parentAndChildLocationIds = Whitebox.invokeMethod(locationHelper, "getParentAndChildLocationIds", "Bukesa Urban Health Centre"); assertEquals("44de66fb-e6c6-4bae-92bb-386dfe626eba", parentAndChildLocationIds.first); } | public static LocationHelper getInstance() { return instance; } | LocationHelper { public static LocationHelper getInstance() { return instance; } } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public static LocationHelper getInstance() { return instance; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testLocationIdsFromHierarchy() { AllSettings allSettings = Mockito.spy(CoreLibrary.getInstance().context().allSettings()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "allSettings", allSettings); SettingsRepository settingsRepository = ReflectionHelpers.getField(allSettings, "settingsRepository"); settingsRepository.updateMasterRepository(repository); AllSharedPreferences allSharedPreferences = Mockito.spy(CoreLibrary.getInstance().context().allSharedPreferences()); ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn("d60e1ee9-19e9-4e7d-a949-39f790a0ceda").when(allSharedPreferences).fetchDefaultTeamId(Mockito.nullable(String.class)); Mockito.doReturn("{\"locationsHierarchy\":{\"map\":{\"02472eaf-2e85-44c7-8720-ae15b915f9ed\":{\"children\":{\"9429fcd2-fdbd-4026-a3ce-6890a791efda\":{\"children\":{\"fc747bcd-f812-4229-b40e-9de496e016ac\":{\"children\":{\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\":{\"children\":{\"718b2864-7d6a-44c8-b5b6-bb375f82654e\":{\"children\":{\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\":{\"id\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"label\":\"Kabila Village\",\"node\":{\"locationId\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"name\":\"Kabila Village\",\"parentLocation\":{\"locationId\":\"718b2864-7d6a-44c8-b5b6-bb375f82654e\",\"name\":\"Huruma\",\"parentLocation\":{\"locationId\":\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\",\"name\":\"Kabila\",\"serverVersion\":0,\"voided\":false},\"serverVersion\":0,\"voided\":false},\"tags\":[\"Village\"],\"serverVersion\":0,\"voided\":false},\"parent\":\"718b2864-7d6a-44c8-b5b6-bb375f82654e\"}},\"id\":\"718b2864-7d6a-44c8-b5b6-bb375f82654e\",\"label\":\"Huruma\",\"node\":{\"locationId\":\"718b2864-7d6a-44c8-b5b6-bb375f82654e\",\"name\":\"Huruma\",\"parentLocation\":{\"locationId\":\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\",\"name\":\"Kabila\",\"parentLocation\":{\"locationId\":\"fc747bcd-f812-4229-b40e-9de496e016ac\",\"name\":\"Magu DC\",\"serverVersion\":0,\"voided\":false},\"serverVersion\":0,\"voided\":false},\"tags\":[\"MOH Jhpiego Facility Name\"],\"serverVersion\":0,\"voided\":false},\"parent\":\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\"}},\"id\":\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\",\"label\":\"Kabila\",\"node\":{\"locationId\":\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\",\"name\":\"Kabila\",\"parentLocation\":{\"locationId\":\"fc747bcd-f812-4229-b40e-9de496e016ac\",\"name\":\"Magu DC\",\"parentLocation\":{\"locationId\":\"9429fcd2-fdbd-4026-a3ce-6890a791efda\",\"name\":\"Mwanza\",\"serverVersion\":0,\"voided\":false},\"serverVersion\":0,\"voided\":false},\"tags\":[\"Ward\"],\"serverVersion\":0,\"voided\":false},\"parent\":\"fc747bcd-f812-4229-b40e-9de496e016ac\"}},\"id\":\"fc747bcd-f812-4229-b40e-9de496e016ac\",\"label\":\"Magu DC\",\"node\":{\"locationId\":\"fc747bcd-f812-4229-b40e-9de496e016ac\",\"name\":\"Magu DC\",\"parentLocation\":{\"locationId\":\"9429fcd2-fdbd-4026-a3ce-6890a791efda\",\"name\":\"Mwanza\",\"parentLocation\":{\"locationId\":\"02472eaf-2e85-44c7-8720-ae15b915f9ed\",\"name\":\"Tanzania\",\"serverVersion\":0,\"voided\":false},\"serverVersion\":0,\"voided\":false},\"tags\":[\"District\"],\"serverVersion\":0,\"voided\":false},\"parent\":\"9429fcd2-fdbd-4026-a3ce-6890a791efda\"}},\"id\":\"9429fcd2-fdbd-4026-a3ce-6890a791efda\",\"label\":\"Mwanza\",\"node\":{\"locationId\":\"9429fcd2-fdbd-4026-a3ce-6890a791efda\",\"name\":\"Mwanza\",\"parentLocation\":{\"locationId\":\"02472eaf-2e85-44c7-8720-ae15b915f9ed\",\"name\":\"Tanzania\",\"serverVersion\":0,\"voided\":false},\"tags\":[\"Region\"],\"serverVersion\":0,\"voided\":false},\"parent\":\"02472eaf-2e85-44c7-8720-ae15b915f9ed\"}},\"id\":\"02472eaf-2e85-44c7-8720-ae15b915f9ed\",\"label\":\"Tanzania\",\"node\":{\"locationId\":\"02472eaf-2e85-44c7-8720-ae15b915f9ed\",\"name\":\"Tanzania\",\"tags\":[\"Country\"],\"serverVersion\":0,\"voided\":false}}},\"parentChildren\":{\"02472eaf-2e85-44c7-8720-ae15b915f9ed\":[\"9429fcd2-fdbd-4026-a3ce-6890a791efda\"],\"9429fcd2-fdbd-4026-a3ce-6890a791efda\":[\"fc747bcd-f812-4229-b40e-9de496e016ac\"],\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\":[\"718b2864-7d6a-44c8-b5b6-bb375f82654e\"],\"fc747bcd-f812-4229-b40e-9de496e016ac\":[\"2d0d9d5b-f5cf-40c1-8f84-d0cef48250c7\"],\"718b2864-7d6a-44c8-b5b6-bb375f82654e\":[\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\"]}}}") .when(anmLocationController).get(); LocationHelper spiedLocationHelper = Mockito.spy(locationHelper); ReflectionHelpers.setStaticField(LocationHelper.class, "instance", spiedLocationHelper); String locationIds = spiedLocationHelper.locationIdsFromHierarchy(); Mockito.verify(spiedLocationHelper).locationsFromHierarchy(Mockito.eq(true), Mockito.nullable(String.class)); assertEquals("718b2864-7d6a-44c8-b5b6-bb375f82654e,2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8", locationIds); } | public String locationIdsFromHierarchy() { if (Utils.isEmptyCollection(locationIds)) { locationIds = locationsFromHierarchy(true, null); } if (!Utils.isEmptyCollection(locationIds)) { return StringUtils.join(locationIds, ","); } return null; } | LocationHelper { public String locationIdsFromHierarchy() { if (Utils.isEmptyCollection(locationIds)) { locationIds = locationsFromHierarchy(true, null); } if (!Utils.isEmptyCollection(locationIds)) { return StringUtils.join(locationIds, ","); } return null; } } | LocationHelper { public String locationIdsFromHierarchy() { if (Utils.isEmptyCollection(locationIds)) { locationIds = locationsFromHierarchy(true, null); } if (!Utils.isEmptyCollection(locationIds)) { return StringUtils.join(locationIds, ","); } return null; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public String locationIdsFromHierarchy() { if (Utils.isEmptyCollection(locationIds)) { locationIds = locationsFromHierarchy(true, null); } if (!Utils.isEmptyCollection(locationIds)) { return StringUtils.join(locationIds, ","); } return null; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public String locationIdsFromHierarchy() { if (Utils.isEmptyCollection(locationIds)) { locationIds = locationsFromHierarchy(true, null); } if (!Utils.isEmptyCollection(locationIds)) { return StringUtils.join(locationIds, ","); } return null; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGenerateDefaultLocationHierarchy() { ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("District"); allowedLevels.add("Rural Health Centre"); allowedLevels.add("Village"); allowedLevels.add("Canton"); allowedLevels.add("Sub-district"); AllSharedPreferences spiedAllSharedPreferences = Mockito.spy((AllSharedPreferences) ReflectionHelpers.getField(locationHelper, "allSharedPreferences")); ReflectionHelpers.setField(locationHelper, "allSharedPreferences", spiedAllSharedPreferences); Mockito.doReturn("NL1").when(spiedAllSharedPreferences).fetchRegisteredANM(); Mockito.doReturn("1b0ba804-54c3-40ef-820b-a8eaffa5d054").when(spiedAllSharedPreferences).fetchDefaultLocalityId("NL1"); ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn(anmLocation1) .when(anmLocationController).get(); List<String> locations = locationHelper.generateDefaultLocationHierarchy(allowedLevels); assertEquals(2, locations.size()); assertEquals("ra Nchelenge", locations.get(0)); assertEquals("ra Kashikishi HAHC", locations.get(1)); } | public List<String> generateDefaultLocationHierarchy(List<String> allowedLevels) { if (Utils.isEmptyCollection(allowedLevels)) { return new ArrayList<>(); } try { String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { List<String> curResult = getDefaultLocationHierarchy(defaultLocationUuid, entry.getValue(), new ArrayList<>(), allowedLevels); if (!Utils.isEmptyCollection(curResult)) { return curResult; } } } } catch (Exception e) { Timber.e(e); } return null; } | LocationHelper { public List<String> generateDefaultLocationHierarchy(List<String> allowedLevels) { if (Utils.isEmptyCollection(allowedLevels)) { return new ArrayList<>(); } try { String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { List<String> curResult = getDefaultLocationHierarchy(defaultLocationUuid, entry.getValue(), new ArrayList<>(), allowedLevels); if (!Utils.isEmptyCollection(curResult)) { return curResult; } } } } catch (Exception e) { Timber.e(e); } return null; } } | LocationHelper { public List<String> generateDefaultLocationHierarchy(List<String> allowedLevels) { if (Utils.isEmptyCollection(allowedLevels)) { return new ArrayList<>(); } try { String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { List<String> curResult = getDefaultLocationHierarchy(defaultLocationUuid, entry.getValue(), new ArrayList<>(), allowedLevels); if (!Utils.isEmptyCollection(curResult)) { return curResult; } } } } catch (Exception e) { Timber.e(e); } return null; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public List<String> generateDefaultLocationHierarchy(List<String> allowedLevels) { if (Utils.isEmptyCollection(allowedLevels)) { return new ArrayList<>(); } try { String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { List<String> curResult = getDefaultLocationHierarchy(defaultLocationUuid, entry.getValue(), new ArrayList<>(), allowedLevels); if (!Utils.isEmptyCollection(curResult)) { return curResult; } } } } catch (Exception e) { Timber.e(e); } return null; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public List<String> generateDefaultLocationHierarchy(List<String> allowedLevels) { if (Utils.isEmptyCollection(allowedLevels)) { return new ArrayList<>(); } try { String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { List<String> curResult = getDefaultLocationHierarchy(defaultLocationUuid, entry.getValue(), new ArrayList<>(), allowedLevels); if (!Utils.isEmptyCollection(curResult)) { return curResult; } } } } catch (Exception e) { Timber.e(e); } return null; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGenerateLocationHierarchyTreeShouldReturnEmptyList() { String locationData = anmLocation1; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("Canton"); LinkedHashMap<String, TreeNode<String, Location>> map = AssetHandler.jsonStringToJava(locationData, LocationTree.class).getLocationsHierarchy(); List<FormLocation> formLocationsList = locationHelper.generateLocationHierarchyTree(false, allowedLevels, map); assertEquals(0, formLocationsList.size()); } | public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGenerateLocationHierarchyTreeWithMapShouldReturnListWithOtherFormLocationOnly() { locationHelper = Mockito.spy(locationHelper); String locationData = anmLocation1; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("Canton"); LinkedHashMap<String, TreeNode<String, Location>> map = AssetHandler.jsonStringToJava(locationData, LocationTree.class).getLocationsHierarchy(); List<FormLocation> formLocationsList = locationHelper.generateLocationHierarchyTree(true, allowedLevels, map); assertEquals(1, formLocationsList.size()); FormLocation formLocation = formLocationsList.get(0); assertEquals("Other", formLocation.name); assertEquals("Other", formLocation.key); assertEquals("", formLocation.level); } | public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGenerateLocationHierarchyTreeWithMapAndOtherOptionFalseShouldReturnEmptyList() { locationHelper = Mockito.spy(locationHelper); String locationData = anmLocation1; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("Canton"); LinkedHashMap<String, TreeNode<String, Location>> map = AssetHandler.jsonStringToJava(locationData, LocationTree.class).getLocationsHierarchy(); List<FormLocation> formLocationsList = locationHelper.generateLocationHierarchyTree(false, allowedLevels, map); assertEquals(0, formLocationsList.size()); } | public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void shouldReturnString10WhenStringValueIs10() { String value = IntegerUtil.tryParse("10", "0"); Assert.assertEquals(value, "10"); } | public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } |
@Test public void testGenerateLocationHierarchyTreeWithMapShouldReturnListWithZambiaFormLocation() { locationHelper = Mockito.spy(locationHelper); String locationData = anmLocation1; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("Country"); allowedLevels.add("Province"); allowedLevels.add("Region"); allowedLevels.add("District"); allowedLevels.add("Sub-district"); allowedLevels.add("Operational Area"); LinkedHashMap<String, TreeNode<String, Location>> map = AssetHandler.jsonStringToJava(locationData, LocationTree.class).getLocationsHierarchy(); List<FormLocation> formLocationsList = locationHelper.generateLocationHierarchyTree(false, allowedLevels, map); assertEquals(1, formLocationsList.size()); FormLocation formLocation = formLocationsList.get(0); assertEquals("Zambia", formLocation.name); assertEquals("ra Zambia", formLocation.key); assertEquals("", formLocation.level); assertEquals(1, formLocation.nodes.size()); } | public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels) { LinkedHashMap<String, TreeNode<String, Location>> map = map(); return generateLocationHierarchyTree(withOtherOption, allowedLevels, map); } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGetOpenMrsReadableName() { assertEquals("Zambia", locationHelper.getOpenMrsReadableName("ra Zambia")); } | public String getOpenMrsReadableName(String name) { if (StringUtils.isBlank(name)) { return ""; } String readableName = name; try { Pattern prefixPattern = Pattern.compile("^[a-z]{2} (.*)$"); Matcher prefixMatcher = prefixPattern.matcher(readableName); if (prefixMatcher.find()) { readableName = prefixMatcher.group(1); } if (readableName.contains(":")) { String[] splitName = readableName.split(":"); readableName = splitName[splitName.length - 1].trim(); } } catch (Exception e) { Timber.e(e); } return readableName; } | LocationHelper { public String getOpenMrsReadableName(String name) { if (StringUtils.isBlank(name)) { return ""; } String readableName = name; try { Pattern prefixPattern = Pattern.compile("^[a-z]{2} (.*)$"); Matcher prefixMatcher = prefixPattern.matcher(readableName); if (prefixMatcher.find()) { readableName = prefixMatcher.group(1); } if (readableName.contains(":")) { String[] splitName = readableName.split(":"); readableName = splitName[splitName.length - 1].trim(); } } catch (Exception e) { Timber.e(e); } return readableName; } } | LocationHelper { public String getOpenMrsReadableName(String name) { if (StringUtils.isBlank(name)) { return ""; } String readableName = name; try { Pattern prefixPattern = Pattern.compile("^[a-z]{2} (.*)$"); Matcher prefixMatcher = prefixPattern.matcher(readableName); if (prefixMatcher.find()) { readableName = prefixMatcher.group(1); } if (readableName.contains(":")) { String[] splitName = readableName.split(":"); readableName = splitName[splitName.length - 1].trim(); } } catch (Exception e) { Timber.e(e); } return readableName; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public String getOpenMrsReadableName(String name) { if (StringUtils.isBlank(name)) { return ""; } String readableName = name; try { Pattern prefixPattern = Pattern.compile("^[a-z]{2} (.*)$"); Matcher prefixMatcher = prefixPattern.matcher(readableName); if (prefixMatcher.find()) { readableName = prefixMatcher.group(1); } if (readableName.contains(":")) { String[] splitName = readableName.split(":"); readableName = splitName[splitName.length - 1].trim(); } } catch (Exception e) { Timber.e(e); } return readableName; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public String getOpenMrsReadableName(String name) { if (StringUtils.isBlank(name)) { return ""; } String readableName = name; try { Pattern prefixPattern = Pattern.compile("^[a-z]{2} (.*)$"); Matcher prefixMatcher = prefixPattern.matcher(readableName); if (prefixMatcher.find()) { readableName = prefixMatcher.group(1); } if (readableName.contains(":")) { String[] splitName = readableName.split(":"); readableName = splitName[splitName.length - 1].trim(); } } catch (Exception e) { Timber.e(e); } return readableName; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGetOpenMrsLocationName() { ANMLocationController anmLocationController = Mockito.spy(CoreLibrary.getInstance().context().anmLocationController()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "anmLocationController", anmLocationController); Mockito.doReturn(anmLocation2) .when(anmLocationController).get(); assertEquals("Jambula Girls School", locationHelper.getOpenMrsLocationName("982eb3f3-b7e3-450f-a38e-d067f2345212")); } | public String getOpenMrsLocationName(String locationId) { if (StringUtils.isBlank(locationId)) { Timber.e("Location id is null"); return null; } String response = locationId; try { LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { String curResult = getOpenMrsLocationName(locationId, entry.getValue()); if (StringUtils.isNotBlank(curResult)) { response = curResult; break; } } } else { Timber.e("locationData doesn't have locationHierarchy"); } } catch (Exception e) { Timber.e(e); } return response; } | LocationHelper { public String getOpenMrsLocationName(String locationId) { if (StringUtils.isBlank(locationId)) { Timber.e("Location id is null"); return null; } String response = locationId; try { LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { String curResult = getOpenMrsLocationName(locationId, entry.getValue()); if (StringUtils.isNotBlank(curResult)) { response = curResult; break; } } } else { Timber.e("locationData doesn't have locationHierarchy"); } } catch (Exception e) { Timber.e(e); } return response; } } | LocationHelper { public String getOpenMrsLocationName(String locationId) { if (StringUtils.isBlank(locationId)) { Timber.e("Location id is null"); return null; } String response = locationId; try { LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { String curResult = getOpenMrsLocationName(locationId, entry.getValue()); if (StringUtils.isNotBlank(curResult)) { response = curResult; break; } } } else { Timber.e("locationData doesn't have locationHierarchy"); } } catch (Exception e) { Timber.e(e); } return response; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public String getOpenMrsLocationName(String locationId) { if (StringUtils.isBlank(locationId)) { Timber.e("Location id is null"); return null; } String response = locationId; try { LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { String curResult = getOpenMrsLocationName(locationId, entry.getValue()); if (StringUtils.isNotBlank(curResult)) { response = curResult; break; } } } else { Timber.e("locationData doesn't have locationHierarchy"); } } catch (Exception e) { Timber.e(e); } return response; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public String getOpenMrsLocationName(String locationId) { if (StringUtils.isBlank(locationId)) { Timber.e("Location id is null"); return null; } String response = locationId; try { LinkedHashMap<String, TreeNode<String, Location>> map = map(); if (!Utils.isEmptyMap(map)) { for (Map.Entry<String, TreeNode<String, Location>> entry : map.entrySet()) { String curResult = getOpenMrsLocationName(locationId, entry.getValue()); if (StringUtils.isNotBlank(curResult)) { response = curResult; break; } } } else { Timber.e("locationData doesn't have locationHierarchy"); } } catch (Exception e) { Timber.e(e); } return response; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGetAdvancedDataCaptureStrategies() { ReflectionHelpers.setStaticField(LocationHelper.class, "instance", null); String advancedDataStrategyType = "Mobile Clinic"; ArrayList<String> allowedLevels = new ArrayList<>(); allowedLevels.add("County"); allowedLevels.add("Ward"); allowedLevels.add("Facility"); ArrayList<String> advancedDataStrategy = new ArrayList<>(); advancedDataStrategy.add(advancedDataStrategyType); LocationHelper.init(allowedLevels, "Facility", advancedDataStrategy); locationHelper = LocationHelper.getInstance(); List<String> defaultLocationLevel = locationHelper.getAdvancedDataCaptureStrategies(); assertEquals(1, defaultLocationLevel.size()); assertEquals(advancedDataStrategyType, defaultLocationLevel.get(0)); } | public List<String> getAdvancedDataCaptureStrategies() { return ADVANCED_DATA_CAPTURE_LEVELS; } | LocationHelper { public List<String> getAdvancedDataCaptureStrategies() { return ADVANCED_DATA_CAPTURE_LEVELS; } } | LocationHelper { public List<String> getAdvancedDataCaptureStrategies() { return ADVANCED_DATA_CAPTURE_LEVELS; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); } | LocationHelper { public List<String> getAdvancedDataCaptureStrategies() { return ADVANCED_DATA_CAPTURE_LEVELS; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } | LocationHelper { public List<String> getAdvancedDataCaptureStrategies() { return ADVANCED_DATA_CAPTURE_LEVELS; } private LocationHelper(List<String> allowedLevels, String defaultLocationLevel); private LocationHelper(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static void init(List<String> allowedLevels, String defaultLocationLevel); static void init(List<String> allowedLevels, String defaultLocationLevel, List<String> advancedDataCaptureStrategies); static LocationHelper getInstance(); String locationIdsFromHierarchy(); List<String> locationNamesFromHierarchy(String defaultLocation); List<String> locationsFromHierarchy(boolean fetchLocationIds, String defaultLocation); String getDefaultLocation(); String getOpenMrsLocationId(@NonNull String locationName); String getOpenMrsLocationName(String locationId); List<String> getOpenMrsLocationHierarchy(String locationId, boolean onlyAllowedLevels); List<String> generateDefaultLocationHierarchy(List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels); List<FormLocation> generateLocationHierarchyTree(boolean withOtherOption, List<String> allowedLevels, Map<String, TreeNode<String, Location>> map); String getOpenMrsReadableName(String name); List<String> getDefaultLocationHierarchy(String defaultLocationUuid, TreeNode<String,
Location> openMrsLocationData, List<String> parents, List<String> allowedLevels); void setParentAndChildLocationIds(String currLocation); String getParentLocationId(); String getChildLocationId(); void setParentLocationId(String parentId); void setChildLocationId(String childId); LinkedHashMap<String, TreeNode<String, Location>> map(); List<String> getAllowedLevels(); String getDefaultLocationLevel(); List<String> getAdvancedDataCaptureStrategies(); } |
@Test public void testGetDateFormat() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date now = new Date(); Assert.assertEquals(sdf.format(now), AbstractDao.getDobDateFormat().format(now)); } | public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } | AbstractDao { public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } } | AbstractDao { public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } } | AbstractDao { public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } | AbstractDao { public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } |
@Test public void testGetNativeFormsDateFormat() { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date now = new Date(); Assert.assertEquals(sdf.format(now), AbstractDao.getNativeFormsDateFormat().format(now)); } | public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } | AbstractDao { public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } } | AbstractDao { public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } } | AbstractDao { public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } | AbstractDao { public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } |
@Test public void testObjectsConstructedEqualsCursorSize() { MatrixCursor cursor = new MatrixCursor(new String[]{"count"}); cursor.addRow(new Object[]{"1"}); Mockito.doReturn(cursor).when(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any(String[].class)); SampleAbstractDaoImp.setRepository(repository); int count = SampleAbstractDaoImp.getCountOfEvents(); Assert.assertEquals(count, 1); } | protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } |
@Test public void testErrorInSerializationReturnsNull() { MatrixCursor cursor = new MatrixCursor(new String[]{"count"}); cursor.addRow(new Object[]{"1"}); Mockito.doReturn(cursor).when(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any(String[].class)); SampleAbstractDaoImp.setRepository(repository); List<Alert> alerts = SampleAbstractDaoImp.getAllAlerts(); Assert.assertNull(alerts); } | protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } | AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } |
@Test public void testUpdateDB() { String sql = "update table set col1 = 'value' where id = x"; AbstractDao.setRepository(repository); AbstractDao.updateDB(sql); Mockito.verify(sqLiteDatabase).rawExecSQL(sql); } | protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } | AbstractDao { protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } } | AbstractDao { protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } } | AbstractDao { protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } | AbstractDao { protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); } |
@Test public void testGetLocationsByTags() { LocationsDao.setRepository(repository); MatrixCursor matrixCursor = new MatrixCursor(new String[]{"uuid", "location_name", "parent_id"}); matrixCursor.addRow(new Object[]{"fb7ed5db-138d-4e6f-94d8-bc443b58dadb", "Tabata Dampo", "bcf5a36d-fb53-4de9-9813-01f1d480e3fe"}); matrixCursor.addRow(new Object[]{"69d24450-ec06-450c-bf05-ee7ebb7f47e4", "Ebrahim Haji", "bcf5a36d-fb53-4de9-9813-01f1d480e3fe"}); Mockito.doReturn(matrixCursor).when(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any(String[].class)); HashSet<String> tags = new HashSet<>(); tags.add("tag1"); tags.add("tag2"); List<Location> locations = LocationsDao.getLocationsByTags(tags); Mockito.verify(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any()); Assert.assertEquals(locations.size(), 2); Assert.assertEquals(locations.get(0).getId(), "fb7ed5db-138d-4e6f-94d8-bc443b58dadb"); Assert.assertEquals(locations.get(0).getProperties().getParentId(), "bcf5a36d-fb53-4de9-9813-01f1d480e3fe"); Assert.assertEquals(locations.get(0).getProperties().getName(), "Tabata Dampo"); Assert.assertEquals(locations.get(1).getId(), "69d24450-ec06-450c-bf05-ee7ebb7f47e4"); Assert.assertEquals(locations.get(1).getProperties().getParentId(), "bcf5a36d-fb53-4de9-9813-01f1d480e3fe"); Assert.assertEquals(locations.get(1).getProperties().getName(), "Ebrahim Haji"); } | public static List<Location> getLocationsByTags(Set<String> tags) { String sql = String.format("SELECT uuid, location.name as location_name, parent_id\n" + "FROM location\n" + " INNER JOIN location_tag on location.uuid = location_tag.location_id\n" + "WHERE location_tag.name IN ('%s');", StringUtils.join(tags, "', '")); DataMap<Location> dataMap = cursor -> { Location location = new Location(); location.setId(getCursorValue(cursor, UUID)); LocationProperty property = new LocationProperty(); property.setUid(getCursorValue(cursor, UUID)); property.setParentId(getCursorValue(cursor, PARENT_ID)); property.setName(getCursorValue(cursor, LOCATION_NAME)); location.setProperties(property); return location; }; return AbstractDao.readData(sql, dataMap); } | LocationsDao extends AbstractDao { public static List<Location> getLocationsByTags(Set<String> tags) { String sql = String.format("SELECT uuid, location.name as location_name, parent_id\n" + "FROM location\n" + " INNER JOIN location_tag on location.uuid = location_tag.location_id\n" + "WHERE location_tag.name IN ('%s');", StringUtils.join(tags, "', '")); DataMap<Location> dataMap = cursor -> { Location location = new Location(); location.setId(getCursorValue(cursor, UUID)); LocationProperty property = new LocationProperty(); property.setUid(getCursorValue(cursor, UUID)); property.setParentId(getCursorValue(cursor, PARENT_ID)); property.setName(getCursorValue(cursor, LOCATION_NAME)); location.setProperties(property); return location; }; return AbstractDao.readData(sql, dataMap); } } | LocationsDao extends AbstractDao { public static List<Location> getLocationsByTags(Set<String> tags) { String sql = String.format("SELECT uuid, location.name as location_name, parent_id\n" + "FROM location\n" + " INNER JOIN location_tag on location.uuid = location_tag.location_id\n" + "WHERE location_tag.name IN ('%s');", StringUtils.join(tags, "', '")); DataMap<Location> dataMap = cursor -> { Location location = new Location(); location.setId(getCursorValue(cursor, UUID)); LocationProperty property = new LocationProperty(); property.setUid(getCursorValue(cursor, UUID)); property.setParentId(getCursorValue(cursor, PARENT_ID)); property.setName(getCursorValue(cursor, LOCATION_NAME)); location.setProperties(property); return location; }; return AbstractDao.readData(sql, dataMap); } } | LocationsDao extends AbstractDao { public static List<Location> getLocationsByTags(Set<String> tags) { String sql = String.format("SELECT uuid, location.name as location_name, parent_id\n" + "FROM location\n" + " INNER JOIN location_tag on location.uuid = location_tag.location_id\n" + "WHERE location_tag.name IN ('%s');", StringUtils.join(tags, "', '")); DataMap<Location> dataMap = cursor -> { Location location = new Location(); location.setId(getCursorValue(cursor, UUID)); LocationProperty property = new LocationProperty(); property.setUid(getCursorValue(cursor, UUID)); property.setParentId(getCursorValue(cursor, PARENT_ID)); property.setName(getCursorValue(cursor, LOCATION_NAME)); location.setProperties(property); return location; }; return AbstractDao.readData(sql, dataMap); } static List<Location> getLocationsByTags(Set<String> tags); } | LocationsDao extends AbstractDao { public static List<Location> getLocationsByTags(Set<String> tags) { String sql = String.format("SELECT uuid, location.name as location_name, parent_id\n" + "FROM location\n" + " INNER JOIN location_tag on location.uuid = location_tag.location_id\n" + "WHERE location_tag.name IN ('%s');", StringUtils.join(tags, "', '")); DataMap<Location> dataMap = cursor -> { Location location = new Location(); location.setId(getCursorValue(cursor, UUID)); LocationProperty property = new LocationProperty(); property.setUid(getCursorValue(cursor, UUID)); property.setParentId(getCursorValue(cursor, PARENT_ID)); property.setName(getCursorValue(cursor, LOCATION_NAME)); location.setProperties(property); return location; }; return AbstractDao.readData(sql, dataMap); } static List<Location> getLocationsByTags(Set<String> tags); } |
@Test public void shouldReturnStringDefaultValueWhenStringIsEmpty() { String value = IntegerUtil.tryParse("", "1"); Assert.assertEquals(value, "1"); } | public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } | IntegerUtil { public static Integer tryParse(String value, int defaultValue) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return defaultValue; } } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } |
@Test public void testGetScreenDpiReturnsCorrectValuesForMediumDensity() { Mockito.doReturn(resources).when(context).getResources(); DisplayMetrics displayMetrics = new DisplayMetrics(); displayMetrics.density = 0.76f; Mockito.doReturn(displayMetrics).when(resources).getDisplayMetrics(); DisplayUtils.ScreenDpi screenDpi = DisplayUtils.getScreenDpi(context); Assert.assertEquals(DisplayUtils.ScreenDpi.MDPI, screenDpi); displayMetrics = new DisplayMetrics(); displayMetrics.density = 1.0f; Mockito.doReturn(displayMetrics).when(resources).getDisplayMetrics(); screenDpi = DisplayUtils.getScreenDpi(context); Assert.assertEquals(DisplayUtils.ScreenDpi.MDPI, screenDpi); } | public static ScreenDpi getScreenDpi(Context context) { float density = context.getResources().getDisplayMetrics().density; ScreenDpi dpi = ScreenDpi.XXXHDPI; if (density <= 0.75) { dpi = ScreenDpi.LDPI; } else if (density > 0.75 && density <= 1.0) { dpi = ScreenDpi.MDPI; } else if (density > 1.0 && density <= 1.5) { dpi = ScreenDpi.HDPI; } else if (density > 1.5 && density <= 2.0) { dpi = ScreenDpi.XHDPI; } else if (density > 2.0 && density <= 3.0) { dpi = ScreenDpi.XXHDPI; } return dpi; } | DisplayUtils { public static ScreenDpi getScreenDpi(Context context) { float density = context.getResources().getDisplayMetrics().density; ScreenDpi dpi = ScreenDpi.XXXHDPI; if (density <= 0.75) { dpi = ScreenDpi.LDPI; } else if (density > 0.75 && density <= 1.0) { dpi = ScreenDpi.MDPI; } else if (density > 1.0 && density <= 1.5) { dpi = ScreenDpi.HDPI; } else if (density > 1.5 && density <= 2.0) { dpi = ScreenDpi.XHDPI; } else if (density > 2.0 && density <= 3.0) { dpi = ScreenDpi.XXHDPI; } return dpi; } } | DisplayUtils { public static ScreenDpi getScreenDpi(Context context) { float density = context.getResources().getDisplayMetrics().density; ScreenDpi dpi = ScreenDpi.XXXHDPI; if (density <= 0.75) { dpi = ScreenDpi.LDPI; } else if (density > 0.75 && density <= 1.0) { dpi = ScreenDpi.MDPI; } else if (density > 1.0 && density <= 1.5) { dpi = ScreenDpi.HDPI; } else if (density > 1.5 && density <= 2.0) { dpi = ScreenDpi.XHDPI; } else if (density > 2.0 && density <= 3.0) { dpi = ScreenDpi.XXHDPI; } return dpi; } } | DisplayUtils { public static ScreenDpi getScreenDpi(Context context) { float density = context.getResources().getDisplayMetrics().density; ScreenDpi dpi = ScreenDpi.XXXHDPI; if (density <= 0.75) { dpi = ScreenDpi.LDPI; } else if (density > 0.75 && density <= 1.0) { dpi = ScreenDpi.MDPI; } else if (density > 1.0 && density <= 1.5) { dpi = ScreenDpi.HDPI; } else if (density > 1.5 && density <= 2.0) { dpi = ScreenDpi.XHDPI; } else if (density > 2.0 && density <= 3.0) { dpi = ScreenDpi.XXHDPI; } return dpi; } static ScreenDpi getScreenDpi(Context context); static int getDisplayWidth(Activity activity); static int getDisplayHeight(Activity activity); static double getScreenSize(Activity activity); } | DisplayUtils { public static ScreenDpi getScreenDpi(Context context) { float density = context.getResources().getDisplayMetrics().density; ScreenDpi dpi = ScreenDpi.XXXHDPI; if (density <= 0.75) { dpi = ScreenDpi.LDPI; } else if (density > 0.75 && density <= 1.0) { dpi = ScreenDpi.MDPI; } else if (density > 1.0 && density <= 1.5) { dpi = ScreenDpi.HDPI; } else if (density > 1.5 && density <= 2.0) { dpi = ScreenDpi.XHDPI; } else if (density > 2.0 && density <= 3.0) { dpi = ScreenDpi.XXHDPI; } return dpi; } static ScreenDpi getScreenDpi(Context context); static int getDisplayWidth(Activity activity); static int getDisplayHeight(Activity activity); static double getScreenSize(Activity activity); } |
@Test public void testConvertDrawableToBitmap() { BottomNavigationHelper spyBottomNavigationHelper = Mockito.spy(bottomNavigationHelper); Resources resources = Mockito.mock(Resources.class); Assert.assertNotNull(resources); Mockito.doReturn(drawable).when(resources).getDrawable(INITIALS_RESOURCE_ID); Assert.assertNotNull(drawable); Assert.assertNull(bitmap.copy(Bitmap.Config.ARGB_8888, true)); Assert.assertNotNull(spyBottomNavigationHelper.convertDrawableResToBitmap(INITIALS_RESOURCE_ID, resources)); } | protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } @SuppressLint("RestrictedApi") void disableShiftMode(BottomNavigationView view); BitmapDrawable writeOnDrawable(int drawableId, String initials, Resources resources); } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } @SuppressLint("RestrictedApi") void disableShiftMode(BottomNavigationView view); BitmapDrawable writeOnDrawable(int drawableId, String initials, Resources resources); } |
@Test public void testConvertGradientDrawableToBitmap() { Assert.assertNotNull(bottomNavigationHelper.convertDrawableResToBitmap(R.drawable.bottom_bar_initials_background, RuntimeEnvironment.application.getResources())); } | protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } @SuppressLint("RestrictedApi") void disableShiftMode(BottomNavigationView view); BitmapDrawable writeOnDrawable(int drawableId, String initials, Resources resources); } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } @SuppressLint("RestrictedApi") void disableShiftMode(BottomNavigationView view); BitmapDrawable writeOnDrawable(int drawableId, String initials, Resources resources); } |
@Test public void testConvertBitmapDrawableToBitmap() { Assert.assertNotNull(bottomNavigationHelper.convertDrawableResToBitmap(R.drawable.child_boy_infant, RuntimeEnvironment.application.getResources())); } | protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } @SuppressLint("RestrictedApi") void disableShiftMode(BottomNavigationView view); BitmapDrawable writeOnDrawable(int drawableId, String initials, Resources resources); } | BottomNavigationHelper { protected Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Resources resources) { Drawable drawable = resources.getDrawable(drawableId); if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } else if (drawable instanceof GradientDrawable) { GradientDrawable gradientDrawable = (GradientDrawable) drawable; int width = drawable.getIntrinsicWidth() > 0 ? drawable.getIntrinsicWidth() : 27; int height = drawable.getIntrinsicHeight() > 0 ? drawable.getIntrinsicHeight() : 27; Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); gradientDrawable.setBounds(0, 0, width, height); gradientDrawable.setStroke(2, resources.getColor(R.color.light_grey_text)); gradientDrawable.setColor(resources.getColor(R.color.transparent)); gradientDrawable.setFilterBitmap(true); gradientDrawable.draw(canvas); return bitmap; } else { Bitmap bit = BitmapFactory.decodeResource(resources, drawableId); return bit.copy(Bitmap.Config.ARGB_8888, true); } } @SuppressLint("RestrictedApi") void disableShiftMode(BottomNavigationView view); BitmapDrawable writeOnDrawable(int drawableId, String initials, Resources resources); } |
@Test public void assertshouldReturn3PageCountFor50Clients() { SmartRegisterPaginatedAdapter adapter = getAdapterWithFakeClients(FIFTY); Assert.assertEquals(adapter.pageCount(), THREE); } | public int pageCount() { return pageCount; } | SmartRegisterPaginatedAdapter extends BaseAdapter { public int pageCount() { return pageCount; } } | SmartRegisterPaginatedAdapter extends BaseAdapter { public int pageCount() { return pageCount; } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); } | SmartRegisterPaginatedAdapter extends BaseAdapter { public int pageCount() { return pageCount; } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); } | SmartRegisterPaginatedAdapter extends BaseAdapter { public int pageCount() { return pageCount; } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); } |
@Test public void assertgetItemShouldReturnRespectiveItem() { SmartRegisterPaginatedAdapter adapter = getAdapterWithFakeClients(FIFTY); Assert.assertEquals(((ECClient) adapter.getItem(ZERO)).name(), NameZERO); Assert.assertEquals(((ECClient) adapter.getItem(FOURTYNINE)).name(), NameFOURTYNINE); } | @Override public Object getItem(int i) { return filteredClients.get(i); } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public Object getItem(int i) { return filteredClients.get(i); } } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public Object getItem(int i) { return filteredClients.get(i); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public Object getItem(int i) { return filteredClients.get(i); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public Object getItem(int i) { return filteredClients.get(i); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); } |
@Test public void assertgetViewShouldDelegateCallToProviderGetViewWithProperClient() { FakeClientsProvider fakeClientsProvider = new FakeClientsProvider(getSmartRegisterClients(FIFTY)); SmartRegisterPaginatedAdapter adapter = getAdapter(fakeClientsProvider); adapter.getView(ZERO, null, null); Assert.assertEquals(NameZERO, fakeClientsProvider.getViewCurrentClient.name()); adapter.getView(FOURTYNINE, null, null); Assert.assertEquals(NameFOURTYNINE, fakeClientsProvider.getViewCurrentClient.name()); } | @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); } | SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); } |
@Test public void testGetCount() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getCount(), 3); } | @Override public int getCount() { return locationNames.size(); } | ServiceLocationsAdapter extends BaseAdapter { @Override public int getCount() { return locationNames.size(); } } | ServiceLocationsAdapter extends BaseAdapter { @Override public int getCount() { return locationNames.size(); } ServiceLocationsAdapter(Context context, List<String> locationNames); } | ServiceLocationsAdapter extends BaseAdapter { @Override public int getCount() { return locationNames.size(); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } | ServiceLocationsAdapter extends BaseAdapter { @Override public int getCount() { return locationNames.size(); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } |
@Test public void testGetItemId() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getItemId(0), 2321); } | @Override public long getItemId(int position) { return position + 2321; } | ServiceLocationsAdapter extends BaseAdapter { @Override public long getItemId(int position) { return position + 2321; } } | ServiceLocationsAdapter extends BaseAdapter { @Override public long getItemId(int position) { return position + 2321; } ServiceLocationsAdapter(Context context, List<String> locationNames); } | ServiceLocationsAdapter extends BaseAdapter { @Override public long getItemId(int position) { return position + 2321; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } | ServiceLocationsAdapter extends BaseAdapter { @Override public long getItemId(int position) { return position + 2321; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } |
@Test public void testGetLocationAt() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getLocationAt(0), "test1"); } | public String getLocationAt(int position) { return locationNames.get(position); } | ServiceLocationsAdapter extends BaseAdapter { public String getLocationAt(int position) { return locationNames.get(position); } } | ServiceLocationsAdapter extends BaseAdapter { public String getLocationAt(int position) { return locationNames.get(position); } ServiceLocationsAdapter(Context context, List<String> locationNames); } | ServiceLocationsAdapter extends BaseAdapter { public String getLocationAt(int position) { return locationNames.get(position); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } | ServiceLocationsAdapter extends BaseAdapter { public String getLocationAt(int position) { return locationNames.get(position); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } |
@Test public void testGetLocationNames() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); List<String> names = adapter.getLocationNames(); Assert.assertEquals(names.get(0), "test1"); } | public List<String> getLocationNames() { return locationNames; } | ServiceLocationsAdapter extends BaseAdapter { public List<String> getLocationNames() { return locationNames; } } | ServiceLocationsAdapter extends BaseAdapter { public List<String> getLocationNames() { return locationNames; } ServiceLocationsAdapter(Context context, List<String> locationNames); } | ServiceLocationsAdapter extends BaseAdapter { public List<String> getLocationNames() { return locationNames; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } | ServiceLocationsAdapter extends BaseAdapter { public List<String> getLocationNames() { return locationNames; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } |
@Test public void assertIntegerCompareReturnsInt() { Assert.assertEquals(IntegerUtil.compare(1, 2), -1); Assert.assertEquals(IntegerUtil.compare(2, 2), 0); Assert.assertEquals(IntegerUtil.compare(3, 2), 1); } | public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } | IntegerUtil { public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } } | IntegerUtil { public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } } | IntegerUtil { public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } | IntegerUtil { public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); } |
@Test public void testGetView() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); itemsListView.setAdapter(adapter); when(applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).thenReturn(layoutInflater); Mockito.doReturn(linearLayout).when(layoutInflater).inflate(R.layout.location_picker_dropdown_item, null); ArrayList<String> ALLOWED_LEVELS; String DEFAULT_LOCATION_LEVEL = "Health Facility"; String SCHOOL = "School"; ALLOWED_LEVELS = new ArrayList<>(); ALLOWED_LEVELS.add(DEFAULT_LOCATION_LEVEL); ALLOWED_LEVELS.add(SCHOOL); LocationHelper.init(ALLOWED_LEVELS, "Health Facility"); when(locationHelper.getOpenMrsReadableName(anyString())).thenReturn("three"); Mockito.doReturn(textView).when(linearLayout).findViewById(android.R.id.text1); Mockito.doReturn(imageView).when(linearLayout).findViewById(R.id.checkbox); adapter.getView(0, null, null); Mockito.verify(layoutInflater).inflate(R.layout.location_picker_dropdown_item, null); } | @Override public View getView(int position, View convertView, ViewGroup parent) { if (!views.containsKey(locationNames.get(position))) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.location_picker_dropdown_item, null); view.setId(position + 2321); TextView text1 = view.findViewById(android.R.id.text1); text1.setText(LocationHelper.getInstance().getOpenMrsReadableName(locationNames.get(position))); views.put(locationNames.get(position), view); } refreshView(views.get(locationNames.get(position)), locationNames.get(position).equals(selectedLocation)); return views.get(locationNames.get(position)); } | ServiceLocationsAdapter extends BaseAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { if (!views.containsKey(locationNames.get(position))) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.location_picker_dropdown_item, null); view.setId(position + 2321); TextView text1 = view.findViewById(android.R.id.text1); text1.setText(LocationHelper.getInstance().getOpenMrsReadableName(locationNames.get(position))); views.put(locationNames.get(position), view); } refreshView(views.get(locationNames.get(position)), locationNames.get(position).equals(selectedLocation)); return views.get(locationNames.get(position)); } } | ServiceLocationsAdapter extends BaseAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { if (!views.containsKey(locationNames.get(position))) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.location_picker_dropdown_item, null); view.setId(position + 2321); TextView text1 = view.findViewById(android.R.id.text1); text1.setText(LocationHelper.getInstance().getOpenMrsReadableName(locationNames.get(position))); views.put(locationNames.get(position), view); } refreshView(views.get(locationNames.get(position)), locationNames.get(position).equals(selectedLocation)); return views.get(locationNames.get(position)); } ServiceLocationsAdapter(Context context, List<String> locationNames); } | ServiceLocationsAdapter extends BaseAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { if (!views.containsKey(locationNames.get(position))) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.location_picker_dropdown_item, null); view.setId(position + 2321); TextView text1 = view.findViewById(android.R.id.text1); text1.setText(LocationHelper.getInstance().getOpenMrsReadableName(locationNames.get(position))); views.put(locationNames.get(position), view); } refreshView(views.get(locationNames.get(position)), locationNames.get(position).equals(selectedLocation)); return views.get(locationNames.get(position)); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } | ServiceLocationsAdapter extends BaseAdapter { @Override public View getView(int position, View convertView, ViewGroup parent) { if (!views.containsKey(locationNames.get(position))) { LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.location_picker_dropdown_item, null); view.setId(position + 2321); TextView text1 = view.findViewById(android.R.id.text1); text1.setText(LocationHelper.getInstance().getOpenMrsReadableName(locationNames.get(position))); views.put(locationNames.get(position), view); } refreshView(views.get(locationNames.get(position)), locationNames.get(position).equals(selectedLocation)); return views.get(locationNames.get(position)); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); } |
@Test public void testOnRunJobStartsCorrectService() { SyncTaskServiceJob syncTaskServiceJob = new SyncTaskServiceJob(SyncTaskIntentService.class); SyncTaskServiceJob syncTaskServiceJobSpy = Mockito.spy(syncTaskServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncTaskServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncTaskServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncTaskIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | SyncTaskServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncTaskServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncTaskServiceJob(Class<? extends SyncTaskIntentService> serviceClass); } | SyncTaskServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncTaskServiceJob(Class<? extends SyncTaskIntentService> serviceClass); } | SyncTaskServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncTaskServiceJob(Class<? extends SyncTaskIntentService> serviceClass); static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { ValidateSyncDataServiceJob validateSyncDataServiceJob = new ValidateSyncDataServiceJob(); ValidateSyncDataServiceJob validateSyncDataServiceJobSpy = Mockito.spy(validateSyncDataServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(validateSyncDataServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); validateSyncDataServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.ValidateIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | ValidateSyncDataServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | ValidateSyncDataServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | ValidateSyncDataServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | ValidateSyncDataServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { CampaignServiceJob campaignServiceJob = new CampaignServiceJob(); CampaignServiceJob campaignServiceJobJobSpy = Mockito.spy(campaignServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(campaignServiceJobJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); campaignServiceJobJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.CampaignIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | CampaignServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | CampaignServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | CampaignServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | CampaignServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { PullUniqueIdsServiceJob pullUniqueIdsServiceJob = new PullUniqueIdsServiceJob(); PullUniqueIdsServiceJob pullUniqueIdsServiceJobSpy = Mockito.spy(pullUniqueIdsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(pullUniqueIdsServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); pullUniqueIdsServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.PullUniqueIdsIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | PullUniqueIdsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | PullUniqueIdsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | PullUniqueIdsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | PullUniqueIdsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { ExtendedSyncServiceJob extendedSyncServiceJob = new ExtendedSyncServiceJob(); ExtendedSyncServiceJob syncServiceJobSpy = Mockito.spy(extendedSyncServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.ExtendedSyncIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | ExtendedSyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | ExtendedSyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | ExtendedSyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | ExtendedSyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { SyncLocationsByLevelAndTagsServiceJob syncLocationsByLevelAndTagsServiceJob = new SyncLocationsByLevelAndTagsServiceJob(); SyncLocationsByLevelAndTagsServiceJob syncLocationsByLevelAndTagsServiceJobSpy = Mockito.spy(syncLocationsByLevelAndTagsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncLocationsByLevelAndTagsServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncLocationsByLevelAndTagsServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncLocationsByLevelAndTagsIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | SyncLocationsByLevelAndTagsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncLocationsByLevelAndTagsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncLocationsByLevelAndTagsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncLocationsByLevelAndTagsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { DocumentConfigurationServiceJob documentConfigurationServiceJob = new DocumentConfigurationServiceJob(DocumentConfigurationIntentService.class); DocumentConfigurationServiceJob documentConfigurationServiceJobSpy = Mockito.spy(documentConfigurationServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(documentConfigurationServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); documentConfigurationServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.DocumentConfigurationIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | DocumentConfigurationServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | DocumentConfigurationServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } DocumentConfigurationServiceJob(Class<? extends DocumentConfigurationIntentService> serviceClass); } | DocumentConfigurationServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } DocumentConfigurationServiceJob(Class<? extends DocumentConfigurationIntentService> serviceClass); } | DocumentConfigurationServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } DocumentConfigurationServiceJob(Class<? extends DocumentConfigurationIntentService> serviceClass); static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { SyncServiceJob syncServiceJob = new SyncServiceJob(SyncIntentService.class); SyncServiceJob syncServiceJobSpy = Mockito.spy(syncServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | SyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncServiceJob(Class<? extends SyncIntentService> serviceClass); } | SyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncServiceJob(Class<? extends SyncIntentService> serviceClass); } | SyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncServiceJob(Class<? extends SyncIntentService> serviceClass); static final String TAG; } |
@Test public void testOnRunJobStartsCorrectService() { SyncLocationsByTeamIdsJob syncLocationsByTeamIdsJob = new SyncLocationsByTeamIdsJob(); SyncLocationsByTeamIdsJob syncLocationsByTeamIdsJobSpy = Mockito.spy(syncLocationsByTeamIdsJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncLocationsByTeamIdsJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncLocationsByTeamIdsJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncLocationsByTeamIdsIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | SyncLocationsByTeamIdsJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncLocationsByTeamIdsJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncLocationsByTeamIdsJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncLocationsByTeamIdsJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void assertGetDurationTest() { Locale locale = RuntimeEnvironment.application.getApplicationContext().getResources().getConfiguration().locale; Assert.assertEquals("1d", DateUtil.getDuration(100000000l, locale)); Assert.assertEquals("5w 1d", DateUtil.getDuration(3110400000l, locale)); Assert.assertEquals("5w", DateUtil.getDuration(3024000000l, locale)); Assert.assertEquals("3m 1w", DateUtil.getDuration(TimeUnit.DAYS.toMillis(100), locale)); Assert.assertEquals("1y", DateUtil.getDuration(31363200000l, locale)); Assert.assertEquals("1y 1m", DateUtil.getDuration(36500000000l, locale)); Assert.assertEquals("2y", DateUtil.getDuration(63113852000l, locale)); Assert.assertEquals("1d", DateUtil.getDuration(100000000l)); Assert.assertNotNull(DateUtil.getDuration(RuntimeEnvironment.application, new DateTime(0))); Assert.assertNull(DateUtil.getDuration(RuntimeEnvironment.application, null)); } | public static String getDuration(DateTime dateTime) { return getDuration(CoreLibrary.getInstance().context().applicationContext(), dateTime); } | DateUtil { public static String getDuration(DateTime dateTime) { return getDuration(CoreLibrary.getInstance().context().applicationContext(), dateTime); } } | DateUtil { public static String getDuration(DateTime dateTime) { return getDuration(CoreLibrary.getInstance().context().applicationContext(), dateTime); } } | DateUtil { public static String getDuration(DateTime dateTime) { return getDuration(CoreLibrary.getInstance().context().applicationContext(), dateTime); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); } | DateUtil { public static String getDuration(DateTime dateTime) { return getDuration(CoreLibrary.getInstance().context().applicationContext(), dateTime); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; } |
@Test public void testOnRunJobStartsCorrectService() { SyncAllLocationsServiceJob syncAllLocationsServiceJob = new SyncAllLocationsServiceJob(); SyncAllLocationsServiceJob spy = Mockito.spy(syncAllLocationsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(spy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); spy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); assertEquals("org.smartregister.sync.intent.SyncAllLocationsIntentService", intent.getValue().getComponent().getClassName()); } | @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } | SyncAllLocationsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncAllLocationsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncAllLocationsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } } | SyncAllLocationsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; } |
@Test public void testSerialize() { Campaign campaign = gson.fromJson(campaignJson, Campaign.class); assertEquals(campaignJson, gson.toJson(campaign)); assertEquals(campaign.getTitle(),"2019 IRS Season 1"); } | public String getTitle() { return title; } | Campaign { public String getTitle() { return title; } } | Campaign { public String getTitle() { return title; } } | Campaign { public String getTitle() { return title; } String getIdentifier(); void setIdentifier(String identifier); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); TaskStatus getStatus(); void setStatus(TaskStatus status); ExecutionPeriod getExecutionPeriod(); void setExecutionPeriod(ExecutionPeriod executionPeriod); DateTime getAuthoredOn(); void setAuthoredOn(DateTime authoredOn); DateTime getLastModified(); void setLastModified(DateTime lastModified); String getOwner(); void setOwner(String owner); long getServerVersion(); void setServerVersion(long serverVersion); } | Campaign { public String getTitle() { return title; } String getIdentifier(); void setIdentifier(String identifier); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); TaskStatus getStatus(); void setStatus(TaskStatus status); ExecutionPeriod getExecutionPeriod(); void setExecutionPeriod(ExecutionPeriod executionPeriod); DateTime getAuthoredOn(); void setAuthoredOn(DateTime authoredOn); DateTime getLastModified(); void setLastModified(DateTime lastModified); String getOwner(); void setOwner(String owner); long getServerVersion(); void setServerVersion(long serverVersion); } |
@Test public void testCloseCaseShouldReturnFalseIfCloseCaseIsEmpty() { ClientProcessorForJava clientProcessor = new ClientProcessorForJava(context); assertFalse(clientProcessor.closeCase(new Client("1233-2"), new ArrayList<>())); } | public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void testCloseCaseShouldPassCorrectValuesToCloseCase() { ClientProcessorForJava clientProcessor = new ClientProcessorForJava(context); CommonRepository commonRepository = Mockito.mock(CommonRepository.class); ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); PowerMockito.when(coreLibrary.context()).thenReturn(opensrpContext); PowerMockito.when(opensrpContext.commonrepository("child")).thenReturn(commonRepository); assertTrue(clientProcessor.closeCase(new Client("1233-2"), Arrays.asList("child"))); Mockito.verify(commonRepository).closeCase(closeCaseArgumentCaptor.capture(), closeCaseArgumentCaptor.capture()); assertEquals("1233-2", closeCaseArgumentCaptor.getAllValues().get(0)); assertEquals("child", closeCaseArgumentCaptor.getAllValues().get(1)); } | public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean closeCase(Client client, List<String> closesCase) { try { if (closesCase == null || closesCase.isEmpty()) { return false; } String baseEntityId = client.getBaseEntityId(); for (String tableName : closesCase) { closeCase(tableName, baseEntityId); updateFTSsearch(tableName, baseEntityId, null); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void testGetColumnMappingsShouldReturnTheCorrectTable() throws IOException { ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); Mockito.when(coreLibrary.getEcClientFieldsFile()).thenReturn("ec_client_fields.json"); AssetManager assetManager = Mockito.mock(AssetManager.class); Mockito.when(context.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open("ec_client_fields.json")).thenReturn(new ByteArrayInputStream(ClientData.ec_client_fields_json.getBytes())); Table ecHousehold = clientProcessor.getColumnMappings("ec_household"); assertNotNull(ecHousehold); assertEquals(ecHousehold.name, "ec_household"); } | public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void testGetColumnMappingsShouldReturnNullIfFileIsNotRead() throws IOException { ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); Mockito.when(coreLibrary.getEcClientFieldsFile()).thenReturn("ec_client_fields.json"); AssetManager assetManager = Mockito.mock(AssetManager.class); Mockito.when(context.getAssets()).thenReturn(assetManager); Mockito.when(assetManager.open("ec_client_fields.json")).thenReturn(null); Table ecHousehold = clientProcessor.getColumnMappings("ec_household"); assertNull(ecHousehold); } | public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Table getColumnMappings(String registerName) { try { ClientField clientField = assetJsonToJava(CoreLibrary.getInstance().getEcClientFieldsFile(), ClientField.class); if (clientField == null) { return null; } List<Table> bindObjects = clientField.bindobjects; for (Table bindObject : bindObjects) { if (bindObject.name.equalsIgnoreCase(registerName)) { return bindObject; } } } catch (Exception e) { Timber.e(e); } return null; } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void testUpdateClientDetailsTableShouldNotSaveClientDetailsIdConfigIsFalse() { ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); DetailsRepository detailsRepository = Mockito.mock(DetailsRepository.class); SyncConfiguration syncConfiguration = Mockito.mock(SyncConfiguration.class); Mockito.when(coreLibrary.getSyncConfiguration()).thenReturn(syncConfiguration); Mockito.when(syncConfiguration.updateClientDetailsTable()).thenReturn(false); Mockito.when(coreLibrary.context()).thenReturn(opensrpContext); Mockito.when(opensrpContext.detailsRepository()).thenReturn(detailsRepository); Event event = new Event(); clientProcessor.updateClientDetailsTable(event, new Client("2323-2")); assertTrue(Boolean.valueOf(event.getDetails().get(ClientProcessorForJava.detailsUpdated))); Mockito.verify(detailsRepository, Mockito.never()).add(anyString(), anyString(), anyString(), anyLong()); } | public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void testUpdateClientDetailsTableShouldSaveClientDetailsIdConfigIsTrue() { ReflectionHelpers.setStaticField(CoreLibrary.class, "instance", coreLibrary); DetailsRepository detailsRepository = Mockito.mock(DetailsRepository.class); SyncConfiguration syncConfiguration = Mockito.mock(SyncConfiguration.class); Mockito.when(coreLibrary.getSyncConfiguration()).thenReturn(syncConfiguration); Mockito.when(syncConfiguration.updateClientDetailsTable()).thenReturn(true); Mockito.when(coreLibrary.context()).thenReturn(opensrpContext); Mockito.when(opensrpContext.detailsRepository()).thenReturn(detailsRepository); DateTime dateTime = new DateTime(); Event event = new Event(); event.setEventDate(dateTime); Obs obs = new Obs(); obs.setFieldCode("12212AAAAA"); obs.setFormSubmissionField("reminders"); Object value = (Object) "no"; obs.setValues(Arrays.asList(value)); obs.setHumanReadableValue(new ArrayList<>()); obs.setFieldDataType("text"); event.addObs(obs); Client client = new Client("234-13"); client.setGender("Female"); Map<String, Object> attribsMap = new HashMap<>(); attribsMap.put("national_id", "423"); attribsMap.put("phone_number", "0707070"); client.setAttributes(attribsMap); clientProcessor.updateClientDetailsTable(event, client); assertTrue(Boolean.valueOf(event.getDetails().get(ClientProcessorForJava.detailsUpdated))); Mockito.verify(detailsRepository, Mockito.atLeast(4)).add(anyString(), anyString(), anyString(), anyLong()); } | public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public void updateClientDetailsTable(Event event, Client client) { try { Timber.d("Started updateClientDetailsTable"); if (CoreLibrary.getInstance().getSyncConfiguration().updateClientDetailsTable()) { String baseEntityId = client.getBaseEntityId(); Long timestamp = getEventDate(event.getEventDate()); Map<String, String> genderInfo = getGender(client); saveClientDetails(baseEntityId, genderInfo, timestamp); Map<String, String> addressInfo = getClientAddressAsMap(client); saveClientDetails(baseEntityId, addressInfo, timestamp); Map<String, String> attributes = getClientAttributes(client); saveClientDetails(baseEntityId, attributes, timestamp); Map<String, String> obs = getObsFromEvent(event); saveClientDetails(baseEntityId, obs, timestamp); } event.addDetails(detailsUpdated, Boolean.TRUE.toString()); Timber.d("Finished updateClientDetailsTable"); } catch (Exception e) { Timber.e(e); } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processFieldShouldReturnFalse() { assertFalse(clientProcessor.processField(null, null, null)); } | public Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client) { try { if (field == null) { return false; } String dataSegment = null; String fieldName = field.field; String fieldValue = field.field_value; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = field.concept; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } List<String> createsCase = field.creates_case; List<String> closesCase = field.closes_case; if (StringUtils.isNotBlank(dataSegment)) { List<String> responseValues = field.values; Object dataSegmentObject = getValue(event, dataSegment); if (dataSegmentObject != null) { if (dataSegmentObject instanceof List) { List dataSegmentList = (List) dataSegmentObject; for (Object segment : dataSegmentList) { Object value = getValue(segment, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; Object values = getValue(segment, responseKey); List<String> docSegmentResponseValues = new ArrayList<>(); if (values instanceof List) { docSegmentResponseValues = getValues((List) values); } if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } else if (dataSegmentObject instanceof Map) { Map map = (Map) dataSegmentObject; if (map.containsKey(fieldName)) { Object objectValue = map.get(fieldName); if (objectValue != null && objectValue instanceof String) { String docSegmentFieldValue = objectValue.toString(); if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } } } else { Object value = getValue(event, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client) { try { if (field == null) { return false; } String dataSegment = null; String fieldName = field.field; String fieldValue = field.field_value; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = field.concept; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } List<String> createsCase = field.creates_case; List<String> closesCase = field.closes_case; if (StringUtils.isNotBlank(dataSegment)) { List<String> responseValues = field.values; Object dataSegmentObject = getValue(event, dataSegment); if (dataSegmentObject != null) { if (dataSegmentObject instanceof List) { List dataSegmentList = (List) dataSegmentObject; for (Object segment : dataSegmentList) { Object value = getValue(segment, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; Object values = getValue(segment, responseKey); List<String> docSegmentResponseValues = new ArrayList<>(); if (values instanceof List) { docSegmentResponseValues = getValues((List) values); } if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } else if (dataSegmentObject instanceof Map) { Map map = (Map) dataSegmentObject; if (map.containsKey(fieldName)) { Object objectValue = map.get(fieldName); if (objectValue != null && objectValue instanceof String) { String docSegmentFieldValue = objectValue.toString(); if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } } } else { Object value = getValue(event, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client) { try { if (field == null) { return false; } String dataSegment = null; String fieldName = field.field; String fieldValue = field.field_value; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = field.concept; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } List<String> createsCase = field.creates_case; List<String> closesCase = field.closes_case; if (StringUtils.isNotBlank(dataSegment)) { List<String> responseValues = field.values; Object dataSegmentObject = getValue(event, dataSegment); if (dataSegmentObject != null) { if (dataSegmentObject instanceof List) { List dataSegmentList = (List) dataSegmentObject; for (Object segment : dataSegmentList) { Object value = getValue(segment, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; Object values = getValue(segment, responseKey); List<String> docSegmentResponseValues = new ArrayList<>(); if (values instanceof List) { docSegmentResponseValues = getValues((List) values); } if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } else if (dataSegmentObject instanceof Map) { Map map = (Map) dataSegmentObject; if (map.containsKey(fieldName)) { Object objectValue = map.get(fieldName); if (objectValue != null && objectValue instanceof String) { String docSegmentFieldValue = objectValue.toString(); if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } } } else { Object value = getValue(event, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client) { try { if (field == null) { return false; } String dataSegment = null; String fieldName = field.field; String fieldValue = field.field_value; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = field.concept; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } List<String> createsCase = field.creates_case; List<String> closesCase = field.closes_case; if (StringUtils.isNotBlank(dataSegment)) { List<String> responseValues = field.values; Object dataSegmentObject = getValue(event, dataSegment); if (dataSegmentObject != null) { if (dataSegmentObject instanceof List) { List dataSegmentList = (List) dataSegmentObject; for (Object segment : dataSegmentList) { Object value = getValue(segment, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; Object values = getValue(segment, responseKey); List<String> docSegmentResponseValues = new ArrayList<>(); if (values instanceof List) { docSegmentResponseValues = getValues((List) values); } if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } else if (dataSegmentObject instanceof Map) { Map map = (Map) dataSegmentObject; if (map.containsKey(fieldName)) { Object objectValue = map.get(fieldName); if (objectValue != null && objectValue instanceof String) { String docSegmentFieldValue = objectValue.toString(); if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } } } else { Object value = getValue(event, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client) { try { if (field == null) { return false; } String dataSegment = null; String fieldName = field.field; String fieldValue = field.field_value; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = field.concept; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } List<String> createsCase = field.creates_case; List<String> closesCase = field.closes_case; if (StringUtils.isNotBlank(dataSegment)) { List<String> responseValues = field.values; Object dataSegmentObject = getValue(event, dataSegment); if (dataSegmentObject != null) { if (dataSegmentObject instanceof List) { List dataSegmentList = (List) dataSegmentObject; for (Object segment : dataSegmentList) { Object value = getValue(segment, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; Object values = getValue(segment, responseKey); List<String> docSegmentResponseValues = new ArrayList<>(); if (values instanceof List) { docSegmentResponseValues = getValues((List) values); } if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } else if (dataSegmentObject instanceof Map) { Map map = (Map) dataSegmentObject; if (map.containsKey(fieldName)) { Object objectValue = map.get(fieldName); if (objectValue != null && objectValue instanceof String) { String docSegmentFieldValue = objectValue.toString(); if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } } } else { Object value = getValue(event, fieldName); String docSegmentFieldValue = value != null ? value.toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processCaseModelShouldReturnFalseWhenCreatesCaseParamIsNull() { assertFalse(clientProcessor.processCaseModel(null, null, null)); } | public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void assertCheckIfDateThreeMonthsOlderReturnsBoolean() { Assert.assertEquals(DateUtil.checkIfDateThreeMonthsOlder(new Date()), false); } | public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } | DateUtil { public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } } | DateUtil { public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } } | DateUtil { public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); } | DateUtil { public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; } |
@Test public void processClientClassShouldFalseWhenClassificationRuleIsNull() { Event event = new Event(); Client client = new Client("bei"); Assert.assertFalse(clientProcessor.processClientClass(null, event, client)); } | public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processClientClassShouldFalseWhenEventIsNull() { Client client = new Client("bei"); ClassificationRule classificationRule = gson.fromJson("{\"comment\":\"Child: This rule checks whether a given case belongs to Child register\",\"rule\":{\"type\":\"event\",\"fields\":[{\"field\":\"eventType\",\"field_value\":\"New Woman Registration\",\"creates_case\":[\"ec_client\",\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Birth Registration\",\"creates_case\":[\"ec_client\",\"ec_child_details\"]},{\"field\":\"eventType\",\"field_value\":\"Update Birth Registration\",\"creates_case\":[\"ec_client\",\"ec_child_details\"]},{\"field\":\"eventType\",\"field_value\":\"ANC Close\",\"creates_case\":[\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"ANC Registration\",\"creates_case\":[\"ec_client\",\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Update ANC Registration\",\"creates_case\":[\"ec_client\",\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Visit\",\"creates_case\":[\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Opd Registration\",\"creates_case\":[\"ec_client\"]}]}}", ClassificationRule.class); Assert.assertFalse(clientProcessor.processClientClass(classificationRule, null, client)); } | public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processClientClassShouldFalseWhenClientIsNull() { Event event = new Event(); ClassificationRule classificationRule = gson.fromJson("{\"comment\":\"Child: This rule checks whether a given case belongs to Child register\",\"rule\":{\"type\":\"event\",\"fields\":[{\"field\":\"eventType\",\"field_value\":\"New Woman Registration\",\"creates_case\":[\"ec_client\",\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Birth Registration\",\"creates_case\":[\"ec_client\",\"ec_child_details\"]},{\"field\":\"eventType\",\"field_value\":\"Update Birth Registration\",\"creates_case\":[\"ec_client\",\"ec_child_details\"]},{\"field\":\"eventType\",\"field_value\":\"ANC Close\",\"creates_case\":[\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"ANC Registration\",\"creates_case\":[\"ec_client\",\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Update ANC Registration\",\"creates_case\":[\"ec_client\",\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Visit\",\"creates_case\":[\"ec_mother_details\"]},{\"field\":\"eventType\",\"field_value\":\"Opd Registration\",\"creates_case\":[\"ec_client\"]}]}}", ClassificationRule.class); Assert.assertFalse(clientProcessor.processClientClass(classificationRule, event, null)); } | public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processClientClass(ClassificationRule clientClass, Event event, Client client) { try { if (clientClass == null) { return false; } if (event == null) { return false; } if (client == null) { return false; } Rule rule = clientClass.rule; List<org.smartregister.domain.jsonmapping.Field> fields = rule.fields; for (org.smartregister.domain.jsonmapping.Field field : fields) { processField(field, event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processCaseModelWhenGivenColumnConfigurationFromEventObsShouldPopulateContentValuesAsPerColumnConfiguration() { String eventJson = "{\"baseEntityId\":\"021a1da2-cebf-44fa-9ef3-3ffc18fa6356\",\"entityType\":\"vaccination\",\"eventDate\":\"2018-10-15T20:00:00.000-04:00\",\"eventType\":\"Vaccination\",\"formSubmissionId\":\"e9c0c4ec-63c3-4104-958e-21e133efd3b2\",\"locationId\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"obs\":[{\"fieldCode\":\"1410AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"date\",\"fieldType\":\"concept\",\"formSubmissionField\":\"rota_2\",\"humanReadableValues\":[],\"parentCode\":\"159698AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"saveObsAsArray\":false,\"values\":[\"2018-10-16\"]},{\"fieldCode\":\"1418AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"calculate\",\"fieldType\":\"concept\",\"formSubmissionField\":\"rota_2_dose\",\"humanReadableValues\":[],\"parentCode\":\"159698AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"saveObsAsArray\":false,\"values\":[\"2\"]}],\"providerId\":\"chwone\",\"version\":1567465052005,\"clientApplicationVersion\":1,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-10-07T05:49:52.992-04:00\",\"dateEdited\":\"2019-09-18T06:10:56.784-04:00\",\"serverVersion\":1568801628709}"; String columnJson = "{\"column_name\":\"name\",\"json_mapping\":{\"field\":\"obs.fieldCode\",\"concept\":\"1410AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"value_field\":\"formSubmissionField\"}}"; Event event = JsonFormUtils.gson.fromJson(eventJson, Event.class); Column column = JsonFormUtils.gson.fromJson(columnJson, Column.class); ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", "021a1da2-cebf-44fa-9ef3-3ffc18fa6356"); clientProcessor.processCaseModel(event, null, column, contentValues); assertEquals("rota_2", contentValues.getAsString("name")); } | public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processCaseModelWhenGivenColumnConfigurationFromEventFieldShouldPopulateContentValues() { String eventJson = "{\"baseEntityId\":\"021a1da2-cebf-44fa-9ef3-3ffc18fa6356\",\"entityType\":\"vaccination\",\"eventDate\":\"2018-10-15T20:00:00.000-04:00\",\"eventType\":\"Vaccination\",\"formSubmissionId\":\"e9c0c4ec-63c3-4104-958e-21e133efd3b2\",\"locationId\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"obs\":[{\"fieldCode\":\"1410AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"date\",\"fieldType\":\"concept\",\"formSubmissionField\":\"rota_2\",\"humanReadableValues\":[],\"parentCode\":\"159698AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"saveObsAsArray\":false,\"values\":[\"2018-10-16\"]},{\"fieldCode\":\"1418AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"calculate\",\"fieldType\":\"concept\",\"formSubmissionField\":\"rota_2_dose\",\"humanReadableValues\":[],\"parentCode\":\"159698AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"saveObsAsArray\":false,\"values\":[\"2\"]}],\"providerId\":\"chwone\",\"version\":1567465052005,\"clientApplicationVersion\":1,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-10-07T05:49:52.992-04:00\",\"dateEdited\":\"2019-09-18T06:10:56.784-04:00\",\"serverVersion\":1568801628709}"; String columnJson = "{\"column_name\":\"anmid\",\"json_mapping\":{\"field\":\"providerId\"}}"; Event event = JsonFormUtils.gson.fromJson(eventJson, Event.class); Column column = JsonFormUtils.gson.fromJson(columnJson, Column.class); ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", "021a1da2-cebf-44fa-9ef3-3ffc18fa6356"); clientProcessor.processCaseModel(event, null, column, contentValues); assertEquals("chwone", contentValues.getAsString("anmid")); } | public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processCaseModelWhenGivenColumnConfigurationFromClientIdentifiersFieldShouldPopulateContentValues() { String eventJson = "{\"baseEntityId\":\"3a221190-c004-4297-88bd-4b925e19098f\",\"entityType\":\"ec_family_member\",\"eventDate\":\"2019-09-23T20:00:00.000-04:00\",\"eventType\":\"Family Member Registration\",\"formSubmissionId\":\"af7143d3-33d9-4bb2-9fe5-14937b4ae92f\",\"locationId\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"obs\":[{\"fieldCode\":\"\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"surname\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"Kim\"]},{\"fieldCode\":\"\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"age_calculated\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"18.0\"]},{\"fieldCode\":\"\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"wra\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"0\"]},{\"fieldCode\":\"162558AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"disabilities\",\"humanReadableValues\":[\"No\"],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"1066AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]},{\"fieldCode\":\"159635AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"phone_number\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"0723433455\"]},{\"fieldCode\":\"1542AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"service_provider\",\"humanReadableValues\":[\"None\"],\"parentCode\":\"1542AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"saveObsAsArray\":false,\"values\":[\"164369AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]},{\"fieldCode\":\"163137AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"start\",\"fieldType\":\"concept\",\"formSubmissionField\":\"start\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"2019-09-24 10:18:41\"]},{\"fieldCode\":\"163138AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"end\",\"fieldType\":\"concept\",\"formSubmissionField\":\"end\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"2019-09-24 10:21:34\"]},{\"fieldCode\":\"163152AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"phonenumber\",\"fieldType\":\"concept\",\"formSubmissionField\":\"phonenumber\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"+15555215554\"]}],\"providerId\":\"chwone\",\"version\":1569309694752,\"clientApplicationVersion\":2,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-09-24T03:44:30.108-04:00\",\"dateEdited\":\"2019-11-13T00:42:43.387-05:00\",\"serverVersion\":1573623789891}"; String clientJson = "{\"birthdate\":\"2001-09-23T20:00:00.000-04:00\",\"birthdateApprox\":false,\"deathdateApprox\":false,\"firstName\":\"Jonny\",\"gender\":\"Male\",\"middleName\":\"Kamau\",\"relationships\":{\"family\":[\"af3e29be-88ee-4063-bb02-963a64c664ab\"]},\"addresses\":[],\"attributes\":{\"id_avail\":\"[\\\"chk_none\\\"]\",\"Community_Leader\":\"[\\\"chk_none\\\"]\",\"Health_Insurance_Type\":\"iCHF\",\"Health_Insurance_Number\":\"123\"},\"baseEntityId\":\"3a221190-c004-4297-88bd-4b925e19098f\",\"identifiers\":{\"opensrp_id\":\"4602652\"},\"clientApplicationVersion\":2,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-09-24T03:44:30.015-04:00\",\"serverVersion\":1569311069836}"; String columnJson = "{\"column_name\":\"unique_id\",\"json_mapping\":{\"field\":\"identifiers.opensrp_id\"},\"type\":\"Client\"}"; Event event = JsonFormUtils.gson.fromJson(eventJson, Event.class); Client client = JsonFormUtils.gson.fromJson(clientJson, Client.class); Column column = JsonFormUtils.gson.fromJson(columnJson, Column.class); ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", "3a221190-c004-4297-88bd-4b925e19098f"); clientProcessor.processCaseModel(event, client, column, contentValues); assertEquals("4602652", contentValues.getAsString("unique_id")); } | public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processCaseModelWhenGivenColumnConfigurationFromClientRelationshipsFieldShouldPopulateContentValues() { String eventJson = "{\"baseEntityId\":\"3a221190-c004-4297-88bd-4b925e19098f\",\"entityType\":\"ec_family_member\",\"eventDate\":\"2019-09-23T20:00:00.000-04:00\",\"eventType\":\"Family Member Registration\",\"formSubmissionId\":\"af7143d3-33d9-4bb2-9fe5-14937b4ae92f\",\"locationId\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"obs\":[{\"fieldCode\":\"\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"surname\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"Kim\"]},{\"fieldCode\":\"\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"age_calculated\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"18.0\"]},{\"fieldCode\":\"\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"wra\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"0\"]},{\"fieldCode\":\"162558AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"disabilities\",\"humanReadableValues\":[\"No\"],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"1066AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]},{\"fieldCode\":\"159635AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"phone_number\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"0723433455\"]},{\"fieldCode\":\"1542AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"text\",\"fieldType\":\"concept\",\"formSubmissionField\":\"service_provider\",\"humanReadableValues\":[\"None\"],\"parentCode\":\"1542AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"saveObsAsArray\":false,\"values\":[\"164369AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]},{\"fieldCode\":\"163137AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"start\",\"fieldType\":\"concept\",\"formSubmissionField\":\"start\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"2019-09-24 10:18:41\"]},{\"fieldCode\":\"163138AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"end\",\"fieldType\":\"concept\",\"formSubmissionField\":\"end\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"2019-09-24 10:21:34\"]},{\"fieldCode\":\"163152AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\",\"fieldDataType\":\"phonenumber\",\"fieldType\":\"concept\",\"formSubmissionField\":\"phonenumber\",\"humanReadableValues\":[],\"parentCode\":\"\",\"saveObsAsArray\":false,\"values\":[\"+15555215554\"]}],\"providerId\":\"chwone\",\"version\":1569309694752,\"clientApplicationVersion\":2,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-09-24T03:44:30.108-04:00\",\"dateEdited\":\"2019-11-13T00:42:43.387-05:00\",\"serverVersion\":1573623789891}"; String clientJson = "{\"birthdate\":\"2001-09-23T20:00:00.000-04:00\",\"birthdateApprox\":false,\"deathdateApprox\":false,\"firstName\":\"Jonny\",\"gender\":\"Male\",\"middleName\":\"Kamau\",\"relationships\":{\"family\":[\"af3e29be-88ee-4063-bb02-963a64c664ab\"]},\"addresses\":[],\"attributes\":{\"id_avail\":\"[\\\"chk_none\\\"]\",\"Community_Leader\":\"[\\\"chk_none\\\"]\",\"Health_Insurance_Type\":\"iCHF\",\"Health_Insurance_Number\":\"123\"},\"baseEntityId\":\"3a221190-c004-4297-88bd-4b925e19098f\",\"identifiers\":{\"opensrp_id\":\"4602652\"},\"clientApplicationVersion\":2,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-09-24T03:44:30.015-04:00\",\"serverVersion\":1569311069836}"; String columnJson = "{\"column_name\":\"relational_id\",\"json_mapping\":{\"field\":\"relationships.family\"},\"type\":\"Client\"}"; Event event = JsonFormUtils.gson.fromJson(eventJson, Event.class); Client client = JsonFormUtils.gson.fromJson(clientJson, Client.class); Column column = JsonFormUtils.gson.fromJson(columnJson, Column.class); ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", "3a221190-c004-4297-88bd-4b925e19098f"); clientProcessor.processCaseModel(event, client, column, contentValues); assertEquals("af3e29be-88ee-4063-bb02-963a64c664ab", contentValues.getAsString("relational_id")); } | public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processCaseModelWhenGivenColumnConfigurationFromClientAddressesFieldShouldPopulateContentValues() { String eventJson = "{\"baseEntityId\":\"5b85d576-51cd-4ccc-bfd7-2b67d4af89e3\",\"entityType\":\"ec_family\",\"eventDate\":\"2019-09-24T08:12:12.000-04:00\",\"eventType\":\"Update Family Relations\",\"formSubmissionId\":\"fc673dfe-a720-405e-9b2a-0b2e4067364b\",\"locationId\":\"2c3a0ebd-f79d-4128-a6d3-5dfbffbd01c8\",\"obs\":[],\"providerId\":\"chwone\",\"version\":1569316332001,\"clientApplicationVersion\":2,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-09-24T05:13:17.700-04:00\",\"dateEdited\":\"2019-11-13T00:42:43.445-05:00\",\"serverVersion\":1573623789901}"; String clientJson = "{\"birthdate\":\"1970-01-01T01:00:00.000-05:00\",\"birthdateApprox\":false,\"deathdateApprox\":false,\"firstName\":\"Kitoto\",\"gender\":\"Male\",\"lastName\":\"Family\",\"relationships\":{\"family_head\":[\"9f424541-b5c6-46e5-af99-6c8d6d28559c\"],\"primary_caregiver\":[\"41b652a2-167a-4e32-9717-013b5031c972\"]},\"addresses\":[{\"addressFields\":{\"landmark\":\"Chandaria Factory\"},\"addressType\":\"\",\"cityVillage\":\"Kasabuni\"}],\"attributes\":{},\"baseEntityId\":\"5b85d576-51cd-4ccc-bfd7-2b67d4af89e3\",\"identifiers\":{\"opensrp_id\":\"4626057_family\"},\"clientApplicationVersion\":2,\"clientDatabaseVersion\":11,\"dateCreated\":\"2019-09-24T08:10:33.460-04:00\",\"dateEdited\":\"2019-09-24T05:13:17.679-04:00\",\"serverVersion\":1569316449432}"; String columnJson = "{\"column_name\":\"village_town\",\"json_mapping\":{\"field\":\"addresses.cityVillage\"},\"type\":\"Client\"}"; Event event = JsonFormUtils.gson.fromJson(eventJson, Event.class); Client client = JsonFormUtils.gson.fromJson(clientJson, Client.class); Column column = JsonFormUtils.gson.fromJson(columnJson, Column.class); ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", "5b85d576-51cd-4ccc-bfd7-2b67d4af89e3"); ReflectionHelpers.setStaticField(ClientProcessorForJava.class, "instance", clientProcessor); clientProcessor.processCaseModel(event, client, column, contentValues); assertEquals("Kasabuni", contentValues.get("village_town")); } | public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); } | ClientProcessorForJava { public Boolean processCaseModel(Event event, Client client, List<String> createsCase) { try { if (createsCase == null || createsCase.isEmpty()) { return false; } for (String clientType : createsCase) { Table table = getColumnMappings(clientType); List<Column> columns = table.columns; String baseEntityId = client != null ? client.getBaseEntityId() : event != null ? event.getBaseEntityId() : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (Column colObject : columns) { processCaseModel(event, client, colObject, contentValues); } updateIdentifier(contentValues); executeInsertStatement(contentValues, clientType); String entityId=contentValues.getAsString("base_entity_id"); updateFTSsearch(clientType, entityId, contentValues); Long timestamp = getEventDate(event.getEventDate()); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessorForJava(Context context); static ClientProcessorForJava getInstance(Context context); synchronized void processClient(List<EventClient> eventClientList); synchronized void processClient(List<EventClient> eventClientList, boolean localSubmission); void processPlanEvaluation(EventClient eventClient); void completeProcessing(Event event); Boolean processEvent(Event event, Client client, ClientClassification clientClassification); Boolean processClientClass(ClassificationRule clientClass, Event event, Client client); Boolean processField(org.smartregister.domain.jsonmapping.Field field, Event event, Client client); Boolean closeCase(Client client, List<String> closesCase); Boolean processCaseModel(Event event, Client client, List<String> createsCase); void processCaseModel(Event event, Client client, Column column, ContentValues contentValues); void updateClientDetailsTable(Event event, Client client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(Client client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); Table getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); Context getContext(); static final String JSON_ARRAY; } |
@Test public void processClientTest() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = new JSONArray(ClientData.clientJsonArray); ArrayList<JSONObject> clientList = new ArrayList<JSONObject>(); for (int i = 0; i < clientArray.length(); i++) { clientList.add(clientArray.getJSONObject(i)); } PowerMockito.when(cloudantDataHandler.getUpdatedEventsAndAlerts(Mockito.any(Date.class))).thenReturn(eventList); PowerMockito.when(cloudantDataHandler.getClientByBaseEntityId(Mockito.anyString())).thenReturn(clientList.get(0)); PowerMockito.when(sharedPreferences.getLong(Mockito.anyString(), Mockito.anyLong())).thenReturn(0l); SharedPreferences.Editor edit = Mockito.mock(SharedPreferences.Editor.class); PowerMockito.when(sharedPreferences.edit()).thenReturn(edit); PowerMockito.when(edit.putLong(Mockito.anyString(), Mockito.anyLong())).thenReturn(MockEditor.getEditor()); clientProcessor.processClient(); clientProcessor.processClient(eventList); } | public synchronized void processClient() throws Exception { AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences); long lastSyncTimeStamp = allSharedPreferences.fetchLastSyncDate(0); Date lastSyncDate = new Date(lastSyncTimeStamp); String clientClassificationStr = getFileContents("ec_client_classification.json"); String clientAlertsStr = getFileContents("ec_client_alerts.json"); List<JSONObject> eventsAndAlerts = mCloudantDataHandler.getUpdatedEventsAndAlerts(lastSyncDate); if (!eventsAndAlerts.isEmpty()) { for (JSONObject eventOrAlert : eventsAndAlerts) { String type = eventOrAlert.has("type") ? eventOrAlert.getString("type") : null; if (type.equals("Event")) { JSONObject clientClassificationJson = new JSONObject(clientClassificationStr); if (isNullOrEmptyJSONObject(clientClassificationJson)) { continue; } processEvent(eventOrAlert, clientClassificationJson); } else if (type.equals("Action")) { JSONObject clientAlertClassificationJson = new JSONObject(clientAlertsStr); if (isNullOrEmptyJSONObject(clientAlertClassificationJson)) { continue; } processAlert(eventOrAlert, clientAlertClassificationJson); } } } allSharedPreferences.saveLastSyncDate(lastSyncDate.getTime()); } | ClientProcessor { public synchronized void processClient() throws Exception { AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences); long lastSyncTimeStamp = allSharedPreferences.fetchLastSyncDate(0); Date lastSyncDate = new Date(lastSyncTimeStamp); String clientClassificationStr = getFileContents("ec_client_classification.json"); String clientAlertsStr = getFileContents("ec_client_alerts.json"); List<JSONObject> eventsAndAlerts = mCloudantDataHandler.getUpdatedEventsAndAlerts(lastSyncDate); if (!eventsAndAlerts.isEmpty()) { for (JSONObject eventOrAlert : eventsAndAlerts) { String type = eventOrAlert.has("type") ? eventOrAlert.getString("type") : null; if (type.equals("Event")) { JSONObject clientClassificationJson = new JSONObject(clientClassificationStr); if (isNullOrEmptyJSONObject(clientClassificationJson)) { continue; } processEvent(eventOrAlert, clientClassificationJson); } else if (type.equals("Action")) { JSONObject clientAlertClassificationJson = new JSONObject(clientAlertsStr); if (isNullOrEmptyJSONObject(clientAlertClassificationJson)) { continue; } processAlert(eventOrAlert, clientAlertClassificationJson); } } } allSharedPreferences.saveLastSyncDate(lastSyncDate.getTime()); } } | ClientProcessor { public synchronized void processClient() throws Exception { AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences); long lastSyncTimeStamp = allSharedPreferences.fetchLastSyncDate(0); Date lastSyncDate = new Date(lastSyncTimeStamp); String clientClassificationStr = getFileContents("ec_client_classification.json"); String clientAlertsStr = getFileContents("ec_client_alerts.json"); List<JSONObject> eventsAndAlerts = mCloudantDataHandler.getUpdatedEventsAndAlerts(lastSyncDate); if (!eventsAndAlerts.isEmpty()) { for (JSONObject eventOrAlert : eventsAndAlerts) { String type = eventOrAlert.has("type") ? eventOrAlert.getString("type") : null; if (type.equals("Event")) { JSONObject clientClassificationJson = new JSONObject(clientClassificationStr); if (isNullOrEmptyJSONObject(clientClassificationJson)) { continue; } processEvent(eventOrAlert, clientClassificationJson); } else if (type.equals("Action")) { JSONObject clientAlertClassificationJson = new JSONObject(clientAlertsStr); if (isNullOrEmptyJSONObject(clientAlertClassificationJson)) { continue; } processAlert(eventOrAlert, clientAlertClassificationJson); } } } allSharedPreferences.saveLastSyncDate(lastSyncDate.getTime()); } ClientProcessor(Context context); } | ClientProcessor { public synchronized void processClient() throws Exception { AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences); long lastSyncTimeStamp = allSharedPreferences.fetchLastSyncDate(0); Date lastSyncDate = new Date(lastSyncTimeStamp); String clientClassificationStr = getFileContents("ec_client_classification.json"); String clientAlertsStr = getFileContents("ec_client_alerts.json"); List<JSONObject> eventsAndAlerts = mCloudantDataHandler.getUpdatedEventsAndAlerts(lastSyncDate); if (!eventsAndAlerts.isEmpty()) { for (JSONObject eventOrAlert : eventsAndAlerts) { String type = eventOrAlert.has("type") ? eventOrAlert.getString("type") : null; if (type.equals("Event")) { JSONObject clientClassificationJson = new JSONObject(clientClassificationStr); if (isNullOrEmptyJSONObject(clientClassificationJson)) { continue; } processEvent(eventOrAlert, clientClassificationJson); } else if (type.equals("Action")) { JSONObject clientAlertClassificationJson = new JSONObject(clientAlertsStr); if (isNullOrEmptyJSONObject(clientAlertClassificationJson)) { continue; } processAlert(eventOrAlert, clientAlertClassificationJson); } } } allSharedPreferences.saveLastSyncDate(lastSyncDate.getTime()); } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); } | ClientProcessor { public synchronized void processClient() throws Exception { AllSharedPreferences allSharedPreferences = new AllSharedPreferences(preferences); long lastSyncTimeStamp = allSharedPreferences.fetchLastSyncDate(0); Date lastSyncDate = new Date(lastSyncTimeStamp); String clientClassificationStr = getFileContents("ec_client_classification.json"); String clientAlertsStr = getFileContents("ec_client_alerts.json"); List<JSONObject> eventsAndAlerts = mCloudantDataHandler.getUpdatedEventsAndAlerts(lastSyncDate); if (!eventsAndAlerts.isEmpty()) { for (JSONObject eventOrAlert : eventsAndAlerts) { String type = eventOrAlert.has("type") ? eventOrAlert.getString("type") : null; if (type.equals("Event")) { JSONObject clientClassificationJson = new JSONObject(clientClassificationStr); if (isNullOrEmptyJSONObject(clientClassificationJson)) { continue; } processEvent(eventOrAlert, clientClassificationJson); } else if (type.equals("Action")) { JSONObject clientAlertClassificationJson = new JSONObject(clientAlertsStr); if (isNullOrEmptyJSONObject(clientAlertClassificationJson)) { continue; } processAlert(eventOrAlert, clientAlertClassificationJson); } } } allSharedPreferences.saveLastSyncDate(lastSyncDate.getTime()); } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; } |
@Test public void assertProcessFieldReturnsTrue() throws Exception { final JSONObject fieldObject = new JSONObject(ClientData.ec_client_fields_json); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = new JSONArray(ClientData.clientJsonArray); ArrayList<JSONObject> clientList = new ArrayList<JSONObject>(); for (int i = 0; i < clientArray.length(); i++) { clientList.add(clientArray.getJSONObject(i)); } JSONArray fieldArray = fieldObject.getJSONArray("bindobjects"); Assert.assertEquals(clientProcessor.processField(fieldArray.getJSONObject(0), eventList.get(0), clientList.get(0)), Boolean.TRUE); } | public Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client) { try { if (fieldJson == null || fieldJson.length() == 0) { return false; } String dataSegment = null; String fieldName = fieldJson.has("field") ? fieldJson.getString("field") : null; String fieldValue = fieldJson.has("field_value") ? fieldJson.getString("field_value") : null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = fieldJson.has("concept") ? fieldJson.getString("concept") : null; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } JSONArray createsCase = fieldJson.has("creates_case") ? fieldJson.getJSONArray("creates_case") : null; JSONArray closesCase = fieldJson.has("closes_case") ? fieldJson.getJSONArray("closes_case") : null; if (dataSegment != null && !dataSegment.isEmpty()) { JSONArray responseValue = fieldJson.has(responseKey) ? fieldJson.getJSONArray(responseKey) : null; List<String> responseValues = getValues(responseValue); if (event.has(dataSegment)) { JSONArray jsonDataSegment = event.getJSONArray(dataSegment); for (int j = 0; j < jsonDataSegment.length(); j++) { JSONObject segmentJsonObject = jsonDataSegment.getJSONObject(j); String docSegmentFieldValue = segmentJsonObject.has(fieldName) ? segmentJsonObject.get(fieldName) .toString() : ""; List<String> docSegmentResponseValues = segmentJsonObject.has(responseKey) ? getValues( segmentJsonObject.get(responseKey)) : null; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } else { String docSegmentFieldValue = event.has(fieldName) ? event.get(fieldName).toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessor { public Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client) { try { if (fieldJson == null || fieldJson.length() == 0) { return false; } String dataSegment = null; String fieldName = fieldJson.has("field") ? fieldJson.getString("field") : null; String fieldValue = fieldJson.has("field_value") ? fieldJson.getString("field_value") : null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = fieldJson.has("concept") ? fieldJson.getString("concept") : null; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } JSONArray createsCase = fieldJson.has("creates_case") ? fieldJson.getJSONArray("creates_case") : null; JSONArray closesCase = fieldJson.has("closes_case") ? fieldJson.getJSONArray("closes_case") : null; if (dataSegment != null && !dataSegment.isEmpty()) { JSONArray responseValue = fieldJson.has(responseKey) ? fieldJson.getJSONArray(responseKey) : null; List<String> responseValues = getValues(responseValue); if (event.has(dataSegment)) { JSONArray jsonDataSegment = event.getJSONArray(dataSegment); for (int j = 0; j < jsonDataSegment.length(); j++) { JSONObject segmentJsonObject = jsonDataSegment.getJSONObject(j); String docSegmentFieldValue = segmentJsonObject.has(fieldName) ? segmentJsonObject.get(fieldName) .toString() : ""; List<String> docSegmentResponseValues = segmentJsonObject.has(responseKey) ? getValues( segmentJsonObject.get(responseKey)) : null; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } else { String docSegmentFieldValue = event.has(fieldName) ? event.get(fieldName).toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessor { public Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client) { try { if (fieldJson == null || fieldJson.length() == 0) { return false; } String dataSegment = null; String fieldName = fieldJson.has("field") ? fieldJson.getString("field") : null; String fieldValue = fieldJson.has("field_value") ? fieldJson.getString("field_value") : null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = fieldJson.has("concept") ? fieldJson.getString("concept") : null; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } JSONArray createsCase = fieldJson.has("creates_case") ? fieldJson.getJSONArray("creates_case") : null; JSONArray closesCase = fieldJson.has("closes_case") ? fieldJson.getJSONArray("closes_case") : null; if (dataSegment != null && !dataSegment.isEmpty()) { JSONArray responseValue = fieldJson.has(responseKey) ? fieldJson.getJSONArray(responseKey) : null; List<String> responseValues = getValues(responseValue); if (event.has(dataSegment)) { JSONArray jsonDataSegment = event.getJSONArray(dataSegment); for (int j = 0; j < jsonDataSegment.length(); j++) { JSONObject segmentJsonObject = jsonDataSegment.getJSONObject(j); String docSegmentFieldValue = segmentJsonObject.has(fieldName) ? segmentJsonObject.get(fieldName) .toString() : ""; List<String> docSegmentResponseValues = segmentJsonObject.has(responseKey) ? getValues( segmentJsonObject.get(responseKey)) : null; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } else { String docSegmentFieldValue = event.has(fieldName) ? event.get(fieldName).toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); } | ClientProcessor { public Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client) { try { if (fieldJson == null || fieldJson.length() == 0) { return false; } String dataSegment = null; String fieldName = fieldJson.has("field") ? fieldJson.getString("field") : null; String fieldValue = fieldJson.has("field_value") ? fieldJson.getString("field_value") : null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = fieldJson.has("concept") ? fieldJson.getString("concept") : null; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } JSONArray createsCase = fieldJson.has("creates_case") ? fieldJson.getJSONArray("creates_case") : null; JSONArray closesCase = fieldJson.has("closes_case") ? fieldJson.getJSONArray("closes_case") : null; if (dataSegment != null && !dataSegment.isEmpty()) { JSONArray responseValue = fieldJson.has(responseKey) ? fieldJson.getJSONArray(responseKey) : null; List<String> responseValues = getValues(responseValue); if (event.has(dataSegment)) { JSONArray jsonDataSegment = event.getJSONArray(dataSegment); for (int j = 0; j < jsonDataSegment.length(); j++) { JSONObject segmentJsonObject = jsonDataSegment.getJSONObject(j); String docSegmentFieldValue = segmentJsonObject.has(fieldName) ? segmentJsonObject.get(fieldName) .toString() : ""; List<String> docSegmentResponseValues = segmentJsonObject.has(responseKey) ? getValues( segmentJsonObject.get(responseKey)) : null; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } else { String docSegmentFieldValue = event.has(fieldName) ? event.get(fieldName).toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); } | ClientProcessor { public Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client) { try { if (fieldJson == null || fieldJson.length() == 0) { return false; } String dataSegment = null; String fieldName = fieldJson.has("field") ? fieldJson.getString("field") : null; String fieldValue = fieldJson.has("field_value") ? fieldJson.getString("field_value") : null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; String concept = fieldJson.has("concept") ? fieldJson.getString("concept") : null; if (concept != null) { fieldValue = concept; responseKey = VALUES_KEY; } } JSONArray createsCase = fieldJson.has("creates_case") ? fieldJson.getJSONArray("creates_case") : null; JSONArray closesCase = fieldJson.has("closes_case") ? fieldJson.getJSONArray("closes_case") : null; if (dataSegment != null && !dataSegment.isEmpty()) { JSONArray responseValue = fieldJson.has(responseKey) ? fieldJson.getJSONArray(responseKey) : null; List<String> responseValues = getValues(responseValue); if (event.has(dataSegment)) { JSONArray jsonDataSegment = event.getJSONArray(dataSegment); for (int j = 0; j < jsonDataSegment.length(); j++) { JSONObject segmentJsonObject = jsonDataSegment.getJSONObject(j); String docSegmentFieldValue = segmentJsonObject.has(fieldName) ? segmentJsonObject.get(fieldName) .toString() : ""; List<String> docSegmentResponseValues = segmentJsonObject.has(responseKey) ? getValues( segmentJsonObject.get(responseKey)) : null; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue) && (!Collections .disjoint(responseValues, docSegmentResponseValues))) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } } } else { String docSegmentFieldValue = event.has(fieldName) ? event.get(fieldName).toString() : ""; if (docSegmentFieldValue.equalsIgnoreCase(fieldValue)) { processCaseModel(event, client, createsCase); closeCase(client, closesCase); } } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; } |
@Test public void assertIsVaidDateReturnsBoolean() { Assert.assertEquals(DateUtil.isValidDate(null), false); Assert.assertEquals(DateUtil.isValidDate("invaliddate"), false); Assert.assertEquals(DateUtil.isValidDate("2017-10-20"), true); } | public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } | DateUtil { public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } } | DateUtil { public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } } | DateUtil { public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); } | DateUtil { public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; } |
@Test public void instantiatesSuccessfullyOnConstructorCall() throws Exception { Assert.assertNotNull(new ClientProcessor(context.applicationContext())); Assert.assertNotNull(ClientProcessor.getInstance(context.applicationContext())); } | public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } | ClientProcessor { public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } } | ClientProcessor { public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } ClientProcessor(Context context); } | ClientProcessor { public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); } | ClientProcessor { public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; } |
@Test public void ProcessEventReturnsNotNull() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = new JSONArray(ClientData.clientJsonArray); ArrayList<JSONObject> clientList = new ArrayList<JSONObject>(); for (int i = 0; i < clientArray.length(); i++) { clientList.add(clientArray.getJSONObject(i)); } Assert.assertNotNull(clientProcessor.processEvent(eventList.get(0), clientList.get(0), new JSONObject(ClientData.clientClassificationJson))); } | public Boolean processEvent(JSONObject event, JSONObject clientClassificationJson) throws Exception { try { String baseEntityId = event.getString(baseEntityIdJSONKey); if (event.has("creator")) { Timber.i("EVENT from openmrs"); } JSONObject client = getClient(baseEntityId); if (isNullOrEmptyJSONObject(client)) { return false; } if (client.has("deathdate") && !client.getString("deathdate").isEmpty()) { return false; } JSONArray clientClasses = clientClassificationJson .getJSONArray("case_classification_rules"); if (isNullOrEmptyJSONArray(clientClasses)) { return false; } for (int i = 0; i < clientClasses.length(); i++) { JSONObject clientClass = clientClasses.getJSONObject(i); processClientClass(clientClass, event, client); } boolean updated = event.has(detailsUpdated) && event.getBoolean(detailsUpdated); if (!updated) { updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessor { public Boolean processEvent(JSONObject event, JSONObject clientClassificationJson) throws Exception { try { String baseEntityId = event.getString(baseEntityIdJSONKey); if (event.has("creator")) { Timber.i("EVENT from openmrs"); } JSONObject client = getClient(baseEntityId); if (isNullOrEmptyJSONObject(client)) { return false; } if (client.has("deathdate") && !client.getString("deathdate").isEmpty()) { return false; } JSONArray clientClasses = clientClassificationJson .getJSONArray("case_classification_rules"); if (isNullOrEmptyJSONArray(clientClasses)) { return false; } for (int i = 0; i < clientClasses.length(); i++) { JSONObject clientClass = clientClasses.getJSONObject(i); processClientClass(clientClass, event, client); } boolean updated = event.has(detailsUpdated) && event.getBoolean(detailsUpdated); if (!updated) { updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessor { public Boolean processEvent(JSONObject event, JSONObject clientClassificationJson) throws Exception { try { String baseEntityId = event.getString(baseEntityIdJSONKey); if (event.has("creator")) { Timber.i("EVENT from openmrs"); } JSONObject client = getClient(baseEntityId); if (isNullOrEmptyJSONObject(client)) { return false; } if (client.has("deathdate") && !client.getString("deathdate").isEmpty()) { return false; } JSONArray clientClasses = clientClassificationJson .getJSONArray("case_classification_rules"); if (isNullOrEmptyJSONArray(clientClasses)) { return false; } for (int i = 0; i < clientClasses.length(); i++) { JSONObject clientClass = clientClasses.getJSONObject(i); processClientClass(clientClass, event, client); } boolean updated = event.has(detailsUpdated) && event.getBoolean(detailsUpdated); if (!updated) { updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); } | ClientProcessor { public Boolean processEvent(JSONObject event, JSONObject clientClassificationJson) throws Exception { try { String baseEntityId = event.getString(baseEntityIdJSONKey); if (event.has("creator")) { Timber.i("EVENT from openmrs"); } JSONObject client = getClient(baseEntityId); if (isNullOrEmptyJSONObject(client)) { return false; } if (client.has("deathdate") && !client.getString("deathdate").isEmpty()) { return false; } JSONArray clientClasses = clientClassificationJson .getJSONArray("case_classification_rules"); if (isNullOrEmptyJSONArray(clientClasses)) { return false; } for (int i = 0; i < clientClasses.length(); i++) { JSONObject clientClass = clientClasses.getJSONObject(i); processClientClass(clientClass, event, client); } boolean updated = event.has(detailsUpdated) && event.getBoolean(detailsUpdated); if (!updated) { updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); } | ClientProcessor { public Boolean processEvent(JSONObject event, JSONObject clientClassificationJson) throws Exception { try { String baseEntityId = event.getString(baseEntityIdJSONKey); if (event.has("creator")) { Timber.i("EVENT from openmrs"); } JSONObject client = getClient(baseEntityId); if (isNullOrEmptyJSONObject(client)) { return false; } if (client.has("deathdate") && !client.getString("deathdate").isEmpty()) { return false; } JSONArray clientClasses = clientClassificationJson .getJSONArray("case_classification_rules"); if (isNullOrEmptyJSONArray(clientClasses)) { return false; } for (int i = 0; i < clientClasses.length(); i++) { JSONObject clientClass = clientClasses.getJSONObject(i); processClientClass(clientClass, event, client); } boolean updated = event.has(detailsUpdated) && event.getBoolean(detailsUpdated); if (!updated) { updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; } |
@Test public void getClientAddressAsMapReturnsNotNull() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = new JSONArray(ClientData.clientJsonArray); ArrayList<JSONObject> clientList = new ArrayList<JSONObject>(); for (int i = 0; i < clientArray.length(); i++) { clientList.add(clientArray.getJSONObject(i)); } Assert.assertNotNull(clientProcessor.getClientAddressAsMap(clientList.get(0))); } | public Map<String, String> getClientAddressAsMap(JSONObject client) { Map<String, String> addressMap = new HashMap<String, String>(); try { String addressFieldsKey = "addressFields"; String addressesKey = "addresses"; if (client.has(addressesKey)) { JSONArray addressJsonArray = client.getJSONArray(addressesKey); if (addressJsonArray != null && addressJsonArray.length() > 0) { JSONObject addressJson = addressJsonArray.getJSONObject(0); if (addressJson.has(addressFieldsKey)) { JSONObject addressFields = addressJson.getJSONObject(addressFieldsKey); Iterator<String> it = addressFields.keys(); while (it.hasNext()) { String key = it.next(); String value = addressFields.getString(key); addressMap.put(key, value); } } Iterator<String> it = addressJson.keys(); while (it.hasNext()) { String key = it.next(); boolean shouldSkipNode = addressJson.get(key) instanceof JSONArray || addressJson .get(key) instanceof JSONObject; if (!shouldSkipNode) { String value = addressJson.getString(key); addressMap.put(key, value); } } } } } catch (Exception e) { Timber.e(e); } return addressMap; } | ClientProcessor { public Map<String, String> getClientAddressAsMap(JSONObject client) { Map<String, String> addressMap = new HashMap<String, String>(); try { String addressFieldsKey = "addressFields"; String addressesKey = "addresses"; if (client.has(addressesKey)) { JSONArray addressJsonArray = client.getJSONArray(addressesKey); if (addressJsonArray != null && addressJsonArray.length() > 0) { JSONObject addressJson = addressJsonArray.getJSONObject(0); if (addressJson.has(addressFieldsKey)) { JSONObject addressFields = addressJson.getJSONObject(addressFieldsKey); Iterator<String> it = addressFields.keys(); while (it.hasNext()) { String key = it.next(); String value = addressFields.getString(key); addressMap.put(key, value); } } Iterator<String> it = addressJson.keys(); while (it.hasNext()) { String key = it.next(); boolean shouldSkipNode = addressJson.get(key) instanceof JSONArray || addressJson .get(key) instanceof JSONObject; if (!shouldSkipNode) { String value = addressJson.getString(key); addressMap.put(key, value); } } } } } catch (Exception e) { Timber.e(e); } return addressMap; } } | ClientProcessor { public Map<String, String> getClientAddressAsMap(JSONObject client) { Map<String, String> addressMap = new HashMap<String, String>(); try { String addressFieldsKey = "addressFields"; String addressesKey = "addresses"; if (client.has(addressesKey)) { JSONArray addressJsonArray = client.getJSONArray(addressesKey); if (addressJsonArray != null && addressJsonArray.length() > 0) { JSONObject addressJson = addressJsonArray.getJSONObject(0); if (addressJson.has(addressFieldsKey)) { JSONObject addressFields = addressJson.getJSONObject(addressFieldsKey); Iterator<String> it = addressFields.keys(); while (it.hasNext()) { String key = it.next(); String value = addressFields.getString(key); addressMap.put(key, value); } } Iterator<String> it = addressJson.keys(); while (it.hasNext()) { String key = it.next(); boolean shouldSkipNode = addressJson.get(key) instanceof JSONArray || addressJson .get(key) instanceof JSONObject; if (!shouldSkipNode) { String value = addressJson.getString(key); addressMap.put(key, value); } } } } } catch (Exception e) { Timber.e(e); } return addressMap; } ClientProcessor(Context context); } | ClientProcessor { public Map<String, String> getClientAddressAsMap(JSONObject client) { Map<String, String> addressMap = new HashMap<String, String>(); try { String addressFieldsKey = "addressFields"; String addressesKey = "addresses"; if (client.has(addressesKey)) { JSONArray addressJsonArray = client.getJSONArray(addressesKey); if (addressJsonArray != null && addressJsonArray.length() > 0) { JSONObject addressJson = addressJsonArray.getJSONObject(0); if (addressJson.has(addressFieldsKey)) { JSONObject addressFields = addressJson.getJSONObject(addressFieldsKey); Iterator<String> it = addressFields.keys(); while (it.hasNext()) { String key = it.next(); String value = addressFields.getString(key); addressMap.put(key, value); } } Iterator<String> it = addressJson.keys(); while (it.hasNext()) { String key = it.next(); boolean shouldSkipNode = addressJson.get(key) instanceof JSONArray || addressJson .get(key) instanceof JSONObject; if (!shouldSkipNode) { String value = addressJson.getString(key); addressMap.put(key, value); } } } } } catch (Exception e) { Timber.e(e); } return addressMap; } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); } | ClientProcessor { public Map<String, String> getClientAddressAsMap(JSONObject client) { Map<String, String> addressMap = new HashMap<String, String>(); try { String addressFieldsKey = "addressFields"; String addressesKey = "addresses"; if (client.has(addressesKey)) { JSONArray addressJsonArray = client.getJSONArray(addressesKey); if (addressJsonArray != null && addressJsonArray.length() > 0) { JSONObject addressJson = addressJsonArray.getJSONObject(0); if (addressJson.has(addressFieldsKey)) { JSONObject addressFields = addressJson.getJSONObject(addressFieldsKey); Iterator<String> it = addressFields.keys(); while (it.hasNext()) { String key = it.next(); String value = addressFields.getString(key); addressMap.put(key, value); } } Iterator<String> it = addressJson.keys(); while (it.hasNext()) { String key = it.next(); boolean shouldSkipNode = addressJson.get(key) instanceof JSONArray || addressJson .get(key) instanceof JSONObject; if (!shouldSkipNode) { String value = addressJson.getString(key); addressMap.put(key, value); } } } } } catch (Exception e) { Timber.e(e); } return addressMap; } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; } |
@Test public void processCaseModelReturnsNotNUll() throws Exception { JSONArray eventArray = new JSONArray(ClientData.eventJsonArray); final ArrayList<JSONObject> eventList = new ArrayList<JSONObject>(); for (int i = 0; i < eventArray.length(); i++) { eventList.add(eventArray.getJSONObject(i)); } JSONArray clientArray = new JSONArray(ClientData.clientJsonArray); ArrayList<JSONObject> clientList = new ArrayList<JSONObject>(); for (int i = 0; i < clientArray.length(); i++) { clientList.add(clientArray.getJSONObject(i)); } JSONObject clientClassification = new JSONObject(ClientData.clientClassificationJson); JSONArray clientClassificationArray = clientClassification.getJSONArray("case_classification_rules"); JSONObject clientClassificationRulesObject = clientClassificationArray.getJSONObject(0); JSONArray creates_case = clientClassificationRulesObject.getJSONObject("rule").getJSONArray("fields").getJSONObject(0).getJSONArray("creates_case"); Boolean b = clientProcessor.processCaseModel(eventList.get(0), clientList.get(0), creates_case); Assert.assertEquals(Boolean.TRUE, b); } | public Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase) { try { if (createsCase == null || createsCase.length() == 0) { return false; } for (int openCase = 0; openCase < createsCase.length(); openCase++) { String clientType = createsCase.getString(openCase); JSONObject columnMappings = getColumnMappings(clientType); JSONArray columns = columnMappings.getJSONArray("columns"); String baseEntityId = client.getString(baseEntityIdJSONKey); String expectedEncounterType = event.has("eventType") ? event.getString("eventType") : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (int i = 0; i < columns.length(); i++) { JSONObject colObject = columns.getJSONObject(i); String docType = colObject.getString("type"); String columnName = colObject.getString("column_name"); JSONObject jsonMapping = colObject.getJSONObject("json_mapping"); String dataSegment = null; String fieldName = jsonMapping.getString("field"); String fieldValue = null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; fieldValue = jsonMapping.has("concept") ? jsonMapping.getString("concept") : (jsonMapping.has("formSubmissionField") ? jsonMapping .getString("formSubmissionField") : null); if (fieldValue != null) { responseKey = VALUES_KEY; } } JSONObject jsonDocument = docType.equalsIgnoreCase("Event") ? event : client; Object jsonDocSegment; if (dataSegment != null) { jsonDocSegment = jsonDocument.has(dataSegment) ? jsonDocument.get(dataSegment) : null; } else { jsonDocSegment = jsonDocument; } if (dataSegment != null && dataSegment.equalsIgnoreCase("addresses")) { Map<String, String> addressMap = getClientAddressAsMap(client); if (addressMap.containsKey(fieldName)) { contentValues.put(columnName, addressMap.get(fieldName)); } continue; } if (dataSegment != null && dataSegment.equalsIgnoreCase("relationships")) { JSONObject relationshipsObject = jsonDocument .getJSONObject("relationships"); JSONArray relationshipsArray = relationshipsObject.getJSONArray(fieldName); if (relationshipsArray != null && relationshipsArray.length() > 0) { List<String> relationalIds = getValues(relationshipsArray); contentValues.put(columnName, relationalIds.get(0)); } continue; } String encounterType = jsonMapping.has("event_type") ? jsonMapping.getString("event_type") : null; if (jsonDocSegment instanceof JSONArray) { JSONArray jsonDocSegmentArray = (JSONArray) jsonDocSegment; for (int j = 0; j < jsonDocSegmentArray.length(); j++) { JSONObject jsonDocObject = jsonDocSegmentArray.getJSONObject(j); String columnValue = null; if (fieldValue == null) { if (jsonDocObject.has(fieldName)) { columnValue = jsonDocObject.getString(fieldName); } } else { String expectedFieldValue = jsonDocObject.getString(fieldName); boolean encounterTypeMatches = (encounterType == null) || (encounterType != null && encounterType .equalsIgnoreCase(expectedEncounterType)); if (encounterTypeMatches && expectedFieldValue .equalsIgnoreCase(fieldValue)) { columnValue = getValues(jsonDocObject.get(responseKey)).get(0); } } if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocObject); contentValues.put(columnName, columnValue); } } } else { String columnValue = null; JSONObject jsonDocSegmentObject = (JSONObject) jsonDocSegment; columnValue = jsonDocSegmentObject.has(fieldName) ? jsonDocSegmentObject .getString(fieldName) : ""; if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocSegmentObject); contentValues.put(columnName, columnValue); } } } updateIdenitifier(contentValues); Long id = executeInsertStatement(contentValues, clientType); updateFTSsearch(clientType, baseEntityId, contentValues); Long timestamp = getEventDate(event.get("eventDate")); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } | ClientProcessor { public Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase) { try { if (createsCase == null || createsCase.length() == 0) { return false; } for (int openCase = 0; openCase < createsCase.length(); openCase++) { String clientType = createsCase.getString(openCase); JSONObject columnMappings = getColumnMappings(clientType); JSONArray columns = columnMappings.getJSONArray("columns"); String baseEntityId = client.getString(baseEntityIdJSONKey); String expectedEncounterType = event.has("eventType") ? event.getString("eventType") : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (int i = 0; i < columns.length(); i++) { JSONObject colObject = columns.getJSONObject(i); String docType = colObject.getString("type"); String columnName = colObject.getString("column_name"); JSONObject jsonMapping = colObject.getJSONObject("json_mapping"); String dataSegment = null; String fieldName = jsonMapping.getString("field"); String fieldValue = null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; fieldValue = jsonMapping.has("concept") ? jsonMapping.getString("concept") : (jsonMapping.has("formSubmissionField") ? jsonMapping .getString("formSubmissionField") : null); if (fieldValue != null) { responseKey = VALUES_KEY; } } JSONObject jsonDocument = docType.equalsIgnoreCase("Event") ? event : client; Object jsonDocSegment; if (dataSegment != null) { jsonDocSegment = jsonDocument.has(dataSegment) ? jsonDocument.get(dataSegment) : null; } else { jsonDocSegment = jsonDocument; } if (dataSegment != null && dataSegment.equalsIgnoreCase("addresses")) { Map<String, String> addressMap = getClientAddressAsMap(client); if (addressMap.containsKey(fieldName)) { contentValues.put(columnName, addressMap.get(fieldName)); } continue; } if (dataSegment != null && dataSegment.equalsIgnoreCase("relationships")) { JSONObject relationshipsObject = jsonDocument .getJSONObject("relationships"); JSONArray relationshipsArray = relationshipsObject.getJSONArray(fieldName); if (relationshipsArray != null && relationshipsArray.length() > 0) { List<String> relationalIds = getValues(relationshipsArray); contentValues.put(columnName, relationalIds.get(0)); } continue; } String encounterType = jsonMapping.has("event_type") ? jsonMapping.getString("event_type") : null; if (jsonDocSegment instanceof JSONArray) { JSONArray jsonDocSegmentArray = (JSONArray) jsonDocSegment; for (int j = 0; j < jsonDocSegmentArray.length(); j++) { JSONObject jsonDocObject = jsonDocSegmentArray.getJSONObject(j); String columnValue = null; if (fieldValue == null) { if (jsonDocObject.has(fieldName)) { columnValue = jsonDocObject.getString(fieldName); } } else { String expectedFieldValue = jsonDocObject.getString(fieldName); boolean encounterTypeMatches = (encounterType == null) || (encounterType != null && encounterType .equalsIgnoreCase(expectedEncounterType)); if (encounterTypeMatches && expectedFieldValue .equalsIgnoreCase(fieldValue)) { columnValue = getValues(jsonDocObject.get(responseKey)).get(0); } } if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocObject); contentValues.put(columnName, columnValue); } } } else { String columnValue = null; JSONObject jsonDocSegmentObject = (JSONObject) jsonDocSegment; columnValue = jsonDocSegmentObject.has(fieldName) ? jsonDocSegmentObject .getString(fieldName) : ""; if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocSegmentObject); contentValues.put(columnName, columnValue); } } } updateIdenitifier(contentValues); Long id = executeInsertStatement(contentValues, clientType); updateFTSsearch(clientType, baseEntityId, contentValues); Long timestamp = getEventDate(event.get("eventDate")); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } } | ClientProcessor { public Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase) { try { if (createsCase == null || createsCase.length() == 0) { return false; } for (int openCase = 0; openCase < createsCase.length(); openCase++) { String clientType = createsCase.getString(openCase); JSONObject columnMappings = getColumnMappings(clientType); JSONArray columns = columnMappings.getJSONArray("columns"); String baseEntityId = client.getString(baseEntityIdJSONKey); String expectedEncounterType = event.has("eventType") ? event.getString("eventType") : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (int i = 0; i < columns.length(); i++) { JSONObject colObject = columns.getJSONObject(i); String docType = colObject.getString("type"); String columnName = colObject.getString("column_name"); JSONObject jsonMapping = colObject.getJSONObject("json_mapping"); String dataSegment = null; String fieldName = jsonMapping.getString("field"); String fieldValue = null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; fieldValue = jsonMapping.has("concept") ? jsonMapping.getString("concept") : (jsonMapping.has("formSubmissionField") ? jsonMapping .getString("formSubmissionField") : null); if (fieldValue != null) { responseKey = VALUES_KEY; } } JSONObject jsonDocument = docType.equalsIgnoreCase("Event") ? event : client; Object jsonDocSegment; if (dataSegment != null) { jsonDocSegment = jsonDocument.has(dataSegment) ? jsonDocument.get(dataSegment) : null; } else { jsonDocSegment = jsonDocument; } if (dataSegment != null && dataSegment.equalsIgnoreCase("addresses")) { Map<String, String> addressMap = getClientAddressAsMap(client); if (addressMap.containsKey(fieldName)) { contentValues.put(columnName, addressMap.get(fieldName)); } continue; } if (dataSegment != null && dataSegment.equalsIgnoreCase("relationships")) { JSONObject relationshipsObject = jsonDocument .getJSONObject("relationships"); JSONArray relationshipsArray = relationshipsObject.getJSONArray(fieldName); if (relationshipsArray != null && relationshipsArray.length() > 0) { List<String> relationalIds = getValues(relationshipsArray); contentValues.put(columnName, relationalIds.get(0)); } continue; } String encounterType = jsonMapping.has("event_type") ? jsonMapping.getString("event_type") : null; if (jsonDocSegment instanceof JSONArray) { JSONArray jsonDocSegmentArray = (JSONArray) jsonDocSegment; for (int j = 0; j < jsonDocSegmentArray.length(); j++) { JSONObject jsonDocObject = jsonDocSegmentArray.getJSONObject(j); String columnValue = null; if (fieldValue == null) { if (jsonDocObject.has(fieldName)) { columnValue = jsonDocObject.getString(fieldName); } } else { String expectedFieldValue = jsonDocObject.getString(fieldName); boolean encounterTypeMatches = (encounterType == null) || (encounterType != null && encounterType .equalsIgnoreCase(expectedEncounterType)); if (encounterTypeMatches && expectedFieldValue .equalsIgnoreCase(fieldValue)) { columnValue = getValues(jsonDocObject.get(responseKey)).get(0); } } if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocObject); contentValues.put(columnName, columnValue); } } } else { String columnValue = null; JSONObject jsonDocSegmentObject = (JSONObject) jsonDocSegment; columnValue = jsonDocSegmentObject.has(fieldName) ? jsonDocSegmentObject .getString(fieldName) : ""; if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocSegmentObject); contentValues.put(columnName, columnValue); } } } updateIdenitifier(contentValues); Long id = executeInsertStatement(contentValues, clientType); updateFTSsearch(clientType, baseEntityId, contentValues); Long timestamp = getEventDate(event.get("eventDate")); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); } | ClientProcessor { public Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase) { try { if (createsCase == null || createsCase.length() == 0) { return false; } for (int openCase = 0; openCase < createsCase.length(); openCase++) { String clientType = createsCase.getString(openCase); JSONObject columnMappings = getColumnMappings(clientType); JSONArray columns = columnMappings.getJSONArray("columns"); String baseEntityId = client.getString(baseEntityIdJSONKey); String expectedEncounterType = event.has("eventType") ? event.getString("eventType") : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (int i = 0; i < columns.length(); i++) { JSONObject colObject = columns.getJSONObject(i); String docType = colObject.getString("type"); String columnName = colObject.getString("column_name"); JSONObject jsonMapping = colObject.getJSONObject("json_mapping"); String dataSegment = null; String fieldName = jsonMapping.getString("field"); String fieldValue = null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; fieldValue = jsonMapping.has("concept") ? jsonMapping.getString("concept") : (jsonMapping.has("formSubmissionField") ? jsonMapping .getString("formSubmissionField") : null); if (fieldValue != null) { responseKey = VALUES_KEY; } } JSONObject jsonDocument = docType.equalsIgnoreCase("Event") ? event : client; Object jsonDocSegment; if (dataSegment != null) { jsonDocSegment = jsonDocument.has(dataSegment) ? jsonDocument.get(dataSegment) : null; } else { jsonDocSegment = jsonDocument; } if (dataSegment != null && dataSegment.equalsIgnoreCase("addresses")) { Map<String, String> addressMap = getClientAddressAsMap(client); if (addressMap.containsKey(fieldName)) { contentValues.put(columnName, addressMap.get(fieldName)); } continue; } if (dataSegment != null && dataSegment.equalsIgnoreCase("relationships")) { JSONObject relationshipsObject = jsonDocument .getJSONObject("relationships"); JSONArray relationshipsArray = relationshipsObject.getJSONArray(fieldName); if (relationshipsArray != null && relationshipsArray.length() > 0) { List<String> relationalIds = getValues(relationshipsArray); contentValues.put(columnName, relationalIds.get(0)); } continue; } String encounterType = jsonMapping.has("event_type") ? jsonMapping.getString("event_type") : null; if (jsonDocSegment instanceof JSONArray) { JSONArray jsonDocSegmentArray = (JSONArray) jsonDocSegment; for (int j = 0; j < jsonDocSegmentArray.length(); j++) { JSONObject jsonDocObject = jsonDocSegmentArray.getJSONObject(j); String columnValue = null; if (fieldValue == null) { if (jsonDocObject.has(fieldName)) { columnValue = jsonDocObject.getString(fieldName); } } else { String expectedFieldValue = jsonDocObject.getString(fieldName); boolean encounterTypeMatches = (encounterType == null) || (encounterType != null && encounterType .equalsIgnoreCase(expectedEncounterType)); if (encounterTypeMatches && expectedFieldValue .equalsIgnoreCase(fieldValue)) { columnValue = getValues(jsonDocObject.get(responseKey)).get(0); } } if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocObject); contentValues.put(columnName, columnValue); } } } else { String columnValue = null; JSONObject jsonDocSegmentObject = (JSONObject) jsonDocSegment; columnValue = jsonDocSegmentObject.has(fieldName) ? jsonDocSegmentObject .getString(fieldName) : ""; if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocSegmentObject); contentValues.put(columnName, columnValue); } } } updateIdenitifier(contentValues); Long id = executeInsertStatement(contentValues, clientType); updateFTSsearch(clientType, baseEntityId, contentValues); Long timestamp = getEventDate(event.get("eventDate")); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); } | ClientProcessor { public Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase) { try { if (createsCase == null || createsCase.length() == 0) { return false; } for (int openCase = 0; openCase < createsCase.length(); openCase++) { String clientType = createsCase.getString(openCase); JSONObject columnMappings = getColumnMappings(clientType); JSONArray columns = columnMappings.getJSONArray("columns"); String baseEntityId = client.getString(baseEntityIdJSONKey); String expectedEncounterType = event.has("eventType") ? event.getString("eventType") : null; ContentValues contentValues = new ContentValues(); contentValues.put("base_entity_id", baseEntityId); contentValues.put("is_closed", 0); for (int i = 0; i < columns.length(); i++) { JSONObject colObject = columns.getJSONObject(i); String docType = colObject.getString("type"); String columnName = colObject.getString("column_name"); JSONObject jsonMapping = colObject.getJSONObject("json_mapping"); String dataSegment = null; String fieldName = jsonMapping.getString("field"); String fieldValue = null; String responseKey = null; if (fieldName != null && fieldName.contains(".")) { String fieldNameArray[] = fieldName.split("\\."); dataSegment = fieldNameArray[0]; fieldName = fieldNameArray[1]; fieldValue = jsonMapping.has("concept") ? jsonMapping.getString("concept") : (jsonMapping.has("formSubmissionField") ? jsonMapping .getString("formSubmissionField") : null); if (fieldValue != null) { responseKey = VALUES_KEY; } } JSONObject jsonDocument = docType.equalsIgnoreCase("Event") ? event : client; Object jsonDocSegment; if (dataSegment != null) { jsonDocSegment = jsonDocument.has(dataSegment) ? jsonDocument.get(dataSegment) : null; } else { jsonDocSegment = jsonDocument; } if (dataSegment != null && dataSegment.equalsIgnoreCase("addresses")) { Map<String, String> addressMap = getClientAddressAsMap(client); if (addressMap.containsKey(fieldName)) { contentValues.put(columnName, addressMap.get(fieldName)); } continue; } if (dataSegment != null && dataSegment.equalsIgnoreCase("relationships")) { JSONObject relationshipsObject = jsonDocument .getJSONObject("relationships"); JSONArray relationshipsArray = relationshipsObject.getJSONArray(fieldName); if (relationshipsArray != null && relationshipsArray.length() > 0) { List<String> relationalIds = getValues(relationshipsArray); contentValues.put(columnName, relationalIds.get(0)); } continue; } String encounterType = jsonMapping.has("event_type") ? jsonMapping.getString("event_type") : null; if (jsonDocSegment instanceof JSONArray) { JSONArray jsonDocSegmentArray = (JSONArray) jsonDocSegment; for (int j = 0; j < jsonDocSegmentArray.length(); j++) { JSONObject jsonDocObject = jsonDocSegmentArray.getJSONObject(j); String columnValue = null; if (fieldValue == null) { if (jsonDocObject.has(fieldName)) { columnValue = jsonDocObject.getString(fieldName); } } else { String expectedFieldValue = jsonDocObject.getString(fieldName); boolean encounterTypeMatches = (encounterType == null) || (encounterType != null && encounterType .equalsIgnoreCase(expectedEncounterType)); if (encounterTypeMatches && expectedFieldValue .equalsIgnoreCase(fieldValue)) { columnValue = getValues(jsonDocObject.get(responseKey)).get(0); } } if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocObject); contentValues.put(columnName, columnValue); } } } else { String columnValue = null; JSONObject jsonDocSegmentObject = (JSONObject) jsonDocSegment; columnValue = jsonDocSegmentObject.has(fieldName) ? jsonDocSegmentObject .getString(fieldName) : ""; if (columnValue != null) { columnValue = getHumanReadableConceptResponse(columnValue, jsonDocSegmentObject); contentValues.put(columnName, columnValue); } } } updateIdenitifier(contentValues); Long id = executeInsertStatement(contentValues, clientType); updateFTSsearch(clientType, baseEntityId, contentValues); Long timestamp = getEventDate(event.get("eventDate")); addContentValuesToDetailsTable(contentValues, timestamp); updateClientDetailsTable(event, client); } return true; } catch (Exception e) { Timber.e(e); return null; } } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; } |
@Test public void onHandleIntentShouldProcessEventsIfPeerToPeerUnprocessedEventsReturnsTrue() throws Exception { p2pProcessRecordsService.onHandleIntent(null); Mockito.verify(eventClientRepository, Mockito.never()).getMaxRowId(Mockito.any(EventClientRepository.Table.class)); Mockito.verify(clientProcessorForJava, Mockito.never()).processClient(ArgumentMatchers.<List< EventClient>>any()); } | @Override protected void onHandleIntent(@Nullable Intent intent) { super.onHandleIntent(intent); AllSharedPreferences allSharedPreferences = CoreLibrary.getInstance().context().allSharedPreferences(); if (allSharedPreferences.isPeerToPeerUnprocessedEvents()) { CoreLibrary.getInstance().setPeerToPeerProcessing(true); long eventsMaxRowId = allSharedPreferences.getLastPeerToPeerSyncProcessedEvent(); EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); while (eventsMaxRowId > -1) { EventClientQueryResult eventClientQueryResult = eventClientRepository.fetchEventClientsByRowId(eventsMaxRowId); List<EventClient> eventClientList = eventClientQueryResult.getEventClientList(); if (eventClientList.size() > 0) { try { DrishtiApplication.getInstance().getClientProcessor().processClient(eventClientList); int tableMaxRowId = eventClientRepository.getMaxRowId(EventClientRepository.Table.event); if (tableMaxRowId == eventClientQueryResult.maxRowId) { eventsMaxRowId = -1; allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); } else { eventsMaxRowId = eventClientQueryResult.maxRowId; allSharedPreferences.setLastPeerToPeerSyncProcessedEvent(eventClientQueryResult.maxRowId); } Timber.i("Finished processing %s EventClients", String.valueOf(eventClientList.size())); } catch (Exception e) { Timber.e(e); } } else { allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); break; } } sendSyncStatusBroadcastMessage(FetchStatus.fetched); } } | P2pProcessRecordsService extends BaseSyncIntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { super.onHandleIntent(intent); AllSharedPreferences allSharedPreferences = CoreLibrary.getInstance().context().allSharedPreferences(); if (allSharedPreferences.isPeerToPeerUnprocessedEvents()) { CoreLibrary.getInstance().setPeerToPeerProcessing(true); long eventsMaxRowId = allSharedPreferences.getLastPeerToPeerSyncProcessedEvent(); EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); while (eventsMaxRowId > -1) { EventClientQueryResult eventClientQueryResult = eventClientRepository.fetchEventClientsByRowId(eventsMaxRowId); List<EventClient> eventClientList = eventClientQueryResult.getEventClientList(); if (eventClientList.size() > 0) { try { DrishtiApplication.getInstance().getClientProcessor().processClient(eventClientList); int tableMaxRowId = eventClientRepository.getMaxRowId(EventClientRepository.Table.event); if (tableMaxRowId == eventClientQueryResult.maxRowId) { eventsMaxRowId = -1; allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); } else { eventsMaxRowId = eventClientQueryResult.maxRowId; allSharedPreferences.setLastPeerToPeerSyncProcessedEvent(eventClientQueryResult.maxRowId); } Timber.i("Finished processing %s EventClients", String.valueOf(eventClientList.size())); } catch (Exception e) { Timber.e(e); } } else { allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); break; } } sendSyncStatusBroadcastMessage(FetchStatus.fetched); } } } | P2pProcessRecordsService extends BaseSyncIntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { super.onHandleIntent(intent); AllSharedPreferences allSharedPreferences = CoreLibrary.getInstance().context().allSharedPreferences(); if (allSharedPreferences.isPeerToPeerUnprocessedEvents()) { CoreLibrary.getInstance().setPeerToPeerProcessing(true); long eventsMaxRowId = allSharedPreferences.getLastPeerToPeerSyncProcessedEvent(); EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); while (eventsMaxRowId > -1) { EventClientQueryResult eventClientQueryResult = eventClientRepository.fetchEventClientsByRowId(eventsMaxRowId); List<EventClient> eventClientList = eventClientQueryResult.getEventClientList(); if (eventClientList.size() > 0) { try { DrishtiApplication.getInstance().getClientProcessor().processClient(eventClientList); int tableMaxRowId = eventClientRepository.getMaxRowId(EventClientRepository.Table.event); if (tableMaxRowId == eventClientQueryResult.maxRowId) { eventsMaxRowId = -1; allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); } else { eventsMaxRowId = eventClientQueryResult.maxRowId; allSharedPreferences.setLastPeerToPeerSyncProcessedEvent(eventClientQueryResult.maxRowId); } Timber.i("Finished processing %s EventClients", String.valueOf(eventClientList.size())); } catch (Exception e) { Timber.e(e); } } else { allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); break; } } sendSyncStatusBroadcastMessage(FetchStatus.fetched); } } P2pProcessRecordsService(String name); P2pProcessRecordsService(); } | P2pProcessRecordsService extends BaseSyncIntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { super.onHandleIntent(intent); AllSharedPreferences allSharedPreferences = CoreLibrary.getInstance().context().allSharedPreferences(); if (allSharedPreferences.isPeerToPeerUnprocessedEvents()) { CoreLibrary.getInstance().setPeerToPeerProcessing(true); long eventsMaxRowId = allSharedPreferences.getLastPeerToPeerSyncProcessedEvent(); EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); while (eventsMaxRowId > -1) { EventClientQueryResult eventClientQueryResult = eventClientRepository.fetchEventClientsByRowId(eventsMaxRowId); List<EventClient> eventClientList = eventClientQueryResult.getEventClientList(); if (eventClientList.size() > 0) { try { DrishtiApplication.getInstance().getClientProcessor().processClient(eventClientList); int tableMaxRowId = eventClientRepository.getMaxRowId(EventClientRepository.Table.event); if (tableMaxRowId == eventClientQueryResult.maxRowId) { eventsMaxRowId = -1; allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); } else { eventsMaxRowId = eventClientQueryResult.maxRowId; allSharedPreferences.setLastPeerToPeerSyncProcessedEvent(eventClientQueryResult.maxRowId); } Timber.i("Finished processing %s EventClients", String.valueOf(eventClientList.size())); } catch (Exception e) { Timber.e(e); } } else { allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); break; } } sendSyncStatusBroadcastMessage(FetchStatus.fetched); } } P2pProcessRecordsService(String name); P2pProcessRecordsService(); @Override void onDestroy(); } | P2pProcessRecordsService extends BaseSyncIntentService { @Override protected void onHandleIntent(@Nullable Intent intent) { super.onHandleIntent(intent); AllSharedPreferences allSharedPreferences = CoreLibrary.getInstance().context().allSharedPreferences(); if (allSharedPreferences.isPeerToPeerUnprocessedEvents()) { CoreLibrary.getInstance().setPeerToPeerProcessing(true); long eventsMaxRowId = allSharedPreferences.getLastPeerToPeerSyncProcessedEvent(); EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); while (eventsMaxRowId > -1) { EventClientQueryResult eventClientQueryResult = eventClientRepository.fetchEventClientsByRowId(eventsMaxRowId); List<EventClient> eventClientList = eventClientQueryResult.getEventClientList(); if (eventClientList.size() > 0) { try { DrishtiApplication.getInstance().getClientProcessor().processClient(eventClientList); int tableMaxRowId = eventClientRepository.getMaxRowId(EventClientRepository.Table.event); if (tableMaxRowId == eventClientQueryResult.maxRowId) { eventsMaxRowId = -1; allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); } else { eventsMaxRowId = eventClientQueryResult.maxRowId; allSharedPreferences.setLastPeerToPeerSyncProcessedEvent(eventClientQueryResult.maxRowId); } Timber.i("Finished processing %s EventClients", String.valueOf(eventClientList.size())); } catch (Exception e) { Timber.e(e); } } else { allSharedPreferences.resetLastPeerToPeerSyncProcessedEvent(); break; } } sendSyncStatusBroadcastMessage(FetchStatus.fetched); } } P2pProcessRecordsService(String name); P2pProcessRecordsService(); @Override void onDestroy(); } |
@Test public void onDestroyShouldSetPeerProcessingToFalse() { CoreLibrary.getInstance().setPeerToPeerProcessing(true); Assert.assertTrue(CoreLibrary.getInstance().isPeerToPeerProcessing()); p2pProcessRecordsService.onDestroy(); Assert.assertFalse(CoreLibrary.getInstance().isPeerToPeerProcessing()); } | @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } | P2pProcessRecordsService extends BaseSyncIntentService { @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } } | P2pProcessRecordsService extends BaseSyncIntentService { @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } P2pProcessRecordsService(String name); P2pProcessRecordsService(); } | P2pProcessRecordsService extends BaseSyncIntentService { @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } P2pProcessRecordsService(String name); P2pProcessRecordsService(); @Override void onDestroy(); } | P2pProcessRecordsService extends BaseSyncIntentService { @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } P2pProcessRecordsService(String name); P2pProcessRecordsService(); @Override void onDestroy(); } |
@Test public void testInit() { assertNotNull(Whitebox.getInternalState(syncIntentService, "httpAgent")); assertNotNull(Whitebox.getInternalState(syncIntentService, "syncUtils")); assertNotNull(Whitebox.getInternalState(syncIntentService, "context")); } | protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } | SyncIntentService extends BaseSyncIntentService { protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } } | SyncIntentService extends BaseSyncIntentService { protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testHandleSyncSendFetchStartedBroadCast() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(true); when(syncUtils.isAppVersionAllowed()).thenReturn(true); syncIntentService.handleSync(); verify(syncIntentService, times(2)).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getAllValues().get(0).getAction()); assertEquals(FetchStatus.fetchStarted, intentArgumentCaptor.getAllValues().get(0).getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS)); } | protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testHandleSyncCallsLogoutUserIfHasValidAuthorizationIsFalse() throws AuthenticatorException, OperationCanceledException, IOException { Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(false); when(syncConfiguration.disableSyncToServerIfUserIsDisabled()).thenReturn(true); syncIntentService.handleSync(); verify(syncUtils).logoutUser(); } | protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testHandleSyncCallsLogOutUserIfAppVersionIsNotAllowedAnd() throws AuthenticatorException, OperationCanceledException, IOException { syncIntentService = spy(syncIntentService); Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(true); when(syncConfiguration.disableSyncToServerIfUserIsDisabled()).thenReturn(true); syncIntentService.handleSync(); verify(syncUtils).logoutUser(); } | protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void assertWeekDifferenceReturnsInt() { LocalDate start = new LocalDate(1447487308000l); LocalDate end = new LocalDate(1510645708000l); Assert.assertEquals(DateUtil.weekDifference(start, end), 104); } | public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } | DateUtil { public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } } | DateUtil { public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } } | DateUtil { public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); } | DateUtil { public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; } |
@Test public void testPullEcFromServerWhenSyncFilterParamIsNull() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getValue().getAction()); assertEquals(FetchStatus.fetchedFailed, intentArgumentCaptor.getValue().getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS)); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testPullEcFromServerWhenSyncFilterValueIsNull() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); when(syncConfiguration.getSyncFilterParam()).thenReturn(SyncFilter.LOCATION); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getValue().getAction()); assertEquals(FetchStatus.fetchedFailed, intentArgumentCaptor.getValue().getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS)); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testPullEcFromServerWhenHttpAgentIsNull() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); Whitebox.setInternalState(syncIntentService, "httpAgent", (Object[]) null); assertNull(Whitebox.getInternalState(syncIntentService, "httpAgent")); when(syncConfiguration.getSyncFilterParam()).thenReturn(SyncFilter.LOCATION); when(syncConfiguration.getSyncFilterValue()).thenReturn("location-1"); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getValue().getAction()); assertEquals(FetchStatus.fetchedFailed, intentArgumentCaptor.getValue().getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS)); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testPullEcFromServerUsingPOSTUsesCorrectURLAndParams() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); initMocksForPullECFromServerUsingPOST(); ResponseStatus responseStatus = ResponseStatus.failure; responseStatus.setDisplayValue(ResponseErrorStatus.malformed_url.name()); Mockito.doReturn(new Response<>(responseStatus, null)) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals("{\"locationId\":\"location-1\",\"serverVersion\":0,\"limit\":250,\"return_count\":true}", requestString); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testPullEcFromServerWithURLError() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); initMocksForPullECFromServerUsingPOST(); ResponseStatus responseStatus = ResponseStatus.failure; responseStatus.setDisplayValue(ResponseErrorStatus.malformed_url.name()); Mockito.doReturn(new Response<>(responseStatus, null)) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getValue().getAction()); FetchStatus actualFetchStatus = (FetchStatus) intentArgumentCaptor.getValue().getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS); assertEquals(FetchStatus.fetchedFailed, actualFetchStatus); assertEquals("malformed_url", actualFetchStatus.displayValue()); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testPullEcFromServerWithTimeoutError() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); initMocksForPullECFromServerUsingPOST(); ResponseStatus responseStatus = ResponseStatus.failure; responseStatus.setDisplayValue(ResponseErrorStatus.timeout.name()); Mockito.doReturn(new Response<>(responseStatus, null)) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getValue().getAction()); FetchStatus actualFetchStatus = (FetchStatus) intentArgumentCaptor.getValue().getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS); assertEquals(FetchStatus.fetchedFailed, actualFetchStatus); assertEquals("timeout", actualFetchStatus.displayValue()); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testFetchFailedWithCountLessThanMaxSyncRetryCallsFetchRetry() { when(syncConfiguration.getSyncMaxRetries()).thenReturn(1); initMocksForPullECFromServerUsingPOST(); syncIntentService = spy(syncIntentService); ResponseStatus responseStatus = ResponseStatus.failure; Mockito.doReturn(new Response<>(responseStatus, null)) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); syncIntentService.fetchFailed(0); verify(syncIntentService).fetchFailed(1); } | public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } | SyncIntentService extends BaseSyncIntentService { public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } } | SyncIntentService extends BaseSyncIntentService { public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testSuccessfulPullEcFromServerWithNullPayloadSendsNothingFetchedBroadcast() { initMocksForPullECFromServerUsingPOST(); syncIntentService = spy(syncIntentService); ResponseStatus responseStatus = ResponseStatus.success; Mockito.doReturn(new Response<>(responseStatus, null).withTotalRecords(0l)) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); syncIntentService.pullECFromServer(); verify(syncIntentService).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getValue().getAction()); FetchStatus actualFetchStatus = (FetchStatus) intentArgumentCaptor.getValue().getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS); assertEquals(FetchStatus.nothingFetched, actualFetchStatus); } | protected void pullECFromServer() { fetchRetry(0, true); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { protected void pullECFromServer() { fetchRetry(0, true); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void testPushECToServer() throws Exception { syncIntentService = spy(syncIntentService); Map<String, Object> pendingEvents = new HashMap<>(); List<JSONObject> clients = new ArrayList<>(); JSONObject client = new JSONObject(clientJson); clients.add(client); List<JSONObject> events = new ArrayList<>(); JSONObject event = new JSONObject(eventJson); events.add(event); pendingEvents.put(AllConstants.KEY.CLIENTS, clients); pendingEvents.put(AllConstants.KEY.EVENTS, events); JSONObject expectedRequest = new JSONObject(); Object value = pendingEvents.get(AllConstants.KEY.CLIENTS); expectedRequest.put(AllConstants.KEY.CLIENTS, value); expectedRequest.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS)); Whitebox.setInternalState(syncIntentService, "httpAgent", httpAgent); when(eventClientRepository.getUnSyncedEventsCount()).thenReturn(2); when(eventClientRepository.getUnSyncedEvents(EVENT_PUSH_LIMIT)).thenReturn(pendingEvents, new HashMap<>()); Mockito.doReturn(new Response<>(ResponseStatus.success, null)) .when(httpAgent).post(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); Whitebox.invokeMethod(syncIntentService, "pushECToServer", eventClientRepository); verify(eventClientRepository).markEventsAsSynced(pendingEvents); verify(syncIntentService).updateProgress(1,2); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals(expectedRequest.toString(), requestString); } | private boolean pushECToServer(EventClientRepository db) { boolean isSuccessfulPushSync = true; int totalEventCount = db.getUnSyncedEventsCount(); int eventsUploadedCount = 0; while (true) { Map<String, Object> pendingEvents = db.getUnSyncedEvents(EVENT_PUSH_LIMIT); if (pendingEvents.isEmpty()) { break; } String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); if (baseUrl.endsWith(context.getString(R.string.url_separator))) { baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(context.getString(R.string.url_separator))); } JSONObject request = new JSONObject(); try { if (pendingEvents.containsKey(AllConstants.KEY.CLIENTS)) { Object value = pendingEvents.get(AllConstants.KEY.CLIENTS); request.put(AllConstants.KEY.CLIENTS, value); if (value instanceof List) { eventsUploadedCount += ((List) value).size(); } } if (pendingEvents.containsKey(AllConstants.KEY.EVENTS)) { request.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS)); } } catch (JSONException e) { Timber.e(e); } String jsonPayload = request.toString(); Response<String> response = httpAgent.post( MessageFormat.format("{0}/{1}", baseUrl, ADD_URL), jsonPayload); if (response.isFailure()) { Timber.e("Events sync failed."); isSuccessfulPushSync = false; } db.markEventsAsSynced(pendingEvents); Timber.i("Events synced successfully."); updateProgress(eventsUploadedCount, totalEventCount); } return isSuccessfulPushSync; } | SyncIntentService extends BaseSyncIntentService { private boolean pushECToServer(EventClientRepository db) { boolean isSuccessfulPushSync = true; int totalEventCount = db.getUnSyncedEventsCount(); int eventsUploadedCount = 0; while (true) { Map<String, Object> pendingEvents = db.getUnSyncedEvents(EVENT_PUSH_LIMIT); if (pendingEvents.isEmpty()) { break; } String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); if (baseUrl.endsWith(context.getString(R.string.url_separator))) { baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(context.getString(R.string.url_separator))); } JSONObject request = new JSONObject(); try { if (pendingEvents.containsKey(AllConstants.KEY.CLIENTS)) { Object value = pendingEvents.get(AllConstants.KEY.CLIENTS); request.put(AllConstants.KEY.CLIENTS, value); if (value instanceof List) { eventsUploadedCount += ((List) value).size(); } } if (pendingEvents.containsKey(AllConstants.KEY.EVENTS)) { request.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS)); } } catch (JSONException e) { Timber.e(e); } String jsonPayload = request.toString(); Response<String> response = httpAgent.post( MessageFormat.format("{0}/{1}", baseUrl, ADD_URL), jsonPayload); if (response.isFailure()) { Timber.e("Events sync failed."); isSuccessfulPushSync = false; } db.markEventsAsSynced(pendingEvents); Timber.i("Events synced successfully."); updateProgress(eventsUploadedCount, totalEventCount); } return isSuccessfulPushSync; } } | SyncIntentService extends BaseSyncIntentService { private boolean pushECToServer(EventClientRepository db) { boolean isSuccessfulPushSync = true; int totalEventCount = db.getUnSyncedEventsCount(); int eventsUploadedCount = 0; while (true) { Map<String, Object> pendingEvents = db.getUnSyncedEvents(EVENT_PUSH_LIMIT); if (pendingEvents.isEmpty()) { break; } String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); if (baseUrl.endsWith(context.getString(R.string.url_separator))) { baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(context.getString(R.string.url_separator))); } JSONObject request = new JSONObject(); try { if (pendingEvents.containsKey(AllConstants.KEY.CLIENTS)) { Object value = pendingEvents.get(AllConstants.KEY.CLIENTS); request.put(AllConstants.KEY.CLIENTS, value); if (value instanceof List) { eventsUploadedCount += ((List) value).size(); } } if (pendingEvents.containsKey(AllConstants.KEY.EVENTS)) { request.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS)); } } catch (JSONException e) { Timber.e(e); } String jsonPayload = request.toString(); Response<String> response = httpAgent.post( MessageFormat.format("{0}/{1}", baseUrl, ADD_URL), jsonPayload); if (response.isFailure()) { Timber.e("Events sync failed."); isSuccessfulPushSync = false; } db.markEventsAsSynced(pendingEvents); Timber.i("Events synced successfully."); updateProgress(eventsUploadedCount, totalEventCount); } return isSuccessfulPushSync; } SyncIntentService(); SyncIntentService(String name); } | SyncIntentService extends BaseSyncIntentService { private boolean pushECToServer(EventClientRepository db) { boolean isSuccessfulPushSync = true; int totalEventCount = db.getUnSyncedEventsCount(); int eventsUploadedCount = 0; while (true) { Map<String, Object> pendingEvents = db.getUnSyncedEvents(EVENT_PUSH_LIMIT); if (pendingEvents.isEmpty()) { break; } String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); if (baseUrl.endsWith(context.getString(R.string.url_separator))) { baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(context.getString(R.string.url_separator))); } JSONObject request = new JSONObject(); try { if (pendingEvents.containsKey(AllConstants.KEY.CLIENTS)) { Object value = pendingEvents.get(AllConstants.KEY.CLIENTS); request.put(AllConstants.KEY.CLIENTS, value); if (value instanceof List) { eventsUploadedCount += ((List) value).size(); } } if (pendingEvents.containsKey(AllConstants.KEY.EVENTS)) { request.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS)); } } catch (JSONException e) { Timber.e(e); } String jsonPayload = request.toString(); Response<String> response = httpAgent.post( MessageFormat.format("{0}/{1}", baseUrl, ADD_URL), jsonPayload); if (response.isFailure()) { Timber.e("Events sync failed."); isSuccessfulPushSync = false; } db.markEventsAsSynced(pendingEvents); Timber.i("Events synced successfully."); updateProgress(eventsUploadedCount, totalEventCount); } return isSuccessfulPushSync; } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); } | SyncIntentService extends BaseSyncIntentService { private boolean pushECToServer(EventClientRepository db) { boolean isSuccessfulPushSync = true; int totalEventCount = db.getUnSyncedEventsCount(); int eventsUploadedCount = 0; while (true) { Map<String, Object> pendingEvents = db.getUnSyncedEvents(EVENT_PUSH_LIMIT); if (pendingEvents.isEmpty()) { break; } String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); if (baseUrl.endsWith(context.getString(R.string.url_separator))) { baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(context.getString(R.string.url_separator))); } JSONObject request = new JSONObject(); try { if (pendingEvents.containsKey(AllConstants.KEY.CLIENTS)) { Object value = pendingEvents.get(AllConstants.KEY.CLIENTS); request.put(AllConstants.KEY.CLIENTS, value); if (value instanceof List) { eventsUploadedCount += ((List) value).size(); } } if (pendingEvents.containsKey(AllConstants.KEY.EVENTS)) { request.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS)); } } catch (JSONException e) { Timber.e(e); } String jsonPayload = request.toString(); Response<String> response = httpAgent.post( MessageFormat.format("{0}/{1}", baseUrl, ADD_URL), jsonPayload); if (response.isFailure()) { Timber.e("Events sync failed."); isSuccessfulPushSync = false; } db.markEventsAsSynced(pendingEvents); Timber.i("Events synced successfully."); updateProgress(eventsUploadedCount, totalEventCount); } return isSuccessfulPushSync; } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; } |
@Test public void onStartCommandShouldInstantiateVariables() { Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "httpAgent")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "manifestRepository")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "clientFormRepository")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "configuration")); documentConfigurationIntentService.onStartCommand(null, 0, 900); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "httpAgent")); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "manifestRepository")); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "clientFormRepository")); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "configuration")); } | @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLibrary.getInstance().context().getClientFormRepository(); configuration = CoreLibrary.getInstance().context().configuration(); return super.onStartCommand(intent, flags, startId); } | DocumentConfigurationIntentService extends BaseSyncIntentService { @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLibrary.getInstance().context().getClientFormRepository(); configuration = CoreLibrary.getInstance().context().configuration(); return super.onStartCommand(intent, flags, startId); } } | DocumentConfigurationIntentService extends BaseSyncIntentService { @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLibrary.getInstance().context().getClientFormRepository(); configuration = CoreLibrary.getInstance().context().configuration(); return super.onStartCommand(intent, flags, startId); } DocumentConfigurationIntentService(); DocumentConfigurationIntentService(String name); } | DocumentConfigurationIntentService extends BaseSyncIntentService { @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLibrary.getInstance().context().getClientFormRepository(); configuration = CoreLibrary.getInstance().context().configuration(); return super.onStartCommand(intent, flags, startId); } DocumentConfigurationIntentService(); DocumentConfigurationIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); } | DocumentConfigurationIntentService extends BaseSyncIntentService { @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLibrary.getInstance().context().getClientFormRepository(); configuration = CoreLibrary.getInstance().context().configuration(); return super.onStartCommand(intent, flags, startId); } DocumentConfigurationIntentService(); DocumentConfigurationIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); } |
@Test public void formatDateTest() { Assert.assertEquals("03-10-2019", DateUtil.formatDate(new LocalDate("2019-10-03"), "dd-MM-YYY")); Assert.assertEquals("", DateUtil.formatDate(new LocalDate("2019-10-03"), "KK-TT")); } | public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } | DateUtil { public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } } | DateUtil { public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } } | DateUtil { public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); } | DateUtil { public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; } |
@Test public void processSettingsShouldReturnTrueWhenIntentIsNull() throws JSONException { settingsSyncIntentService.syncSettingsServiceHelper = Mockito.spy(settingsSyncIntentService.syncSettingsServiceHelper); Assert.assertTrue(settingsSyncIntentService.processSettings(null)); Mockito.verify(settingsSyncIntentService.syncSettingsServiceHelper, Mockito.never()).processIntent(); } | protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); @Override void onCreate(); } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); @Override void onCreate(); static final String SETTINGS_URL; static final String EVENT_SYNC_COMPLETE; } |
@Test public void processSettingsShouldReturnTrueAndCallProcessIntentWhenIntentIsNotNull() throws JSONException { settingsSyncIntentService.syncSettingsServiceHelper = Mockito.spy(settingsSyncIntentService.syncSettingsServiceHelper); Mockito.doReturn(30).when(settingsSyncIntentService.syncSettingsServiceHelper).processIntent(); Intent intent = new Intent(); Assert.assertTrue(settingsSyncIntentService.processSettings(intent)); Mockito.verify(settingsSyncIntentService.syncSettingsServiceHelper, Mockito.times(1)).processIntent(); Assert.assertEquals(30, intent.getIntExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, 0)); } | protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); @Override void onCreate(); } | SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); @Override void onCreate(); static final String SETTINGS_URL; static final String EVENT_SYNC_COMPLETE; } |
@Test public void onCreateShouldCreateSyncSettingsServiceHelper() { settingsSyncIntentService = Robolectric.buildIntentService(SettingsSyncIntentService.class) .get(); Assert.assertNull(settingsSyncIntentService.syncSettingsServiceHelper); settingsSyncIntentService.onCreate(); Assert.assertNotNull(settingsSyncIntentService.syncSettingsServiceHelper); } | @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } | SettingsSyncIntentService extends BaseSyncIntentService { @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } } | SettingsSyncIntentService extends BaseSyncIntentService { @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } SettingsSyncIntentService(); } | SettingsSyncIntentService extends BaseSyncIntentService { @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } SettingsSyncIntentService(); @Override void onCreate(); } | SettingsSyncIntentService extends BaseSyncIntentService { @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } SettingsSyncIntentService(); @Override void onCreate(); static final String SETTINGS_URL; static final String EVENT_SYNC_COMPLETE; } |
@Test public void testSyncTasks() { taskServiceHelper.syncTasks(); verify(taskServiceHelper).syncCreatedTaskToServer(); verify(taskServiceHelper).syncTaskStatusToServer(); } | public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } | TaskServiceHelper extends BaseHelper { public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } } | TaskServiceHelper extends BaseHelper { public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); } | TaskServiceHelper extends BaseHelper { public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); } | TaskServiceHelper extends BaseHelper { public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); static final String TASK_LAST_SYNC_DATE; static final String UPDATE_STATUS_URL; static final String ADD_TASK_URL; static final String SYNC_TASK_URL; static final Gson taskGson; } |
@Test public void testSyncTaskStatusToServer() { TaskUpdate taskUpdate = new TaskUpdate(); taskUpdate.setIdentifier(planId); taskUpdate.setBusinessStatus("Not Visited"); taskUpdate.setStatus("Cancelled"); when(taskRepository.getUnSyncedTaskStatus()).thenReturn(Collections.singletonList(taskUpdate)); Mockito.doReturn(new Response<>(ResponseStatus.success, "{task_ids : [\"eb3cd7e1-c849-5230-8d49-943218018f9f\"]}")) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); taskServiceHelper.syncTaskStatusToServer(); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals("[{\"identifier\":\"eb3cd7e1-c849-5230-8d49-943218018f9f\",\"status\":\"Cancelled\",\"businessStatus\":\"Not Visited\"}]", requestString); verify(taskRepository).markTaskAsSynced(taskUpdate.getIdentifier()); } | public void syncTaskStatusToServer() { HTTPAgent httpAgent = getHttpAgent(); List<TaskUpdate> updates = taskRepository.getUnSyncedTaskStatus(); if (!updates.isEmpty()) { String jsonPayload = new Gson().toJson(updates); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, UPDATE_STATUS_URL), jsonPayload); if (response.isFailure()) { Timber.e("Update Status failedd: %s", response.payload()); return; } if (response.payload() != null) { try { JSONObject idObject = new JSONObject(response.payload()); JSONArray updatedIds = idObject.optJSONArray("task_ids"); if (updatedIds != null) { for (int i = 0; i < updatedIds.length(); i++) { taskRepository.markTaskAsSynced(updatedIds.get(i).toString()); } } } catch (JSONException e) { Timber.e(e, "Error processing the tasks payload: %s", response.payload()); } } } } | TaskServiceHelper extends BaseHelper { public void syncTaskStatusToServer() { HTTPAgent httpAgent = getHttpAgent(); List<TaskUpdate> updates = taskRepository.getUnSyncedTaskStatus(); if (!updates.isEmpty()) { String jsonPayload = new Gson().toJson(updates); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, UPDATE_STATUS_URL), jsonPayload); if (response.isFailure()) { Timber.e("Update Status failedd: %s", response.payload()); return; } if (response.payload() != null) { try { JSONObject idObject = new JSONObject(response.payload()); JSONArray updatedIds = idObject.optJSONArray("task_ids"); if (updatedIds != null) { for (int i = 0; i < updatedIds.length(); i++) { taskRepository.markTaskAsSynced(updatedIds.get(i).toString()); } } } catch (JSONException e) { Timber.e(e, "Error processing the tasks payload: %s", response.payload()); } } } } } | TaskServiceHelper extends BaseHelper { public void syncTaskStatusToServer() { HTTPAgent httpAgent = getHttpAgent(); List<TaskUpdate> updates = taskRepository.getUnSyncedTaskStatus(); if (!updates.isEmpty()) { String jsonPayload = new Gson().toJson(updates); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, UPDATE_STATUS_URL), jsonPayload); if (response.isFailure()) { Timber.e("Update Status failedd: %s", response.payload()); return; } if (response.payload() != null) { try { JSONObject idObject = new JSONObject(response.payload()); JSONArray updatedIds = idObject.optJSONArray("task_ids"); if (updatedIds != null) { for (int i = 0; i < updatedIds.length(); i++) { taskRepository.markTaskAsSynced(updatedIds.get(i).toString()); } } } catch (JSONException e) { Timber.e(e, "Error processing the tasks payload: %s", response.payload()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); } | TaskServiceHelper extends BaseHelper { public void syncTaskStatusToServer() { HTTPAgent httpAgent = getHttpAgent(); List<TaskUpdate> updates = taskRepository.getUnSyncedTaskStatus(); if (!updates.isEmpty()) { String jsonPayload = new Gson().toJson(updates); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, UPDATE_STATUS_URL), jsonPayload); if (response.isFailure()) { Timber.e("Update Status failedd: %s", response.payload()); return; } if (response.payload() != null) { try { JSONObject idObject = new JSONObject(response.payload()); JSONArray updatedIds = idObject.optJSONArray("task_ids"); if (updatedIds != null) { for (int i = 0; i < updatedIds.length(); i++) { taskRepository.markTaskAsSynced(updatedIds.get(i).toString()); } } } catch (JSONException e) { Timber.e(e, "Error processing the tasks payload: %s", response.payload()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); } | TaskServiceHelper extends BaseHelper { public void syncTaskStatusToServer() { HTTPAgent httpAgent = getHttpAgent(); List<TaskUpdate> updates = taskRepository.getUnSyncedTaskStatus(); if (!updates.isEmpty()) { String jsonPayload = new Gson().toJson(updates); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, UPDATE_STATUS_URL), jsonPayload); if (response.isFailure()) { Timber.e("Update Status failedd: %s", response.payload()); return; } if (response.payload() != null) { try { JSONObject idObject = new JSONObject(response.payload()); JSONArray updatedIds = idObject.optJSONArray("task_ids"); if (updatedIds != null) { for (int i = 0; i < updatedIds.length(); i++) { taskRepository.markTaskAsSynced(updatedIds.get(i).toString()); } } } catch (JSONException e) { Timber.e(e, "Error processing the tasks payload: %s", response.payload()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); static final String TASK_LAST_SYNC_DATE; static final String UPDATE_STATUS_URL; static final String ADD_TASK_URL; static final String SYNC_TASK_URL; static final Gson taskGson; } |
@Test public void testSynCreatedTaskToServerSuccessfully() { Task expectedTask = TaskServiceHelper.taskGson.fromJson(taskJSon, new TypeToken<Task>() { }.getType()); expectedTask.setSyncStatus(BaseRepository.TYPE_Created); ArrayList tasks = new ArrayList(); tasks.add(expectedTask); String expectedJsonPayload = TaskServiceHelper.taskGson.toJson(tasks); when(taskRepository.getAllUnsynchedCreatedTasks()).thenReturn(tasks); Mockito.doReturn(new Response<>(ResponseStatus.success, "{task_ids : [\"c256c9d8-fe9b-4763-b5af-26585dcbe6bf\"]}")) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); taskServiceHelper.syncCreatedTaskToServer(); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals(expectedJsonPayload, requestString); verify(taskRepository).getAllUnsynchedCreatedTasks(); verify(taskRepository).markTaskAsSynced(expectedTask.getIdentifier()); } | public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); static final String TASK_LAST_SYNC_DATE; static final String UPDATE_STATUS_URL; static final String ADD_TASK_URL; static final String SYNC_TASK_URL; static final Gson taskGson; } |
@Test public void testSynCreatedTaskToServerWithFailure() { Task expectedTask = TaskServiceHelper.taskGson.fromJson(taskJSon, new TypeToken<Task>() { }.getType()); expectedTask.setSyncStatus(BaseRepository.TYPE_Created); ArrayList tasks = new ArrayList(); tasks.add(expectedTask); String expectedJsonPayload = TaskServiceHelper.taskGson.toJson(tasks); when(taskRepository.getAllUnsynchedCreatedTasks()).thenReturn(tasks); Mockito.doReturn(new Response<>(ResponseStatus.failure, "")) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); taskServiceHelper.syncCreatedTaskToServer(); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals(expectedJsonPayload, requestString); verify(taskRepository).getAllUnsynchedCreatedTasks(); verifyNoMoreInteractions(taskRepository); } | public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); static final String TASK_LAST_SYNC_DATE; static final String UPDATE_STATUS_URL; static final String ADD_TASK_URL; static final String SYNC_TASK_URL; static final Gson taskGson; } |
@Test public void testSynCreatedTaskToServerWithTasksNotProcessedResponse() { Task expectedTask = TaskServiceHelper.taskGson.fromJson(taskJSon, new TypeToken<Task>() { }.getType()); expectedTask.setSyncStatus(BaseRepository.TYPE_Created); ArrayList tasks = new ArrayList(); tasks.add(expectedTask); String expectedJsonPayload = TaskServiceHelper.taskGson.toJson(tasks); when(taskRepository.getAllUnsynchedCreatedTasks()).thenReturn(tasks); Mockito.doReturn(new Response<>(ResponseStatus.success, "Tasks with identifiers not processed: c256c9d8-fe9b-4763-b5af-26585dcbe6bf")) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); taskServiceHelper.syncCreatedTaskToServer(); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals(expectedJsonPayload, requestString); verify(taskRepository).getAllUnsynchedCreatedTasks(); verifyNoMoreInteractions(taskRepository); } | public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); } | TaskServiceHelper extends BaseHelper { public void syncCreatedTaskToServer() { HTTPAgent httpAgent = getHttpAgent(); List<Task> tasks = taskRepository.getAllUnsynchedCreatedTasks(); if (!tasks.isEmpty()) { String jsonPayload = taskGson.toJson(tasks); String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL(); Response<String> response = httpAgent.postWithJsonResponse( MessageFormat.format("{0}/{1}", baseUrl, ADD_TASK_URL), jsonPayload); if (response.isFailure()) { Timber.e("Failed to create new tasks on server.: %s", response.payload()); return; } Set<String> unprocessedIds = new HashSet<>(); if (StringUtils.isNotBlank(response.payload())) { if (response.payload().startsWith(TASKS_NOT_PROCESSED)) { unprocessedIds.addAll(Arrays.asList(response.payload().substring(TASKS_NOT_PROCESSED.length()).split(","))); } for (Task task : tasks) { if (!unprocessedIds.contains(task.getIdentifier())) taskRepository.markTaskAsSynced(task.getIdentifier()); } } } } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); static final String TASK_LAST_SYNC_DATE; static final String UPDATE_STATUS_URL; static final String ADD_TASK_URL; static final String SYNC_TASK_URL; static final Gson taskGson; } |
@Test public void testSyncPlansCallsSendSyncProgressDialog() { Whitebox.setInternalState(planIntentServiceHelper, "totalRecords", 10l); planIntentServiceHelper.syncPlans(); verify(planIntentServiceHelper).sendSyncProgressBroadcast(syncProgressArgumentCaptor.capture(),any()); assertEquals(SyncEntity.PLANS, syncProgressArgumentCaptor.getValue().getSyncEntity()); assertEquals(10l, syncProgressArgumentCaptor.getValue().getTotalRecords()); assertEquals(0, syncProgressArgumentCaptor.getValue().getPercentageSynced()); } | public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); } | PlanIntentServiceHelper extends BaseHelper { public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); } } | PlanIntentServiceHelper extends BaseHelper { public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); } | PlanIntentServiceHelper extends BaseHelper { public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); static PlanIntentServiceHelper getInstance(); void syncPlans(); } | PlanIntentServiceHelper extends BaseHelper { public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); static PlanIntentServiceHelper getInstance(); void syncPlans(); static final String SYNC_PLANS_URL; static final String PLAN_LAST_SYNC_DATE; } |
@Test public void testBatchFetchPlansFromServer() { PlanDefinition expectedPlan = PlanIntentServiceHelper.gson.fromJson(planJson, new TypeToken<PlanDefinition>() { }.getType()); ArrayList plans = new ArrayList(); plans.add(expectedPlan); Mockito.doReturn(new Response<>(ResponseStatus.success, PlanIntentServiceHelper.gson.toJson(plans)).withTotalRecords(1L), new Response<>(ResponseStatus.success, PlanIntentServiceHelper.gson.toJson(new ArrayList<>())).withTotalRecords(0l)) .when(httpAgent).post(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); planIntentServiceHelper.syncPlans(); String syncUrl = stringArgumentCaptor.getAllValues().get(0); assertEquals("https: String requestString = stringArgumentCaptor.getAllValues().get(1); assertEquals("{\"organizations\":[\"org1\",\"org2\"],\"serverVersion\":0,\"return_count\":true}", requestString); verify(planDefinitionRepository).addOrUpdate(planDefinitionArgumentCaptor.capture()); PlanDefinition actualPlan = planDefinitionArgumentCaptor.getValue(); assertEquals(expectedPlan.getIdentifier(), actualPlan.getIdentifier()); assertEquals(expectedPlan.getName(), actualPlan.getName()); assertEquals(expectedPlan.getTitle(), actualPlan.getTitle()); assertEquals(expectedPlan.getServerVersion(), actualPlan.getServerVersion()); assertEquals(expectedPlan.getVersion(), actualPlan.getVersion()); } | private int batchFetchPlansFromServer(boolean returnCount) { int batchFetchCount = 0; try { long serverVersion = 0; try { serverVersion = Long.parseLong(allSharedPreferences.getPreference(PLAN_LAST_SYNC_DATE)); } catch (NumberFormatException e) { Timber.e(e, "EXCEPTION %s", e.toString()); } if (serverVersion > 0) { serverVersion += 1; } Long maxServerVersion = 0l; String organizationIds = allSharedPreferences.getPreference(AllConstants.ORGANIZATION_IDS); String plansResponse = fetchPlans(Arrays.asList(organizationIds.split(",")), serverVersion, returnCount); List<PlanDefinition> plans = gson.fromJson(plansResponse, new TypeToken<List<PlanDefinition>>() { }.getType()); for (PlanDefinition plan : plans) { try { planDefinitionRepository.addOrUpdate(plan); } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } } if (!Utils.isEmptyCollection(plans)) { batchFetchCount = plans.size(); allSharedPreferences.savePreference(PLAN_LAST_SYNC_DATE, String.valueOf(getPlanDefinitionMaxServerVersion(plans, maxServerVersion))); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); batchFetchPlansFromServer(false); } } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } return batchFetchCount; } | PlanIntentServiceHelper extends BaseHelper { private int batchFetchPlansFromServer(boolean returnCount) { int batchFetchCount = 0; try { long serverVersion = 0; try { serverVersion = Long.parseLong(allSharedPreferences.getPreference(PLAN_LAST_SYNC_DATE)); } catch (NumberFormatException e) { Timber.e(e, "EXCEPTION %s", e.toString()); } if (serverVersion > 0) { serverVersion += 1; } Long maxServerVersion = 0l; String organizationIds = allSharedPreferences.getPreference(AllConstants.ORGANIZATION_IDS); String plansResponse = fetchPlans(Arrays.asList(organizationIds.split(",")), serverVersion, returnCount); List<PlanDefinition> plans = gson.fromJson(plansResponse, new TypeToken<List<PlanDefinition>>() { }.getType()); for (PlanDefinition plan : plans) { try { planDefinitionRepository.addOrUpdate(plan); } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } } if (!Utils.isEmptyCollection(plans)) { batchFetchCount = plans.size(); allSharedPreferences.savePreference(PLAN_LAST_SYNC_DATE, String.valueOf(getPlanDefinitionMaxServerVersion(plans, maxServerVersion))); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); batchFetchPlansFromServer(false); } } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } return batchFetchCount; } } | PlanIntentServiceHelper extends BaseHelper { private int batchFetchPlansFromServer(boolean returnCount) { int batchFetchCount = 0; try { long serverVersion = 0; try { serverVersion = Long.parseLong(allSharedPreferences.getPreference(PLAN_LAST_SYNC_DATE)); } catch (NumberFormatException e) { Timber.e(e, "EXCEPTION %s", e.toString()); } if (serverVersion > 0) { serverVersion += 1; } Long maxServerVersion = 0l; String organizationIds = allSharedPreferences.getPreference(AllConstants.ORGANIZATION_IDS); String plansResponse = fetchPlans(Arrays.asList(organizationIds.split(",")), serverVersion, returnCount); List<PlanDefinition> plans = gson.fromJson(plansResponse, new TypeToken<List<PlanDefinition>>() { }.getType()); for (PlanDefinition plan : plans) { try { planDefinitionRepository.addOrUpdate(plan); } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } } if (!Utils.isEmptyCollection(plans)) { batchFetchCount = plans.size(); allSharedPreferences.savePreference(PLAN_LAST_SYNC_DATE, String.valueOf(getPlanDefinitionMaxServerVersion(plans, maxServerVersion))); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); batchFetchPlansFromServer(false); } } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } return batchFetchCount; } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); } | PlanIntentServiceHelper extends BaseHelper { private int batchFetchPlansFromServer(boolean returnCount) { int batchFetchCount = 0; try { long serverVersion = 0; try { serverVersion = Long.parseLong(allSharedPreferences.getPreference(PLAN_LAST_SYNC_DATE)); } catch (NumberFormatException e) { Timber.e(e, "EXCEPTION %s", e.toString()); } if (serverVersion > 0) { serverVersion += 1; } Long maxServerVersion = 0l; String organizationIds = allSharedPreferences.getPreference(AllConstants.ORGANIZATION_IDS); String plansResponse = fetchPlans(Arrays.asList(organizationIds.split(",")), serverVersion, returnCount); List<PlanDefinition> plans = gson.fromJson(plansResponse, new TypeToken<List<PlanDefinition>>() { }.getType()); for (PlanDefinition plan : plans) { try { planDefinitionRepository.addOrUpdate(plan); } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } } if (!Utils.isEmptyCollection(plans)) { batchFetchCount = plans.size(); allSharedPreferences.savePreference(PLAN_LAST_SYNC_DATE, String.valueOf(getPlanDefinitionMaxServerVersion(plans, maxServerVersion))); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); batchFetchPlansFromServer(false); } } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } return batchFetchCount; } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); static PlanIntentServiceHelper getInstance(); void syncPlans(); } | PlanIntentServiceHelper extends BaseHelper { private int batchFetchPlansFromServer(boolean returnCount) { int batchFetchCount = 0; try { long serverVersion = 0; try { serverVersion = Long.parseLong(allSharedPreferences.getPreference(PLAN_LAST_SYNC_DATE)); } catch (NumberFormatException e) { Timber.e(e, "EXCEPTION %s", e.toString()); } if (serverVersion > 0) { serverVersion += 1; } Long maxServerVersion = 0l; String organizationIds = allSharedPreferences.getPreference(AllConstants.ORGANIZATION_IDS); String plansResponse = fetchPlans(Arrays.asList(organizationIds.split(",")), serverVersion, returnCount); List<PlanDefinition> plans = gson.fromJson(plansResponse, new TypeToken<List<PlanDefinition>>() { }.getType()); for (PlanDefinition plan : plans) { try { planDefinitionRepository.addOrUpdate(plan); } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } } if (!Utils.isEmptyCollection(plans)) { batchFetchCount = plans.size(); allSharedPreferences.savePreference(PLAN_LAST_SYNC_DATE, String.valueOf(getPlanDefinitionMaxServerVersion(plans, maxServerVersion))); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); batchFetchPlansFromServer(false); } } catch (Exception e) { Timber.e(e, "EXCEPTION %s", e.toString()); } return batchFetchCount; } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); static PlanIntentServiceHelper getInstance(); void syncPlans(); static final String SYNC_PLANS_URL; static final String PLAN_LAST_SYNC_DATE; } |
@Test public void getLocalDateTest() { Assert.assertEquals(new LocalDate("2019-10-03"), DateUtil.getLocalDate("03/10/2019")); Assert.assertEquals(null, DateUtil.getLocalDate("03-15-2019")); } | public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } | DateUtil { public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } } | DateUtil { public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } } | DateUtil { public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); } | DateUtil { public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; } |
@Test public void testProcessIntent() throws JSONException { AllSettings allSettings = Mockito.spy(CoreLibrary.getInstance().context().allSettings()); ReflectionHelpers.setField(CoreLibrary.getInstance().context(), "allSettings", allSettings); SettingsRepository settingsRepository = ReflectionHelpers.getField(allSettings, "settingsRepository"); settingsRepository.updateMasterRepository(repository); Mockito.doReturn(coreLibrary).when(syncSettingsServiceHelper).getInstance(); Mockito.doReturn(true).when(syncConfiguration).resolveSettings(); Mockito.doReturn(true).when(syncConfiguration).hasExtraSettingsSync(); Mockito.doReturn(true).when(syncConfiguration).hasGlobalSettings(); Mockito.doReturn("team-uuid").when(syncConfiguration).getSettingsSyncFilterValue(); Mockito.doReturn(settings).when(context).allSettings(); Mockito.doReturn(new ArrayList<Setting>()).when(settings).getUnsyncedSettings(); Mockito.doReturn(SyncFilter.TEAM).when(syncSettingsServiceHelper).getSettingsSyncFilterParam(); List<String> params = new ArrayList<>(); params.add("locationId=location-uuid"); Mockito.doReturn(params).when(syncConfiguration).getExtraSettingsParameters(); Mockito.doReturn(new Response<>(ResponseStatus.success, settingsResponse)).when(syncSettingsServiceHelper).getResponse(ArgumentMatchers.anyString(), ArgumentMatchers.anyString()); Mockito.doReturn(SAMPLE_TEST_TOKEN).when(syncSettingsServiceHelper).getAccessToken(); int size = syncSettingsServiceHelper.processIntent(); Assert.assertEquals(3, size); } | public int processIntent() throws JSONException { try { JSONObject response = pushSettingsToServer(); if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) { JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS); Setting setting; for (int i = 0; i < records.length(); i++) { setting = getInstance().context().allSettings().getSetting(records.getString(0)); setting.setSyncStatus(SyncStatus.SYNCED.name()); getInstance().context().allSettings().putSetting(setting); } } } catch (JSONException e) { Timber.e(e); } JSONArray settings = getSettings(); if (settings != null && settings.length() > 0) { ServerSettingsHelper.saveSetting(settings); } return settings == null ? 0 : settings.length(); } | SyncSettingsServiceHelper { public int processIntent() throws JSONException { try { JSONObject response = pushSettingsToServer(); if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) { JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS); Setting setting; for (int i = 0; i < records.length(); i++) { setting = getInstance().context().allSettings().getSetting(records.getString(0)); setting.setSyncStatus(SyncStatus.SYNCED.name()); getInstance().context().allSettings().putSetting(setting); } } } catch (JSONException e) { Timber.e(e); } JSONArray settings = getSettings(); if (settings != null && settings.length() > 0) { ServerSettingsHelper.saveSetting(settings); } return settings == null ? 0 : settings.length(); } } | SyncSettingsServiceHelper { public int processIntent() throws JSONException { try { JSONObject response = pushSettingsToServer(); if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) { JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS); Setting setting; for (int i = 0; i < records.length(); i++) { setting = getInstance().context().allSettings().getSetting(records.getString(0)); setting.setSyncStatus(SyncStatus.SYNCED.name()); getInstance().context().allSettings().putSetting(setting); } } } catch (JSONException e) { Timber.e(e); } JSONArray settings = getSettings(); if (settings != null && settings.length() > 0) { ServerSettingsHelper.saveSetting(settings); } return settings == null ? 0 : settings.length(); } SyncSettingsServiceHelper(String baseUrl, HTTPAgent httpAgent); } | SyncSettingsServiceHelper { public int processIntent() throws JSONException { try { JSONObject response = pushSettingsToServer(); if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) { JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS); Setting setting; for (int i = 0; i < records.length(); i++) { setting = getInstance().context().allSettings().getSetting(records.getString(0)); setting.setSyncStatus(SyncStatus.SYNCED.name()); getInstance().context().allSettings().putSetting(setting); } } } catch (JSONException e) { Timber.e(e); } JSONArray settings = getSettings(); if (settings != null && settings.length() > 0) { ServerSettingsHelper.saveSetting(settings); } return settings == null ? 0 : settings.length(); } SyncSettingsServiceHelper(String baseUrl, HTTPAgent httpAgent); int processIntent(); JSONArray pullSettingsFromServer(String syncFilterValue, String accessToken); JSONArray pullGlobalSettingsFromServer(String accessToken); } | SyncSettingsServiceHelper { public int processIntent() throws JSONException { try { JSONObject response = pushSettingsToServer(); if (response != null && response.has(AllConstants.INTENT_KEY.VALIDATED_RECORDS)) { JSONArray records = response.getJSONArray(AllConstants.INTENT_KEY.VALIDATED_RECORDS); Setting setting; for (int i = 0; i < records.length(); i++) { setting = getInstance().context().allSettings().getSetting(records.getString(0)); setting.setSyncStatus(SyncStatus.SYNCED.name()); getInstance().context().allSettings().putSetting(setting); } } } catch (JSONException e) { Timber.e(e); } JSONArray settings = getSettings(); if (settings != null && settings.length() > 0) { ServerSettingsHelper.saveSetting(settings); } return settings == null ? 0 : settings.length(); } SyncSettingsServiceHelper(String baseUrl, HTTPAgent httpAgent); int processIntent(); JSONArray pullSettingsFromServer(String syncFilterValue, String accessToken); JSONArray pullGlobalSettingsFromServer(String accessToken); } |
@Test public void testRemoveLocationsFromHierarchyShouldRemoveLocations() throws Exception { Set<String> locations = new HashSet<>(Arrays.asList("853934ee-d1a6-4b69-9191-59047edbc9a8", "4ed8f536-5c08-4203-8a90-a7e13becb01d")); validateAssignmentHelper.removeLocationsFromHierarchy(locationTree, locations); verify(settingsRepository).saveANMLocation(stringArgumentCaptor.capture()); assertNotEquals(locationHierarchy, stringArgumentCaptor.getValue()); LocationTree locationTree = gson.fromJson(stringArgumentCaptor.getValue(), LocationTree.class); assertFalse(locationTree.hasLocation("853934ee-d1a6-4b69-9191-59047edbc9a8")); assertFalse(locationTree.hasLocation("4ed8f536-5c08-4203-8a90-a7e13becb01d")); assertFalse(locationTree.hasLocation("67c5e0a4-132f-457b-b573-9abf5ec95c75")); verify(anmLocationController).evict(); } | @VisibleForTesting protected void removeLocationsFromHierarchy(LocationTree locationTree, Set<String> removedAssignments) throws AuthenticatorException, OperationCanceledException, IOException { for (String removedAssignment : removedAssignments) { locationTree.deleteLocation(removedAssignment); } settingsRepository.saveANMLocation(gson.toJson(locationTree)); anmLocationController.evict(); String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); if (StringUtils.isNotBlank(defaultLocationUuid) && removedAssignments.contains(defaultLocationUuid)) { logoff(R.string.default_location_revoked_logged_off); } } | ValidateAssignmentHelper extends BaseHelper { @VisibleForTesting protected void removeLocationsFromHierarchy(LocationTree locationTree, Set<String> removedAssignments) throws AuthenticatorException, OperationCanceledException, IOException { for (String removedAssignment : removedAssignments) { locationTree.deleteLocation(removedAssignment); } settingsRepository.saveANMLocation(gson.toJson(locationTree)); anmLocationController.evict(); String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); if (StringUtils.isNotBlank(defaultLocationUuid) && removedAssignments.contains(defaultLocationUuid)) { logoff(R.string.default_location_revoked_logged_off); } } } | ValidateAssignmentHelper extends BaseHelper { @VisibleForTesting protected void removeLocationsFromHierarchy(LocationTree locationTree, Set<String> removedAssignments) throws AuthenticatorException, OperationCanceledException, IOException { for (String removedAssignment : removedAssignments) { locationTree.deleteLocation(removedAssignment); } settingsRepository.saveANMLocation(gson.toJson(locationTree)); anmLocationController.evict(); String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); if (StringUtils.isNotBlank(defaultLocationUuid) && removedAssignments.contains(defaultLocationUuid)) { logoff(R.string.default_location_revoked_logged_off); } } ValidateAssignmentHelper(SyncUtils syncUtils); } | ValidateAssignmentHelper extends BaseHelper { @VisibleForTesting protected void removeLocationsFromHierarchy(LocationTree locationTree, Set<String> removedAssignments) throws AuthenticatorException, OperationCanceledException, IOException { for (String removedAssignment : removedAssignments) { locationTree.deleteLocation(removedAssignment); } settingsRepository.saveANMLocation(gson.toJson(locationTree)); anmLocationController.evict(); String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); if (StringUtils.isNotBlank(defaultLocationUuid) && removedAssignments.contains(defaultLocationUuid)) { logoff(R.string.default_location_revoked_logged_off); } } ValidateAssignmentHelper(SyncUtils syncUtils); void validateUserAssignment(); } | ValidateAssignmentHelper extends BaseHelper { @VisibleForTesting protected void removeLocationsFromHierarchy(LocationTree locationTree, Set<String> removedAssignments) throws AuthenticatorException, OperationCanceledException, IOException { for (String removedAssignment : removedAssignments) { locationTree.deleteLocation(removedAssignment); } settingsRepository.saveANMLocation(gson.toJson(locationTree)); anmLocationController.evict(); String defaultLocationUuid = allSharedPreferences.fetchDefaultLocalityId(allSharedPreferences.fetchRegisteredANM()); if (StringUtils.isNotBlank(defaultLocationUuid) && removedAssignments.contains(defaultLocationUuid)) { logoff(R.string.default_location_revoked_logged_off); } } ValidateAssignmentHelper(SyncUtils syncUtils); void validateUserAssignment(); static final String ACTION_ASSIGNMENT_REMOVED; static final String ASSIGNMENTS_REMOVED; static final Gson gson; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.