Skip to content

HADOOP-18003. Add a method appendIfAbsent for CallerContext #3644

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,26 @@ public Builder append(String key, String value) {
return this;
}

/**
* Append new field which contains key and value to the context
* if the key("key:") is absent.
* @param key the key of field.
* @param value the value of field.
* @return the builder.
*/
public Builder appendIfAbsent(String key, String value) {
if (sb.toString().contains(key + KEY_VALUE_SEPARATOR)) {
return this;
}
if (isValid(key) && isValid(value)) {
if (sb.length() > 0) {
sb.append(fieldSeparator);
}
sb.append(key).append(KEY_VALUE_SEPARATOR).append(value);
}
return this;
}

public CallerContext build() {
return new CallerContext(this);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,37 @@ public void testBuilderAppend() {
builder.build().getContext());
}

@Test
public void testBuilderAppendIfAbsent() {
Configuration conf = new Configuration();
conf.set(HADOOP_CALLER_CONTEXT_SEPARATOR_KEY, "$");
CallerContext.Builder builder = new CallerContext.Builder(null, conf);
builder.append("key1", "value1");
Assert.assertEquals("key1:value1",
builder.build().getContext());

// Append an existed key with different value.
builder.appendIfAbsent("key1", "value2");
String[] items = builder.build().getContext().split("\\$");
Assert.assertEquals(1, items.length);
Assert.assertEquals("key1:value1",
builder.build().getContext());

// Append an absent key.
builder.appendIfAbsent("key2", "value2");
String[] items2 = builder.build().getContext().split("\\$");
Assert.assertEquals(2, items2.length);
Assert.assertEquals("key1:value1$key2:value2",
builder.build().getContext());

// Append a key that is a substring of an existing key.
builder.appendIfAbsent("key", "value");
String[] items3 = builder.build().getContext().split("\\$");
Assert.assertEquals(3, items3.length);
Assert.assertEquals("key1:value1$key2:value2$key:value",
builder.build().getContext());
}

@Test(expected = IllegalArgumentException.class)
public void testNewBuilder() {
Configuration conf = new Configuration();
Expand Down