Skip to content

Commit 0029f22

Browse files
tomscutomalley
authored andcommitted
HADOOP-18003. Add a method appendIfAbsent for CallerContext (#3644)
Cherry-picked from 573b358f by Owen O'Malley
1 parent f9d40ed commit 0029f22

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/CallerContext.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,26 @@ public Builder append(String key, String value) {
228228
return this;
229229
}
230230

231+
/**
232+
* Append new field which contains key and value to the context
233+
* if the key("key:") is absent.
234+
* @param key the key of field.
235+
* @param value the value of field.
236+
* @return the builder.
237+
*/
238+
public Builder appendIfAbsent(String key, String value) {
239+
if (sb.toString().contains(key + KEY_VALUE_SEPARATOR)) {
240+
return this;
241+
}
242+
if (isValid(key) && isValid(value)) {
243+
if (sb.length() > 0) {
244+
sb.append(fieldSeparator);
245+
}
246+
sb.append(key).append(KEY_VALUE_SEPARATOR).append(value);
247+
}
248+
return this;
249+
}
250+
231251
public CallerContext build() {
232252
return new CallerContext(this);
233253
}

hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/ipc/TestCallerContext.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,37 @@ public void testBuilderAppend() {
4242
builder.build().getContext());
4343
}
4444

45+
@Test
46+
public void testBuilderAppendIfAbsent() {
47+
Configuration conf = new Configuration();
48+
conf.set(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, "$");
49+
CallerContext.Builder builder = new CallerContext.Builder(null, conf);
50+
builder.append("key1", "value1");
51+
Assert.assertEquals("key1:value1",
52+
builder.build().getContext());
53+
54+
// Append an existed key with different value.
55+
builder.appendIfAbsent("key1", "value2");
56+
String[] items = builder.build().getContext().split("\\$");
57+
Assert.assertEquals(1, items.length);
58+
Assert.assertEquals("key1:value1",
59+
builder.build().getContext());
60+
61+
// Append an absent key.
62+
builder.appendIfAbsent("key2", "value2");
63+
String[] items2 = builder.build().getContext().split("\\$");
64+
Assert.assertEquals(2, items2.length);
65+
Assert.assertEquals("key1:value1$key2:value2",
66+
builder.build().getContext());
67+
68+
// Append a key that is a substring of an existing key.
69+
builder.appendIfAbsent("key", "value");
70+
String[] items3 = builder.build().getContext().split("\\$");
71+
Assert.assertEquals(3, items3.length);
72+
Assert.assertEquals("key1:value1$key2:value2$key:value",
73+
builder.build().getContext());
74+
}
75+
4576
@Test(expected = IllegalArgumentException.class)
4677
public void testNewBuilder() {
4778
Configuration conf = new Configuration();

0 commit comments

Comments
 (0)