From 73d5862150422c79e1801a8835e76eed971ccbc3 Mon Sep 17 00:00:00 2001 From: Arif Burak Demiray <57103426+arifBurakDemiray@users.noreply.github.com> Date: Tue, 16 Jan 2024 13:51:18 +0000 Subject: [PATCH 1/3] fix: remove unused parantheses (#225) --- .../java/ly/count/java/demo/BackendModeExample.java | 2 +- .../count/java/demo/BackendModePerformanceTests.java | 4 ++-- sdk-java/src/main/java/ly/count/sdk/java/Config.java | 4 ++-- .../java/ly/count/sdk/java/internal/EventImpl.java | 6 +++--- .../count/sdk/java/internal/ModuleBackendMode.java | 5 ++--- .../ly/count/sdk/java/internal/ModuleEvents.java | 6 +++--- .../ly/count/sdk/java/internal/ModuleLocation.java | 2 +- .../count/sdk/java/internal/ModuleUserProfile.java | 2 +- .../main/java/ly/count/sdk/java/internal/Params.java | 12 ++++++------ .../java/ly/count/sdk/java/internal/SessionImpl.java | 6 +++--- .../ly/count/sdk/java/internal/UserEditorImpl.java | 2 +- .../sdk/java/internal/MigrationHelperTests.java | 2 +- .../ly/count/sdk/java/internal/SdkStorageTests.java | 4 ++-- .../ly/count/sdk/java/internal/SessionImplTests.java | 4 ++-- 14 files changed, 30 insertions(+), 31 deletions(-) diff --git a/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java b/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java index 0946cba65..cbd375edb 100644 --- a/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java +++ b/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java @@ -312,7 +312,7 @@ public static void main(String[] args) throws Exception { String[] sdkStorageRootPath = { System.getProperty("user.home"), "__COUNTLY", "java_test" }; File sdkStorageRootDirectory = new File(String.join(File.separator, sdkStorageRootPath)); - if ((!(sdkStorageRootDirectory.exists() && sdkStorageRootDirectory.isDirectory())) && !sdkStorageRootDirectory.mkdirs()) { + if (!(sdkStorageRootDirectory.exists() && sdkStorageRootDirectory.isDirectory()) && !sdkStorageRootDirectory.mkdirs()) { DemoUtils.println("Directory creation failed"); } diff --git a/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java b/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java index dc2c4931c..8085a6950 100644 --- a/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java +++ b/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java @@ -199,13 +199,13 @@ public static void main(String[] args) throws Exception { case 2: performLargeEventQueueTest(); running = false; - DemoUtils.printf("Time spent: %dms%n", (System.currentTimeMillis() - startTime)); + DemoUtils.printf("Time spent: %dms%n", System.currentTimeMillis() - startTime); break; case 3: startTime = System.currentTimeMillis(); recordBulkDataAndSendToServer(); running = false; - DemoUtils.printf("Time spent: %dms%n", (System.currentTimeMillis() - startTime)); + DemoUtils.printf("Time spent: %dms%n", System.currentTimeMillis() - startTime); break; default: break; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/Config.java b/sdk-java/src/main/java/ly/count/sdk/java/Config.java index 63739bd16..0bee67fce 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/Config.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/Config.java @@ -138,7 +138,7 @@ public boolean equals(Object obj) { return false; } DID did = (DID) obj; - return did.strategy == strategy && (Objects.equals(did.id, id)); + return did.strategy == strategy && Objects.equals(did.id, id); } @Override @@ -379,7 +379,7 @@ public Config disableUnhandledCrashReporting() { this.unhandledCrashReportingEnabled = false; return this; } - + protected String location = null; protected String ip = null; protected String city = null; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java index 239c52b84..43c53e893 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImpl.java @@ -219,13 +219,13 @@ public boolean equals(Object obj) { if (count != event.count) { return false; } - if ((sum != null && !sum.equals(event.sum) || (event.sum != null && !event.sum.equals(sum)))) { + if (sum != null && !sum.equals(event.sum) || (event.sum != null && !event.sum.equals(sum))) { return false; } - if ((duration != null && !duration.equals(event.duration) || (event.duration != null && !event.duration.equals(duration)))) { + if (duration != null && !duration.equals(event.duration) || (event.duration != null && !event.duration.equals(duration))) { return false; } - if ((segmentation != null && !segmentation.equals(event.segmentation) || (event.segmentation != null && !event.segmentation.equals(segmentation)))) { + if (segmentation != null && !segmentation.equals(event.segmentation) || (event.segmentation != null && !event.segmentation.equals(segmentation))) { return false; } return true; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java index c20e0fda1..53bac5a7a 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java @@ -334,13 +334,12 @@ protected Map removeInvalidDataFromSegments(Map for (Map.Entry item : segments.entrySet()) { Object type = item.getValue(); - boolean isValidDataType = (type instanceof Boolean + boolean isValidDataType = type instanceof Boolean || type instanceof Integer || type instanceof Long || type instanceof String || type instanceof Double - || type instanceof Float - ); + || type instanceof Float; if (!isValidDataType) { toRemove.add(item.getKey()); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java index 6ca2564a4..b4a6c771b 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java @@ -44,12 +44,12 @@ public void deviceIdChanged(String oldDeviceId, boolean withMerge) { // this part is to end and record the current view if exists Session session = Countly.session(); - if ((session != null && session.isActive())) { + if (session != null && session.isActive()) { View currentView = ((SessionImpl) session).currentView; if (currentView != null) { currentView.stop(true); } else { - Storage.pushAsync(internalConfig, ((SessionImpl) Countly.session())); + Storage.pushAsync(internalConfig, (SessionImpl) Countly.session()); } } @@ -126,7 +126,7 @@ private void addEventToQueue(EventImpl event) { private void checkEventQueueToSend(boolean forceSend) { L.d("[ModuleEvents] queue size:[" + eventQueue.eqSize() + "] || forceSend: " + forceSend); - if (forceSend || (eventQueue.eqSize() >= internalConfig.getEventsBufferSize())) { + if (forceSend || eventQueue.eqSize() >= internalConfig.getEventsBufferSize()) { addEventsToRequestQ(null); } } diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java index ebde7f777..c81b2adba 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleLocation.java @@ -47,7 +47,7 @@ void sendLocation() { void setLocationInternal(@Nullable String countryCode, @Nullable String cityName, @Nullable String gpsCoordinates, @Nullable String ipAddress) { L.d("[ModuleLocation] setLocationInternal, Setting location parameters, cc[" + countryCode + "] cy[" + city + "] gps[" + gpsCoordinates + "] ip[" + ipAddress + "]"); - if ((countryCode == null && city != null) || (city == null && countryCode != null)) { + if (countryCode != null ^ city != null) { L.w("[ModuleLocation] setLocationInternal, both city and country code need to be set at the same time to be sent"); } country = countryCode; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java index 72cd09a53..9d592aa27 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleUserProfile.java @@ -56,7 +56,7 @@ enum Op { object.put("$max", Math.max(object.optDouble("$max", (Double) value), (Double) value)); json.put(key, object); }), - SET_ONCE(((json, key, value) -> json.put(key, json.optJSONObject(key, new JSONObject()).put("$setOnce", value)))), + SET_ONCE((json, key, value) -> json.put(key, json.optJSONObject(key, new JSONObject()).put("$setOnce", value))), PULL((json, key, value) -> json.put(key, json.optJSONObject(key, new JSONObject()).accumulate("$pull", value))), PUSH((json, key, value) -> json.put(key, json.optJSONObject(key, new JSONObject()).accumulate("$push", value))), PUSH_UNIQUE((json, key, value) -> json.put(key, json.optJSONObject(key, new JSONObject()).accumulate("$addToSet", value))); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java index 7ed453e7a..5fd95ec18 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java @@ -91,12 +91,12 @@ public Params add() { public Params(Object... objects) { params = new StringBuilder(); - if (objects != null && objects.length == 1 && (objects[0] instanceof Object[])) { + if (objects != null && objects.length == 1 && objects[0] instanceof Object[]) { addObjects((Object[]) objects[0]); - } else if (objects != null && objects.length == 1 && (objects[0] instanceof Params)) { - params.append(objects[0].toString()); - } else if (objects != null && objects.length == 1 && (objects[0] instanceof String)) { - params.append(objects[0].toString()); + } else if (objects != null && objects.length == 1 && objects[0] instanceof Params) { + params.append(objects[0]); + } else if (objects != null && objects.length == 1 && objects[0] instanceof String) { + params.append(objects[0]); } else { addObjects(objects); } @@ -276,7 +276,7 @@ private Params addObjects(Object[] objects) { L.e("Bad number of parameters"); } else { for (int i = 0; i < objects.length; i += 2) { - add(objects[i] == null ? ("unknown" + i) : objects[i].toString(), objects.length > i + 1 ? objects[i + 1] : null); + add(objects[i] == null ? "unknown" + i : objects[i].toString(), objects.length > i + 1 ? objects[i + 1] : null); } } return this; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java index 715f9c434..a964a84ca 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/SessionImpl.java @@ -612,13 +612,13 @@ public boolean equals(Object obj) { if (!id.equals(session.id)) { return false; } - if ((began != null && !began.equals(session.began) || (session.began != null && !session.began.equals(began)))) { + if (began != null && !began.equals(session.began) || (session.began != null && !session.began.equals(began))) { return false; } - if ((updated != null && !updated.equals(session.updated) || (session.updated != null && !session.updated.equals(updated)))) { + if (updated != null && !updated.equals(session.updated) || (session.updated != null && !session.updated.equals(updated))) { return false; } - if ((ended != null && !ended.equals(session.ended) || (session.ended != null && !session.ended.equals(ended)))) { + if (ended != null && !ended.equals(session.ended) || (session.ended != null && !session.ended.equals(ended))) { return false; } if (!params.equals(session.params)) { diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java index 4d988eaad..33e586cca 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/UserEditorImpl.java @@ -72,7 +72,7 @@ public UserEditor setPicture(byte[] picture) { @Override public UserEditor setPicturePath(String picturePath) { L.d("[UserEditorImpl] setPicturePath, picturePath = " + picturePath); - if (picturePath == null || Utils.isValidURL(picturePath) || (new File(picturePath)).isFile()) { + if (picturePath == null || Utils.isValidURL(picturePath) || new File(picturePath).isFile()) { //if it is a thing we can use, continue return set(PredefinedUserPropertyKeys.PICTURE_PATH, picturePath); } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java index 1a7cd7905..6487cb4fb 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java @@ -72,7 +72,7 @@ public void beforeTest() { private void initStorage() { InternalConfig config = (new InternalConfig(TestUtils.getBaseConfig())); config.setLogger(mock(Log.class)); - storageProvider = (new SDKStorage()).init(config); + storageProvider = new SDKStorage().init(config); } /** diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkStorageTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkStorageTests.java index ae32cbfc5..0b9da8351 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkStorageTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/SdkStorageTests.java @@ -30,7 +30,7 @@ public void stop() { //doing all of this just to stop the Task //todo eliminate this InternalConfig config = TestUtils.getInternalConfigWithLogger(TestUtils.getBaseConfig()); - SDKStorage storageProvider = (new SDKStorage()).init(config); + SDKStorage storageProvider = new SDKStorage().init(config); storageProvider.stop(config, true); } @@ -41,7 +41,7 @@ public void stop() { */ @Test public void getDeviceID() { - SDKStorage storageProvider = (new SDKStorage()).init(TestUtils.getInternalConfigWithLogger(TestUtils.getBaseConfig())); + SDKStorage storageProvider = new SDKStorage().init(TestUtils.getInternalConfigWithLogger(TestUtils.getBaseConfig())); Assert.assertNull(storageProvider.getDeviceID()); } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java index 72456e207..ba5eb8413 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/SessionImplTests.java @@ -531,8 +531,8 @@ public void equals_notInstanceOf() { */ @Test public void equals_differentId() { - validateNotEquals(1, ((session, session2) -> ts -> { - })); + validateNotEquals(1, (session, session2) -> ts -> { + }); } /** From 2799ed371bdf27979ff6381fcb7ffa45c5fad1bb Mon Sep 17 00:00:00 2001 From: Arif Burak Demiray <57103426+arifBurakDemiray@users.noreply.github.com> Date: Tue, 16 Jan 2024 13:52:13 +0000 Subject: [PATCH 2/3] feat: changes with map initializers (#222) --- .../count/java/demo/BackendModeExample.java | 69 ++++++------- .../demo/BackendModePerformanceTests.java | 63 ++++++------ .../sdk/java/internal/BackendModeTests.java | 97 +++++++++---------- 3 files changed, 103 insertions(+), 126 deletions(-) diff --git a/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java b/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java index cbd375edb..a160fc6b4 100644 --- a/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java +++ b/app-java/src/main/java/ly/count/java/demo/BackendModeExample.java @@ -1,9 +1,9 @@ package ly.count.java.demo; import java.io.File; -import java.util.HashMap; import java.util.Map; import java.util.Scanner; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; @@ -14,7 +14,7 @@ public class BackendModeExample { final static String COUNTLY_SERVER_URL = "https://xxx.server.ly/"; private static void recordUserDetailAndProperties() { - Map userDetail = new HashMap<>(); + Map userDetail = new ConcurrentHashMap<>(); userDetail.put("name", "Full Name"); userDetail.put("username", "username1"); userDetail.put("email", "user@gmail.com"); @@ -32,7 +32,7 @@ private static void recordUserDetailAndProperties() { } private static void recordView() { - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("visit", "1"); segmentation.put("segment", "Windows"); segmentation.put("start", "1"); @@ -41,23 +41,20 @@ private static void recordView() { } private static void recordEvent() { - Map segment = new HashMap() {{ - put("Time Spent", 60); - put("Retry Attempts", 60); - }}; - + Map segment = new ConcurrentHashMap<>(); + segment.put("Time Spent", 60); + segment.put("Retry Attempts", 60); Countly.instance().backendM().recordEvent(DEVICE_ID, "Event Key", 1, 0.1, 5.0, segment, null); } private static void recordExceptionWithThrowableAndSegmentation() { - Map segmentation = new HashMap() {{ - put("login page", "authenticate request"); - }}; - Map crashDetails = new HashMap() {{ - put("_os", "Windows 11"); - put("_os_version", "11.202"); - put("_logs", "main page"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("logout page", "authenticate request"); + + Map crashDetails = new ConcurrentHashMap<>(); + crashDetails.put("_os", "Windows 10"); + crashDetails.put("_os_version", "10.202"); + crashDetails.put("_logs", "logout page"); try { int a = 10 / 0; } catch (Exception e) { @@ -66,15 +63,13 @@ private static void recordExceptionWithThrowableAndSegmentation() { } private static void recordExceptionWithMessageAndSegmentation() { - Map segmentation = new HashMap() {{ - put("login page", "authenticate request"); - }}; - - Map crashDetails = new HashMap() {{ - put("_os", "Windows 11"); - put("_os_version", "11.202"); - put("_logs", "main page"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("login page", "authenticate request"); + + Map crashDetails = new ConcurrentHashMap<>(); + crashDetails.put("_os", "Windows 11"); + crashDetails.put("_os_version", "11.202"); + crashDetails.put("_logs", "main page"); try { int a = 10 / 0; } catch (Exception e) { @@ -83,7 +78,7 @@ private static void recordExceptionWithMessageAndSegmentation() { } private static void recordDirectRequest() { - Map requestData = new HashMap<>(); + Map requestData = new ConcurrentHashMap<>(); requestData.put("device_id", "id"); requestData.put("timestamp", "1646640780130"); requestData.put("end_session", "1"); @@ -92,18 +87,16 @@ private static void recordDirectRequest() { } private static void startSession() { - Map metrics = new HashMap() {{ - put("_os", "Android"); - put("_os_version", "10"); - put("_app_version", "1.2"); - }}; - - Map location = new HashMap() {{ - put("ip_address", "192.168.1.1"); - put("city", "Lahore"); - put("country_code", "PK"); - put("location", "31.5204,74.3587"); - }}; + Map metrics = new ConcurrentHashMap<>(); + metrics.put("_os", "Windows"); + metrics.put("_os_version", "10"); + metrics.put("_app_version", "1.2"); + + Map location = new ConcurrentHashMap<>(); + location.put("ip_address", "IP_ADDR"); + location.put("city", "Lahore"); + location.put("country_code", "PK"); + location.put("location", "31.5204,74.3587"); Countly.instance().backendM().sessionBegin(DEVICE_ID, metrics, location, null); } diff --git a/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java b/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java index 8085a6950..ebb842f10 100644 --- a/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java +++ b/app-java/src/main/java/ly/count/java/demo/BackendModePerformanceTests.java @@ -1,9 +1,9 @@ package ly.count.java.demo; import java.io.File; -import java.util.HashMap; import java.util.Map; import java.util.Scanner; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import ly.count.sdk.java.internal.Device; @@ -50,10 +50,9 @@ static void performLargeRequestQueueSizeTest() { DemoUtils.printf("Adding %d requests(events) into request Queue%n", batchSize); for (int i = 1; i < batchSize; ++i) { - Map segment = new HashMap() {{ - put("Time Spent", 60); - put("Retry Attempts", 60); - }}; + Map segment = new ConcurrentHashMap<>(); + segment.put("Time Spent", 60); + segment.put("Retry Attempts", 60); Countly.backendMode().recordEvent(DEVICE_ID, "Event Key " + i, 1, 0.1, 5.0, segment, null); } @@ -61,16 +60,13 @@ static void performLargeRequestQueueSizeTest() { DemoUtils.printf("Adding %d requests(crash) into request Queue%n", batchSize); for (int i = 1; i < batchSize; ++i) { - Map segmentation = new HashMap() {{ - put("login page", "authenticate request"); - }}; - - Map crashDetails = new HashMap() {{ - put("_os", "Windows 11"); - put("_os_version", "11.202"); - put("_logs", "main page"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("signup page", "authenticate request"); + Map crashDetails = new ConcurrentHashMap<>(); + crashDetails.put("_os", "Windows 8"); + crashDetails.put("_os_version", "8.202"); + crashDetails.put("_logs", "main page"); Countly.backendMode().recordException(DEVICE_ID, "Message: " + i, "stack traces " + 1, segmentation, crashDetails, null); } @@ -79,7 +75,7 @@ static void performLargeRequestQueueSizeTest() { for (int i = 1; i < batchSize; ++i) { // User detail - Map userDetail = new HashMap<>(); + Map userDetail = new ConcurrentHashMap<>(); userDetail.put("name", "Full Name"); userDetail.put("username", "username1"); userDetail.put("email", "user@gmail.com"); @@ -98,19 +94,16 @@ static void performLargeRequestQueueSizeTest() { DemoUtils.printf("Adding %d requests(sessions) into request Queue%n", batchSize); for (int i = 1; i < batchSize; ++i) { - Map metrics = new HashMap() {{ - put("_os", "Android"); - put("_os_version", "10"); - put("_app_version", "1.2"); - }}; - - Map location = new HashMap() {{ - put("ip_address", "192.168.1.1"); - put("city", "Lahore"); - put("country_code", "PK"); - put("location", "31.5204,74.3587"); - }}; - + Map metrics = new ConcurrentHashMap<>(); + metrics.put("_os", "MacOs"); + metrics.put("_os_version", "13"); + metrics.put("_app_version", "1.3"); + + Map location = new ConcurrentHashMap<>(); + location.put("ip_address", "IP_ADDR"); + location.put("city", "Lahore"); + location.put("country_code", "PK"); + location.put("location", "31.5204,74.3587"); Countly.backendMode().sessionBegin(DEVICE_ID, metrics, location, null); } @@ -131,10 +124,9 @@ static void performLargeEventQueueTest() { DemoUtils.printf("Adding %d events into event Queue against deviceID = %s%n", 1_000_00, "device-id-" + d); for (int i = 1; i <= noOfEvents; ++i) { - Map segment = new HashMap() {{ - put("Time Spent", 60); - put("Retry Attempts", 60); - }}; + Map segment = new ConcurrentHashMap<>(); + segment.put("Time Spent", 60); + segment.put("Retry Attempts", 60); Countly.backendMode().recordEvent("device-id-" + d, "Event Key " + i, 1, 0.1, 5.0, segment, null); } @@ -159,10 +151,9 @@ static void recordBulkDataAndSendToServer() throws InterruptedException { Thread.sleep(secondsToSleep * 1000); } else { if (remaining > 0) { - Map segment = new HashMap() {{ - put("Time Spent", 60); - put("Retry Attempts", 60); - }}; + Map segment = new ConcurrentHashMap<>(); + segment.put("Time Spent", 60); + segment.put("Retry Attempts", 60); Countly.backendMode().recordEvent("device-id", "Event Key " + remaining, 1, 0.1, 5.0, segment, null); --remaining; diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java index d86bee281..a1f2fa764 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/BackendModeTests.java @@ -7,6 +7,7 @@ import java.util.Calendar; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import org.json.JSONArray; @@ -73,15 +74,13 @@ public void testConfigurationValues() { public void testMethodRecordView() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap() {{ - put("name", "SampleView"); - put("visit", "1"); - put("segment", "Windows"); - put("start", "1"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("visit", "1"); + segmentation.put("segment", "Windows"); + segmentation.put("start", "1"); Assert.assertEquals(0L, moduleBackendMode.eventQSize); - backendMode.recordView("device-id-1", "SampleView", segmentation, 1646640780130L); + backendMode.recordView("device-id-1", TestUtils.keysValues[0], segmentation, 1646640780130L); JSONArray events = moduleBackendMode.eventQueues.get("device-id-1"); Assert.assertEquals(1L, events.length()); @@ -96,12 +95,12 @@ public void testMethodRecordView() { validateEventFields("[CLY]_view", 1, null, null, 1, expectedHour, expectedTimestamp, event); JSONObject segments = event.getJSONObject("segmentation"); - Assert.assertEquals("SampleView", segments.get("name")); + Assert.assertEquals(TestUtils.keysValues[0], segments.get("name")); Assert.assertEquals("1", segments.get("visit")); Assert.assertEquals("Windows", segments.get("segment")); Assert.assertEquals("1", segments.get("start")); - backendMode.recordView("device-id-2", "SampleView2", null, 1646640780130L); + backendMode.recordView("device-id-2", TestUtils.keysValues[1], null, 1646640780130L); events = moduleBackendMode.eventQueues.get("device-id-2"); Assert.assertEquals(1L, events.length()); @@ -112,7 +111,7 @@ public void testMethodRecordView() { validateEventFields("[CLY]_view", 1, null, null, 1, expectedHour, expectedTimestamp, event); segments = event.getJSONObject("segmentation"); - Assert.assertEquals("SampleView2", segments.get("name")); + Assert.assertEquals(TestUtils.keysValues[1], segments.get("name")); } /** @@ -122,17 +121,16 @@ public void testMethodRecordView() { public void testMethodRecordViewWithInvalidData() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap() {{ - put("name", "SampleView"); - put("visit", "1"); - put("segment", "Windows"); - put("start", "1"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("name", TestUtils.keysValues[0]); + segmentation.put("visit", "1"); + segmentation.put("segment", "Windows"); + segmentation.put("start", "1"); /* Invalid Device ID */ Assert.assertEquals(0L, moduleBackendMode.eventQSize); - backendMode.recordView("", "SampleView1", segmentation, 1646640780130L); - backendMode.recordView(null, "SampleView1", segmentation, 1646640780130L); + backendMode.recordView("", TestUtils.keysValues[0], segmentation, 1646640780130L); + backendMode.recordView(null, TestUtils.keysValues[1], segmentation, 1646640780130L); Assert.assertTrue(moduleBackendMode.eventQueues.isEmpty()); Assert.assertEquals(0L, moduleBackendMode.eventQSize); @@ -154,7 +152,7 @@ public void testMethodRecordViewWithInvalidData() { public void testMethodRecordEventWithSingleDeviceID() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key1", "value1"); segmentation.put("key2", "value2"); @@ -185,7 +183,7 @@ public void testMethodRecordEventWithSingleDeviceID() { public void testMethodRecordEventWithInvalidData() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key1", "value1"); segmentation.put("key2", "value2"); @@ -216,11 +214,11 @@ public void testMethodRecordEventWithInvalidData() { public void testMethodRecordEventWithMultipleDeviceID() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key1", "value1"); segmentation.put("key2", "value2"); - Map segmentation1 = new HashMap<>(); + Map segmentation1 = new ConcurrentHashMap<>(); segmentation1.put("key3", "value3"); segmentation1.put("key4", "value4"); @@ -282,11 +280,11 @@ public void testMethodRecordEventWithMultipleDeviceID() { public void TestEventThreshHoldWithSingleAndMultiple() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key1", "value1"); segmentation.put("key2", "value2"); - Map segmentation1 = new HashMap<>(); + Map segmentation1 = new ConcurrentHashMap<>(); segmentation1.put("key3", "value3"); segmentation1.put("key4", "value4"); @@ -342,11 +340,11 @@ public void TestEventThreshHoldWithSingleAndMultiple() { public void testFunctionalityAddEventsIntoRequestQueueOnSessionUpdate() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key1", "value1"); segmentation.put("key2", "value2"); - Map segmentation1 = new HashMap<>(); + Map segmentation1 = new ConcurrentHashMap<>(); segmentation1.put("key3", "value3"); segmentation1.put("key4", "value4"); @@ -378,11 +376,11 @@ public void testFunctionalityAddEventsIntoRequestQueueOnSessionUpdate() { public void testFunctionalityAddEventsIntoRequestQueueOnSessionEnd() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key1", "value1"); segmentation.put("key2", "value2"); - Map segmentation1 = new HashMap<>(); + Map segmentation1 = new ConcurrentHashMap<>(); segmentation1.put("key3", "value3"); segmentation1.put("key4", "value4"); @@ -419,16 +417,15 @@ public void testFunctionalityAddEventsIntoRequestQueueOnSessionEnd() { @Test public void testMethodSessionBegin() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map metrics = new HashMap<>(); + Map metrics = new ConcurrentHashMap<>(); metrics.put("os", "windows"); metrics.put("app-version", "0.1"); - Map location = new HashMap() {{ - put("ip_address", "192.168.1.1"); - put("city", "Lahore"); - put("country_code", "PK"); - put("location", "31.5204,74.3587"); - }}; + Map location = new ConcurrentHashMap<>(); + location.put("ip_address", "IP_ADDR"); + location.put("city", "Lahore"); + location.put("country_code", "PK"); + location.put("location", "31.5204,74.3587"); backendMode.sessionBegin("device-id-1", metrics, location, 1646640780130L); @@ -440,7 +437,7 @@ public void testMethodSessionBegin() { Assert.assertEquals("Lahore", request.params.get("city")); Assert.assertEquals("PK", request.params.get("country_code")); - Assert.assertEquals("192.168.1.1", request.params.get("ip_address")); + Assert.assertEquals("IP_ADDR", request.params.get("ip_address")); Assert.assertEquals("31.5204,74.3587", request.params.get("location")); Assert.assertEquals("windows", sessionJson.get("os")); @@ -455,7 +452,7 @@ public void testMethodSessionBegin() { @Test public void testMethodSessionBeginWithInvalidData() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map metrics = new HashMap<>(); + Map metrics = new ConcurrentHashMap<>(); metrics.put("os", "windows"); metrics.put("app-version", "0.1"); @@ -526,16 +523,13 @@ public void testMethodSessionEndWithInvalidData() { @Test public void testMethodRecordException() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap() {{ - put("key1", "value1"); - }}; - - Map crashDetails = new HashMap() {{ - put("_error", "Custom Error"); - put("_logs", "Logs"); - put("_os", "Operating System"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("key1", "value1"); + Map crashDetails = new ConcurrentHashMap<>(); + crashDetails.put("_error", "Custom Error"); + crashDetails.put("_logs", "Logs"); + crashDetails.put("_os", "Operating System"); try { int a = 10 / 0; } catch (Exception e) { @@ -583,9 +577,8 @@ public void testMethodRecordException() { @Test public void testMethodRecordExceptionWithInvalidData() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); - Map segmentation = new HashMap() {{ - put("key1", "value1"); - }}; + Map segmentation = new ConcurrentHashMap<>(); + segmentation.put("key1", "value1"); backendMode.recordException("", null, segmentation, null, 1646640780130L); Assert.assertTrue(SDKCore.instance.requestQueueMemory.isEmpty()); @@ -841,7 +834,7 @@ public void testRecordDirectRequest() { ModuleBackendMode.BackendMode backendMode = moduleBackendMode.new BackendMode(); // Direct request with timestamp and device id - Map requestData = new HashMap<>(); + Map requestData = new ConcurrentHashMap<>(); requestData.put("data1", "value1"); requestData.put("device_id", "device-id-1"); requestData.put("timestamp", "1647938191782"); @@ -862,7 +855,7 @@ public void testRecordDirectRequest() { validateRequestTimeFields("device-id-2", 1647938191782L, request); // Direct request without timestamp and device id - requestData = new HashMap<>(); + requestData = new ConcurrentHashMap<>(); requestData.put("data2", "value2"); requestData.put("data4", "value4"); @@ -880,7 +873,7 @@ public void testRecordDirectRequest() { } private Map populateUserProperties(boolean addUserDetail, boolean addCustomDetail, boolean addOperation) { - Map userDetail = new HashMap<>(); + Map userDetail = new ConcurrentHashMap<>(); if (addUserDetail) { userDetail.put("name", "Full Name"); userDetail.put("username", "username1"); From 2562fb13f59fe7682dec88d59da43b2bacac8787 Mon Sep 17 00:00:00 2001 From: Arif Burak Demiray <57103426+arifBurakDemiray@users.noreply.github.com> Date: Tue, 16 Jan 2024 13:59:10 +0000 Subject: [PATCH 3/3] [Java] Fixing codacy - ConcurrentHashMap (#221) * feat: concurrent hash map * fix: codacy * fix: codacy * fix: revert split up * feat: revert transport * fix: rever change * fix: revert splitted --- .../src/main/java/ly/count/sdk/java/Config.java | 4 ++-- .../java/ly/count/sdk/java/internal/CrashImpl.java | 3 ++- .../java/ly/count/sdk/java/internal/Device.java | 8 ++++---- .../count/sdk/java/internal/ModuleBackendMode.java | 7 ++++--- .../sdk/java/internal/ModuleDeviceIdCore.java | 4 ++-- .../ly/count/sdk/java/internal/ModuleFeedback.java | 4 ++-- .../java/ly/count/sdk/java/internal/Params.java | 4 ++-- .../java/ly/count/sdk/java/internal/SDKCore.java | 6 +++--- .../java/ly/count/sdk/java/internal/Utils.java | 4 ++-- .../ly/count/sdk/java/internal/ConfigTests.java | 4 ++-- .../ly/count/sdk/java/internal/DeviceTests.java | 7 +++---- .../ly/count/sdk/java/internal/EventImplTests.java | 13 +++++++------ .../sdk/java/internal/MigrationHelperTests.java | 12 ++++++------ .../count/sdk/java/internal/ModuleEventsTests.java | 14 +++++++------- .../sdk/java/internal/ModuleFeedbackTests.java | 11 ++++++----- .../java/ly/count/sdk/java/internal/TestUtils.java | 11 +++++------ .../count/sdk/java/internal/TimedEventsTests.java | 6 +++--- .../ly/count/sdk/java/internal/UtilsTests.java | 5 +++-- 18 files changed, 65 insertions(+), 62 deletions(-) diff --git a/sdk-java/src/main/java/ly/count/sdk/java/Config.java b/sdk-java/src/main/java/ly/count/sdk/java/Config.java index 0bee67fce..93836f3f2 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/Config.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/Config.java @@ -4,12 +4,12 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.internal.CoreFeature; import ly.count.sdk.java.internal.Log; import ly.count.sdk.java.internal.LogCallback; @@ -214,7 +214,7 @@ public String toString() { */ protected boolean enableBackendMode = false; - protected final Map metricOverride = new HashMap<>(); + protected final Map metricOverride = new ConcurrentHashMap<>(); /** * Salt string for parameter tampering protection diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java index 8abab68ec..72e6003ec 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/CrashImpl.java @@ -8,6 +8,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Crash; import org.json.JSONException; import org.json.JSONObject; @@ -150,7 +151,7 @@ public Map getSegments() { return null; } JSONObject object = this.data.getJSONObject("_custom"); - Map map = new HashMap<>(); + Map map = new ConcurrentHashMap<>(); Iterator iterator = object.keys(); while (iterator.hasNext()) { String key = iterator.next(); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Device.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Device.java index bb5c9e0e2..7746a72a5 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Device.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Device.java @@ -1,15 +1,15 @@ package ly.count.sdk.java.internal; import com.sun.management.OperatingSystemMXBean; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.lang.management.ManagementFactory; import java.util.Date; -import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Class encapsulating most of device-specific logic: metrics, info, etc. @@ -31,7 +31,7 @@ public class Device { private Log L; - private final Map metricOverride = new HashMap<>(); + private final Map metricOverride = new ConcurrentHashMap<>(); protected Device() { dev = this; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java index 53bac5a7a..6d95307f7 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleBackendMode.java @@ -8,6 +8,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.json.JSONArray; import org.json.JSONObject; @@ -21,7 +22,7 @@ public class ModuleBackendMode extends ModuleBase { protected boolean disabledModule = false; protected int eventQSize = 0; - protected final Map eventQueues = new HashMap<>(); + protected final Map eventQueues = new ConcurrentHashMap<>(); final String[] userPredefinedKeys = { "name", "username", "email", "organization", "phone", "gender", "byear" }; @@ -181,8 +182,8 @@ private void recordUserPropertiesInternal(String deviceID, Map u removeInvalidDataFromSegments(userProperties); - Map userDetail = new HashMap<>(); - Map customDetail = new HashMap<>(); + Map userDetail = new ConcurrentHashMap<>(); + Map customDetail = new ConcurrentHashMap<>(); for (Map.Entry item : userProperties.entrySet()) { if (Arrays.stream(userPredefinedKeys).anyMatch(item.getKey()::equalsIgnoreCase)) { userDetail.put(item.getKey(), item.getValue()); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java index e2923eeae..dbc410e1d 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleDeviceIdCore.java @@ -1,8 +1,8 @@ package ly.count.sdk.java.internal; -import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; @@ -44,7 +44,7 @@ public String generate(InternalConfig config) { } } - private static final Map generators = new HashMap<>(); + private static final Map generators = new ConcurrentHashMap<>(); protected DeviceId deviceIdInterface; diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java index a0ee1da9d..c8659ac75 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleFeedback.java @@ -1,10 +1,10 @@ package ly.count.sdk.java.internal; import java.util.ArrayList; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; import ly.count.sdk.java.Countly; import org.json.JSONArray; @@ -243,7 +243,7 @@ private void reportFeedbackWidgetManuallyInternal(CountlyFeedbackWidget widgetIn } } - Map segm = new HashMap<>(); + Map segm = new ConcurrentHashMap<>(); segm.put("platform", internalConfig.getSdkPlatform()); segm.put("app_version", cachedAppVersion); segm.put("widget_id", widgetInfo.widgetId); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java index 5fd95ec18..356e5006f 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Params.java @@ -3,9 +3,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.json.JSONException; import org.json.JSONObject; @@ -230,7 +230,7 @@ public String remove(final String key) { * @return map of the Params object */ public Map map() { - Map map = new HashMap<>(); + Map map = new ConcurrentHashMap<>(); List pairs = new ArrayList<>(Arrays.asList(params.toString().split("&"))); for (String pair : pairs) { String[] comps = pair.split("="); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java index 259cfb4a4..0991a7cfd 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/SDKCore.java @@ -2,11 +2,11 @@ import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; import ly.count.sdk.java.Config; @@ -74,7 +74,7 @@ protected static void registerDefaultModuleMappings() { /** * Selected by config map of module mappings */ - private static final Map> moduleMappings = new HashMap<>(); + private static final Map> moduleMappings = new ConcurrentHashMap<>(); protected static void registerModuleMapping(int feature, Class cls) { if (cls != null) { @@ -427,7 +427,7 @@ public void init(final InternalConfig givenConfig) { //setup and perform migrations MigrationHelper migrationHelper = new MigrationHelper(L); migrationHelper.setupMigrations(config.storageProvider); - Map migrationParams = new HashMap<>(); + Map migrationParams = new ConcurrentHashMap<>(); migrationParams.put("sdk_path", config.getSdkStorageRootDirectory()); migrationHelper.applyMigrations(migrationParams); diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java index 1195edadd..e8c11b6b4 100644 --- a/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java +++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java @@ -17,10 +17,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * Utility class @@ -269,7 +269,7 @@ public static Map fixSegmentKeysAndValues(final int keyLength, f return segments; } - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); for (Map.Entry entry : segments.entrySet()) { String k = entry.getKey(); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigTests.java index ba0f25ebb..2832b92ff 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ConfigTests.java @@ -1,8 +1,8 @@ package ly.count.sdk.java.internal; import java.net.URL; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import org.junit.Assert; import org.junit.Test; @@ -126,7 +126,7 @@ public void metricOverride() { Map initialVals = internalConfig.getMetricOverride(); Assert.assertEquals(0, initialVals.size()); - Map newVals = new HashMap<>(); + Map newVals = new ConcurrentHashMap<>(); newVals.put("a", "1"); newVals.put("b", "2"); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/DeviceTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/DeviceTests.java index dca75b431..72be03fba 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/DeviceTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/DeviceTests.java @@ -1,10 +1,9 @@ package ly.count.sdk.java.internal; -import org.json.JSONObject; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.junit.Assert; import org.junit.Test; -import java.util.HashMap; -import java.util.Map; public class DeviceTests { @@ -13,7 +12,7 @@ public class DeviceTests { */ @Test public void metricOverride_1() { - Map newVals = new HashMap<>(); + Map newVals = new ConcurrentHashMap<>(); newVals.put("a12345", "1qwer"); newVals.put("b5678", "2sdfg"); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/EventImplTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/EventImplTests.java index 23644ecc7..c8225d820 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/EventImplTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/EventImplTests.java @@ -3,6 +3,7 @@ import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; @@ -110,7 +111,7 @@ public void recorderCalledAfterRecord() { Assert.assertEquals(true, eventImpl1.getSegment("test")); }, "test_event", L); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("test", true); event.count = 5; @@ -130,7 +131,7 @@ public void validateToJson() { EventImpl event = new EventImpl((event1) -> { }, "test_buy_event", L); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("valid", false); event.duration = 34.0; @@ -161,7 +162,7 @@ public void validateFromJson() { EventImpl event = new EventImpl((event1) -> { }, "test_sell_event", L); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("sold", true); event.count = 3; @@ -214,7 +215,7 @@ public void validateFromJson_toJson_segmentation() { segmentation.put("divisor", 0.2f); event.segmentation = segmentation; - Map expectedSegmentation = new HashMap<>(); + Map expectedSegmentation = new ConcurrentHashMap<>(); expectedSegmentation.put("sold", true); expectedSegmentation.put("price", BigDecimal.valueOf(9.43)); expectedSegmentation.put("quantity", 3); @@ -242,7 +243,7 @@ public void testGetters() { EventImpl event = new EventImpl((event1) -> { }, "test_getter_event", L); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("get_func", 90); event.count = 47; @@ -270,7 +271,7 @@ public void testSetters() { event.setDuration(78); event.setSum(46); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("donated_amount", "37656387"); event.setSegmentation(segmentation); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java index 6487cb4fb..419a6edfc 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/MigrationHelperTests.java @@ -4,9 +4,9 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Countly; import org.junit.After; import org.junit.Assert; @@ -156,7 +156,7 @@ public void applyMigrations_legacyToLatest() { MigrationHelper migrationHelper = new MigrationHelper(mock(Log.class)); migrationHelper.setupMigrations(storageProvider); Assert.assertEquals(0, migrationHelper.currentDataModelVersion); //legacy state - Map migrationParams = new HashMap<>(); + Map migrationParams = new ConcurrentHashMap<>(); migrationParams.put("sdk_path", TestUtils.getTestSDirectory()); //apply migrations migrationHelper.applyMigrations(migrationParams); @@ -179,7 +179,7 @@ public void applyMigrations_latestToLatest() throws IOException { migrationHelper.setupMigrations(storageProvider); Assert.assertEquals(expectedLatestSchemaVersion, migrationHelper.currentDataModelVersion); //latest state //run migration helper apply - migrationHelper.applyMigrations(new HashMap<>()); + migrationHelper.applyMigrations(new ConcurrentHashMap<>()); //check migration version is at the latest after apply both from class and file Assert.assertEquals(expectedLatestSchemaVersion, migrationHelper.currentDataModelVersion); Assert.assertEquals(expectedLatestSchemaVersion, TestUtils.getJsonStorageProperty(SDKStorage.key_migration_version)); @@ -203,7 +203,7 @@ public void applyMigrations_0to1() throws IOException { //run migration helper Assert.assertNull(storageProvider.getDeviceID()); Assert.assertNull(storageProvider.getDeviceIdType()); - Map migrationParams = new HashMap<>(); + Map migrationParams = new ConcurrentHashMap<>(); migrationParams.put("sdk_path", TestUtils.getTestSDirectory()); Assert.assertTrue(migrationHelper.migration_DeleteConfigFile_01(migrationParams)); @@ -291,7 +291,7 @@ public void applyMigrations_1to2_nothingToMigrate() throws IOException { setDataVersionInConfigFile(1); // set previous data version initStorage(); - Map migrationParams = new HashMap<>(); + Map migrationParams = new ConcurrentHashMap<>(); migrationParams.put("sdk_path", TestUtils.getTestSDirectory()); MigrationHelper migrationHelper = new MigrationHelper(mock(Log.class)); @@ -319,7 +319,7 @@ public void applyMigrations_1to2_nullMigrationParams() throws IOException { Assert.assertEquals(1, migrationHelper.currentDataModelVersion); migrationHelper.logger = Mockito.spy(migrationHelper.logger); - Assert.assertFalse(migrationHelper.migration_UserImplFile_02(new HashMap<>())); + Assert.assertFalse(migrationHelper.migration_UserImplFile_02(new ConcurrentHashMap<>())); Assert.assertEquals(2, migrationHelper.currentDataModelVersion); Mockito.verify(migrationHelper.logger, Mockito.times(1)).d("[MigrationHelper] migration_UserImplFile_02, No files to delete, returning"); } diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java index f236e558f..688ee6c7a 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java @@ -1,9 +1,9 @@ package ly.count.sdk.java.internal; import java.io.IOException; -import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import org.junit.After; @@ -42,7 +42,7 @@ public void recordEvent() { TestUtils.validateEQSize(0, moduleEvents.eventQueue); //create segmentation - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("name", "Johny"); segmentation.put("weight", 67); segmentation.put("bald", true); @@ -154,13 +154,13 @@ public void recordEvent_invalidSegment() { TestUtils.validateEQSize(0, moduleEvents.eventQueue); //create segmentation - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("exam_name", "CENG 101"); segmentation.put("score", 67); segmentation.put("cheated", false); - segmentation.put("invalid", new HashMap<>()); + segmentation.put("invalid", new ConcurrentHashMap<>()); - Map expectedSegmentation = new HashMap<>(); + Map expectedSegmentation = new ConcurrentHashMap<>(); expectedSegmentation.put("exam_name", "CENG 101"); expectedSegmentation.put("score", 67); expectedSegmentation.put("cheated", false); @@ -310,7 +310,7 @@ public void endEvent_withSegmentation() { EventImpl timedEvent = moduleEvents.timedEvents.get(eKeys[0]); validateEvent(timedEvent, eKeys[0], null, 1, null, null); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("hair_color", "red"); segmentation.put("hair_length", "short"); segmentation.put("chauffeur", "g3chauffeur"); // @@ -338,7 +338,7 @@ public void endEvent_withSegmentation_negativeCount() { EventImpl timedEvent = moduleEvents.timedEvents.get(eKeys[0]); validateEvent(timedEvent, eKeys[0], null, 1, null, null); - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("horse_name", "Alice"); segmentation.put("bet_amount", 300); segmentation.put("currency", "Dollar"); // diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleFeedbackTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleFeedbackTests.java index b64d50f8e..21110ac29 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleFeedbackTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleFeedbackTests.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import ly.count.sdk.java.Countly; import org.json.JSONArray; @@ -411,7 +412,7 @@ public void reportFeedbackWidgetManually_nullWidgetResultValueKeys() { widgetResult.put("accepted", true); widgetResult.put("rating", 6); - Map expectedWidgetResult = new HashMap<>(); + Map expectedWidgetResult = new ConcurrentHashMap<>(); expectedWidgetResult.put("accepted", true); expectedWidgetResult.put("rating", 6); @@ -429,7 +430,7 @@ public void reportFeedbackWidgetManually_nullWidgetResultValueKeys() { public void reportFeedbackWidgetManually_nonExistingRatingField() { init(TestUtils.getConfigFeedback(Config.Feature.Events)); - Map widgetResult = new HashMap<>(); + Map widgetResult = new ConcurrentHashMap<>(); widgetResult.put("accepted", true); validateRecordingWidgetsManually(createFeedbackWidget(FeedbackWidgetType.nps, "nps1", "npsID1", new String[] { "sa" }), null, widgetResult, 0, false); @@ -445,7 +446,7 @@ public void reportFeedbackWidgetManually_nonExistingRatingField() { public void reportFeedbackWidgetManually_invalidRatingField() { init(TestUtils.getConfigFeedback(Config.Feature.Events)); - Map widgetResult = new HashMap<>(); + Map widgetResult = new ConcurrentHashMap<>(); widgetResult.put("rating", true); validateRecordingWidgetsManually(createFeedbackWidget(FeedbackWidgetType.nps, "nps1", "npsID1", new String[] { "sa" }), null, widgetResult, 0, false); @@ -461,7 +462,7 @@ public void reportFeedbackWidgetManually_invalidRatingField() { public void reportFeedbackWidgetManually_validRatingField() { init(TestUtils.getConfigFeedback(Config.Feature.Events)); - Map widgetResult = new HashMap<>(); + Map widgetResult = new ConcurrentHashMap<>(); widgetResult.put("rating", 11); validateRecordingWidgetsManually(createFeedbackWidget(FeedbackWidgetType.nps, "nps1", "npsID1", new String[] { "sa" }), null, widgetResult, 0, true); @@ -577,7 +578,7 @@ private ModuleEvents moduleEvents() { } private Map requiredWidgetSegmentation(String widgetId, Map widgetResult) { - Map segm = new HashMap<>(); + Map segm = new ConcurrentHashMap<>(); segm.put("platform", getOS()); segm.put("app_version", SDKCore.instance.config.getApplicationVersion()); segm.put("widget_id", widgetId); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java index fb37fbe80..8697a7c39 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java @@ -8,7 +8,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; @@ -155,14 +154,14 @@ protected static Map[] getCurrentRQ(File targetFolder, Log logge //check whether target folder is a directory or not if (!targetFolder.isDirectory()) { logger.e("[TestUtils] " + targetFolder.getAbsolutePath() + " is not a directory"); - return new HashMap[0]; + return new ConcurrentHashMap[0]; } //get all request files from target folder File[] requestFiles = getRequestFiles(targetFolder); //create array of request params - Map[] resultMapArray = new HashMap[requestFiles.length]; + Map[] resultMapArray = new ConcurrentHashMap[requestFiles.length]; for (int i = 0; i < requestFiles.length; i++) { File file = requestFiles[i]; @@ -274,12 +273,12 @@ private static Map parseRequestParams(File file) throws IOExcept try (Scanner scanner = new Scanner(file)) { String firstLine = scanner.nextLine(); if (Utils.isEmptyOrNull(firstLine)) { - return new HashMap<>(); + return new ConcurrentHashMap<>(); } String[] params = firstLine.split("&"); - Map paramMap = new HashMap<>(); + Map paramMap = new ConcurrentHashMap<>(); for (String param : params) { String[] pair = param.split("="); paramMap.put(Utils.urldecode(pair[0]), pair.length == 1 ? "" : Utils.urldecode(pair[1])); @@ -301,7 +300,7 @@ public static Map parseQueryParams(String data) { data = data.replace("?", ""); } String[] params = data.split("&"); - Map paramMap = new HashMap<>(); + Map paramMap = new ConcurrentHashMap<>(); for (String param : params) { String[] pair = param.split("="); paramMap.put(pair[0], pair[1]); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/TimedEventsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/TimedEventsTests.java index 795a0c73f..12df8e064 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/TimedEventsTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/TimedEventsTests.java @@ -1,7 +1,7 @@ package ly.count.sdk.java.internal; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Countly; import ly.count.sdk.java.Event; import org.junit.After; @@ -47,11 +47,11 @@ public void recordEventRegularFlow_base(boolean regularRecord) throws Interrupte Event tEvent = Countly.instance().timedEvent("key"); tEvent.setCount(5).setSum(133).setDuration(456); - Map segm = new HashMap<>(); + Map segm = new ConcurrentHashMap<>(); segm.put("1", "a"); segm.put("5", "b"); - Map targetSegm = new HashMap<>(); + Map targetSegm = new ConcurrentHashMap<>(); targetSegm.put("1", "a"); targetSegm.put("5", "b"); diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsTests.java index a3c83858e..d6e2bf8aa 100644 --- a/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsTests.java +++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsTests.java @@ -13,6 +13,7 @@ import java.util.EnumSet; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import ly.count.sdk.java.Config; import org.junit.Assert; import org.junit.Before; @@ -75,7 +76,7 @@ public void trimValues() { */ @Test public void fixSegmentKeysAndValues() { - Map segmentation = new HashMap<>(); + Map segmentation = new ConcurrentHashMap<>(); segmentation.put("key_10", "value1_"); segmentation.put("key_20", "value2_"); @@ -354,7 +355,7 @@ public void isValidDataType() { Assert.assertFalse(Utils.isValidDataType(null)); Assert.assertFalse(Utils.isValidDataType(new Object())); Assert.assertFalse(Utils.isValidDataType(new ArrayList<>())); - Assert.assertFalse(Utils.isValidDataType(new HashMap<>())); + Assert.assertFalse(Utils.isValidDataType(new ConcurrentHashMap<>())); } /**