Skip to content

Commit 1c006ae

Browse files
zhu-xiaoweixiaoweii
andauthored
feat: add hash code to request query parameter (#40)
Co-authored-by: xiaoweii <xiaoweii@amazom.com>
1 parent 9199c03 commit 1c006ae

File tree

8 files changed

+75
-13
lines changed

8 files changed

+75
-13
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ ext {
6565
],
6666
okhttp: 'com.squareup.okhttp3:okhttp:4.9.1',
6767
junit: 'junit:junit:4.13.2',
68-
mockito: 'org.mockito:mockito-core:3.1.0',
68+
mockito: 'org.mockito:mockito-core:4.11.0',
6969
moco: 'com.github.dreamhead:moco-core:1.4.0',
7070
robolectric: 'org.robolectric:robolectric:4.9.2',
7171
]

clickstream/src/main/java/software/aws/solution/clickstream/client/AnalyticsEvent.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,7 @@ public JSONObject toJSONObject() {
423423
final String carrier = this.deviceDetails.carrier();
424424
final String carrierString = carrier != null ? carrier : "UNKNOWN";
425425

426-
final JSONBuilder builder = new JSONBuilder(this);
426+
final JSONBuilder builder = new JSONBuilder();
427427

428428
// ****************************************************
429429
// ==================System Attributes=================

clickstream/src/main/java/software/aws/solution/clickstream/client/EventRecorder.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public Uri recordEvent(@NonNull final AnalyticsEvent event) {
9090
if (clickstreamContext.getClickstreamConfiguration() != null &&
9191
clickstreamContext.getClickstreamConfiguration().isLogEvents()) {
9292
LOG.info("save event: " + event.getEventType() + " success, event json:");
93-
LOG.info(event.toJSONObject().toString());
93+
LOG.info(event.toString());
9494
}
9595
while (this.dbUtil.getTotalSize() > DEFAULT_MAX_DB_SIZE) {
9696
try (Cursor cursor = this.dbUtil.queryOldestEvents(QUERY_OLDEST_EVENT_LIMIT)) {

clickstream/src/main/java/software/aws/solution/clickstream/client/network/NetRequest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ private static Response request(@NonNull String eventJson, @NonNull ClickstreamC
108108
HttpUrl url = request.url().newBuilder()
109109
.addQueryParameter("platform", "Android")
110110
.addQueryParameter("appId", appId)
111+
.addQueryParameter("hashCode", StringUtil.getHashCode(curStr))
111112
.addQueryParameter("event_bundle_sequence_id", String.valueOf(bundleSequenceId))
112113
.addQueryParameter("compression", compression)
113114
.build();

clickstream/src/main/java/software/aws/solution/clickstream/client/util/JSONBuilder.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,24 +32,22 @@ public class JSONBuilder implements JSONSerializable {
3232

3333
/**
3434
* The constructor of JSONBuilder with parameters.
35-
* @param component the instance of component.
35+
*
3636
*/
37-
public JSONBuilder(Object component) {
38-
if (null != component) {
39-
this.withAttribute("hashCode", Integer.toHexString(component.hashCode()));
40-
}
37+
public JSONBuilder() {
4138
}
4239

4340
/**
4441
* Get the instance of JSONBuilder with key and value.
45-
* @param key The key.
42+
*
43+
* @param key The key.
4644
* @param value The value.
4745
* @return The instance of JSONBuilder.
4846
*/
4947
public JSONBuilder withAttribute(String key, Object value) {
5048
final Object jsonValue = value instanceof JSONSerializable
51-
? ((JSONSerializable) value).toJSONObject()
52-
: value;
49+
? ((JSONSerializable) value).toJSONObject()
50+
: value;
5351
try {
5452
json.putOpt(key, jsonValue);
5553
} catch (final JSONException jsonException) {
@@ -60,6 +58,7 @@ public JSONBuilder withAttribute(String key, Object value) {
6058

6159
/**
6260
* Convert to JSON format.
61+
*
6362
* @return The JSON object.
6463
*/
6564
@Override
@@ -69,6 +68,7 @@ public JSONObject toJSONObject() {
6968

7069
/**
7170
* Convert to string.
71+
*
7272
* @return The string.
7373
*/
7474
@NonNull

clickstream/src/main/java/software/aws/solution/clickstream/client/util/StringUtil.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,17 @@
2323
import java.io.ByteArrayOutputStream;
2424
import java.io.IOException;
2525
import java.io.UnsupportedEncodingException;
26+
import java.security.MessageDigest;
27+
import java.security.NoSuchAlgorithmException;
2628
import java.util.zip.GZIPOutputStream;
2729

2830
/**
2931
* String utility methods.
3032
*/
3133
public final class StringUtil {
3234
private static final Log LOG = LogFactory.getLog(StringUtil.class);
35+
private static final int HASH_CODE_BYTE_LENGTH = 4;
36+
private static final int HASH_CODE_PREFIX = 0xFF;
3337

3438
/**
3539
* Default constructor.
@@ -134,5 +138,35 @@ public static String trimOrPadString(String str, int len, final char pad) {
134138

135139
return s.toString();
136140
}
141+
142+
/**
143+
* method for get event hash code.
144+
*
145+
* @param str event json string
146+
* @return the first 8 sha256 character of the event json
147+
*/
148+
public static String getHashCode(String str) {
149+
MessageDigest digest;
150+
try {
151+
digest = MessageDigest.getInstance("SHA-256");
152+
digest.update(str.getBytes());
153+
return bytesToHexString(digest.digest());
154+
} catch (NoSuchAlgorithmException error) {
155+
LOG.error("Failed to get sha256 for str:" + str);
156+
}
157+
return "";
158+
}
159+
160+
private static String bytesToHexString(byte[] bytes) {
161+
StringBuilder sb = new StringBuilder();
162+
for (int i = 0; i < HASH_CODE_BYTE_LENGTH; i++) {
163+
String hex = Integer.toHexString(HASH_CODE_PREFIX & bytes[i]);
164+
if (hex.length() == 1) {
165+
sb.append('0');
166+
}
167+
sb.append(hex);
168+
}
169+
return sb.toString();
170+
}
137171
}
138172

clickstream/src/test/java/software/aws/solution/clickstream/AnalyticsEventTest.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,11 @@ public static AnalyticsClient getAnalyticsClient() {
6262

6363
/**
6464
* test the analyticsClient with createEvent.
65+
*
66+
* @throws JSONException the json exception
6567
*/
6668
@Test
67-
public void createEvent() {
69+
public void createEvent() throws JSONException {
6870
AnalyticsEvent event = analyticsClient.createEvent("testEvent");
6971
Assert.assertNotNull(event.getEventId());
7072
Assert.assertEquals(event.getEventType(), "testEvent");

clickstream/src/test/java/software/aws/solution/clickstream/EventRecorderTest.java

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
import software.aws.solution.clickstream.client.Event;
4343
import software.aws.solution.clickstream.client.EventRecorder;
4444
import software.aws.solution.clickstream.client.db.ClickstreamDBUtil;
45+
import software.aws.solution.clickstream.client.network.NetRequest;
46+
import software.aws.solution.clickstream.client.util.StringUtil;
4547
import software.aws.solution.clickstream.util.ReflectUtil;
4648

4749
import java.lang.reflect.Method;
@@ -50,8 +52,11 @@
5052
import java.util.concurrent.ThreadPoolExecutor;
5153
import java.util.concurrent.TimeUnit;
5254

55+
import static com.github.dreamhead.moco.Moco.and;
5356
import static com.github.dreamhead.moco.Moco.by;
57+
import static com.github.dreamhead.moco.Moco.eq;
5458
import static com.github.dreamhead.moco.Moco.httpServer;
59+
import static com.github.dreamhead.moco.Moco.query;
5560
import static com.github.dreamhead.moco.Moco.status;
5661
import static com.github.dreamhead.moco.Moco.text;
5762
import static com.github.dreamhead.moco.Moco.uri;
@@ -70,8 +75,10 @@
7075
public class EventRecorderTest {
7176
private static final String COLLECT_SUCCESS = "/collect/success";
7277
private static final String COLLECT_FAIL = "/collect/fail";
78+
private static final String COLLECT_FOR_VERIFY_HASH_CODE = "/collect/hashcode";
7379
private static Runner runner;
7480
private static String jsonString;
81+
private static HttpServer server;
7582

7683
private ClickstreamDBUtil dbUtil;
7784
private EventRecorder eventRecorder;
@@ -87,7 +94,7 @@ public class EventRecorderTest {
8794
@BeforeClass
8895
public static void beforeClass() {
8996
//config and start server
90-
final HttpServer server = httpServer(8082);
97+
server = httpServer(8082);
9198
server.request(by(uri(COLLECT_SUCCESS))).response(status(200), text("success"));
9299
server.request(by(uri(COLLECT_FAIL))).response(status(403), text("fail"));
93100
runner = runner(server);
@@ -164,6 +171,7 @@ public void testRecordEventForReachedMaxDbSize() throws Exception {
164171

165172
/**
166173
* test insert single event when exceed attribute number limit.
174+
*
167175
* @throws JSONException the json exception
168176
*/
169177
@Test
@@ -528,6 +536,23 @@ public void testSubmitAllEventForReachTheQueueLimit() throws Exception {
528536
assertEquals(1001, ((ThreadPoolExecutor) executorService).getTaskCount());
529537
}
530538

539+
/**
540+
* test record event with request parameter hash code.
541+
*
542+
* @throws Exception exception.
543+
*/
544+
@Test
545+
public void testRecordEventRequestWithHashCode() throws Exception {
546+
clickstreamContext.getClickstreamConfiguration().withCompressEvents(false);
547+
setRequestPath(COLLECT_FOR_VERIFY_HASH_CODE);
548+
String eventJson = "[" + event.toJSONObject().toString() + "]";
549+
String eventHashCode = StringUtil.getHashCode(eventJson);
550+
server.request(and(by(uri(COLLECT_FOR_VERIFY_HASH_CODE)), eq(query("hashCode"), eventHashCode)))
551+
.response(status(200), text("success"));
552+
boolean requestResult = NetRequest.uploadEvents(eventJson, clickstreamContext.getClickstreamConfiguration(), 1);
553+
assertTrue(requestResult);
554+
}
555+
531556
/**
532557
* common method to set request path.
533558
*

0 commit comments

Comments
 (0)