Skip to content

Commit d090a7f

Browse files
authored
[Backport 2.x] [Refactor] Remaining Strings utility methods to core library (#9103) (#9134)
This commit refactors the remaining Strings# utility methods from the duplicate :server:Strings class to the :libs:opensearch-core:Strings class. The CollectionUtils class (used by the Strings utility) is also refactored to the :libs:opensearch-common library and the unnecessary Strings.toString(XContentBuilder... static method is finally refactored as an instance method in XContentBuilder. The Strings class is also cleaned up for clarity. Signed-off-by: Nicholas Walter Knize <nknize@apache.org> (cherry picked from commit 4c59810)
1 parent 58ca736 commit d090a7f

File tree

353 files changed

+4023
-4431
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

353 files changed

+4023
-4431
lines changed

client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
import org.opensearch.action.support.ActiveShardCount;
3939
import org.opensearch.client.TimedRequest;
4040
import org.opensearch.client.Validatable;
41-
import org.opensearch.common.Strings;
4241
import org.opensearch.core.common.bytes.BytesArray;
4342
import org.opensearch.core.common.bytes.BytesReference;
4443
import org.opensearch.common.settings.Settings;
@@ -135,7 +134,7 @@ public CreateIndexRequest settings(String source, MediaType mediaType) {
135134
* Allows to set the settings using a json builder.
136135
*/
137136
public CreateIndexRequest settings(XContentBuilder builder) {
138-
settings(Strings.toString(builder), builder.contentType());
137+
settings(builder.toString(), builder.contentType());
139138
return this;
140139
}
141140

client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@
3333
package org.opensearch.client.slm;
3434

3535
import org.opensearch.common.Nullable;
36-
import org.opensearch.common.Strings;
3736
import org.opensearch.common.xcontent.XContentType;
3837
import org.opensearch.core.ParseField;
38+
import org.opensearch.core.common.Strings;
3939
import org.opensearch.core.xcontent.ConstructingObjectParser;
4040
import org.opensearch.core.xcontent.ToXContentObject;
4141
import org.opensearch.core.xcontent.XContentBuilder;

client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@
3333
package org.opensearch.client.slm;
3434

3535
import org.opensearch.common.Nullable;
36-
import org.opensearch.common.Strings;
3736
import org.opensearch.common.xcontent.XContentType;
3837
import org.opensearch.core.ParseField;
38+
import org.opensearch.core.common.Strings;
3939
import org.opensearch.core.xcontent.ConstructingObjectParser;
4040
import org.opensearch.core.xcontent.ToXContentObject;
4141
import org.opensearch.core.xcontent.XContentBuilder;

client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@
3232

3333
package org.opensearch.client.slm;
3434

35-
import org.opensearch.common.Strings;
3635
import org.opensearch.common.unit.TimeValue;
3736
import org.opensearch.common.xcontent.XContentType;
3837
import org.opensearch.core.ParseField;
38+
import org.opensearch.core.common.Strings;
3939
import org.opensearch.core.xcontent.ConstructingObjectParser;
4040
import org.opensearch.core.xcontent.ToXContentFragment;
4141
import org.opensearch.core.xcontent.ToXContentObject;

client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@
3333
package org.opensearch.client.slm;
3434

3535
import org.opensearch.common.Nullable;
36-
import org.opensearch.common.Strings;
3736
import org.opensearch.common.unit.TimeValue;
3837
import org.opensearch.common.xcontent.XContentType;
3938
import org.opensearch.core.ParseField;
39+
import org.opensearch.core.common.Strings;
4040
import org.opensearch.core.xcontent.ConstructingObjectParser;
4141
import org.opensearch.core.xcontent.ToXContentObject;
4242
import org.opensearch.core.xcontent.XContentBuilder;

client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
import org.opensearch.action.get.MultiGetResponse;
4343
import org.opensearch.action.index.IndexRequest;
4444
import org.opensearch.action.search.SearchRequest;
45-
import org.opensearch.common.Strings;
4645
import org.opensearch.core.common.bytes.BytesArray;
4746
import org.opensearch.core.common.unit.ByteSizeUnit;
4847
import org.opensearch.core.common.unit.ByteSizeValue;
@@ -423,7 +422,7 @@ private static BytesArray bytesBulkRequest(String localIndex, int id) throws IOE
423422

424423
XContentBuilder source = jsonBuilder().startObject().field("field", randomRealisticUnicodeOfLengthBetween(1, 30)).endObject();
425424

426-
String request = Strings.toString(action) + "\n" + Strings.toString(source) + "\n";
425+
String request = action + "\n" + source + "\n";
427426
return new BytesArray(request);
428427
}
429428

client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@
5454
import org.opensearch.action.search.SearchScrollRequest;
5555
import org.opensearch.client.core.CountRequest;
5656
import org.opensearch.client.core.CountResponse;
57-
import org.opensearch.common.Strings;
5857
import org.opensearch.core.common.bytes.BytesReference;
5958
import org.opensearch.common.unit.TimeValue;
6059
import org.opensearch.core.xcontent.XContentBuilder;
@@ -769,7 +768,7 @@ public void testSearchScroll() throws Exception {
769768
for (int i = 0; i < 100; i++) {
770769
XContentBuilder builder = jsonBuilder().startObject().field("field", i).endObject();
771770
Request doc = new Request(HttpPut.METHOD_NAME, "/test/_doc/" + Integer.toString(i));
772-
doc.setJsonEntity(Strings.toString(builder));
771+
doc.setJsonEntity(builder.toString());
773772
client().performRequest(doc);
774773
}
775774
client().performRequest(new Request(HttpPost.METHOD_NAME, "/test/_refresh"));
@@ -837,7 +836,7 @@ public void testSearchWithPit() throws Exception {
837836
for (int i = 0; i < 100; i++) {
838837
XContentBuilder builder = jsonBuilder().startObject().field("field", i).endObject();
839838
Request doc = new Request(HttpPut.METHOD_NAME, "/test/_doc/" + Integer.toString(i));
840-
doc.setJsonEntity(Strings.toString(builder));
839+
doc.setJsonEntity(builder.toString());
841840
client().performRequest(doc);
842841
}
843842
client().performRequest(new Request(HttpPost.METHOD_NAME, "/test/_refresh"));

client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
import org.opensearch.client.core.TermVectorsResponse;
7575
import org.opensearch.client.indices.CreateIndexRequest;
7676
import org.opensearch.client.indices.CreateIndexResponse;
77-
import org.opensearch.common.Strings;
77+
import org.opensearch.core.common.Strings;
7878
import org.opensearch.core.common.bytes.BytesArray;
7979
import org.opensearch.common.settings.Settings;
8080
import org.opensearch.core.common.unit.ByteSizeUnit;
@@ -298,15 +298,14 @@ public void testUpdate() throws Exception {
298298

299299
Request request = new Request("POST", "/_scripts/increment-field");
300300
request.setJsonEntity(
301-
Strings.toString(
302-
JsonXContent.contentBuilder()
303-
.startObject()
304-
.startObject("script")
305-
.field("lang", "painless")
306-
.field("source", "ctx._source.field += params.count")
307-
.endObject()
308-
.endObject()
309-
)
301+
JsonXContent.contentBuilder()
302+
.startObject()
303+
.startObject("script")
304+
.field("lang", "painless")
305+
.field("source", "ctx._source.field += params.count")
306+
.endObject()
307+
.endObject()
308+
.toString()
310309
);
311310
Response response = client().performRequest(request);
312311
assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode());

distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@
3535
import org.opensearch.client.Request;
3636
import org.opensearch.client.Response;
3737
import org.opensearch.client.ResponseException;
38-
import org.opensearch.common.Strings;
3938
import org.opensearch.common.xcontent.XContentType;
39+
import org.opensearch.core.common.Strings;
4040
import org.opensearch.search.aggregations.AggregationBuilders;
4141
import org.opensearch.search.builder.SearchSourceBuilder;
4242

libs/core/src/main/java/org/opensearch/core/common/Strings.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,17 @@
99
package org.opensearch.core.common;
1010

1111
import org.apache.lucene.util.BytesRefBuilder;
12+
import org.opensearch.ExceptionsHelper;
13+
import org.opensearch.OpenSearchException;
1214
import org.opensearch.common.Nullable;
1315
import org.opensearch.core.common.bytes.BytesReference;
1416
import org.opensearch.core.common.util.CollectionUtils;
17+
import org.opensearch.core.xcontent.MediaType;
18+
import org.opensearch.core.xcontent.ToXContent;
19+
import org.opensearch.core.xcontent.XContentBuilder;
1520

1621
import java.io.BufferedReader;
22+
import java.io.IOException;
1723
import java.io.StringReader;
1824
import java.util.ArrayList;
1925
import java.util.Arrays;
@@ -680,6 +686,77 @@ public static boolean isAllOrWildcard(String data) {
680686
return "_all".equals(data) || "*".equals(data);
681687
}
682688

689+
/**
690+
* Return a {@link String} that is the json representation of the provided {@link ToXContent}.
691+
* Wraps the output into an anonymous object if needed. The content is not pretty-printed
692+
* nor human readable.
693+
*/
694+
public static String toString(MediaType mediaType, ToXContent toXContent) {
695+
return toString(mediaType, toXContent, false, false);
696+
}
697+
698+
/**
699+
* Return a {@link String} that is the json representation of the provided {@link ToXContent}.
700+
* Wraps the output into an anonymous object if needed.
701+
* Allows to configure the params.
702+
* The content is not pretty-printed nor human readable.
703+
*/
704+
public static String toString(MediaType mediaType, ToXContent toXContent, ToXContent.Params params) {
705+
return toString(mediaType, toXContent, params, false, false);
706+
}
707+
708+
/**
709+
* Return a {@link String} that is the json representation of the provided {@link ToXContent}.
710+
* Wraps the output into an anonymous object if needed. Allows to control whether the outputted
711+
* json needs to be pretty printed and human readable.
712+
*
713+
*/
714+
public static String toString(MediaType mediaType, ToXContent toXContent, boolean pretty, boolean human) {
715+
return toString(mediaType, toXContent, ToXContent.EMPTY_PARAMS, pretty, human);
716+
}
717+
718+
/**
719+
* Return a {@link String} that is the json representation of the provided {@link ToXContent}.
720+
* Wraps the output into an anonymous object if needed.
721+
* Allows to configure the params.
722+
* Allows to control whether the outputted json needs to be pretty printed and human readable.
723+
*/
724+
private static String toString(MediaType mediaType, ToXContent toXContent, ToXContent.Params params, boolean pretty, boolean human) {
725+
try {
726+
XContentBuilder builder = createBuilder(mediaType, pretty, human);
727+
if (toXContent.isFragment()) {
728+
builder.startObject();
729+
}
730+
toXContent.toXContent(builder, params);
731+
if (toXContent.isFragment()) {
732+
builder.endObject();
733+
}
734+
return builder.toString();
735+
} catch (IOException e) {
736+
try {
737+
XContentBuilder builder = createBuilder(mediaType, pretty, human);
738+
builder.startObject();
739+
builder.field("error", "error building toString out of XContent: " + e.getMessage());
740+
builder.field("stack_trace", ExceptionsHelper.stackTrace(e));
741+
builder.endObject();
742+
return builder.toString();
743+
} catch (IOException e2) {
744+
throw new OpenSearchException("cannot generate error message for deserialization", e);
745+
}
746+
}
747+
}
748+
749+
private static XContentBuilder createBuilder(MediaType mediaType, boolean pretty, boolean human) throws IOException {
750+
XContentBuilder builder = XContentBuilder.builder(mediaType.xContent());
751+
if (pretty) {
752+
builder.prettyPrint();
753+
}
754+
if (human) {
755+
builder.humanReadable(true);
756+
}
757+
return builder;
758+
}
759+
683760
/**
684761
* Truncates string to a length less than length. Backtracks to throw out
685762
* high surrogates.

libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232

3333
package org.opensearch.core.xcontent;
3434

35+
import org.opensearch.core.common.bytes.BytesReference;
36+
3537
import java.io.ByteArrayOutputStream;
3638
import java.io.Closeable;
3739
import java.io.Flushable;
@@ -151,6 +153,14 @@ public static XContentBuilder builder(XContent xContent, Set<String> includes, S
151153
DATE_TRANSFORMERS = Collections.unmodifiableMap(dateTransformers);
152154
}
153155

156+
/**
157+
* Returns a string representation of the builder (only applicable for text based xcontent).
158+
*/
159+
@Override
160+
public String toString() {
161+
return BytesReference.bytes(this).utf8ToString();
162+
}
163+
154164
/**
155165
* The writer interface for the serializable content builder
156166
*

libs/core/src/test/java/org/opensearch/core/action/support/DefaultShardOperationFailedExceptionTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
import org.apache.lucene.store.LockObtainFailedException;
4040
import org.opensearch.OpenSearchException;
4141
import org.opensearch.action.support.broadcast.BroadcastShardOperationFailedException;
42-
import org.opensearch.common.Strings;
42+
import org.opensearch.core.common.Strings;
4343
import org.opensearch.core.common.bytes.BytesReference;
4444
import org.opensearch.common.io.stream.BytesStreamOutput;
4545
import org.opensearch.core.common.io.stream.StreamInput;

libs/core/src/test/java/org/opensearch/core/common/StringsTests.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,14 @@
99
package org.opensearch.core.common;
1010

1111
import org.opensearch.common.util.set.Sets;
12+
import org.opensearch.core.xcontent.MediaTypeRegistry;
13+
import org.opensearch.core.xcontent.ToXContent;
14+
import org.opensearch.core.xcontent.ToXContentObject;
1215
import org.opensearch.test.OpenSearchTestCase;
1316

17+
import java.util.Collections;
18+
19+
import static org.hamcrest.Matchers.containsString;
1420
import static org.hamcrest.Matchers.is;
1521

1622
/** tests for Strings utility class */
@@ -63,4 +69,49 @@ public void testSplitStringToSet() {
6369
assertEquals(Strings.tokenizeByCommaToSet(" aa "), Sets.newHashSet("aa"));
6470
assertEquals(Strings.tokenizeByCommaToSet(" "), Sets.newHashSet());
6571
}
72+
73+
public void testToStringToXContent() {
74+
final ToXContent toXContent;
75+
final boolean error;
76+
if (randomBoolean()) {
77+
if (randomBoolean()) {
78+
error = false;
79+
toXContent = (builder, params) -> builder.field("ok", "here").field("catastrophe", "");
80+
} else {
81+
error = true;
82+
toXContent = (builder, params) -> builder.startObject().field("ok", "here").field("catastrophe", "").endObject();
83+
}
84+
} else {
85+
if (randomBoolean()) {
86+
error = false;
87+
toXContent = (ToXContentObject) (builder, params) -> builder.startObject()
88+
.field("ok", "here")
89+
.field("catastrophe", "")
90+
.endObject();
91+
} else {
92+
error = true;
93+
toXContent = (ToXContentObject) (builder, params) -> builder.field("ok", "here").field("catastrophe", "");
94+
}
95+
}
96+
97+
String toString = Strings.toString(MediaTypeRegistry.JSON, toXContent);
98+
if (error) {
99+
assertThat(toString, containsString("\"error\":\"error building toString out of XContent:"));
100+
assertThat(toString, containsString("\"stack_trace\":"));
101+
} else {
102+
assertThat(toString, containsString("\"ok\":\"here\""));
103+
assertThat(toString, containsString("\"catastrophe\":\"\""));
104+
}
105+
}
106+
107+
public void testToStringToXContentWithOrWithoutParams() {
108+
ToXContent toXContent = (builder, params) -> builder.field("color_from_param", params.param("color", "red"));
109+
// Rely on the default value of "color" param when params are not passed
110+
assertThat(Strings.toString(MediaTypeRegistry.JSON, toXContent), containsString("\"color_from_param\":\"red\""));
111+
// Pass "color" param explicitly
112+
assertThat(
113+
Strings.toString(MediaTypeRegistry.JSON, toXContent, new ToXContent.MapParams(Collections.singletonMap("color", "blue"))),
114+
containsString("\"color_from_param\":\"blue\"")
115+
);
116+
}
66117
}

libs/x-content/src/test/java/org/opensearch/common/xcontent/ObjectParserTests.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333

3434
import org.opensearch.common.CheckedFunction;
3535
import org.opensearch.core.ParseField;
36-
import org.opensearch.common.Strings;
3736
import org.opensearch.core.xcontent.XContentParserUtils;
3837
import org.opensearch.core.xcontent.ObjectParser;
3938
import org.opensearch.core.xcontent.ObjectParser.NamedObjectParser;
@@ -449,7 +448,7 @@ public void testAllVariants() throws IOException {
449448
}
450449
builder.field("string_or_null", nullValue ? null : "5");
451450
builder.endObject();
452-
XContentParser parser = createParser(JsonXContent.jsonXContent, Strings.toString(builder));
451+
XContentParser parser = createParser(JsonXContent.jsonXContent, builder.toString());
453452
class TestStruct {
454453
int int_field;
455454
int nullableIntField;

libs/x-content/src/test/java/org/opensearch/common/xcontent/SimpleStruct.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
package org.opensearch.common.xcontent;
3434

3535
import org.opensearch.core.ParseField;
36-
import org.opensearch.common.Strings;
36+
import org.opensearch.core.common.Strings;
3737
import org.opensearch.core.xcontent.ConstructingObjectParser;
3838
import org.opensearch.core.xcontent.ToXContentObject;
3939
import org.opensearch.core.xcontent.XContentBuilder;

0 commit comments

Comments
 (0)