language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | google__guava | guava-tests/test/com/google/common/graph/ValueGraphTest.java | {
"start": 1573,
"end": 21184
} | class ____ {
private static final String DEFAULT = "default";
MutableValueGraph<Integer, String> graph;
@After
public void validateGraphState() {
assertStronglyEquivalent(graph, Graphs.copyOf(graph));
assertStronglyEquivalent(graph, ImmutableValueGraph.copyOf(graph));
Graph<Integer> asGraph = graph.asGraph();
AbstractGraphTest.validateGraph(asGraph);
assertThat(graph.nodes()).isEqualTo(asGraph.nodes());
assertThat(graph.edges()).isEqualTo(asGraph.edges());
assertThat(graph.nodeOrder()).isEqualTo(asGraph.nodeOrder());
assertThat(graph.incidentEdgeOrder()).isEqualTo(asGraph.incidentEdgeOrder());
assertThat(graph.isDirected()).isEqualTo(asGraph.isDirected());
assertThat(graph.allowsSelfLoops()).isEqualTo(asGraph.allowsSelfLoops());
Network<Integer, EndpointPair<Integer>> asNetwork = graph.asNetwork();
AbstractNetworkTest.validateNetwork(asNetwork);
assertThat(graph.nodes()).isEqualTo(asNetwork.nodes());
assertThat(graph.edges()).hasSize(asNetwork.edges().size());
assertThat(graph.nodeOrder()).isEqualTo(asNetwork.nodeOrder());
assertThat(graph.isDirected()).isEqualTo(asNetwork.isDirected());
assertThat(graph.allowsSelfLoops()).isEqualTo(asNetwork.allowsSelfLoops());
assertThat(asNetwork.edgeOrder()).isEqualTo(ElementOrder.unordered());
assertThat(asNetwork.allowsParallelEdges()).isFalse();
assertThat(asNetwork.asGraph()).isEqualTo(graph.asGraph());
for (Integer node : graph.nodes()) {
assertThat(graph.adjacentNodes(node)).isEqualTo(asGraph.adjacentNodes(node));
assertThat(graph.predecessors(node)).isEqualTo(asGraph.predecessors(node));
assertThat(graph.successors(node)).isEqualTo(asGraph.successors(node));
assertThat(graph.degree(node)).isEqualTo(asGraph.degree(node));
assertThat(graph.inDegree(node)).isEqualTo(asGraph.inDegree(node));
assertThat(graph.outDegree(node)).isEqualTo(asGraph.outDegree(node));
for (Integer otherNode : graph.nodes()) {
boolean hasEdge = graph.hasEdgeConnecting(node, otherNode);
assertThat(hasEdge).isEqualTo(asGraph.hasEdgeConnecting(node, otherNode));
assertThat(graph.edgeValueOrDefault(node, otherNode, null) != null).isEqualTo(hasEdge);
assertThat(!graph.edgeValueOrDefault(node, otherNode, DEFAULT).equals(DEFAULT))
.isEqualTo(hasEdge);
}
}
}
@Test
public void directedGraph() {
graph = ValueGraphBuilder.directed().allowsSelfLoops(true).build();
graph.putEdgeValue(1, 2, "valueA");
graph.putEdgeValue(2, 1, "valueB");
graph.putEdgeValue(2, 3, "valueC");
graph.putEdgeValue(4, 4, "valueD");
assertThat(graph.edgeValueOrDefault(1, 2, null)).isEqualTo("valueA");
assertThat(graph.edgeValueOrDefault(2, 1, null)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(2, 3, null)).isEqualTo("valueC");
assertThat(graph.edgeValueOrDefault(4, 4, null)).isEqualTo("valueD");
assertThat(graph.edgeValueOrDefault(1, 2, DEFAULT)).isEqualTo("valueA");
assertThat(graph.edgeValueOrDefault(2, 1, DEFAULT)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(2, 3, DEFAULT)).isEqualTo("valueC");
assertThat(graph.edgeValueOrDefault(4, 4, DEFAULT)).isEqualTo("valueD");
String toString = graph.toString();
assertThat(toString).contains("valueA");
assertThat(toString).contains("valueB");
assertThat(toString).contains("valueC");
assertThat(toString).contains("valueD");
}
@Test
public void undirectedGraph() {
graph = ValueGraphBuilder.undirected().allowsSelfLoops(true).build();
graph.putEdgeValue(1, 2, "valueA");
graph.putEdgeValue(2, 1, "valueB"); // overwrites valueA in undirected case
graph.putEdgeValue(2, 3, "valueC");
graph.putEdgeValue(4, 4, "valueD");
assertThat(graph.edgeValueOrDefault(1, 2, null)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(2, 1, null)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(2, 3, null)).isEqualTo("valueC");
assertThat(graph.edgeValueOrDefault(4, 4, null)).isEqualTo("valueD");
assertThat(graph.edgeValueOrDefault(1, 2, DEFAULT)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(2, 1, DEFAULT)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(2, 3, DEFAULT)).isEqualTo("valueC");
assertThat(graph.edgeValueOrDefault(4, 4, DEFAULT)).isEqualTo("valueD");
String toString = graph.toString();
assertThat(toString).doesNotContain("valueA");
assertThat(toString).contains("valueB");
assertThat(toString).contains("valueC");
assertThat(toString).contains("valueD");
}
@Test
public void incidentEdgeOrder_unordered() {
graph = ValueGraphBuilder.directed().incidentEdgeOrder(ElementOrder.unordered()).build();
assertThat(graph.incidentEdgeOrder()).isEqualTo(ElementOrder.unordered());
}
@Test
public void incidentEdgeOrder_stable() {
graph = ValueGraphBuilder.directed().incidentEdgeOrder(ElementOrder.stable()).build();
assertThat(graph.incidentEdgeOrder()).isEqualTo(ElementOrder.stable());
}
@Test
public void hasEdgeConnecting_directed_correct() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(1, 2))).isTrue();
}
@Test
public void hasEdgeConnecting_directed_backwards() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(2, 1))).isFalse();
}
@Test
public void hasEdgeConnecting_directed_mismatch() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.hasEdgeConnecting(EndpointPair.unordered(1, 2))).isFalse();
assertThat(graph.hasEdgeConnecting(EndpointPair.unordered(2, 1))).isFalse();
}
@Test
public void hasEdgeConnecting_undirected_correct() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.hasEdgeConnecting(EndpointPair.unordered(1, 2))).isTrue();
}
@Test
public void hasEdgeConnecting_undirected_backwards() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.hasEdgeConnecting(EndpointPair.unordered(2, 1))).isTrue();
}
@Test
public void hasEdgeConnecting_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(1, 2))).isFalse();
assertThat(graph.hasEdgeConnecting(EndpointPair.ordered(2, 1))).isFalse();
}
@Test
public void edgeValue_directed_correct() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValue(EndpointPair.ordered(1, 2))).hasValue("A");
}
@Test
public void edgeValue_directed_backwards() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValue(EndpointPair.ordered(2, 1))).isEmpty();
}
@Test
public void edgeValue_directed_mismatch() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class, () -> graph.edgeValue(EndpointPair.unordered(1, 2)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
e =
assertThrows(
IllegalArgumentException.class, () -> graph.edgeValue(EndpointPair.unordered(2, 1)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void edgeValue_undirected_correct() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValue(EndpointPair.unordered(1, 2))).hasValue("A");
}
@Test
public void edgeValue_undirected_backwards() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValue(EndpointPair.unordered(2, 1))).hasValue("A");
}
@Test
public void edgeValue_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
// Check that edgeValue() throws on each possible ordering of an ordered EndpointPair
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class, () -> graph.edgeValue(EndpointPair.ordered(1, 2)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
e =
assertThrows(
IllegalArgumentException.class, () -> graph.edgeValue(EndpointPair.ordered(2, 1)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void edgeValueOrDefault_directed_correct() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValueOrDefault(EndpointPair.ordered(1, 2), "default")).isEqualTo("A");
}
@Test
public void edgeValueOrDefault_directed_backwards() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default"))
.isEqualTo("default");
}
@Test
public void edgeValueOrDefault_directed_mismatch() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> graph.edgeValueOrDefault(EndpointPair.unordered(1, 2), "default"));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
e =
assertThrows(
IllegalArgumentException.class,
() -> graph.edgeValueOrDefault(EndpointPair.unordered(2, 1), "default"));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void edgeValueOrDefault_undirected_correct() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValueOrDefault(EndpointPair.unordered(1, 2), "default")).isEqualTo("A");
}
@Test
public void edgeValueOrDefault_undirected_backwards() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
assertThat(graph.edgeValueOrDefault(EndpointPair.unordered(2, 1), "default")).isEqualTo("A");
}
@Test
public void edgeValueOrDefault_undirected_mismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "A");
// Check that edgeValueOrDefault() throws on each possible ordering of an ordered EndpointPair
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> graph.edgeValueOrDefault(EndpointPair.ordered(1, 2), "default"));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
e =
assertThrows(
IllegalArgumentException.class,
() -> graph.edgeValueOrDefault(EndpointPair.ordered(2, 1), "default"));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void putEdgeValue_directed() {
graph = ValueGraphBuilder.directed().build();
assertThat(graph.putEdgeValue(1, 2, "valueA")).isNull();
assertThat(graph.putEdgeValue(2, 1, "valueB")).isNull();
assertThat(graph.putEdgeValue(1, 2, "valueC")).isEqualTo("valueA");
assertThat(graph.putEdgeValue(2, 1, "valueD")).isEqualTo("valueB");
}
@Test
public void putEdgeValue_directed_orderMismatch() {
graph = ValueGraphBuilder.directed().build();
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> graph.putEdgeValue(EndpointPair.unordered(1, 2), "irrelevant"));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void putEdgeValue_undirected_orderMismatch() {
graph = ValueGraphBuilder.undirected().build();
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class,
() -> graph.putEdgeValue(EndpointPair.ordered(1, 2), "irrelevant"));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void putEdgeValue_undirected() {
graph = ValueGraphBuilder.undirected().build();
assertThat(graph.putEdgeValue(1, 2, "valueA")).isNull();
assertThat(graph.putEdgeValue(2, 1, "valueB")).isEqualTo("valueA");
assertThat(graph.putEdgeValue(1, 2, "valueC")).isEqualTo("valueB");
assertThat(graph.putEdgeValue(2, 1, "valueD")).isEqualTo("valueC");
}
@Test
public void removeEdge_directed() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "valueA");
graph.putEdgeValue(2, 1, "valueB");
graph.putEdgeValue(2, 3, "valueC");
assertThat(graph.removeEdge(1, 2)).isEqualTo("valueA");
assertThat(graph.removeEdge(1, 2)).isNull();
assertThat(graph.removeEdge(2, 1)).isEqualTo("valueB");
assertThat(graph.removeEdge(2, 1)).isNull();
assertThat(graph.removeEdge(2, 3)).isEqualTo("valueC");
assertThat(graph.removeEdge(2, 3)).isNull();
}
@Test
public void removeEdge_undirected() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "valueA");
graph.putEdgeValue(2, 1, "valueB");
graph.putEdgeValue(2, 3, "valueC");
assertThat(graph.removeEdge(1, 2)).isEqualTo("valueB");
assertThat(graph.removeEdge(1, 2)).isNull();
assertThat(graph.removeEdge(2, 1)).isNull();
assertThat(graph.removeEdge(2, 3)).isEqualTo("valueC");
assertThat(graph.removeEdge(2, 3)).isNull();
}
@Test
public void removeEdge_directed_orderMismatch() {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "1->2");
graph.putEdgeValue(2, 1, "2->1");
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class, () -> graph.removeEdge(EndpointPair.unordered(1, 2)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
e =
assertThrows(
IllegalArgumentException.class, () -> graph.removeEdge(EndpointPair.unordered(2, 1)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void removeEdge_undirected_orderMismatch() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "1-2");
// Check that removeEdge() throws on each possible ordering of an ordered EndpointPair
IllegalArgumentException e =
assertThrows(
IllegalArgumentException.class, () -> graph.removeEdge(EndpointPair.ordered(1, 2)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
e =
assertThrows(
IllegalArgumentException.class, () -> graph.removeEdge(EndpointPair.ordered(2, 1)));
assertThat(e).hasMessageThat().contains(ENDPOINTS_MISMATCH);
}
@Test
public void edgeValue_missing() {
graph = ValueGraphBuilder.directed().build();
assertThat(graph.edgeValueOrDefault(1, 2, DEFAULT)).isEqualTo(DEFAULT);
assertThat(graph.edgeValueOrDefault(2, 1, DEFAULT)).isEqualTo(DEFAULT);
assertThat(graph.edgeValue(1, 2).orElse(DEFAULT)).isEqualTo(DEFAULT);
assertThat(graph.edgeValue(2, 1).orElse(DEFAULT)).isEqualTo(DEFAULT);
assertThat(graph.edgeValueOrDefault(1, 2, null)).isNull();
assertThat(graph.edgeValueOrDefault(2, 1, null)).isNull();
assertThat(graph.edgeValue(1, 2).orElse(null)).isNull();
assertThat(graph.edgeValue(2, 1).orElse(null)).isNull();
graph.putEdgeValue(1, 2, "valueA");
graph.putEdgeValue(2, 1, "valueB");
assertThat(graph.edgeValueOrDefault(1, 2, DEFAULT)).isEqualTo("valueA");
assertThat(graph.edgeValueOrDefault(2, 1, DEFAULT)).isEqualTo("valueB");
assertThat(graph.edgeValueOrDefault(1, 2, null)).isEqualTo("valueA");
assertThat(graph.edgeValueOrDefault(2, 1, null)).isEqualTo("valueB");
assertThat(graph.edgeValue(1, 2)).hasValue("valueA");
assertThat(graph.edgeValue(2, 1)).hasValue("valueB");
graph.removeEdge(1, 2);
graph.putEdgeValue(2, 1, "valueC");
assertThat(graph.edgeValueOrDefault(1, 2, DEFAULT)).isEqualTo(DEFAULT);
assertThat(graph.edgeValueOrDefault(2, 1, DEFAULT)).isEqualTo("valueC");
assertThat(graph.edgeValue(1, 2).orElse(DEFAULT)).isEqualTo(DEFAULT);
assertThat(graph.edgeValueOrDefault(1, 2, null)).isNull();
assertThat(graph.edgeValueOrDefault(2, 1, null)).isEqualTo("valueC");
assertThat(graph.edgeValue(1, 2).orElse(null)).isNull();
assertThat(graph.edgeValue(2, 1)).hasValue("valueC");
}
@Test
public void equivalence_considersEdgeValue() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(1, 2, "valueA");
MutableValueGraph<Integer, String> otherGraph = ValueGraphBuilder.undirected().build();
otherGraph.putEdgeValue(1, 2, "valueA");
assertThat(graph).isEqualTo(otherGraph);
otherGraph.putEdgeValue(1, 2, "valueB");
assertThat(graph).isNotEqualTo(otherGraph); // values differ
}
@Test
public void incidentEdges_stableIncidentEdgeOrder_preservesIncidentEdgesOrder_directed() {
graph = ValueGraphBuilder.directed().incidentEdgeOrder(ElementOrder.stable()).build();
graph.putEdgeValue(2, 1, "2-1");
graph.putEdgeValue(2, 3, "2-3");
graph.putEdgeValue(1, 2, "1-2");
assertThat(graph.incidentEdges(2))
.containsExactly(
EndpointPair.ordered(2, 1), EndpointPair.ordered(2, 3), EndpointPair.ordered(1, 2))
.inOrder();
}
@Test
public void incidentEdges_stableIncidentEdgeOrder_preservesIncidentEdgesOrder_undirected() {
graph = ValueGraphBuilder.undirected().incidentEdgeOrder(ElementOrder.stable()).build();
graph.putEdgeValue(2, 3, "2-3");
graph.putEdgeValue(2, 1, "2-1");
graph.putEdgeValue(2, 4, "2-4");
graph.putEdgeValue(1, 2, "1-2"); // Duplicate nodes, different value
assertThat(graph.incidentEdges(2))
.containsExactly(
EndpointPair.unordered(2, 3),
EndpointPair.unordered(1, 2),
EndpointPair.unordered(2, 4))
.inOrder();
}
@Test
public void concurrentIteration() throws Exception {
graph = ValueGraphBuilder.directed().build();
graph.putEdgeValue(1, 2, "A");
graph.putEdgeValue(3, 4, "B");
graph.putEdgeValue(5, 6, "C");
int threadCount = 20;
ExecutorService executor = newFixedThreadPool(threadCount);
CyclicBarrier barrier = new CyclicBarrier(threadCount);
ImmutableList.Builder<Future<?>> futures = ImmutableList.builder();
for (int i = 0; i < threadCount; i++) {
futures.add(
executor.submit(
new Callable<@Nullable Void>() {
@Override
public @Nullable Void call() throws Exception {
barrier.await();
Integer first = graph.nodes().iterator().next();
for (Integer node : graph.nodes()) {
Set<Integer> unused = graph.successors(node);
}
/*
* Also look up an earlier node so that, if the graph is using MapRetrievalCache,
* we read one of the fields declared in that class.
*/
Set<Integer> unused = graph.successors(first);
return null;
}
}));
}
// For more about this test, see the equivalent in AbstractNetworkTest.
for (Future<?> future : futures.build()) {
future.get();
}
executor.shutdown();
}
}
| ValueGraphTest |
java | google__dagger | javatests/dagger/hilt/android/testing/testinstallin/TestInstallInBarTest.java | {
"start": 1918,
"end": 2069
} | class ____ {
@Rule public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
@Module
@InstallIn(SingletonComponent.class)
| TestInstallInBarTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/settings/ClusterGetSettingsAction.java | {
"start": 2691,
"end": 4743
} | class ____ extends ActionResponse {
private final Settings persistentSettings;
private final Settings transientSettings;
private final Settings settings;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Response response = (Response) o;
return Objects.equals(persistentSettings, response.persistentSettings)
&& Objects.equals(transientSettings, response.transientSettings)
&& Objects.equals(settings, response.settings);
}
@Override
public int hashCode() {
return Objects.hash(persistentSettings, transientSettings, settings);
}
public Response(Settings persistentSettings, Settings transientSettings, Settings settings) {
this.persistentSettings = Objects.requireNonNullElse(persistentSettings, Settings.EMPTY);
this.transientSettings = Objects.requireNonNullElse(transientSettings, Settings.EMPTY);
this.settings = Objects.requireNonNullElse(settings, Settings.EMPTY);
}
/**
* NB prior to 9.0 get-component was a TransportMasterNodeReadAction so for BwC we must remain able to write these responses until
* we no longer need to support calling this action remotely.
*/
@UpdateForV10(owner = UpdateForV10.Owner.CORE_INFRA)
@Override
public void writeTo(StreamOutput out) throws IOException {
assert out.getTransportVersion().onOrAfter(TransportVersions.V_8_3_0);
persistentSettings.writeTo(out);
transientSettings.writeTo(out);
settings.writeTo(out);
}
public Settings persistentSettings() {
return persistentSettings;
}
public Settings transientSettings() {
return transientSettings;
}
public Settings settings() {
return settings;
}
}
}
| Response |
java | google__dagger | javatests/dagger/internal/codegen/ModuleValidationTest.java | {
"start": 7267,
"end": 8106
} | interface ____ {",
" Sub create();",
" }",
"}");
CompilerTests.daggerCompiler(module, subcomponent)
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"test.Sub.Factory is a @ProductionSubcomponent.Factory. "
+ "Did you mean to use test.Sub?")
.onSource(module)
.onLine(5);
});
}
@Test
public void moduleSubcomponents_noSubcomponentCreator() {
Source module =
CompilerTests.javaSource(
"test.TestModule",
"package test;",
"",
moduleType.importStatement(),
"",
moduleType.annotationWithSubcomponent("NoBuilder.class"),
" | Factory |
java | apache__dubbo | dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/collector/MetricsCollector.java | {
"start": 1257,
"end": 1843
} | interface ____<E extends TimeCounterEvent> extends MetricsLifeListener<E> {
default boolean isCollectEnabled() {
return false;
}
/**
* Collect metrics as {@link MetricSample}
*
* @return List of MetricSample
*/
List<MetricSample> collect();
/**
* Check if samples have been changed.
* Note that this method will reset the changed flag to false using CAS.
*
* @return true if samples have been changed
*/
boolean calSamplesChanged();
default void initMetrics(MetricsEvent event) {}
;
}
| MetricsCollector |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/log/TestLogLevel.java | {
"start": 12051,
"end": 16024
} | class ____ debug.
*
* @param protocol specify either http or https
* @param authority daemon's web UI address
* @throws Exception if unable to run or log level does not change as expected
*/
private void setLevel(String protocol, String authority, String newLevel)
throws Exception {
String[] setLevelArgs = {"-setlevel", authority, logName,
newLevel, "-protocol", protocol};
CLI cli = new CLI(sslConf);
cli.run(setLevelArgs);
assertEquals(newLevel.toUpperCase(), log.getEffectiveLevel().toString(),
"new level not equal to expected: ");
}
/**
* Test setting log level to "Info".
*
* @throws Exception
*/
@Test
@Timeout(value = 60)
public void testInfoLogLevel() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, false,
"Info");
}
/**
* Test setting log level to "Error".
*
* @throws Exception
*/
@Test
@Timeout(value = 60)
public void testErrorLogLevel() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, false,
"Error");
}
/**
* Server runs HTTP, no SPNEGO.
*
* @throws Exception
*/
@Test
@Timeout(value = 60)
public void testLogLevelByHttp() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, false);
try {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTPS,
false);
fail("A HTTPS Client should not have succeeded in connecting to a " +
"HTTP server");
} catch (SSLException e) {
GenericTestUtils.assertExceptionContains("Error while authenticating "
+ "with endpoint", e);
GenericTestUtils.assertExceptionContains("recognized SSL message", e
.getCause());
}
}
/**
* Server runs HTTP + SPNEGO.
*
* @throws Exception
*/
@Test
@Timeout(value = 60)
public void testLogLevelByHttpWithSpnego() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTP, true);
try {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTP, LogLevel.PROTOCOL_HTTPS,
true);
fail("A HTTPS Client should not have succeeded in connecting to a " +
"HTTP server");
} catch (SSLException e) {
GenericTestUtils.assertExceptionContains("Error while authenticating "
+ "with endpoint", e);
GenericTestUtils.assertExceptionContains("recognized SSL message", e
.getCause());
}
}
/**
* Server runs HTTPS, no SPNEGO.
*
* @throws Exception
*/
@Test
@Timeout(value = 60)
public void testLogLevelByHttps() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTPS,
false);
try {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTP,
false);
fail("A HTTP Client should not have succeeded in connecting to a " +
"HTTPS server");
} catch (SocketException e) {
GenericTestUtils.assertExceptionContains("Error while authenticating "
+ "with endpoint", e);
GenericTestUtils.assertExceptionContains(
"Unexpected end of file from server", e.getCause());
}
}
/**
* Server runs HTTPS + SPNEGO.
*
* @throws Exception
*/
@Test
@Timeout(value = 60)
public void testLogLevelByHttpsWithSpnego() throws Exception {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTPS,
true);
try {
testDynamicLogLevel(LogLevel.PROTOCOL_HTTPS, LogLevel.PROTOCOL_HTTP,
true);
fail("A HTTP Client should not have succeeded in connecting to a " +
"HTTPS server");
} catch (SocketException e) {
GenericTestUtils.assertExceptionContains("Error while authenticating "
+ "with endpoint", e);
GenericTestUtils.assertExceptionContains(
"Unexpected end of file from server", e.getCause());
}
}
} | to |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/JUnitIncompatibleTypeTest.java | {
"start": 3257,
"end": 3663
} | class ____ {
public void test() {
assertArrayEquals(new long[] {1L}, new long[] {2L});
}
}
""")
.doTest();
}
@Test
public void assertArrayEquals_cast() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import static org.junit.Assert.assertArrayEquals;
final | Test |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/ContextLoaderUtilsContextHierarchyTests.java | {
"start": 22028,
"end": 22329
} | class ____ extends
TestClass2WithMultiLevelContextHierarchyAndUnnamedConfig {
}
@ContextHierarchy({//
//
@ContextConfiguration(locations = "1-A.xml", name = "parent"),//
@ContextConfiguration(locations = "1-B.xml") //
})
private static | TestClass3WithMultiLevelContextHierarchyAndUnnamedConfig |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/instant/InstantAssert_isInThePast_Test.java | {
"start": 1046,
"end": 1720
} | class ____ extends InstantAssertBaseTest {
@Test
void should_pass_if_actual_is_in_the_past() {
assertThat(BEFORE).isInThePast();
}
@Test
void should_fail_if_actual_is_in_the_future() {
// WHEN
var assertionError = expectAssertionError(() -> assertThat(AFTER).isInThePast());
// THEN
then(assertionError).hasMessage(shouldBeInThePast(AFTER).create());
}
@Test
void should_fail_if_actual_is_null() {
// GIVEN
Instant actual = null;
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).isInThePast());
// THEN
then(assertionError).hasMessage(actualIsNull());
}
}
| InstantAssert_isInThePast_Test |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/FetchSessionHandler.java | {
"start": 2336,
"end": 2399
} | class ____ the receiving broker side is FetchManager.
*/
public | on |
java | spring-projects__spring-boot | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/shell/ShellCommand.java | {
"start": 978,
"end": 1215
} | class ____ extends AbstractCommand {
public ShellCommand() {
super("shell", "Start a nested shell");
}
@Override
public ExitStatus run(String... args) throws Exception {
new Shell().run();
return ExitStatus.OK;
}
}
| ShellCommand |
java | google__guava | guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ForwardingSortedMultiset.java | {
"start": 3927,
"end": 8231
} | class ____ extends DescendingMultiset<E> {
/** Constructor for use by subclasses. */
public StandardDescendingMultiset() {}
@Override
SortedMultiset<E> forwardMultiset() {
return ForwardingSortedMultiset.this;
}
}
@Override
public @Nullable Entry<E> firstEntry() {
return delegate().firstEntry();
}
/**
* A sensible definition of {@link #firstEntry()} in terms of {@code entrySet().iterator()}.
*
* <p>If you override {@link #entrySet()}, you may wish to override {@link #firstEntry()} to
* forward to this implementation.
*/
protected @Nullable Entry<E> standardFirstEntry() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
return Multisets.immutableEntry(entry.getElement(), entry.getCount());
}
@Override
public @Nullable Entry<E> lastEntry() {
return delegate().lastEntry();
}
/**
* A sensible definition of {@link #lastEntry()} in terms of {@code
* descendingMultiset().entrySet().iterator()}.
*
* <p>If you override {@link #descendingMultiset} or {@link #entrySet()}, you may wish to override
* {@link #firstEntry()} to forward to this implementation.
*/
protected @Nullable Entry<E> standardLastEntry() {
Iterator<Entry<E>> entryIterator = descendingMultiset().entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
return Multisets.immutableEntry(entry.getElement(), entry.getCount());
}
@Override
public @Nullable Entry<E> pollFirstEntry() {
return delegate().pollFirstEntry();
}
/**
* A sensible definition of {@link #pollFirstEntry()} in terms of {@code entrySet().iterator()}.
*
* <p>If you override {@link #entrySet()}, you may wish to override {@link #pollFirstEntry()} to
* forward to this implementation.
*/
protected @Nullable Entry<E> standardPollFirstEntry() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
entry = Multisets.immutableEntry(entry.getElement(), entry.getCount());
entryIterator.remove();
return entry;
}
@Override
public @Nullable Entry<E> pollLastEntry() {
return delegate().pollLastEntry();
}
/**
* A sensible definition of {@link #pollLastEntry()} in terms of {@code
* descendingMultiset().entrySet().iterator()}.
*
* <p>If you override {@link #descendingMultiset()} or {@link #entrySet()}, you may wish to
* override {@link #pollLastEntry()} to forward to this implementation.
*/
protected @Nullable Entry<E> standardPollLastEntry() {
Iterator<Entry<E>> entryIterator = descendingMultiset().entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
entry = Multisets.immutableEntry(entry.getElement(), entry.getCount());
entryIterator.remove();
return entry;
}
@Override
public SortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
return delegate().headMultiset(upperBound, boundType);
}
@Override
public SortedMultiset<E> subMultiset(
E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) {
return delegate().subMultiset(lowerBound, lowerBoundType, upperBound, upperBoundType);
}
/**
* A sensible definition of {@link #subMultiset(Object, BoundType, Object, BoundType)} in terms of
* {@link #headMultiset(Object, BoundType) headMultiset} and {@link #tailMultiset(Object,
* BoundType) tailMultiset}.
*
* <p>If you override either of these methods, you may wish to override {@link
* #subMultiset(Object, BoundType, Object, BoundType)} to forward to this implementation.
*/
protected SortedMultiset<E> standardSubMultiset(
E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) {
return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType);
}
@Override
public SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
return delegate().tailMultiset(lowerBound, boundType);
}
}
| StandardDescendingMultiset |
java | google__gson | gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java | {
"start": 12758,
"end": 16975
} | class ____ allowed
if (raw != originalRaw && fields.length > 0) {
FilterResult filterResult =
ReflectionAccessFilterHelper.getFilterResult(reflectionFilters, raw);
if (filterResult == FilterResult.BLOCK_ALL) {
throw new JsonIOException(
"ReflectionAccessFilter does not permit using reflection for "
+ raw
+ " (supertype of "
+ originalRaw
+ "). Register a TypeAdapter for this type or adjust the access filter.");
}
blockInaccessible = filterResult == FilterResult.BLOCK_INACCESSIBLE;
}
for (Field field : fields) {
boolean serialize = includeField(field, true);
boolean deserialize = includeField(field, false);
if (!serialize && !deserialize) {
continue;
}
// The accessor method is only used for records. If the type is a record, we will read out
// values via its accessor method instead of via reflection. This way we will bypass the
// accessible restrictions
Method accessor = null;
if (isRecord) {
// If there is a static field on a record, there will not be an accessor. Instead we will
// use the default field serialization logic, but for deserialization the field is
// excluded for simplicity.
// Note that Gson ignores static fields by default, but
// GsonBuilder.excludeFieldsWithModifiers can overwrite this.
if (Modifier.isStatic(field.getModifiers())) {
deserialize = false;
} else {
accessor = ReflectionHelper.getAccessor(raw, field);
// If blockInaccessible, skip and perform access check later
if (!blockInaccessible) {
ReflectionHelper.makeAccessible(accessor);
}
// @SerializedName can be placed on accessor method, but it is not supported there
// If field and method have annotation it is not easily possible to determine if
// accessor method is implicit and has inherited annotation, or if it is explicitly
// declared with custom annotation
if (accessor.getAnnotation(SerializedName.class) != null
&& field.getAnnotation(SerializedName.class) == null) {
String methodDescription =
ReflectionHelper.getAccessibleObjectDescription(accessor, false);
throw new JsonIOException(
"@SerializedName on " + methodDescription + " is not supported");
}
}
}
// If blockInaccessible, skip and perform access check later
// For Records if the accessor method is used the field does not have to be made accessible
if (!blockInaccessible && accessor == null) {
ReflectionHelper.makeAccessible(field);
}
Type fieldType = GsonTypes.resolve(type.getType(), raw, field.getGenericType());
List<String> fieldNames = getFieldNames(field);
String serializedName = fieldNames.get(0);
BoundField boundField =
createBoundField(
context,
field,
accessor,
serializedName,
TypeToken.get(fieldType),
serialize,
blockInaccessible);
if (deserialize) {
for (String name : fieldNames) {
BoundField replaced = deserializedFields.put(name, boundField);
if (replaced != null) {
throw createDuplicateFieldException(originalRaw, name, replaced.field, field);
}
}
}
if (serialize) {
BoundField replaced = serializedFields.put(serializedName, boundField);
if (replaced != null) {
throw createDuplicateFieldException(originalRaw, serializedName, replaced.field, field);
}
}
}
type = TypeToken.get(GsonTypes.resolve(type.getType(), raw, raw.getGenericSuperclass()));
raw = type.getRawType();
}
return new FieldsData(deserializedFields, new ArrayList<>(serializedFields.values()));
}
abstract static | is |
java | apache__flink | flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/runtime/SavepointLoader.java | {
"start": 1612,
"end": 2537
} | class ____ is the current classloader for
* the thread.
*
* @param savepointPath The path to an external savepoint.
* @return A state handle to savepoint's metadata.
* @throws IOException Thrown, if the path cannot be resolved, the file system not accessed, or
* the path points to a location that does not seem to be a savepoint.
*/
public static CheckpointMetadata loadSavepointMetadata(String savepointPath)
throws IOException {
CompletedCheckpointStorageLocation location =
AbstractFsCheckpointStorageAccess.resolveCheckpointPointer(savepointPath);
try (DataInputStream stream =
new DataInputStream(location.getMetadataHandle().openInputStream())) {
return Checkpoints.loadCheckpointMetadata(
stream, Thread.currentThread().getContextClassLoader(), savepointPath);
}
}
}
| loader |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandlerComposite.java | {
"start": 1190,
"end": 4284
} | class ____ implements HandlerMethodReturnValueHandler {
private final List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<>();
/**
* Return a read-only list with the registered handlers, or an empty list.
*/
public List<HandlerMethodReturnValueHandler> getHandlers() {
return Collections.unmodifiableList(this.returnValueHandlers);
}
/**
* Whether the given {@linkplain MethodParameter method return type} is supported by any registered
* {@link HandlerMethodReturnValueHandler}.
*/
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return getReturnValueHandler(returnType) != null;
}
private @Nullable HandlerMethodReturnValueHandler getReturnValueHandler(MethodParameter returnType) {
for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) {
if (handler.supportsReturnType(returnType)) {
return handler;
}
}
return null;
}
/**
* Iterate over registered {@link HandlerMethodReturnValueHandler HandlerMethodReturnValueHandlers} and invoke the one that supports it.
* @throws IllegalStateException if no suitable {@link HandlerMethodReturnValueHandler} is found.
*/
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
HandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType);
if (handler == null) {
throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName());
}
handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
}
private @Nullable HandlerMethodReturnValueHandler selectHandler(@Nullable Object value, MethodParameter returnType) {
boolean isAsyncValue = isAsyncReturnValue(value, returnType);
for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) {
if (isAsyncValue && !(handler instanceof AsyncHandlerMethodReturnValueHandler)) {
continue;
}
if (handler.supportsReturnType(returnType)) {
return handler;
}
}
return null;
}
private boolean isAsyncReturnValue(@Nullable Object value, MethodParameter returnType) {
for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) {
if (handler instanceof AsyncHandlerMethodReturnValueHandler asyncHandler &&
asyncHandler.isAsyncReturnValue(value, returnType)) {
return true;
}
}
return false;
}
/**
* Add the given {@link HandlerMethodReturnValueHandler}.
*/
public HandlerMethodReturnValueHandlerComposite addHandler(HandlerMethodReturnValueHandler handler) {
this.returnValueHandlers.add(handler);
return this;
}
/**
* Add the given {@link HandlerMethodReturnValueHandler HandlerMethodReturnValueHandlers}.
*/
public HandlerMethodReturnValueHandlerComposite addHandlers(
@Nullable List<? extends HandlerMethodReturnValueHandler> handlers) {
if (handlers != null) {
this.returnValueHandlers.addAll(handlers);
}
return this;
}
}
| HandlerMethodReturnValueHandlerComposite |
java | google__dagger | javatests/dagger/internal/codegen/IgnoreProvisionKeyWildcardsTest.java | {
"start": 3033,
"end": 4133
} | interface ____ {",
" fun fooExtends(): Foo<out Bar>",
" fun foo(): Foo<Bar>",
"}",
"@Module",
"object MyModule {",
" @Provides fun fooExtends(): Foo<out Bar> = TODO()",
" @Provides fun foo(): Foo<Bar> = TODO()",
"}"),
subject -> {
if (isIgnoreProvisionKeyWildcardsEnabled) {
subject.hasErrorCount(1);
subject.hasErrorContaining(
NEW_LINES_FOR_ERROR_MSG.join(
"Foo<? extends Bar> is bound multiple times:",
" @Provides Foo<Bar> MyModule.foo()",
" @Provides Foo<? extends Bar> MyModule.fooExtends()",
" in component: [MyComponent]"));
} else {
subject.hasErrorCount(0);
}
});
}
@Test
public void testProvidesUniqueBindingsWithMatchingWildcardArguments() {
compile(
/* javaComponentClass = */
NEW_LINES.join(
"@Component(modules = MyModule.class)",
" | MyComponent |
java | apache__dubbo | dubbo-compatible/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java | {
"start": 910,
"end": 2139
} | class ____<T> extends org.apache.dubbo.config.ReferenceConfig<T> {
public ReferenceConfig() {}
public ReferenceConfig(Reference reference) {
super(reference);
}
public void setConsumer(com.alibaba.dubbo.config.ConsumerConfig consumer) {
super.setConsumer(consumer);
}
public void setApplication(com.alibaba.dubbo.config.ApplicationConfig application) {
super.setApplication(application);
}
public void setModule(com.alibaba.dubbo.config.ModuleConfig module) {
super.setModule(module);
}
public void setRegistry(com.alibaba.dubbo.config.RegistryConfig registry) {
super.setRegistry(registry);
}
public void addMethod(com.alibaba.dubbo.config.MethodConfig methodConfig) {
super.addMethod(methodConfig);
}
public void setMonitor(com.alibaba.dubbo.config.MonitorConfig monitor) {
super.setMonitor(monitor);
}
public void setMock(Boolean mock) {
if (mock == null) {
setMock((String) null);
} else {
setMock(String.valueOf(mock));
}
}
public void setInterfaceClass(Class<?> interfaceClass) {
setInterface(interfaceClass);
}
}
| ReferenceConfig |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/coordination/stateless/InMemoryHeartbeatStore.java | {
"start": 577,
"end": 979
} | class ____ implements HeartbeatStore {
Heartbeat heartbeat;
@Override
public void writeHeartbeat(Heartbeat newHeartbeat, ActionListener<Void> listener) {
this.heartbeat = newHeartbeat;
listener.onResponse(null);
}
@Override
public void readLatestHeartbeat(ActionListener<Heartbeat> listener) {
listener.onResponse(heartbeat);
}
}
| InMemoryHeartbeatStore |
java | apache__flink | flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/EvictingWindowSavepointReader.java | {
"start": 2491,
"end": 11412
} | class ____<W extends Window> {
/** The execution environment. Used for creating inputs for reading state. */
private final StreamExecutionEnvironment env;
/**
* The savepoint metadata, which maintains the current set of existing / newly added operator
* states.
*/
private final SavepointMetadataV2 metadata;
/**
* The state backend that was previously used to write existing operator states in this
* savepoint. If null, the reader will use the state backend defined via the cluster
* configuration.
*/
@Nullable private final StateBackend stateBackend;
/** The window serializer used to write the window operator. */
private final TypeSerializer<W> windowSerializer;
EvictingWindowSavepointReader(
StreamExecutionEnvironment env,
SavepointMetadataV2 metadata,
@Nullable StateBackend stateBackend,
TypeSerializer<W> windowSerializer) {
Preconditions.checkNotNull(env, "The execution environment must not be null");
Preconditions.checkNotNull(metadata, "The savepoint metadata must not be null");
Preconditions.checkNotNull(windowSerializer, "The window serializer must not be null");
this.env = env;
this.metadata = metadata;
this.stateBackend = stateBackend;
this.windowSerializer = windowSerializer;
}
/**
* Reads window state generated using a {@link ReduceFunction}.
*
* @param uid The uid of the operator.
* @param function The reduce function used to create the window.
* @param keyType The key type of the window.
* @param reduceType The type information of the reduce function.
* @param <T> The type of the reduce function.
* @param <K> The key type of the operator.
* @return A {@code DataStream} of objects read from keyed state.
* @throws IOException If savepoint does not contain the specified uid.
*/
public <T, K> DataStream<T> reduce(
String uid,
ReduceFunction<T> function,
TypeInformation<K> keyType,
TypeInformation<T> reduceType)
throws IOException {
return reduce(uid, function, new PassThroughReader<>(), keyType, reduceType, reduceType);
}
/**
* Reads window state generated using a {@link ReduceFunction}.
*
* @param uid The uid of the operator.
* @param function The reduce function used to create the window.
* @param readerFunction The window reader function.
* @param keyType The key type of the window.
* @param reduceType The type information of the reduce function.
* @param outputType The output type of the reader function.
* @param <K> The type of the key.
* @param <T> The type of the reduce function.
* @param <OUT> The output type of the reduce function.
* @return A {@code DataStream} of objects read from keyed state.
* @throws IOException If savepoint does not contain the specified uid.
*/
public <K, T, OUT> DataStream<OUT> reduce(
String uid,
ReduceFunction<T> function,
WindowReaderFunction<T, OUT, K, W> readerFunction,
TypeInformation<K> keyType,
TypeInformation<T> reduceType,
TypeInformation<OUT> outputType)
throws IOException {
WindowReaderOperator<?, K, StreamRecord<T>, W, OUT> operator =
WindowReaderOperator.evictingWindow(
new ReduceEvictingWindowReaderFunction<>(readerFunction, function),
keyType,
windowSerializer,
reduceType,
env.getConfig());
return readWindowOperator(uid, outputType, operator);
}
/**
* Reads window state generated using an {@link AggregateFunction}.
*
* @param uid The uid of the operator.
* @param aggregateFunction The aggregate function used to create the window.
* @param keyType The key type of the window.
* @param inputType The type information of the accumulator function.
* @param outputType The output type of the reader function.
* @param <K> The type of the key.
* @param <T> The type of the values that are aggregated.
* @param <ACC> The type of the accumulator (intermediate aggregate state).
* @param <R> The type of the aggregated result.
* @return A {@code DataStream} of objects read from keyed state.
* @throws IOException If savepoint does not contain the specified uid.
*/
public <K, T, ACC, R> DataStream<R> aggregate(
String uid,
AggregateFunction<T, ACC, R> aggregateFunction,
TypeInformation<K> keyType,
TypeInformation<T> inputType,
TypeInformation<R> outputType)
throws IOException {
return aggregate(
uid, aggregateFunction, new PassThroughReader<>(), keyType, inputType, outputType);
}
/**
* Reads window state generated using an {@link AggregateFunction}.
*
* @param uid The uid of the operator.
* @param aggregateFunction The aggregate function used to create the window.
* @param readerFunction The window reader function.
* @param keyType The key type of the window.
* @param inputType The type information of the accumulator function.
* @param outputType The output type of the reader function.
* @param <K> The type of the key.
* @param <T> The type of the values that are aggregated.
* @param <ACC> The type of the accumulator (intermediate aggregate state).
* @param <R> The type of the aggregated result.
* @param <OUT> The output type of the reader function.
* @return A {@code DataStream} of objects read from keyed state.
* @throws IOException If savepoint does not contain the specified uid.
*/
public <K, T, ACC, R, OUT> DataStream<OUT> aggregate(
String uid,
AggregateFunction<T, ACC, R> aggregateFunction,
WindowReaderFunction<R, OUT, K, W> readerFunction,
TypeInformation<K> keyType,
TypeInformation<T> inputType,
TypeInformation<OUT> outputType)
throws IOException {
WindowReaderOperator<?, K, StreamRecord<T>, W, OUT> operator =
WindowReaderOperator.evictingWindow(
new AggregateEvictingWindowReaderFunction<>(
readerFunction, aggregateFunction),
keyType,
windowSerializer,
inputType,
env.getConfig());
return readWindowOperator(uid, outputType, operator);
}
/**
* Reads window state generated without any preaggregation such as {@code WindowedStream#apply}
* and {@code WindowedStream#process}.
*
* @param uid The uid of the operator.
* @param readerFunction The window reader function.
* @param keyType The key type of the window.
* @param stateType The type of records stored in state.
* @param outputType The output type of the reader function.
* @param <K> The type of the key.
* @param <T> The type of the records stored in state.
* @param <OUT> The output type of the reader function.
* @return A {@code DataStream} of objects read from keyed state.
* @throws IOException If the savepoint does not contain the specified uid.
*/
public <K, T, OUT> DataStream<OUT> process(
String uid,
WindowReaderFunction<T, OUT, K, W> readerFunction,
TypeInformation<K> keyType,
TypeInformation<T> stateType,
TypeInformation<OUT> outputType)
throws IOException {
WindowReaderOperator<?, K, StreamRecord<T>, W, OUT> operator =
WindowReaderOperator.evictingWindow(
new ProcessEvictingWindowReader<>(readerFunction),
keyType,
windowSerializer,
stateType,
env.getConfig());
return readWindowOperator(uid, outputType, operator);
}
private <K, T, OUT> DataStream<OUT> readWindowOperator(
String uid,
TypeInformation<OUT> outputType,
WindowReaderOperator<?, K, T, W, OUT> operator)
throws IOException {
KeyedStateInputFormat<K, W, OUT> format =
new KeyedStateInputFormat<>(
metadata.getOperatorState(OperatorIdentifier.forUid(uid)),
stateBackend,
MutableConfig.of(env.getConfiguration()),
operator,
env.getConfig());
return SourceBuilder.fromFormat(env, format, outputType);
}
}
| EvictingWindowSavepointReader |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptDetailsInfo.java | {
"start": 2157,
"end": 10767
} | class ____ implements ResponseBody {
public static final String FIELD_NAME_SUBTASK_INDEX = "subtask";
public static final String FIELD_NAME_STATUS = "status";
public static final String FIELD_NAME_ATTEMPT = "attempt";
public static final String FIELD_NAME_ENDPOINT = "endpoint";
public static final String FIELD_NAME_START_TIME = "start-time";
public static final String FIELD_NAME_COMPATIBLE_START_TIME = "start_time";
public static final String FIELD_NAME_END_TIME = "end-time";
public static final String FIELD_NAME_DURATION = "duration";
public static final String FIELD_NAME_METRICS = "metrics";
public static final String FIELD_NAME_TASKMANAGER_ID = "taskmanager-id";
public static final String FIELD_NAME_STATUS_DURATION = "status-duration";
public static final String FIELD_NAME_OTHER_CONCURRENT_ATTEMPTS = "other-concurrent-attempts";
@JsonProperty(FIELD_NAME_SUBTASK_INDEX)
private final int subtaskIndex;
@JsonProperty(FIELD_NAME_STATUS)
private final ExecutionState status;
@JsonProperty(FIELD_NAME_ATTEMPT)
private final int attempt;
@JsonProperty(FIELD_NAME_ENDPOINT)
private final String endpoint;
@JsonProperty(FIELD_NAME_START_TIME)
private final long startTime;
@Hidden
@JsonProperty(FIELD_NAME_COMPATIBLE_START_TIME)
private final long startTimeCompatible;
@JsonProperty(FIELD_NAME_END_TIME)
private final long endTime;
@JsonProperty(FIELD_NAME_DURATION)
private final long duration;
@JsonProperty(FIELD_NAME_METRICS)
private final IOMetricsInfo ioMetricsInfo;
@JsonProperty(FIELD_NAME_TASKMANAGER_ID)
private final String taskmanagerId;
@JsonProperty(FIELD_NAME_STATUS_DURATION)
private final Map<ExecutionState, Long> statusDuration;
@JsonProperty(FIELD_NAME_OTHER_CONCURRENT_ATTEMPTS)
@JsonInclude(Include.NON_EMPTY)
@Nullable
private final List<SubtaskExecutionAttemptDetailsInfo> otherConcurrentAttempts;
@JsonCreator
// blocked is Nullable since Jackson will assign null if the field is absent while parsing
public SubtaskExecutionAttemptDetailsInfo(
@JsonProperty(FIELD_NAME_SUBTASK_INDEX) int subtaskIndex,
@JsonProperty(FIELD_NAME_STATUS) ExecutionState status,
@JsonProperty(FIELD_NAME_ATTEMPT) int attempt,
@JsonProperty(FIELD_NAME_ENDPOINT) String endpoint,
@JsonProperty(FIELD_NAME_START_TIME) long startTime,
@JsonProperty(FIELD_NAME_END_TIME) long endTime,
@JsonProperty(FIELD_NAME_DURATION) long duration,
@JsonProperty(FIELD_NAME_METRICS) IOMetricsInfo ioMetricsInfo,
@JsonProperty(FIELD_NAME_TASKMANAGER_ID) String taskmanagerId,
@JsonProperty(FIELD_NAME_STATUS_DURATION) Map<ExecutionState, Long> statusDuration,
@JsonProperty(FIELD_NAME_OTHER_CONCURRENT_ATTEMPTS) @Nullable
List<SubtaskExecutionAttemptDetailsInfo> otherConcurrentAttempts) {
this.subtaskIndex = subtaskIndex;
this.status = Preconditions.checkNotNull(status);
this.attempt = attempt;
this.endpoint = Preconditions.checkNotNull(endpoint);
this.startTime = startTime;
this.startTimeCompatible = startTime;
this.endTime = endTime;
this.duration = duration;
this.ioMetricsInfo = Preconditions.checkNotNull(ioMetricsInfo);
this.taskmanagerId = Preconditions.checkNotNull(taskmanagerId);
this.statusDuration = Preconditions.checkNotNull(statusDuration);
this.otherConcurrentAttempts = otherConcurrentAttempts;
}
public int getSubtaskIndex() {
return subtaskIndex;
}
public ExecutionState getStatus() {
return status;
}
public int getAttempt() {
return attempt;
}
public String getEndpoint() {
return endpoint;
}
public long getStartTime() {
return startTime;
}
public long getStartTimeCompatible() {
return startTimeCompatible;
}
public long getEndTime() {
return endTime;
}
public long getDuration() {
return duration;
}
public Map<ExecutionState, Long> getStatusDuration() {
return statusDuration;
}
public long getStatusDuration(ExecutionState state) {
return statusDuration.get(state);
}
public IOMetricsInfo getIoMetricsInfo() {
return ioMetricsInfo;
}
public String getTaskmanagerId() {
return taskmanagerId;
}
public List<SubtaskExecutionAttemptDetailsInfo> getOtherConcurrentAttempts() {
return otherConcurrentAttempts == null ? new ArrayList<>() : otherConcurrentAttempts;
}
public static SubtaskExecutionAttemptDetailsInfo create(
AccessExecution execution,
@Nullable MetricStore.JobMetricStoreSnapshot jobMetrics,
JobID jobID,
JobVertexID jobVertexID,
@Nullable List<SubtaskExecutionAttemptDetailsInfo> otherConcurrentAttempts) {
final ExecutionState status = execution.getState();
final long now = System.currentTimeMillis();
final TaskManagerLocation location = execution.getAssignedResourceLocation();
final String endpoint = location == null ? "(unassigned)" : location.getEndpoint();
String taskmanagerId =
location == null ? "(unassigned)" : location.getResourceID().toString();
long startTime = execution.getStateTimestamp(ExecutionState.DEPLOYING);
if (startTime == 0) {
startTime = -1;
}
final long endTime = status.isTerminal() ? execution.getStateTimestamp(status) : -1;
final long duration = startTime > 0 ? ((endTime > 0 ? endTime : now) - startTime) : -1;
final MutableIOMetrics ioMetrics = new MutableIOMetrics();
ioMetrics.addIOMetrics(execution, jobMetrics, jobID.toString(), jobVertexID.toString());
final IOMetricsInfo ioMetricsInfo =
new IOMetricsInfo(
ioMetrics.getNumBytesIn(),
ioMetrics.isNumBytesInComplete(),
ioMetrics.getNumBytesOut(),
ioMetrics.isNumBytesOutComplete(),
ioMetrics.getNumRecordsIn(),
ioMetrics.isNumRecordsInComplete(),
ioMetrics.getNumRecordsOut(),
ioMetrics.isNumRecordsOutComplete(),
ioMetrics.getAccumulateBackPressuredTime(),
ioMetrics.getAccumulateIdleTime(),
ioMetrics.getAccumulateBusyTime());
return new SubtaskExecutionAttemptDetailsInfo(
execution.getParallelSubtaskIndex(),
status,
execution.getAttemptNumber(),
endpoint,
startTime,
endTime,
duration,
ioMetricsInfo,
taskmanagerId,
getExecutionStateDuration(execution),
otherConcurrentAttempts);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SubtaskExecutionAttemptDetailsInfo that = (SubtaskExecutionAttemptDetailsInfo) o;
return subtaskIndex == that.subtaskIndex
&& status == that.status
&& attempt == that.attempt
&& Objects.equals(endpoint, that.endpoint)
&& startTime == that.startTime
&& startTimeCompatible == that.startTimeCompatible
&& endTime == that.endTime
&& duration == that.duration
&& Objects.equals(ioMetricsInfo, that.ioMetricsInfo)
&& Objects.equals(taskmanagerId, that.taskmanagerId)
&& Objects.equals(statusDuration, that.statusDuration)
&& Objects.equals(otherConcurrentAttempts, that.otherConcurrentAttempts);
}
@Override
public int hashCode() {
return Objects.hash(
subtaskIndex,
status,
attempt,
endpoint,
startTime,
startTimeCompatible,
endTime,
duration,
ioMetricsInfo,
taskmanagerId,
statusDuration,
otherConcurrentAttempts);
}
}
| SubtaskExecutionAttemptDetailsInfo |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/VarCheckerTest.java | {
"start": 9884,
"end": 10529
} | class ____ {
int f(
// BUG: Diagnostic contains: @Var variable is never modified
@Var int x, @Var int y) {
y++;
return x + y;
}
}
""")
.doTest();
}
@Test
public void recordCanonicalConstructor() {
compilationHelper
.addSourceLines(
"Test.java",
"""
// BUG: Diagnostic contains:
public record Test(String x) {
public Test {
x = x.replace('_', ' ');
}
}
""")
.doTest();
}
}
| Test |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/TestOutOfBandAzureBlobOperations.java | {
"start": 1300,
"end": 4300
} | class ____
extends AbstractWasbTestWithTimeout {
private AzureBlobStorageTestAccount testAccount;
private FileSystem fs;
private InMemoryBlockBlobStore backingStore;
@BeforeEach
public void setUp() throws Exception {
testAccount = AzureBlobStorageTestAccount.createMock();
fs = testAccount.getFileSystem();
backingStore = testAccount.getMockStorage().getBackingStore();
}
@AfterEach
public void tearDown() throws Exception {
testAccount.cleanup();
fs = null;
backingStore = null;
}
private void createEmptyBlobOutOfBand(String path) {
backingStore.setContent(
AzureBlobStorageTestAccount.toMockUri(path),
new byte[] { 1, 2 },
new HashMap<String, String>(),
false, 0);
}
@SuppressWarnings("deprecation")
@Test
public void testImplicitFolderListed() throws Exception {
createEmptyBlobOutOfBand("root/b");
// List the blob itself.
FileStatus[] obtained = fs.listStatus(new Path("/root/b"));
assertNotNull(obtained);
assertEquals(1, obtained.length);
assertFalse(obtained[0].isDirectory());
assertEquals("/root/b", obtained[0].getPath().toUri().getPath());
// List the directory
obtained = fs.listStatus(new Path("/root"));
assertNotNull(obtained);
assertEquals(1, obtained.length);
assertFalse(obtained[0].isDirectory());
assertEquals("/root/b", obtained[0].getPath().toUri().getPath());
// Get the directory's file status
FileStatus dirStatus = fs.getFileStatus(new Path("/root"));
assertNotNull(dirStatus);
assertTrue(dirStatus.isDirectory());
assertEquals("/root", dirStatus.getPath().toUri().getPath());
}
@Test
public void testImplicitFolderDeleted() throws Exception {
createEmptyBlobOutOfBand("root/b");
assertTrue(fs.exists(new Path("/root")));
assertTrue(fs.delete(new Path("/root"), true));
assertFalse(fs.exists(new Path("/root")));
}
@Test
public void testFileInImplicitFolderDeleted() throws Exception {
createEmptyBlobOutOfBand("root/b");
assertTrue(fs.exists(new Path("/root")));
assertTrue(fs.delete(new Path("/root/b"), true));
assertTrue(fs.exists(new Path("/root")));
}
@SuppressWarnings("deprecation")
@Test
public void testFileAndImplicitFolderSameName() throws Exception {
createEmptyBlobOutOfBand("root/b");
createEmptyBlobOutOfBand("root/b/c");
FileStatus[] listResult = fs.listStatus(new Path("/root/b"));
// File should win.
assertEquals(1, listResult.length);
assertFalse(listResult[0].isDirectory());
try {
// Trying to delete root/b/c would cause a dilemma for WASB, so
// it should throw.
fs.delete(new Path("/root/b/c"), true);
assertTrue(false, "Should've thrown.");
} catch (AzureException e) {
assertEquals("File /root/b/c has a parent directory /root/b"
+ " which is also a file. Can't resolve.", e.getMessage());
}
}
private static | TestOutOfBandAzureBlobOperations |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ShouldNotBeEqualNormalizingWhitespace_create_Test.java | {
"start": 1268,
"end": 1990
} | class ____ {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldNotBeEqualNormalizingWhitespace(" my\tfoo bar ", " my foo bar ");
// WHEN
String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \" my\tfoo bar \"%n" +
"not to be equal to:%n" +
" \" my foo bar \"%n" +
"after whitespace differences are normalized"));
}
}
| ShouldNotBeEqualNormalizingWhitespace_create_Test |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Issue215_boolean_array.java | {
"start": 280,
"end": 1022
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
boolean[] values = new boolean[128];
Random random = new Random();
for (int i = 0; i < values.length; ++i) {
values[i] = random.nextInt() % 2 == 0;
}
Map<String, boolean[]> map = new HashMap<String, boolean[]>();
map.put("val", values);
String text = JSON.toJSONString(map);
System.out.println(text);
Map<String, boolean[]> map2 = JSON.parseObject(text, new TypeReference<HashMap<String, boolean[]>>() {});
boolean[] values2 = (boolean[]) map2.get("val");
Assert.assertTrue(Arrays.equals(values2, values));
}
}
| Issue215_boolean_array |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java | {
"start": 34966,
"end": 35069
} | class ____ {
public JsonFactory create() {
return new YAMLFactory();
}
}
}
| YamlFactoryInitializer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/BoxedPrimitiveConstructorTest.java | {
"start": 2580,
"end": 3527
} | class ____ {
{
// BUG: Diagnostic contains: byte b = Byte.valueOf("0");
byte b = new Byte("0");
// BUG: Diagnostic contains: double d = Double.valueOf("0");
double d = new Double("0");
// BUG: Diagnostic contains: float f = Float.valueOf("0");
float f = new Float("0");
// BUG: Diagnostic contains: int i = Integer.valueOf("0");
int i = new Integer("0");
// BUG: Diagnostic contains: long j = Long.valueOf("0");
long j = new Long("0");
// BUG: Diagnostic contains: short s = Short.valueOf("0");
short s = new Short("0");
}
}
""")
.doTest();
}
@Test
public void booleanConstant() {
compilationHelper
.addSourceLines(
"Test.java",
"""
public | Test |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/cli/util/CommandExecutor.java | {
"start": 2836,
"end": 3506
} | class ____ {
final String commandOutput;
final int exitCode;
final Exception exception;
final String cmdExecuted;
public Result(String commandOutput, int exitCode, Exception exception,
String cmdExecuted) {
this.commandOutput = commandOutput;
this.exitCode = exitCode;
this.exception = exception;
this.cmdExecuted = cmdExecuted;
}
public String getCommandOutput() {
return commandOutput;
}
public int getExitCode() {
return exitCode;
}
public Exception getException() {
return exception;
}
public String getCommand() {
return cmdExecuted;
}
}
}
| Result |
java | quarkusio__quarkus | extensions/panache/hibernate-reactive-panache/deployment/src/test/java/io/quarkus/hibernate/reactive/panache/test/WithSessionOnDemandTest.java | {
"start": 1829,
"end": 3020
} | class ____ {
@Inject
Mutiny.SessionFactory sessionFactory;
@WithSessionOnDemand
Uni<String> ping() {
Uni<Session> s1 = Panache.getSession();
Uni<Session> s2 = Panache.getSession();
// Test that both unis receive the same session
return s1.chain(s1Val -> s2.map(s2Val -> "" + (s1Val == s2Val)));
}
@WithSessionOnDemand
Uni<String> checkSessionsAreEqualsUnnested() {
Uni<Session> s1 = Panache.getSession();
return sessionFactory.withSession(s2Val -> {
return s1.map(s1Val -> {
return "" + (s1Val == s2Val);
});
});
}
@WithSessionOnDemand
Uni<String> checkSessionsAreEquals() {
return sessionFactory.withSession(s2Val -> Panache.getSession().map(s1Val -> "" + (s1Val == s2Val)));
}
@WithSessionOnDemand
Uni<String> checkSessionsAreEqualsOppositeOrder() {
return Panache.getSession().flatMap(s2Val -> sessionFactory.withSession(s1Val -> Uni.createFrom().item(
"" + (s1Val == s2Val))));
}
}
}
| MrBean |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/BindFailureAnalyzer.java | {
"start": 1757,
"end": 5514
} | class ____ extends AbstractFailureAnalyzer<BindException> {
@Override
protected @Nullable FailureAnalysis analyze(Throwable rootFailure, BindException cause) {
Throwable rootCause = cause.getCause();
if (rootCause instanceof BindValidationException
|| rootCause instanceof UnboundConfigurationPropertiesException) {
return null;
}
return analyzeGenericBindException(rootFailure, cause);
}
private FailureAnalysis analyzeGenericBindException(Throwable rootFailure, BindException cause) {
FailureAnalysis missingParametersAnalysis = MissingParameterNamesFailureAnalyzer
.analyzeForMissingParameters(rootFailure);
StringBuilder description = new StringBuilder(String.format("%s:%n", cause.getMessage()));
ConfigurationProperty property = cause.getProperty();
buildDescription(description, property);
description.append(String.format("%n Reason: %s", getMessage(cause)));
if (missingParametersAnalysis != null) {
MissingParameterNamesFailureAnalyzer.appendPossibility(description);
}
return getFailureAnalysis(description.toString(), cause, missingParametersAnalysis);
}
private void buildDescription(StringBuilder description, @Nullable ConfigurationProperty property) {
if (property != null) {
description.append(String.format("%n Property: %s", property.getName()));
description.append(String.format("%n Value: \"%s\"", property.getValue()));
description.append(String.format("%n Origin: %s", property.getOrigin()));
}
}
private String getMessage(BindException cause) {
Throwable rootCause = getRootCause(cause.getCause());
ConversionFailedException conversionFailure = findCause(cause, ConversionFailedException.class);
if (conversionFailure != null) {
String message = "failed to convert " + conversionFailure.getSourceType() + " to "
+ conversionFailure.getTargetType();
if (rootCause != null) {
message += " (caused by " + getExceptionTypeAndMessage(rootCause) + ")";
}
return message;
}
if (rootCause != null && StringUtils.hasText(rootCause.getMessage())) {
return getExceptionTypeAndMessage(rootCause);
}
return getExceptionTypeAndMessage(cause);
}
private @Nullable Throwable getRootCause(@Nullable Throwable cause) {
Throwable rootCause = cause;
while (rootCause != null && rootCause.getCause() != null) {
rootCause = rootCause.getCause();
}
return rootCause;
}
private String getExceptionTypeAndMessage(Throwable ex) {
String message = ex.getMessage();
return ex.getClass().getName() + (StringUtils.hasText(message) ? ": " + message : "");
}
private FailureAnalysis getFailureAnalysis(String description, BindException cause,
@Nullable FailureAnalysis missingParametersAnalysis) {
StringBuilder action = new StringBuilder("Update your application's configuration");
Collection<String> validValues = findValidValues(cause);
if (!validValues.isEmpty()) {
action.append(String.format(". The following values are valid:%n"));
validValues.forEach((value) -> action.append(String.format("%n %s", value)));
}
if (missingParametersAnalysis != null) {
action.append(String.format("%n%n%s", missingParametersAnalysis.getAction()));
}
return new FailureAnalysis(description, action.toString(), cause);
}
private Collection<String> findValidValues(BindException ex) {
ConversionFailedException conversionFailure = findCause(ex, ConversionFailedException.class);
if (conversionFailure != null) {
Object[] enumConstants = conversionFailure.getTargetType().getType().getEnumConstants();
if (enumConstants != null) {
return Stream.of(enumConstants).map(Object::toString).collect(Collectors.toCollection(TreeSet::new));
}
}
return Collections.emptySet();
}
}
| BindFailureAnalyzer |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/table/lookup/fullcache/ReloadTriggerContext.java | {
"start": 1166,
"end": 2314
} | class ____ implements CacheReloadTrigger.Context {
private final Supplier<CompletableFuture<Void>> cacheLoader;
private final Consumer<Throwable> reloadFailCallback;
public ReloadTriggerContext(
Supplier<CompletableFuture<Void>> cacheLoader, Consumer<Throwable> reloadFailCallback) {
this.cacheLoader = cacheLoader;
this.reloadFailCallback = reloadFailCallback;
}
@Override
public long currentProcessingTime() {
// TODO add processingTime into FunctionContext
return System.currentTimeMillis();
}
@Override
public long currentWatermark() {
// TODO add watermarks into FunctionContext
throw new UnsupportedOperationException(
"Watermarks are currently unsupported in cache reload triggers.");
}
@Override
public CompletableFuture<Void> triggerReload() {
return cacheLoader
.get()
.exceptionally(
th -> {
reloadFailCallback.accept(th);
return null;
});
}
}
| ReloadTriggerContext |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/commit/integration/ITestS3ACommitterMRJob.java | {
"start": 15027,
"end": 15532
} | class ____ committer tests.
* Subclasses of this will be instantiated and drive the parameterized
* test suite.
*
* These classes will be instantiated in a static array of the suite, and
* not bound to a cluster binding or filesystem.
*
* The per-method test {@link #setup()} method will call
* {@link #setup(ClusterBinding, S3AFileSystem)}, to link the instance
* to the specific test cluster <i>and test filesystem</i> in use
* in that test.
*/
private abstract static | for |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ExtensionRegistryTests.java | {
"start": 11043,
"end": 11157
} | class ____ implements MyExtensionApi {
@Override
public void doNothing(String test) {
}
}
static | MyExtension |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeMergeArray.java | {
"start": 8045,
"end": 8292
} | interface ____<T> extends SimpleQueue<T> {
@Nullable
@Override
T poll();
T peek();
void drop();
int consumerIndex();
int producerIndex();
}
static final | SimpleQueueWithConsumerIndex |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/builder/BuilderErrorHandlingTest.java | {
"start": 1494,
"end": 1677
} | class ____ extends RuntimeException
{
ValidationException(String message) {
super(message);
}
}
static | ValidationException |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/Configuration.java | {
"start": 4440,
"end": 4968
} | class ____ {
* // various @Bean definitions ...
* }</pre>
*
* <p>See the {@link ComponentScan @ComponentScan} javadocs for details.
*
* <h2>Working with externalized values</h2>
*
* <h3>Using the {@code Environment} API</h3>
*
* <p>Externalized values may be looked up by injecting the Spring
* {@link org.springframework.core.env.Environment} into a {@code @Configuration}
* class — for example, using the {@code @Autowired} annotation:
*
* <pre class="code">
* @Configuration
* public | AppConfig |
java | spring-projects__spring-framework | buildSrc/src/main/java/org/springframework/build/multirelease/MultiReleaseExtension.java | {
"start": 1543,
"end": 6299
} | class ____ {
private final TaskContainer tasks;
private final SourceSetContainer sourceSets;
private final DependencyHandler dependencies;
private final ObjectFactory objects;
private final ConfigurationContainer configurations;
@Inject
public MultiReleaseExtension(SourceSetContainer sourceSets,
ConfigurationContainer configurations,
TaskContainer tasks,
DependencyHandler dependencies,
ObjectFactory objectFactory) {
this.sourceSets = sourceSets;
this.configurations = configurations;
this.tasks = tasks;
this.dependencies = dependencies;
this.objects = objectFactory;
}
public void releaseVersions(int... javaVersions) {
releaseVersions("src/main/", "src/test/", javaVersions);
}
private void releaseVersions(String mainSourceDirectory, String testSourceDirectory, int... javaVersions) {
for (int javaVersion : javaVersions) {
addLanguageVersion(javaVersion, mainSourceDirectory, testSourceDirectory);
}
}
private void addLanguageVersion(int javaVersion, String mainSourceDirectory, String testSourceDirectory) {
String javaN = "java" + javaVersion;
SourceSet langSourceSet = sourceSets.create(javaN, srcSet -> srcSet.getJava().srcDir(mainSourceDirectory + javaN));
SourceSet testSourceSet = sourceSets.create(javaN + "Test", srcSet -> srcSet.getJava().srcDir(testSourceDirectory + javaN));
SourceSet sharedSourceSet = sourceSets.findByName(SourceSet.MAIN_SOURCE_SET_NAME);
SourceSet sharedTestSourceSet = sourceSets.findByName(SourceSet.TEST_SOURCE_SET_NAME);
FileCollection mainClasses = objects.fileCollection().from(sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput().getClassesDirs());
dependencies.add(javaN + "Implementation", mainClasses);
tasks.named(langSourceSet.getCompileJavaTaskName(), JavaCompile.class, task ->
task.getOptions().getRelease().set(javaVersion)
);
tasks.named(testSourceSet.getCompileJavaTaskName(), JavaCompile.class, task ->
task.getOptions().getRelease().set(javaVersion)
);
TaskProvider<Test> testTask = createTestTask(javaVersion, testSourceSet, sharedTestSourceSet, langSourceSet, sharedSourceSet);
tasks.named("check", task -> task.dependsOn(testTask));
configureMultiReleaseJar(javaVersion, langSourceSet);
}
private TaskProvider<Test> createTestTask(int javaVersion, SourceSet testSourceSet, SourceSet sharedTestSourceSet, SourceSet langSourceSet, SourceSet sharedSourceSet) {
Configuration testImplementation = configurations.getByName(testSourceSet.getImplementationConfigurationName());
testImplementation.extendsFrom(configurations.getByName(sharedTestSourceSet.getImplementationConfigurationName()));
Configuration testCompileOnly = configurations.getByName(testSourceSet.getCompileOnlyConfigurationName());
testCompileOnly.extendsFrom(configurations.getByName(sharedTestSourceSet.getCompileOnlyConfigurationName()));
testCompileOnly.getDependencies().add(dependencies.create(langSourceSet.getOutput().getClassesDirs()));
testCompileOnly.getDependencies().add(dependencies.create(sharedSourceSet.getOutput().getClassesDirs()));
Configuration testRuntimeClasspath = configurations.getByName(testSourceSet.getRuntimeClasspathConfigurationName());
// so here's the deal. MRjars are JARs! Which means that to execute tests, we need
// the JAR on classpath, not just classes + resources as Gradle usually does
testRuntimeClasspath.getAttributes()
.attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.class, LibraryElements.JAR));
TaskProvider<Test> testTask = tasks.register("java" + javaVersion + "Test", Test.class, test -> {
test.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
ConfigurableFileCollection testClassesDirs = objects.fileCollection();
testClassesDirs.from(testSourceSet.getOutput());
testClassesDirs.from(sharedTestSourceSet.getOutput());
test.setTestClassesDirs(testClassesDirs);
ConfigurableFileCollection classpath = objects.fileCollection();
// must put the MRJar first on classpath
classpath.from(tasks.named("jar"));
// then we put the specific test sourceset tests, so that we can override
// the shared versions
classpath.from(testSourceSet.getOutput());
// then we add the shared tests
classpath.from(sharedTestSourceSet.getRuntimeClasspath());
test.setClasspath(classpath);
});
return testTask;
}
private void configureMultiReleaseJar(int version, SourceSet languageSourceSet) {
tasks.named("jar", Jar.class, jar -> {
jar.into("META-INF/versions/" + version, s -> s.from(languageSourceSet.getOutput()));
Attributes attributes = jar.getManifest().getAttributes();
attributes.put("Multi-Release", "true");
});
}
}
| MultiReleaseExtension |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java | {
"start": 34884,
"end": 37214
} | interface ____ the "
+ domainSocketOptionsForManagement.getHost() + " domain socket",
ar.cause()));
} else {
managementInterfaceDomainSocketFuture.complete(ar.result());
}
});
} else {
managementInterfaceDomainSocketFuture.complete(null);
}
return managementInterfaceDomainSocketFuture;
}
private static CompletableFuture<HttpServer> initializeManagementInterface(Vertx vertx,
ManagementInterfaceBuildTimeConfig managementBuildTimeConfig, Handler<HttpServerRequest> managementRouter,
ManagementConfig managementConfig,
LaunchMode launchMode,
List<String> websocketSubProtocols, TlsConfigurationRegistry registry) throws IOException {
httpManagementServerOptions = null;
CompletableFuture<HttpServer> managementInterfaceFuture = new CompletableFuture<>();
if (!managementBuildTimeConfig.enabled() || managementRouter == null || managementConfig == null) {
managementInterfaceFuture.complete(null);
return managementInterfaceFuture;
}
HttpServerOptions httpServerOptionsForManagement = createHttpServerOptionsForManagementInterface(
managementBuildTimeConfig, managementConfig, launchMode,
websocketSubProtocols);
httpManagementServerOptions = HttpServerOptionsUtils.createSslOptionsForManagementInterface(
managementBuildTimeConfig, managementConfig, launchMode,
websocketSubProtocols, registry);
if (httpManagementServerOptions != null && httpManagementServerOptions.getKeyCertOptions() == null) {
httpManagementServerOptions = httpServerOptionsForManagement;
}
if (httpManagementServerOptions != null) {
vertx.createHttpServer(httpManagementServerOptions)
.requestHandler(managementRouter)
.listen(ar -> {
if (ar.failed()) {
managementInterfaceFuture.completeExceptionally(
new IllegalStateException("Unable to start the management | on |
java | quarkusio__quarkus | integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithRouteTargetPortTest.java | {
"start": 501,
"end": 1937
} | class ____ {
private static final String APP_NAME = "openshift-with-route-target-port";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
.setApplicationName(APP_NAME)
.setApplicationVersion("0.1-SNAPSHOT")
.withConfigurationResource(APP_NAME + ".properties");
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
public void assertGeneratedResources() throws IOException {
Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
assertThat(kubernetesDir)
.isDirectoryContaining(p -> p.getFileName().endsWith("openshift.json"))
.isDirectoryContaining(p -> p.getFileName().endsWith("openshift.yml"));
List<HasMetadata> openshiftList = DeserializationUtil
.deserializeAsList(kubernetesDir.resolve("openshift.yml"));
assertThat(openshiftList).filteredOn(i -> "Route".equals(i.getKind())).singleElement().satisfies(i -> {
assertThat(i).isInstanceOfSatisfying(Route.class, r -> {
assertThat(r.getSpec().getPort().getTargetPort().getStrVal()).isEqualTo("my-port");
assertThat(r.getSpec().getHost()).isEqualTo("foo.bar.io");
});
});
}
}
| OpenshiftWithRouteTargetPortTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/doris/parser/DorisExprParser.java | {
"start": 266,
"end": 611
} | class ____
extends StarRocksExprParser {
public DorisExprParser(String sql, SQLParserFeature... features) {
super(new DorisLexer(sql, features));
lexer.nextToken();
dbType = DbType.doris;
}
public DorisExprParser(Lexer lexer) {
super(lexer);
dbType = DbType.doris;
}
}
| DorisExprParser |
java | quarkusio__quarkus | integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithServiceBindingTest.java | {
"start": 651,
"end": 3833
} | class ____ {
private static final String APP_NAME = "kubernetes-with-service-binding";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class))
.setApplicationName(APP_NAME)
.setApplicationVersion("0.1-SNAPSHOT")
.withConfigurationResource(APP_NAME + ".properties")
.setLogFileName("k8s.log")
.setForcedDependencies(List.of(
Dependency.of("io.quarkus", "quarkus-kubernetes", Version.getVersion()),
Dependency.of("io.quarkus", "quarkus-kubernetes-service-binding", Version.getVersion())));
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
public void assertGeneratedResources() throws IOException {
final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
assertThat(kubernetesDir)
.isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json"))
.isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml"));
List<HasMetadata> kubernetesList = DeserializationUtil.deserializeAsList(kubernetesDir.resolve("kubernetes.yml"));
assertThat(kubernetesList).filteredOn(i -> "Deployment".equals(i.getKind())).singleElement().satisfies(i -> {
assertThat(i).isInstanceOfSatisfying(Deployment.class, d -> {
assertThat(d.getMetadata()).satisfies(m -> {
assertThat(m.getName()).isEqualTo(APP_NAME);
});
assertThat(d.getSpec()).satisfies(deploymentSpec -> {
assertThat(deploymentSpec.getTemplate()).satisfies(t -> {
assertThat(t.getSpec()).satisfies(podSpec -> {
});
});
});
});
});
assertThat(kubernetesList).filteredOn(i -> "ServiceBinding".equals(i.getKind())).singleElement().satisfies(i -> {
assertThat(i).isInstanceOfSatisfying(ServiceBinding.class, s -> {
assertThat(s.getMetadata()).satisfies(m -> {
assertThat(m.getName()).isEqualTo(APP_NAME + "-my-db");
});
assertThat(s.getSpec()).satisfies(spec -> {
assertThat(spec.getApplication()).satisfies(a -> {
assertThat(a.getGroup()).isEqualTo("apps");
assertThat(a.getVersion()).isEqualTo("v1");
assertThat(a.getKind()).isEqualTo("Deployment");
});
assertThat(spec.getServices()).hasOnlyOneElementSatisfying(service -> {
assertThat(service.getGroup()).isEqualTo("apps");
assertThat(service.getVersion()).isEqualTo("v1");
assertThat(service.getKind()).isEqualTo("Deployment");
assertThat(service.getName()).isEqualTo("my-postgres");
});
});
});
});
}
}
| KubernetesWithServiceBindingTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/BeanParameterMethodCallThreeBodyOgnlTest.java | {
"start": 2113,
"end": 2372
} | class ____ {
public String route(Object body) {
if (body instanceof List) {
return "bean:foo?method=bar('A','B','C')";
} else {
return null;
}
}
}
public static | MyRouter |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/management/SpringManagedCamelContextTest.java | {
"start": 1560,
"end": 3744
} | class ____ extends ManagedCamelContextTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/management/SpringManagedCamelContextTest.xml");
}
@Test
public void testFindEipNames() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
assertEquals("19-" + context.getName(), context.getManagementName());
ObjectName on = getContextObjectName();
assertTrue(mbeanServer.isRegistered(on), "Should be registered");
@SuppressWarnings("unchecked")
List<String> info = (List<String>) mbeanServer.invoke(on, "findEipNames", null, null);
assertNotNull(info);
assertTrue(info.size() > 150);
assertTrue(info.contains("transform"));
assertTrue(info.contains("split"));
assertTrue(info.contains("from"));
}
@Test
public void testFindEips() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
assertEquals("19-" + context.getName(), context.getManagementName());
ObjectName on = getContextObjectName();
assertTrue(mbeanServer.isRegistered(on), "Should be registered");
@SuppressWarnings("unchecked")
Map<String, Properties> info = (Map<String, Properties>) mbeanServer.invoke(on, "findEips", null, null);
assertNotNull(info);
assertTrue(info.size() > 150);
Properties prop = info.get("transform");
assertNotNull(prop);
assertEquals("transform", prop.get("name"));
assertEquals("org.apache.camel.model.TransformDefinition", prop.get("class"));
}
@Test
public void testListEips() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
assertEquals("19-" + context.getName(), context.getManagementName());
ObjectName on = getContextObjectName();
assertTrue(mbeanServer.isRegistered(on), "Should be registered");
TabularData data = (TabularData) mbeanServer.invoke(on, "listEips", null, null);
assertNotNull(data);
assertTrue(data.size() > 150);
}
}
| SpringManagedCamelContextTest |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/InternalEmptySink.java | {
"start": 733,
"end": 2450
} | interface ____<T> extends Sinks.Empty<T>, ContextHolder {
@Override
default void emitEmpty(Sinks.EmitFailureHandler failureHandler) {
for (;;) {
Sinks.EmitResult emitResult = tryEmitEmpty();
if (emitResult.isSuccess()) {
return;
}
boolean shouldRetry = failureHandler.onEmitFailure(SignalType.ON_COMPLETE,
emitResult);
if (shouldRetry) {
continue;
}
switch (emitResult) {
case FAIL_ZERO_SUBSCRIBER:
case FAIL_OVERFLOW:
case FAIL_CANCELLED:
case FAIL_TERMINATED:
return;
case FAIL_NON_SERIALIZED:
throw new EmissionException(emitResult,
"Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially."
);
default:
throw new EmissionException(emitResult, "Unknown emitResult value");
}
}
}
@Override
default void emitError(Throwable error, Sinks.EmitFailureHandler failureHandler) {
for (;;) {
Sinks.EmitResult emitResult = tryEmitError(error);
if (emitResult.isSuccess()) {
return;
}
boolean shouldRetry = failureHandler.onEmitFailure(SignalType.ON_ERROR,
emitResult);
if (shouldRetry) {
continue;
}
switch (emitResult) {
case FAIL_ZERO_SUBSCRIBER:
case FAIL_OVERFLOW:
case FAIL_CANCELLED:
return;
case FAIL_TERMINATED:
Operators.onErrorDropped(error, currentContext());
return;
case FAIL_NON_SERIALIZED:
throw new EmissionException(emitResult,
"Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially."
);
default:
throw new EmissionException(emitResult, "Unknown emitResult value");
}
}
}
}
| InternalEmptySink |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/ParseUtil.java | {
"start": 992,
"end": 10240
} | class ____ {
private static final String DML_REGEX = "^(\\s)*(SELECT|INSERT|UPDATE|DELETE)";
private static final Pattern DML_PATTERN = Pattern.compile(DML_REGEX, Pattern.CASE_INSENSITIVE); //忽略大小写
private static final String IP_REGEX = "^(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$";
private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX, Pattern.CASE_INSENSITIVE);
private static Logger logger = Logger.getLogger(ParseUtil.class);
public static boolean isDmlSQL(String querySql) {
return DML_PATTERN.matcher(querySql).find();
}
public static boolean isDmlSQL(SQLStatement statement /*String querySql*/) {
// return DML_1_PATTERN.matcher(querySql).find() || DML_2_PATTERN.matcher(querySql).find();
return statement instanceof SQLSelectStatement ||
statement instanceof SQLInsertStatement ||
statement instanceof SQLReplaceStatement ||
statement instanceof SQLUpdateStatement ||
statement instanceof SQLDeleteStatement;
}
public static void main(String[] args) {
// String sql = "alter table sql_perf add index `idx_instance_8` (`host`,`port`,`hashcode`,`item`,`time`,`value`);";
/* String sql = "CREATE INDEX PersonIndex\n" +
"ON Person (LastName) ";*/
// String sql = "CREATE TABLE t (id int );";
// String sql = "ALTER TABLE `app_api_dup_control`\n\tDROP INDEX `idx_url_uuid`,\n\tADD UNIQUE KEY `uk_url_uuid` (uuid, url)";
/* String sql = "ALTER TABLE `push_seed_0000`\n" +
"\tADD KEY `idx_betstatus_gmtcreate` (bet_status, gmt_create),\n" +
"\tADD KEY `idx_winstatus_gmtcreate` (win_status, gmt_create)";*/
// System.out.println(getIdxInfo(sql, "AA", null));
// System.out.println(DateTimeUtils.toYyyyMMddhhmmss(new Date()));
/*String ip = "xx";
System.out.println(IP_PATTERN.matcher(ip).find());*/
/* String sql = "\nalter table `dms_sign_info_0222` modify column `station_id` bigint comment '分拣流水中记录的分拨中心ID'";
List<IdxFlagInfo> list = getIdxInfo(sql,"XX",null);
System.out.println(list);*/
// String sql = "select * from task where status = 1 and valid = 1 and type <> 100 and type <> 99 order by priority desc,gmt_create limit 0,500";
// System.out.println(parseSQL(sql));
/*String sql = "SELECT IFNULL(SUM(CASE WHEN `tms_waybill_detail`.`dissendout_status` = ? AND DATE_ADD(`tms_waybill_detail`.`rdc_accept_time`, INTERVAL ? HOUR) < `tms_waybill_detail`.`dissendout_time` OR `tms_waybill_detail`.`dissendout_status` = ? AND DATE_ADD(`tms_waybill_detail`.`rdc_accept_time`, INTERVAL ? HOUR) < NOW() THEN ? ELSE ? END), ?) AS `count` FROM tms_waybill_detail `tms_waybill_detail` WHERE `tms_waybill_detail`.`rdc_accept_time` >= ? AND `tms_waybill_detail`.`rdc_accept_time` < ? AND `tms_waybill_detail`.`districenter_code` = ? AND `tms_waybill_detail`.`schedule_code` = ?";
String table = "[\"tms_waybill_detail_0014\"]";
String params = "[1,24,0,24,1,0,0,\"2017-01-15 00:00:00\",\"2017-01-15 17:32:03.558\",686,\"10102\"]";
System.out.println("----- : "+restore(sql,table,params));*/
String sql = "/* 0bba613214845441110397435e/0.4.6.25// */select `f`.`id`,`f`.`biz_id`,`f`.`user_id`,`f`.`file_name`,`f`.`parent_id`,`f`.`length`,`f`.`type`,`f`.`stream_key`,`f`.`biz_status`,`f`.`mark`,`f`.`content_modified`,`f`.`status`,`f`.`gmt_create`,`f`.`gmt_modified`,`f`.`md5`,`f`.`extra_str1`,`f`.`extra_str2`,`f`.`extra_str3`,`f`.`extra_num1`,`f`.`extra_num2`,`f`.`extra_num3`,`f`.`safe`,`f`.`open_status`,`f`.`inner_mark`,`f`.`sys_extra`,`f`.`feature`,`f`.`domain_option`,`f`.`version`,`f`.`reference_type`,`f`.`dentry_type`,`f`.`space_id`,`f`.`extension`,`f`.`creator_id`,`f`.`modifier_id`,`f`.`store_type`,`f`.`link_mark`,`f`.`content_type` from ( select `vfs_dentry_2664`.`id` from `vfs_dentry_2664` FORCE INDEX (idx_gmt) where ((`vfs_dentry_2664`.`extra_str1` = '97d45a25df387b4460e5b4151daeb452') AND (`vfs_dentry_2664`.`biz_id` = 62) AND (`vfs_dentry_2664`.`status` = 0) AND (`vfs_dentry_2664`.`user_id` = '11168360') AND (`vfs_dentry_2664`.`dentry_type` = 1)) limit 0,50 ) `t` join `vfs_dentry_2664` `f` on `t`.`id` = `f`.`id` where ((`t`.`id` = `f`.`id`) AND (`f`.`user_id` = 11168360))";
// SQLStatement sqlStatement = getStatement(sql);
String sqlTempalte = parseSQL(sql);
JSONArray array = new JSONArray();
array.add("VFS_DENTRY_001");
System.out.println(restore(sqlTempalte, array.toJSONString(), new JSONArray().toJSONString()));
}
public static boolean isIp(String host) {
return IP_PATTERN.matcher(host).find();
}
private static String filterChar(String name) {
if (StringUtils.isNotBlank(name)) {
String[] names = name.split("\\.");
StringBuilder nameSb = new StringBuilder();
for (String n : names) {
if (n.startsWith("`") && n.endsWith("`")) {
nameSb.append(n.substring(1, n.length() - 1)).append(".");
}
}
return nameSb.substring(0, nameSb.length() - 1);
}
return name;
}
public static String parseSQL(String sql) {
try {
final DbType dbType = JdbcConstants.MYSQL;
return ParameterizedOutputVisitorUtils.parameterize(sql, dbType).toUpperCase();
} catch (Exception ex) {
logger.error("parser sql error : " + sql);
ex.printStackTrace();
}
return null;
}
public static String computeMD5Hex(String sqlTemplate) {
return DigestUtils.md5Hex(sqlTemplate).toUpperCase();
}
public static String restore(String sql, String table, String params/*JSONArray paramsArray, JSONArray destArray*/) {
JSONArray destArray = null;
if (table != null) {
destArray = JSON.parseArray(table.replaceAll("''", "'"));
}
JSONArray paramsArray = JSON.parseArray(params.replaceAll("''", "'"));
DbType dbType = JdbcConstants.MYSQL;
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, dbType);
SQLStatement stmt = stmtList.get(0);
StringBuilder out = new StringBuilder();
SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, dbType);
List<Object> paramsList = new ArrayList(paramsArray);
visitor.setParameters(paramsList);
JSONArray srcArray = getSrcArray(sql);
/*
SchemaStatVisitor schemaStatVisitor = new MySqlSchemaStatVisitor();
stmt.accept(schemaStatVisitor);
JSONArray srcArray = new JSONArray();
for (Map.Entry<TableStat.Name, TableStat> entry : schemaStatVisitor.getTables().entrySet()) {
srcArray.add(entry.getKey().getName());
}*/
if (destArray != null) {
for (int i = 0; i < srcArray.size(); i++) {
visitor.addTableMapping(srcArray.getString(i), destArray.getString(i));
}
}
stmt.accept(visitor);
return out.toString();
}
private static JSONArray getSrcArray(String sql) {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
SQLStatement stmt = stmtList.get(0);
StringBuilder out = new StringBuilder();
SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, JdbcConstants.MYSQL);
List<Object> parameters = new ArrayList<Object>();
visitor.setParameterized(true);
visitor.setParameterizedMergeInList(true);
visitor.setParameters(parameters);
visitor.setExportTables(true);
stmt.accept(visitor);
String srcStr = JSON.toJSONString(visitor.getTables());
return JSON.parseArray(srcStr);
}
public static SQLStatement getStatement(String sql) {
try {
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
return stmtList.get(0);
} catch (Exception ex) {
logger.error("get statement error", ex);
}
return null;
}
public static String getSqlHash(String sql) {
SQLStatement statement = getStatement(sql);
if (null == statement) {
return null;
}
return getSqlHash(statement);
}
public static String getSqlHash(SQLStatement statement) {
try {
StringBuilder out = new StringBuilder();
List<Object> parameters = new ArrayList<Object>();
SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, JdbcConstants.MYSQL);
visitor.setParameterized(true);
visitor.setParameterizedMergeInList(true);
visitor.setParameters(parameters);
// visitor.setExportTables(true);
visitor.setPrettyFormat(false);
statement.accept(visitor);
String sqlTemplate = out.toString();
return DigestUtils.md5Hex(sqlTemplate);
} catch (Exception ex) {
logger.error("parseSql error ", ex);
}
return null;
}
}
| ParseUtil |
java | quarkusio__quarkus | extensions/hibernate-search-orm-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/orm/elasticsearch/runtime/HibernateSearchElasticsearchRuntimeConfigPersistenceUnit.java | {
"start": 7650,
"end": 8081
} | interface ____ {
// @formatter:off
/**
* The synchronization strategy to use when indexing automatically.
*
* @deprecated Use {@code quarkus.hibernate-search-orm.indexing.plan.synchronization.strategy} instead.
*/
// @formatter:on
@ConfigDocDefault("write-sync")
Optional<String> strategy();
}
@ConfigGroup
| AutomaticIndexingSynchronizationConfig |
java | spring-projects__spring-boot | module/spring-boot-webmvc-test/src/test/java/org/springframework/boot/webmvc/test/autoconfigure/mockmvc/WebMvcTestWithWebAppConfigurationTests.java | {
"start": 1335,
"end": 2026
} | class ____ {
@Autowired
private ServletContext servletContext;
@Test
void whenBasePathIsCustomizedResourcesCanBeLoadedFromThatLocation() throws Exception {
testResource("/inwebapp", "src/test/webapp");
testResource("/inmetainfresources", "/META-INF/resources");
testResource("/inresources", "/resources");
testResource("/instatic", "/static");
testResource("/inpublic", "/public");
}
private void testResource(String path, String expectedLocation) throws MalformedURLException {
URL resource = this.servletContext.getResource(path);
assertThat(resource).isNotNull();
assertThat(resource.getPath()).contains(expectedLocation);
}
}
| WebMvcTestWithWebAppConfigurationTests |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/audit/impl/AbstractOperationAuditor.java | {
"start": 1871,
"end": 5797
} | class ____ extends AbstractService
implements OperationAuditor {
private static final Logger LOG =
LoggerFactory.getLogger(AbstractOperationAuditor.class);
/**
* Base of IDs is a UUID.
*/
public static final String BASE = UUID.randomUUID().toString();
/**
* Counter to create unique auditor IDs.
*/
private static final AtomicLong SPAN_ID_COUNTER = new AtomicLong(1);
/**
* Destination for recording statistics, especially duration/count of
* operations.
* Set in {@link #init(OperationAuditorOptions)}.
*/
private IOStatisticsStore iostatistics;
/**
* Options: set in {@link #init(OperationAuditorOptions)}.
*/
private OperationAuditorOptions options;
/**
* Should out of span requests be rejected?
*/
private AtomicBoolean rejectOutOfSpan = new AtomicBoolean(false);
/**
* Auditor ID as a UUID.
*/
private final UUID auditorUUID = UUID.randomUUID();
/**
* ID of the auditor, which becomes that of the filesystem
* in request contexts.
*/
private final String auditorID = auditorUUID.toString();
/**
* Audit flags which can be passed down to subclasses.
*/
private EnumSet<AuditorFlags> auditorFlags;
/**
* Construct.
* @param name name
*
*/
protected AbstractOperationAuditor(final String name) {
super(name);
}
/**
* Sets the IOStats and then calls init().
* @param opts options to initialize with.
*/
@Override
public void init(final OperationAuditorOptions opts) {
this.options = opts;
this.iostatistics = requireNonNull(opts.getIoStatisticsStore());
init(opts.getConfiguration());
}
@Override
protected void serviceInit(final Configuration conf) throws Exception {
super.serviceInit(conf);
setRejectOutOfSpan(AuditIntegration.isRejectOutOfSpan(conf));
LOG.debug("{}: Out of span operations will be {}",
getName(),
isRejectOutOfSpan() ? "rejected" : "ignored");
}
@Override
public String getAuditorId() {
return auditorID;
}
/**
* Get the IOStatistics Store.
* @return the IOStatistics store updated with statistics.
*/
public IOStatisticsStore getIOStatistics() {
return iostatistics;
}
/**
* Get the options this auditor was initialized with.
* @return options.
*/
protected OperationAuditorOptions getOptions() {
return options;
}
/**
* Create a span ID.
* @return a unique span ID.
*/
protected final String createSpanID() {
return String.format("%s-%08d",
auditorID, SPAN_ID_COUNTER.incrementAndGet());
}
/**
* Should out of scope ops be rejected?
* @return true if out of span calls should be rejected.
*/
protected boolean isRejectOutOfSpan() {
return rejectOutOfSpan.get();
}
/**
* Enable/disable out of span rejection.
* @param rejectOutOfSpan new value.
*/
protected void setRejectOutOfSpan(boolean rejectOutOfSpan) {
this.rejectOutOfSpan.set(rejectOutOfSpan);
}
/**
* Update Auditor flags.
* Calls {@link #auditorFlagsChanged(EnumSet)} after the update.
* @param flags audit flags.
*/
@Override
public void setAuditFlags(final EnumSet<AuditorFlags> flags) {
auditorFlags = flags;
auditorFlagsChanged(flags);
}
/**
* Get the current set of auditor flags.
*
* @return the current set of auditor flags.
*/
public EnumSet<AuditorFlags> getAuditorFlags() {
return auditorFlags;
}
/**
* Notification that the auditor flags have been updated.
* @param flags audit flags.
*/
protected void auditorFlagsChanged(EnumSet<AuditorFlags> flags) {
// if out of band operations are allowed, configuration settings are overridden
if (flags.contains(AuditorFlags.PermitOutOfBandOperations)) {
LOG.debug("Out of span operations are required by the stream factory");
setRejectOutOfSpan(false);
}
}
}
| AbstractOperationAuditor |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java | {
"start": 71101,
"end": 72248
} | class ____ implements PropertyAccessor {
private String mapName;
public TestPropertyAccessor(String mapName) {
this.mapName = mapName;
}
@SuppressWarnings("unchecked")
public Map<String, String> getMap(Object target) {
try {
Field f = target.getClass().getDeclaredField(mapName);
return (Map<String, String>) f.get(target);
}
catch (Exception ex) {
}
return null;
}
@Override
public boolean canRead(EvaluationContext context, Object target, String name) {
return getMap(target).containsKey(name);
}
@Override
public boolean canWrite(EvaluationContext context, Object target, String name) {
return getMap(target).containsKey(name);
}
@Override
public Class<?>[] getSpecificTargetClasses() {
return new Class<?>[] {ContextObject.class};
}
@Override
public TypedValue read(EvaluationContext context, Object target, String name) {
return new TypedValue(getMap(target).get(name));
}
@Override
public void write(EvaluationContext context, Object target, String name, Object newValue) {
getMap(target).put(name, (String) newValue);
}
}
static | TestPropertyAccessor |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/api/Schema.java | {
"start": 44312,
"end": 45696
} | class ____ {
private final String columnName;
private final Expression watermarkExpression;
public UnresolvedWatermarkSpec(String columnName, Expression watermarkExpression) {
this.columnName = columnName;
this.watermarkExpression = watermarkExpression;
}
public String getColumnName() {
return columnName;
}
public Expression getWatermarkExpression() {
return watermarkExpression;
}
@Override
public String toString() {
return String.format(
"WATERMARK FOR %s AS %s",
EncodingUtils.escapeIdentifier(columnName),
watermarkExpression.asSummaryString());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UnresolvedWatermarkSpec that = (UnresolvedWatermarkSpec) o;
return columnName.equals(that.columnName)
&& watermarkExpression.equals(that.watermarkExpression);
}
@Override
public int hashCode() {
return Objects.hash(columnName, watermarkExpression);
}
}
/** Super | UnresolvedWatermarkSpec |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RemoveUnusedImportsTest.java | {
"start": 13226,
"end": 13476
} | interface ____ {}
}
""")
.addSourceLines(
"B.java",
"""
package pkg;
// BUG: Diagnostic contains: resolves to pkg.A.List
import java.util.List;
| List |
java | apache__camel | components/camel-jetty/src/test/java/org/apache/camel/component/jetty/rest/RestJettyGetTest.java | {
"start": 1126,
"end": 2232
} | class ____ extends BaseJettyTest {
@Test
public void testJettyProducerGet() {
String out = template.requestBody("http://localhost:" + getPort() + "/users/123/basic", null, String.class);
assertEquals("123;Donald Duck", out);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// configure to use jetty on localhost with the given port
restConfiguration().component("jetty").host("localhost").port(getPort());
// use the rest DSL to define the rest services
rest("/users/").get("{id}/basic").to("direct:basic");
from("direct:basic").to("mock:input").process(new Processor() {
public void process(Exchange exchange) {
String id = exchange.getIn().getHeader("id", String.class);
exchange.getMessage().setBody(id + ";Donald Duck");
}
});
}
};
}
}
| RestJettyGetTest |
java | google__guava | android/guava/src/com/google/common/collect/RegularContiguousSet.java | {
"start": 7690,
"end": 8465
} | class ____<C extends Comparable> implements Serializable {
final Range<C> range;
final DiscreteDomain<C> domain;
private SerializedForm(Range<C> range, DiscreteDomain<C> domain) {
this.range = range;
this.domain = domain;
}
private Object readResolve() {
return new RegularContiguousSet<>(range, domain);
}
}
@GwtIncompatible
@J2ktIncompatible
@Override
Object writeReplace() {
return new SerializedForm<>(range, domain);
}
@GwtIncompatible
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Use SerializedForm");
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
| SerializedForm |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java | {
"start": 75056,
"end": 75496
} | class ____<
K extends Number, V extends Comparable<K>> {
public abstract ImmutableMap<String, V> map();
public abstract ImmutableTable<String, K, V> table();
public static <K extends Number, V extends Comparable<K>> Builder<K, V> builder() {
return new AutoValue_AutoValueTest_BuilderWithExoticPropertyBuilders.Builder<K, V>();
}
@AutoValue.Builder
public abstract static | BuilderWithExoticPropertyBuilders |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/mock/web/MockHttpServletMapping.java | {
"start": 1087,
"end": 2123
} | class ____ implements HttpServletMapping {
private final String matchValue;
private final String pattern;
private final String servletName;
private final @Nullable MappingMatch mappingMatch;
public MockHttpServletMapping(
String matchValue, String pattern, String servletName, @Nullable MappingMatch match) {
this.matchValue = matchValue;
this.pattern = pattern;
this.servletName = servletName;
this.mappingMatch = match;
}
@Override
public String getMatchValue() {
return this.matchValue;
}
@Override
public String getPattern() {
return this.pattern;
}
@Override
public String getServletName() {
return this.servletName;
}
@Override
public @Nullable MappingMatch getMappingMatch() {
return this.mappingMatch;
}
@Override
public String toString() {
return "MockHttpServletMapping [matchValue=\"" + this.matchValue + "\", " +
"pattern=\"" + this.pattern + "\", servletName=\"" + this.servletName + "\", " +
"mappingMatch=" + this.mappingMatch + "]";
}
}
| MockHttpServletMapping |
java | apache__spark | common/sketch/src/main/java/org/apache/spark/util/sketch/Platform.java | {
"start": 1032,
"end": 5344
} | class ____ {
private static final Unsafe _UNSAFE;
public static final int BYTE_ARRAY_OFFSET;
public static final int INT_ARRAY_OFFSET;
public static final int LONG_ARRAY_OFFSET;
public static final int DOUBLE_ARRAY_OFFSET;
public static int getInt(Object object, long offset) {
return _UNSAFE.getInt(object, offset);
}
public static void putInt(Object object, long offset, int value) {
_UNSAFE.putInt(object, offset, value);
}
public static boolean getBoolean(Object object, long offset) {
return _UNSAFE.getBoolean(object, offset);
}
public static void putBoolean(Object object, long offset, boolean value) {
_UNSAFE.putBoolean(object, offset, value);
}
public static byte getByte(Object object, long offset) {
return _UNSAFE.getByte(object, offset);
}
public static void putByte(Object object, long offset, byte value) {
_UNSAFE.putByte(object, offset, value);
}
public static short getShort(Object object, long offset) {
return _UNSAFE.getShort(object, offset);
}
public static void putShort(Object object, long offset, short value) {
_UNSAFE.putShort(object, offset, value);
}
public static long getLong(Object object, long offset) {
return _UNSAFE.getLong(object, offset);
}
public static void putLong(Object object, long offset, long value) {
_UNSAFE.putLong(object, offset, value);
}
public static float getFloat(Object object, long offset) {
return _UNSAFE.getFloat(object, offset);
}
public static void putFloat(Object object, long offset, float value) {
_UNSAFE.putFloat(object, offset, value);
}
public static double getDouble(Object object, long offset) {
return _UNSAFE.getDouble(object, offset);
}
public static void putDouble(Object object, long offset, double value) {
_UNSAFE.putDouble(object, offset, value);
}
public static Object getObjectVolatile(Object object, long offset) {
return _UNSAFE.getObjectVolatile(object, offset);
}
public static void putObjectVolatile(Object object, long offset, Object value) {
_UNSAFE.putObjectVolatile(object, offset, value);
}
public static long allocateMemory(long size) {
return _UNSAFE.allocateMemory(size);
}
public static void freeMemory(long address) {
_UNSAFE.freeMemory(address);
}
public static void copyMemory(
Object src, long srcOffset, Object dst, long dstOffset, long length) {
// Check if dstOffset is before or after srcOffset to determine if we should copy
// forward or backwards. This is necessary in case src and dst overlap.
if (dstOffset < srcOffset) {
while (length > 0) {
long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
_UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size);
length -= size;
srcOffset += size;
dstOffset += size;
}
} else {
srcOffset += length;
dstOffset += length;
while (length > 0) {
long size = Math.min(length, UNSAFE_COPY_THRESHOLD);
srcOffset -= size;
dstOffset -= size;
_UNSAFE.copyMemory(src, srcOffset, dst, dstOffset, size);
length -= size;
}
}
}
/**
* Raises an exception bypassing compiler checks for checked exceptions.
*/
public static void throwException(Throwable t) {
_UNSAFE.throwException(t);
}
/**
* Limits the number of bytes to copy per {@link Unsafe#copyMemory(long, long, long)} to
* allow safepoint polling during a large copy.
*/
private static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L;
static {
sun.misc.Unsafe unsafe;
try {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = (sun.misc.Unsafe) unsafeField.get(null);
} catch (Throwable cause) {
unsafe = null;
}
_UNSAFE = unsafe;
if (_UNSAFE != null) {
BYTE_ARRAY_OFFSET = _UNSAFE.arrayBaseOffset(byte[].class);
INT_ARRAY_OFFSET = _UNSAFE.arrayBaseOffset(int[].class);
LONG_ARRAY_OFFSET = _UNSAFE.arrayBaseOffset(long[].class);
DOUBLE_ARRAY_OFFSET = _UNSAFE.arrayBaseOffset(double[].class);
} else {
BYTE_ARRAY_OFFSET = 0;
INT_ARRAY_OFFSET = 0;
LONG_ARRAY_OFFSET = 0;
DOUBLE_ARRAY_OFFSET = 0;
}
}
}
| Platform |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/sort/BufferedKVExternalSorterTest.java | {
"start": 2431,
"end": 7499
} | class ____ {
private static final int PAGE_SIZE = MemoryManager.DEFAULT_PAGE_SIZE;
private IOManager ioManager;
private BinaryRowDataSerializer keySerializer;
private BinaryRowDataSerializer valueSerializer;
private NormalizedKeyComputer computer;
private RecordComparator comparator;
private int spillNumber;
private int recordNumberPerFile;
private Configuration conf;
BufferedKVExternalSorterTest(int spillNumber, int recordNumberPerFile, boolean spillCompress) {
ioManager = new IOManagerAsync();
conf = new Configuration();
conf.set(ExecutionConfigOptions.TABLE_EXEC_SORT_MAX_NUM_FILE_HANDLES, 5);
if (!spillCompress) {
conf.set(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_ENABLED, false);
}
this.spillNumber = spillNumber;
this.recordNumberPerFile = recordNumberPerFile;
}
@Parameters(name = "spillNumber-{0} recordNumberPerFile-{1} spillCompress-{2}")
private static List<Object[]> getDataSize() {
List<Object[]> paras = new ArrayList<>();
paras.add(new Object[] {3, 1000, true});
paras.add(new Object[] {3, 1000, false});
paras.add(new Object[] {10, 1000, true});
paras.add(new Object[] {10, 1000, false});
paras.add(new Object[] {10, 10000, true});
paras.add(new Object[] {10, 10000, false});
return paras;
}
@BeforeEach
void beforeTest() throws InstantiationException, IllegalAccessException {
this.ioManager = new IOManagerAsync();
this.keySerializer = new BinaryRowDataSerializer(2);
this.valueSerializer = new BinaryRowDataSerializer(2);
this.computer = IntNormalizedKeyComputer.INSTANCE;
this.comparator = IntRecordComparator.INSTANCE;
}
@AfterEach
void afterTest() throws Exception {
this.ioManager.close();
}
@TestTemplate
void test() throws Exception {
BufferedKVExternalSorter sorter =
new BufferedKVExternalSorter(
ioManager,
keySerializer,
valueSerializer,
computer,
comparator,
PAGE_SIZE,
conf.get(ExecutionConfigOptions.TABLE_EXEC_SORT_MAX_NUM_FILE_HANDLES),
conf.get(ExecutionConfigOptions.TABLE_EXEC_SPILL_COMPRESSION_ENABLED),
(int)
conf.get(
ExecutionConfigOptions
.TABLE_EXEC_SPILL_COMPRESSION_BLOCK_SIZE)
.getBytes());
TestMemorySegmentPool pool = new TestMemorySegmentPool(PAGE_SIZE);
List<Integer> expected = new ArrayList<>();
for (int i = 0; i < spillNumber; i++) {
ArrayList<MemorySegment> segments = new ArrayList<>();
SimpleCollectingOutputView out =
new SimpleCollectingOutputView(segments, pool, PAGE_SIZE);
writeKVToBuffer(keySerializer, valueSerializer, out, expected, recordNumberPerFile);
sorter.sortAndSpill(segments, recordNumberPerFile, pool);
}
Collections.sort(expected);
MutableObjectIterator<Tuple2<BinaryRowData, BinaryRowData>> iterator =
sorter.getKVIterator();
Tuple2<BinaryRowData, BinaryRowData> kv =
new Tuple2<>(keySerializer.createInstance(), valueSerializer.createInstance());
int count = 0;
while ((kv = iterator.next(kv)) != null) {
assertThat(kv.f0.getInt(0)).isEqualTo((int) expected.get(count));
assertThat(kv.f1.getInt(0)).isEqualTo(expected.get(count) * -3 + 177);
count++;
}
assertThat(count).isEqualTo(expected.size());
sorter.close();
}
private void writeKVToBuffer(
BinaryRowDataSerializer keySerializer,
BinaryRowDataSerializer valueSerializer,
SimpleCollectingOutputView out,
List<Integer> expecteds,
int length)
throws IOException {
Random random = new Random();
int stringLength = 30;
for (int i = 0; i < length; i++) {
BinaryRowData key = randomRow(random, stringLength);
BinaryRowData val = key.copy();
val.setInt(0, val.getInt(0) * -3 + 177);
expecteds.add(key.getInt(0));
keySerializer.serializeToPages(key, out);
valueSerializer.serializeToPages(val, out);
}
}
public static BinaryRowData randomRow(Random random, int stringLength) {
BinaryRowData row = new BinaryRowData(2);
BinaryRowWriter writer = new BinaryRowWriter(row);
writer.writeInt(0, random.nextInt());
writer.writeString(1, StringData.fromString(RandomStringUtils.random(stringLength)));
writer.complete();
return row;
}
}
| BufferedKVExternalSorterTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/map/MapAssert_containsValue_Test.java | {
"start": 965,
"end": 1601
} | class ____ extends MapAssertBaseTest {
@Override
protected MapAssert<Object, Object> invoke_api_method() {
return assertions.containsValue("value1");
}
@Override
protected void verify_internal_effects() {
Mockito.verify(maps).assertContainsValue(getInfo(assertions), getActual(assertions), (Object) "value1", null);
}
@Test
void should_honor_custom_value_equals_when_comparing_entry_values() {
// GIVEN
var map = map("key1", "value1", "key2", "value2");
// WHEN/THEN
then(map).usingEqualsForValues(String::equalsIgnoreCase)
.containsValue("VALUE1");
}
}
| MapAssert_containsValue_Test |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/util/JSONWrappedObject.java | {
"start": 187,
"end": 496
} | class ____ can be used to decorate serialized
* value with arbitrary literal prefix and suffix. This can be used for
* example to construct arbitrary Javascript values (similar to how basic
* function name and parenthesis are used with JSONP).
*
* @see tools.jackson.databind.util.JSONPObject
*/
public | that |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/jackson/SavedCookieMixinTests.java | {
"start": 1128,
"end": 3631
} | class ____ extends AbstractMixinTests {
// @formatter:off
private static final String COOKIE_JSON = "{"
+ "\"@class\": \"org.springframework.security.web.savedrequest.SavedCookie\", "
+ "\"name\": \"SESSION\", "
+ "\"value\": \"123456789\", "
+ "\"maxAge\": -1, "
+ "\"path\": null, "
+ "\"secure\":false, "
+ "\"domain\": null"
+ "}";
// @formatter:on
// @formatter:off
private static final String COOKIES_JSON = "[\"java.util.ArrayList\", ["
+ COOKIE_JSON
+ "]]";
// @formatter:on
@Test
public void serializeWithDefaultConfigurationTest() throws JacksonException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
String actualJson = this.mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(COOKIE_JSON, actualJson, true);
}
@Test
@Disabled("No supported by Jackson 3 as ObjectMapper/JsonMapper is immutable")
public void serializeWithOverrideConfigurationTest() throws JacksonException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
// this.mapper.setVisibility(PropertyAccessor.FIELD,
// JsonAutoDetect.Visibility.PUBLIC_ONLY)
// .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
String actualJson = this.mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(COOKIE_JSON, actualJson, true);
}
@Test
public void serializeSavedCookieWithList() throws JacksonException, JSONException {
List<SavedCookie> savedCookies = new ArrayList<>();
savedCookies.add(new SavedCookie(new Cookie("SESSION", "123456789")));
String actualJson = this.mapper.writeValueAsString(savedCookies);
JSONAssert.assertEquals(COOKIES_JSON, actualJson, true);
}
@Test
@SuppressWarnings("unchecked")
public void deserializeSavedCookieWithList() {
List<SavedCookie> savedCookies = (List<SavedCookie>) this.mapper.readValue(COOKIES_JSON, Object.class);
assertThat(savedCookies).isNotNull().hasSize(1);
assertThat(savedCookies.get(0).getName()).isEqualTo("SESSION");
assertThat(savedCookies.get(0).getValue()).isEqualTo("123456789");
}
@Test
public void deserializeSavedCookieJsonTest() {
SavedCookie savedCookie = (SavedCookie) this.mapper.readValue(COOKIE_JSON, Object.class);
assertThat(savedCookie).isNotNull();
assertThat(savedCookie.getName()).isEqualTo("SESSION");
assertThat(savedCookie.getValue()).isEqualTo("123456789");
assertThat(savedCookie.isSecure()).isEqualTo(false);
}
}
| SavedCookieMixinTests |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ProxyType.java | {
"start": 689,
"end": 812
} | enum ____ indicating a desired proxy type.
*
* @author Juergen Hoeller
* @since 7.0
* @see Proxyable#value()
*/
public | for |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/HistogramValues.java | {
"start": 599,
"end": 1058
} | class ____ {
/**
* Advance this instance to the given document id
* @return true if there is a value for this document
*/
public abstract boolean advanceExact(int doc) throws IOException;
/**
* Get the {@link HistogramValue} associated with the current document.
* The returned {@link HistogramValue} might be reused across calls.
*/
public abstract HistogramValue histogram() throws IOException;
}
| HistogramValues |
java | quarkusio__quarkus | extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/errors/EchoOpenError.java | {
"start": 265,
"end": 573
} | class ____ {
static final CountDownLatch OPEN_CALLED = new CountDownLatch(1);
@OnOpen
void open() {
OPEN_CALLED.countDown();
throw new IllegalStateException("I cannot do it!");
}
@OnTextMessage
String echo(String message) {
return message;
}
} | EchoOpenError |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsManagedHttpRequestExecutor.java | {
"start": 1676,
"end": 4311
} | class ____ extends HttpRequestExecutor {
public AbfsManagedHttpRequestExecutor(final int expect100WaitTimeout) {
super(expect100WaitTimeout);
}
/**{@inheritDoc}*/
@Override
public HttpResponse execute(final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context) throws IOException, HttpException {
if (context instanceof AbfsManagedHttpClientContext
&& conn instanceof AbfsManagedApacheHttpConnection) {
((AbfsManagedApacheHttpConnection) conn).setManagedHttpContext(
(AbfsManagedHttpClientContext) context);
}
return super.execute(request, conn, context);
}
/**{@inheritDoc}*/
@Override
protected HttpResponse doSendRequest(final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context) throws IOException, HttpException {
final HttpClientConnection inteceptedConnection;
if (context instanceof AbfsManagedHttpClientContext) {
inteceptedConnection
= ((AbfsManagedHttpClientContext) context).interceptConnectionActivity(
conn);
} else {
inteceptedConnection = conn;
}
final HttpResponse res = super.doSendRequest(request, inteceptedConnection,
context);
/*
* ApacheHttpClient implementation does not raise an exception if the status
* of expect100 hand-shake is not less than 200. Although it sends payload only
* if the statusCode of the expect100 hand-shake is 100.
*
* ADLS can send any failure statusCode in exect100 handshake. So, an exception
* needs to be explicitly raised if expect100 assertion is failure but the
* ApacheHttpClient has not raised an exception.
*
* Response is only returned by this method if there is no expect100 request header
* or the expect100 assertion is failed.
*/
if (request != null && request.containsHeader(EXPECT) && res != null) {
throw new AbfsApacheHttpExpect100Exception(res);
}
return res;
}
/**{@inheritDoc}*/
@Override
protected HttpResponse doReceiveResponse(final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context) throws HttpException, IOException {
final HttpClientConnection interceptedConnection;
if (context instanceof AbfsManagedHttpClientContext) {
interceptedConnection
= ((AbfsManagedHttpClientContext) context).interceptConnectionActivity(
conn);
} else {
interceptedConnection = conn;
}
return super.doReceiveResponse(request,
interceptedConnection, context);
}
}
| AbfsManagedHttpRequestExecutor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cid/CompositeIdWithGeneratorTest.java | {
"start": 1124,
"end": 12350
} | class ____ {
private DateFormat df = SimpleDateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG );
private Calendar cal = new GregorianCalendar( 2021, 1, 31, 17, 30, 0 );
@Test
public void testCompositeIdSimple(SessionFactoryScope scope) {
PurchaseRecord record = new PurchaseRecord();
scope.inTransaction(
session -> {
// persist the record to get the id generated
record.setTimestamp( cal.getTime() );
session.persist( record );
}
);
// test that the id was generated
PurchaseRecord.Id generatedId = record.getId();
Date timestamp = record.getTimestamp();
assertThat( generatedId ).isNotNull();
assertThat( generatedId.getPurchaseSequence() ).isNotNull();
assertTrue( generatedId.getPurchaseNumber() > 0 );
PurchaseRecord find1 = scope.fromTransaction(
session -> {
// find the record, and see that the ids match
PurchaseRecord find = session.get( PurchaseRecord.class, generatedId );
assertThat( find ).isNotNull();
assertThat( find.getId() ).isEqualTo( generatedId );
assertThat( df.format( find.getTimestamp() ) ).isEqualTo( df.format( timestamp ) );
return find;
}
);
PurchaseRecord record2 = new PurchaseRecord();
scope.inTransaction(
session -> {
// generate another new record
cal.roll( Calendar.SECOND, true );
record2.setTimestamp( cal.getTime() );
session.persist( record2 );
}
);
PurchaseRecord.Id generatedId2 = record2.getId();
Date timestamp2 = record2.getTimestamp();
PurchaseRecord find2 = scope.fromTransaction(
session -> {
return session.get( PurchaseRecord.class, generatedId2 );
}
);
// test that the ids are different
PurchaseRecord.Id id1 = find1.getId();
PurchaseRecord.Id id2 = find2.getId();
String seq1 = id1.getPurchaseSequence();
String seq2 = id2.getPurchaseSequence();
int num1 = id1.getPurchaseNumber();
int num2 = id2.getPurchaseNumber();
assertThat( df.format( find2.getTimestamp() ) ).isEqualTo( df.format( timestamp2 ) );
assertThat( id1 ).isNotEqualTo( id2 );
assertThat( seq1 ).isNotEqualTo( seq2 );
assertThat( num1 ).isNotEqualTo( num2 );
}
@Test
public void testDetachedProperty(SessionFactoryScope scope) {
PurchaseRecord record = new PurchaseRecord();
scope.inTransaction(
session -> {
// persist the record
cal.roll( Calendar.SECOND, true );
record.setTimestamp( cal.getTime() );
session.persist( record );
}
);
PurchaseRecord.Id generatedId = record.getId();
// change a non-id property, but do not persist
Date persistedTimestamp = record.getTimestamp();
cal.roll( Calendar.SECOND, true );
Date newTimestamp = cal.getTime();
record.setTimestamp( newTimestamp );
PurchaseRecord find = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId )
);
// see that we get the original id, and the original timestamp
assertThat( find.getId() ).isEqualTo( generatedId );
assertThat( df.format( find.getTimestamp() ) ).isEqualTo( df.format( persistedTimestamp ) );
scope.inTransaction(
session -> {
// update with the new timestamp
session.merge( record );
}
);
// find the newly updated record
PurchaseRecord find2 = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId )
);
// see that we get the original id, and the new timestamp
assertThat( find2.getId() ).isEqualTo( generatedId );
assertThat( df.format( find2.getTimestamp() ) ).isEqualTo( df.format( newTimestamp ) );
}
@Test
public void testDetachedId(SessionFactoryScope scope) {
Date timestamp1 = cal.getTime();
cal.roll( Calendar.SECOND, true );
Date timestamp2 = cal.getTime();
PurchaseRecord record1 = new PurchaseRecord();
PurchaseRecord record2 = new PurchaseRecord();
scope.inTransaction(
session -> {
// persist two records
record1.setTimestamp( timestamp1 );
record2.setTimestamp( timestamp2 );
session.persist( record1 );
session.persist( record2 );
}
);
PurchaseRecord.Id generatedId1 = record1.getId();
PurchaseRecord.Id generatedId2 = record2.getId();
// change the ids around - effectively making record1 have the same id as record2
// do not persist yet
PurchaseRecord.Id toChangeId1 = new PurchaseRecord.Id();
toChangeId1.setPurchaseNumber( record2.getId().getPurchaseNumber() );
toChangeId1.setPurchaseSequence( record2.getId().getPurchaseSequence() );
record1.setId( toChangeId1 );
PurchaseRecord find1 = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId1 )
);
PurchaseRecord find2 = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId2 )
);
// see that we get the original ids (and timestamps)
// i.e. weren't changed by changing the detached object
assertThat( find1.getId() ).isEqualTo( generatedId1 );
assertThat( df.format( find1.getTimestamp() ) ).isEqualTo( df.format( timestamp1 ) );
assertThat( find2.getId() ).isEqualTo( generatedId2 );
assertThat( df.format( find2.getTimestamp() ) ).isEqualTo( df.format( timestamp2 ) );
scope.inTransaction(
session ->
// update with the new changed record id
session.merge( record1 )
);
// test that record1 did not get a new generated id, and kept record2's id
PurchaseRecord.Id foundId1 = record1.getId();
assertThat( toChangeId1 ).isSameAs( foundId1 );
assertThat( foundId1.getPurchaseNumber() ).isEqualTo( toChangeId1.getPurchaseNumber() );
assertThat( foundId1.getPurchaseSequence() ).isEqualTo( toChangeId1.getPurchaseSequence() );
// find record 2 and see that it has the timestamp originally found in record 1
PurchaseRecord find3 = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId2 )
);
// see that we get the original id (2), and the new timestamp (1)
assertThat( df.format( find3.getTimestamp() ) ).isEqualTo( df.format( timestamp1 ) );
assertThat( find3.getId() ).isEqualTo( generatedId2 );
}
@Test
public void testLoad(SessionFactoryScope scope) {
PurchaseRecord record = new PurchaseRecord();
scope.inTransaction(
session -> {
// persist the record, then get the id and timestamp back
record.setTimestamp( cal.getTime() );
session.persist( record );
}
);
PurchaseRecord.Id id = record.getId();
Date timestamp = record.getTimestamp();
// using the given id, load a transient record
PurchaseRecord toLoad = new PurchaseRecord();
scope.inTransaction(
session ->
session.load( toLoad, id )
);
// show that the correct timestamp and ids were loaded
assertThat( toLoad.getId() ).isEqualTo( id );
assertThat( df.format( toLoad.getTimestamp() ) ).isEqualTo( df.format( timestamp ) );
}
@Test
public void testEvict(SessionFactoryScope scope) {
Date timestamp1 = cal.getTime();
cal.roll( Calendar.SECOND, true );
Date timestamp2 = cal.getTime();
PurchaseRecord record = new PurchaseRecord();
scope.inTransaction(
session -> {
// persist the record, then evict it, then make changes to it ("within" the session)
record.setTimestamp( timestamp1 );
session.persist( record );
session.flush();
session.evict( record );
record.setTimestamp( timestamp2 );
}
);
PurchaseRecord.Id generatedId = record.getId();
// now, re-fetch the record and show that the timestamp change wasn't persisted
PurchaseRecord persistent = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId )
);
assertThat( persistent.getId() ).isEqualTo( generatedId );
assertThat( df.format( persistent.getTimestamp() ) ).isEqualTo( df.format( timestamp1 ) );
}
@Test
public void testMerge(SessionFactoryScope scope) {
Date timestamp1 = cal.getTime();
cal.roll( Calendar.SECOND, true );
Date timestamp2 = cal.getTime();
PurchaseRecord record = new PurchaseRecord();
scope.inTransaction(
session -> {
// persist the record
record.setTimestamp( timestamp1 );
session.persist( record );
}
);
// test that the id was generated
PurchaseRecord.Id generatedId = record.getId();
assertThat( generatedId ).isNotNull();
assertThat( generatedId.getPurchaseSequence() ).isNotNull();
PurchaseRecord persistent = scope.fromTransaction(
session -> {
// update detached object, retrieve persistent object, then merge
PurchaseRecord detached = record;
detached.setTimestamp( timestamp2 );
PurchaseRecord p = session.get( PurchaseRecord.class, generatedId );
// show that the timestamp hasn't changed
assertThat( df.format( p.getTimestamp() ) ).isEqualTo( df.format( timestamp1 ) );
session.merge( detached );
return p;
}
);
// show that the persistent object was changed only after the session flush
assertThat( df.format( persistent.getTimestamp() ) ).isEqualTo( df.format( timestamp2 ) );
// show that the persistent store was updated - not just the in-memory object
scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId )
);
assertThat( df.format( persistent.getTimestamp() ) ).isEqualTo( df.format( timestamp2 ) );
}
@Test
public void testDelete(SessionFactoryScope scope) {
PurchaseRecord record = new PurchaseRecord();
// persist the record
scope.inTransaction(
session ->
session.persist( record )
);
PurchaseRecord.Id generatedId = record.getId();
// re-fetch, then delete the record
scope.inTransaction(
session -> {
PurchaseRecord find = session.get( PurchaseRecord.class, generatedId );
session.remove( find );
assertFalse( session.contains( find ) );
}
);
// attempt to re-fetch - show it was deleted
PurchaseRecord find = scope.fromTransaction(
session ->
session.get( PurchaseRecord.class, generatedId )
);
assertThat( find ).isNull();
}
@Test
public void testGeneratedIdsWithChildren(SessionFactoryScope scope) {
// set up the record and details
PurchaseRecord record = new PurchaseRecord();
Set details = record.getDetails();
details.add( new PurchaseDetail( record, "p@1", 1 ) );
details.add( new PurchaseDetail( record, "p@2", 2 ) );
scope.inTransaction(
session ->
session.persist( record )
);
// show that the ids were generated (non-zero) and come out the same
int foundPurchaseNumber = record.getId().getPurchaseNumber();
String foundPurchaseSequence = record.getId().getPurchaseSequence();
assertThat( record.getId() ).isNotNull();
assertThat( foundPurchaseNumber ).isGreaterThan( 0 );
assertThat( foundPurchaseSequence ).isNotNull();
// search on detail1 by itself and show it got the parent's id
// doAfterTransactionCompletion a find to show that it will wire together fine
PurchaseRecord foundRecord = scope.fromTransaction(
session ->
session.get(
PurchaseRecord.class,
new PurchaseRecord.Id( foundPurchaseNumber, foundPurchaseSequence )
)
);
// some simple test to see it fetched
assertThat( foundRecord.getDetails().size() ).isEqualTo( 2 );
}
}
| CompositeIdWithGeneratorTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/EmptySetMultibindingContributionsTest.java | {
"start": 1302,
"end": 2842
} | class ____ {
@Parameters(name = "{0}")
public static List<Object[]> data() {
return Arrays.asList(
new Object[][] {
{Collections.class.getCanonicalName() + ".emptySet()"},
{ImmutableSet.class.getCanonicalName() + ".of()"},
{ImmutableSortedSet.class.getCanonicalName() + ".of()"},
{"new " + HashSet.class.getCanonicalName() + "<>()"},
{"new " + LinkedHashSet.class.getCanonicalName() + "<>()"},
{"new " + TreeSet.class.getCanonicalName() + "<>()"},
{Sets.class.getCanonicalName() + ".newHashSet()"},
{Sets.class.getCanonicalName() + ".newLinkedHashSet()"},
{Sets.class.getCanonicalName() + ".newConcurrentHashSet()"},
{EnumSet.class.getCanonicalName() + ".noneOf(java.util.concurrent.TimeUnit.class)"},
});
}
private final String emptySetSnippet;
private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(
EmptySetMultibindingContributions.class, getClass());
public EmptySetMultibindingContributionsTest(String emptySetSnippet) {
this.emptySetSnippet = emptySetSnippet;
}
@Test
public void elementsIntoSetMethod_emptySet() {
testHelper
.addInputLines(
"in/Test.java",
"import dagger.Module;",
"import dagger.Provides;",
"import dagger.multibindings.ElementsIntoSet;",
"import java.util.Set;",
"@Module",
" | EmptySetMultibindingContributionsTest |
java | apache__logging-log4j2 | log4j-1.2-api/src/test/java/org/apache/log4j/xml/DOMTestCase.java | {
"start": 4172,
"end": 6847
} | class ____ checked when evaluating parameters. See bug 43325.
*
*/
@Test
void testOverrideSubst() {
final DOMConfigurator configurator = new DOMConfigurator();
configurator.doConfigure(
DOMTestCase.class.getResource("/DOMTestCase/DOMTestCase1.xml"), LogManager.getLoggerRepository());
final String name = "A1";
final Appender appender = Logger.getRootLogger().getAppender(name);
assertNotNull(appender, name);
final AppenderWrapper wrapper = (AppenderWrapper) appender;
assertNotNull(wrapper, name);
final org.apache.logging.log4j.core.appender.FileAppender a1 =
(org.apache.logging.log4j.core.appender.FileAppender) wrapper.getAppender();
assertNotNull(a1, wrapper.toString());
final String file = a1.getFileName();
assertNotNull(file, a1.toString());
}
/**
* Tests that reset="true" on log4j:configuration element resets repository before configuration.
*
*/
@Test
void testReset() {
final VectorAppender appender = new VectorAppender();
appender.setName("V1");
Logger.getRootLogger().addAppender(appender);
DOMConfigurator.configure(DOMTestCase.class.getResource("/DOMTestCase/testReset.xml"));
assertNull(Logger.getRootLogger().getAppender("V1"));
}
/**
* Test of log4j.throwableRenderer support. See bug 45721.
*/
@Test
@UsingStatusListener
void testThrowableRenderer(ListStatusListener listener) {
DOMConfigurator.configure(DOMTestCase.class.getResource("/DOMTestCase/testThrowableRenderer.xml"));
assertThat(listener.findStatusData(org.apache.logging.log4j.Level.WARN))
.anySatisfy(status -> assertThat(status.getMessage().getFormattedMessage())
.contains("Log4j 1 throwable renderers are not supported"));
}
@Test
@SetTestProperty(key = "log4j1.compatibility", value = "false")
void when_compatibility_disabled_configurator_is_no_op() {
final Logger rootLogger = Logger.getRootLogger();
final Logger logger = Logger.getLogger("org.apache.log4j.xml");
assertThat(logger.getLevel()).isNull();
final URL configURL = DOMTestCase.class.getResource("/DOMTestCase/DOMTestCase1.xml");
DOMConfigurator.configure(configURL);
assertThat(rootLogger.getAppender("A1")).isNull();
assertThat(rootLogger.getAppender("A2")).isNull();
assertThat(rootLogger.getLevel()).isNotEqualTo(Level.TRACE);
assertThat(logger.getAppender("A1")).isNull();
assertThat(logger.getLevel()).isNull();
}
}
| is |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/util/concurrent/KeyedLockTests.java | {
"start": 5004,
"end": 8146
} | class ____ extends Thread {
private CountDownLatch startLatch;
KeyedLock<String> connectionLock;
String[] names;
ConcurrentHashMap<String, Integer> counter;
ConcurrentHashMap<String, AtomicInteger> safeCounter;
final int numRuns = scaledRandomIntBetween(5000, 50000);
public AcquireAndReleaseThread(
CountDownLatch startLatch,
KeyedLock<String> connectionLock,
String[] names,
ConcurrentHashMap<String, Integer> counter,
ConcurrentHashMap<String, AtomicInteger> safeCounter
) {
this.startLatch = startLatch;
this.connectionLock = connectionLock;
this.names = names;
this.counter = counter;
this.safeCounter = safeCounter;
}
@Override
public void run() {
startLatch.countDown();
try {
startLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < numRuns; i++) {
String curName = names[randomInt(names.length - 1)];
assert connectionLock.isHeldByCurrentThread(curName) == false;
Releasable lock;
if (randomIntBetween(0, 10) < 4) {
int tries = 0;
boolean stepOut = false;
while ((lock = connectionLock.tryAcquire(curName)) == null) {
assertFalse(connectionLock.isHeldByCurrentThread(curName));
if (tries++ == 10) {
stepOut = true;
break;
}
}
if (stepOut) {
break;
}
} else {
lock = connectionLock.acquire(curName);
}
try (Releasable ignore = lock) {
assert connectionLock.isHeldByCurrentThread(curName);
assert connectionLock.isHeldByCurrentThread(curName + "bla") == false;
if (randomBoolean()) {
try (Releasable reentrantIgnored = connectionLock.acquire(curName)) {
// just acquire this and make sure we can :)
Thread.yield();
}
}
Integer integer = counter.get(curName);
if (integer == null) {
counter.put(curName, 1);
} else {
counter.put(curName, integer.intValue() + 1);
}
}
AtomicInteger atomicInteger = new AtomicInteger(0);
AtomicInteger value = safeCounter.putIfAbsent(curName, atomicInteger);
if (value == null) {
atomicInteger.incrementAndGet();
} else {
value.incrementAndGet();
}
}
}
}
}
| AcquireAndReleaseThread |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/query/functionscore/FieldValueFactorFunctionBuilder.java | {
"start": 1396,
"end": 7639
} | class ____ extends ScoreFunctionBuilder<FieldValueFactorFunctionBuilder> {
public static final String NAME = "field_value_factor";
public static final FieldValueFactorFunction.Modifier DEFAULT_MODIFIER = FieldValueFactorFunction.Modifier.NONE;
public static final float DEFAULT_FACTOR = 1;
private final String field;
private float factor = DEFAULT_FACTOR;
private Double missing;
private FieldValueFactorFunction.Modifier modifier = DEFAULT_MODIFIER;
public FieldValueFactorFunctionBuilder(String fieldName) {
if (fieldName == null) {
throw new IllegalArgumentException("field_value_factor: field must not be null");
}
this.field = fieldName;
}
/**
* Read from a stream.
*/
public FieldValueFactorFunctionBuilder(StreamInput in) throws IOException {
super(in);
field = in.readString();
factor = in.readFloat();
missing = in.readOptionalDouble();
modifier = FieldValueFactorFunction.Modifier.readFromStream(in);
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeString(field);
out.writeFloat(factor);
out.writeOptionalDouble(missing);
modifier.writeTo(out);
}
@Override
public String getName() {
return NAME;
}
public String fieldName() {
return this.field;
}
public FieldValueFactorFunctionBuilder factor(float boostFactor) {
this.factor = boostFactor;
return this;
}
public float factor() {
return this.factor;
}
/**
* Value used instead of the field value for documents that don't have that field defined.
*/
public FieldValueFactorFunctionBuilder missing(double missing) {
this.missing = missing;
return this;
}
public Double missing() {
return this.missing;
}
public FieldValueFactorFunctionBuilder modifier(FieldValueFactorFunction.Modifier modifier) {
if (modifier == null) {
throw new IllegalArgumentException("field_value_factor: modifier must not be null");
}
this.modifier = modifier;
return this;
}
public FieldValueFactorFunction.Modifier modifier() {
return this.modifier;
}
@Override
public void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(getName());
builder.field("field", field);
builder.field("factor", factor);
if (missing != null) {
builder.field("missing", missing);
}
builder.field("modifier", modifier.name().toLowerCase(Locale.ROOT));
builder.endObject();
}
@Override
protected boolean doEquals(FieldValueFactorFunctionBuilder functionBuilder) {
return Objects.equals(this.field, functionBuilder.field)
&& Objects.equals(this.factor, functionBuilder.factor)
&& Objects.equals(this.missing, functionBuilder.missing)
&& Objects.equals(this.modifier, functionBuilder.modifier);
}
@Override
protected int doHashCode() {
return Objects.hash(this.field, this.factor, this.missing, this.modifier);
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
@Override
protected ScoreFunction doToFunction(SearchExecutionContext context) {
IndexNumericFieldData fieldData = null;
if (context.isFieldMapped(field)) {
fieldData = context.getForField(context.getFieldType(field), MappedFieldType.FielddataOperation.SEARCH);
} else {
if (missing == null) {
throw new ElasticsearchException("Unable to find a field mapper for field [" + field + "]. No 'missing' value defined.");
}
}
return new FieldValueFactorFunction(field, factor, modifier, missing, fieldData);
}
public static FieldValueFactorFunctionBuilder fromXContent(XContentParser parser) throws IOException, ParsingException {
String currentFieldName = null;
String field = null;
float boostFactor = FieldValueFactorFunctionBuilder.DEFAULT_FACTOR;
FieldValueFactorFunction.Modifier modifier = FieldValueFactorFunction.Modifier.NONE;
Double missing = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if ("field".equals(currentFieldName)) {
field = parser.text();
} else if ("factor".equals(currentFieldName)) {
boostFactor = parser.floatValue();
} else if ("modifier".equals(currentFieldName)) {
modifier = FieldValueFactorFunction.Modifier.fromString(parser.text());
} else if ("missing".equals(currentFieldName)) {
missing = parser.doubleValue();
} else {
throw new ParsingException(parser.getTokenLocation(), NAME + " query does not support [" + currentFieldName + "]");
}
} else if ("factor".equals(currentFieldName)
&& (token == XContentParser.Token.START_ARRAY || token == XContentParser.Token.START_OBJECT)) {
throw new ParsingException(
parser.getTokenLocation(),
"[" + NAME + "] field 'factor' does not support lists or objects"
);
}
}
if (field == null) {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] required field 'field' missing");
}
FieldValueFactorFunctionBuilder fieldValueFactorFunctionBuilder = new FieldValueFactorFunctionBuilder(field).factor(boostFactor)
.modifier(modifier);
if (missing != null) {
fieldValueFactorFunctionBuilder.missing(missing);
}
return fieldValueFactorFunctionBuilder;
}
}
| FieldValueFactorFunctionBuilder |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/customexceptions/UnwrappedExceptionTest.java | {
"start": 10550,
"end": 10771
} | class ____ extends IntermediateMappedException {
public UnwrapIfNoMatchWithIntermediateException(Throwable cause) {
super(cause);
}
}
public static | UnwrapIfNoMatchWithIntermediateException |
java | spring-projects__spring-security | oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java | {
"start": 3079,
"end": 18010
} | class ____ {
private OAuth2AuthorizationCodeGrantWebFilter filter;
@Mock
private ReactiveAuthenticationManager authenticationManager;
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
@Mock
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
@Mock
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
@BeforeEach
public void setup() {
this.filter = new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository);
this.filter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
}
@Test
public void constructorWhenAuthenticationManagerNullThenIllegalArgumentException() {
this.authenticationManager = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository));
}
@Test
public void constructorWhenClientRegistrationRepositoryNullThenIllegalArgumentException() {
this.clientRegistrationRepository = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository));
}
@Test
public void constructorWhenAuthorizedClientRepositoryNullThenIllegalArgumentException() {
this.authorizedClientRepository = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager,
this.clientRegistrationRepository, this.authorizedClientRepository));
}
@Test
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null));
}
@Test
public void filterWhenNotMatchThenAuthenticationManagerNotCalled() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
}
@Test
public void filterWhenMatchThenAuthorizedClientSaved() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(AnonymousAuthenticationToken.class),
any());
}
// gh-7966
@Test
public void filterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
// 1) redirect_uri with query parameters
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback", parameters);
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(1)).authenticate(any());
// 2) redirect_uri with query parameters AND authorization response additional
// parameters
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(2)).authenticate(any());
}
// gh-7966
@Test
public void filterWhenAuthorizationRequestRedirectUriParametersNotMatchThenNotProcessed() {
String requestUri = "/authorization/callback";
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockServerHttpRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
// 1) Parameter value
Map<String, String> parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.put("param2", "value8");
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(
createAuthorizationRequest(requestUri, parametersNotMatch));
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
// 2) Parameter order
parametersNotMatch = new LinkedHashMap<>();
parametersNotMatch.put("param2", "value2");
parametersNotMatch.put("param1", "value1");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
// 3) Parameter missing
parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.remove("param2");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verifyNoInteractions(this.authenticationManager);
}
@Test
public void filterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
ServerRequestCache requestCache = mock(ServerRequestCache.class);
given(requestCache.getRedirectUri(any(ServerWebExchange.class)))
.willReturn(Mono.just(URI.create("/saved-request")));
this.filter.setRequestCache(requestCache);
this.filter.filter(exchange, chain).block();
verify(requestCache).getRedirectUri(exchange);
assertThat(exchange.getResponse().getHeaders().getLocation().toString()).isEqualTo("/saved-request");
}
// gh-8609
@Test
public void filterWhenAuthenticationConverterThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.filter.filter(exchange, chain).block())
.satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode")
.isEqualTo("client_registration_not_found"));
verifyNoInteractions(this.authenticationManager);
}
// gh-8609
@Test
public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest,
clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error"))));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(),
Collections.emptyList());
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.filter.filter(exchange, chain).block())
.satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error"));
}
private static OAuth2AuthorizationRequest createOAuth2AuthorizationRequest(
MockServerHttpRequest authorizationRequest, ClientRegistration registration) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registration.getRegistrationId());
// @formatter:off
return TestOAuth2AuthorizationRequests.request()
.attributes(attributes)
.redirectUri(authorizationRequest.getURI().toString())
.build();
// @formatter:on
}
private static MockServerHttpRequest createAuthorizationRequest(String requestUri) {
return createAuthorizationRequest(requestUri, new LinkedHashMap<>());
}
private static MockServerHttpRequest createAuthorizationRequest(String requestUri, Map<String, String> parameters) {
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest.get(requestUri);
if (!CollectionUtils.isEmpty(parameters)) {
parameters.forEach(builder::queryParam);
}
return builder.build();
}
private static MockServerHttpRequest createAuthorizationResponse(MockServerHttpRequest authorizationRequest) {
return createAuthorizationResponse(authorizationRequest, new LinkedHashMap<>());
}
private static MockServerHttpRequest createAuthorizationResponse(MockServerHttpRequest authorizationRequest,
Map<String, String> additionalParameters) {
MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest
.get(authorizationRequest.getURI().toString());
builder.queryParam(OAuth2ParameterNames.CODE, "code");
builder.queryParam(OAuth2ParameterNames.STATE, "state");
additionalParameters.forEach(builder::queryParam);
builder.cookies(authorizationRequest.getCookies());
return builder.build();
}
}
| OAuth2AuthorizationCodeGrantWebFilterTests |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/ConnectorStatusTests.java | {
"start": 406,
"end": 964
} | class ____ extends ESTestCase {
public void testConnectorStatus_WithValidConnectorStatusString() {
ConnectorStatus connectorStatus = ConnectorTestUtils.getRandomConnectorStatus();
assertThat(ConnectorStatus.connectorStatus(connectorStatus.toString()), equalTo(connectorStatus));
}
public void testConnectorStatus_WithInvalidConnectorStatusString_ExpectIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> ConnectorStatus.connectorStatus("invalid connector status"));
}
}
| ConnectorStatusTests |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/BeanioDataFormat.java | {
"start": 1531,
"end": 5651
} | class ____ extends DataFormatDefinition {
@XmlAttribute(required = true)
private String mapping;
@XmlAttribute(required = true)
private String streamName;
@XmlAttribute
@Metadata(javaType = "java.lang.Boolean")
private String ignoreUnidentifiedRecords;
@XmlAttribute
@Metadata(javaType = "java.lang.Boolean")
private String ignoreUnexpectedRecords;
@XmlAttribute
@Metadata(javaType = "java.lang.Boolean")
private String ignoreInvalidRecords;
@XmlAttribute
@Metadata(label = "advanced")
private String encoding;
@XmlAttribute
@Metadata(label = "advanced")
private String beanReaderErrorHandlerType;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String unmarshalSingleObject;
public BeanioDataFormat() {
super("beanio");
}
protected BeanioDataFormat(BeanioDataFormat source) {
super(source);
this.mapping = source.mapping;
this.streamName = source.streamName;
this.ignoreUnidentifiedRecords = source.ignoreUnidentifiedRecords;
this.ignoreUnexpectedRecords = source.ignoreUnexpectedRecords;
this.ignoreInvalidRecords = source.ignoreInvalidRecords;
this.encoding = source.encoding;
this.beanReaderErrorHandlerType = source.beanReaderErrorHandlerType;
this.unmarshalSingleObject = source.unmarshalSingleObject;
}
private BeanioDataFormat(BeanioDataFormat.Builder builder) {
this();
this.mapping = builder.mapping;
this.streamName = builder.streamName;
this.ignoreUnidentifiedRecords = builder.ignoreUnidentifiedRecords;
this.ignoreUnexpectedRecords = builder.ignoreUnexpectedRecords;
this.ignoreInvalidRecords = builder.ignoreInvalidRecords;
this.encoding = builder.encoding;
this.beanReaderErrorHandlerType = builder.beanReaderErrorHandlerType;
this.unmarshalSingleObject = builder.unmarshalSingleObject;
}
@Override
public BeanioDataFormat copyDefinition() {
return new BeanioDataFormat(this);
}
public String getMapping() {
return mapping;
}
/**
* The BeanIO mapping file. Is by default loaded from the classpath. You can prefix with file:, http:, or classpath:
* to denote from where to load the mapping file.
*/
public void setMapping(String mapping) {
this.mapping = mapping;
}
public String getStreamName() {
return streamName;
}
/**
* The name of the stream to use.
*/
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public String getIgnoreUnidentifiedRecords() {
return ignoreUnidentifiedRecords;
}
/**
* Whether to ignore unidentified records.
*/
public void setIgnoreUnidentifiedRecords(String ignoreUnidentifiedRecords) {
this.ignoreUnidentifiedRecords = ignoreUnidentifiedRecords;
}
public String getIgnoreUnexpectedRecords() {
return ignoreUnexpectedRecords;
}
/**
* Whether to ignore unexpected records.
*/
public void setIgnoreUnexpectedRecords(String ignoreUnexpectedRecords) {
this.ignoreUnexpectedRecords = ignoreUnexpectedRecords;
}
public String getIgnoreInvalidRecords() {
return ignoreInvalidRecords;
}
/**
* Whether to ignore invalid records.
*/
public void setIgnoreInvalidRecords(String ignoreInvalidRecords) {
this.ignoreInvalidRecords = ignoreInvalidRecords;
}
public String getEncoding() {
return encoding;
}
/**
* The charset to use.
* <p/>
* Is by default the JVM platform default charset.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getBeanReaderErrorHandlerType() {
return beanReaderErrorHandlerType;
}
/**
* To use a custom org.apache.camel.dataformat.beanio.BeanIOErrorHandler as error handler while parsing. Configure
* the fully qualified | BeanioDataFormat |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java | {
"start": 30921,
"end": 31187
} | interface ____ extends Matcher {
/**
* Perform a match against the next byte of the stream and return true
* if the delimiter is fully matched.
*/
boolean match(byte b);
}
/**
* Matcher for a single byte delimiter.
*/
private static | NestedMatcher |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/service/BatchSummary.java | {
"start": 614,
"end": 954
} | class ____ {
private final LazyInitializable<String, RuntimeException> lazyDescription;
public BatchSummary(Supplier<String> stringSupplier) {
lazyDescription = new LazyInitializable<>(stringSupplier::get);
}
@Override
public String toString() {
return lazyDescription.getOrCompute();
}
}
| BatchSummary |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedAssociationEmbeddableTest.java | {
"start": 3964,
"end": 4364
} | class ____ {
@Id
private Long id;
@OneToMany( mappedBy = "compositeKey.report", cascade = ALL, orphanRemoval = true, fetch = FetchType.EAGER )
private List<ReportTrip> reportTripList = new ArrayList<>();
public Report() {
}
public Report(Long id) {
this.id = id;
}
public List<ReportTrip> getReportTripList() {
return reportTripList;
}
}
@Embeddable
public static | Report |
java | elastic__elasticsearch | x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterResourceTests.java | {
"start": 2603,
"end": 31713
} | class ____ extends AbstractPublishableHttpResourceTestCase {
private final ClusterState state = mockClusterState(true);
private final ClusterService clusterService = mockClusterService(state);
private final MockLicenseState licenseState = mock(MockLicenseState.class);
private final boolean remoteClusterHasWatcher = randomBoolean();
private final boolean validLicense = randomBoolean();
/**
* kibana, logstash, beats and enterprise search
*/
private final int EXPECTED_TEMPLATES = TEMPLATE_NAMES.length;
private final int EXPECTED_WATCHES = ClusterAlertsUtil.WATCH_IDS.length;
private final RestClient client = mock(RestClient.class);
private final Response versionResponse = mock(Response.class);
private final List<String> templateNames = new ArrayList<>(EXPECTED_TEMPLATES);
private final List<String> watchNames = new ArrayList<>(EXPECTED_WATCHES);
private final Settings exporterSettings = Settings.builder()
.put("xpack.monitoring.exporters._http.cluster_alerts.management.enabled", true)
.build();
private final MultiHttpResource resources = HttpExporter.createResources(
new Exporter.Config("_http", "http", exporterSettings, clusterService, licenseState)
).allResources;
@Before
public void setupResources() {
templateNames.addAll(Arrays.stream(TEMPLATE_NAMES).collect(Collectors.toList()));
watchNames.addAll(Arrays.stream(ClusterAlertsUtil.WATCH_IDS).map(id -> "my_cluster_uuid_" + id).collect(Collectors.toList()));
assertThat("Not all templates are supplied", templateNames, hasSize(EXPECTED_TEMPLATES));
assertThat("Not all watches are supplied", watchNames, hasSize(EXPECTED_WATCHES));
}
public void awaitCheckAndPublish(final Boolean expected) {
awaitCheckAndPublish(resources, expected);
}
public void awaitCheckAndPublish(HttpResource resource, final Boolean expected) {
awaitCheckAndPublish(resource, expected != null ? new ResourcePublishResult(expected) : null);
}
public void awaitCheckAndPublish(HttpResource resource, final ResourcePublishResult expected) {
resource.checkAndPublish(client, wrapMockListener(publishListener));
verifyPublishListener(expected);
}
public void testInvalidVersionBlocks() {
final HttpEntity entity = new StringEntity("{\"version\":{\"number\":\"3.0.0\"}}", ContentType.APPLICATION_JSON);
when(versionResponse.getEntity()).thenReturn(entity);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), is("/")), versionResponse);
assertTrue(resources.isDirty());
awaitCheckAndPublish(
resources,
new ResourcePublishResult(
false,
"version [3.0.0] < [7.0.0] and NOT supported for [xpack.monitoring.exporters._http]",
HttpResource.State.DIRTY
)
);
// ensure it didn't magically become clean
assertTrue(resources.isDirty());
verifyVersionCheck();
verifyNoMoreInteractions(client);
}
public void testTemplateCheckBlocksAfterSuccessfulVersion() {
final Exception exception = failureGetException();
final boolean firstSucceeds = randomBoolean();
int expectedGets = 1;
final ResourcePublishResult expectedResult;
whenValidVersionResponse();
// failure in the middle of various templates being checked/published; suggests a node dropped
if (firstSucceeds) {
final boolean successfulFirst = randomBoolean();
// -2 from one success + a necessary failure after it!
final int extraPasses = randomIntBetween(0, EXPECTED_TEMPLATES - 2);
final int successful = randomIntBetween(0, extraPasses);
final int unsuccessful = extraPasses - successful;
final String templateName = templateNames.get(0);
final Response first;
if (successfulFirst) {
first = successfulGetResourceResponse("/_template/", templateName);
} else {
first = unsuccessfulGetResourceResponse("/_template/", templateName);
}
final List<Response> otherResponses = getTemplateResponses(1, successful, unsuccessful);
// last check fails implies that N - 2 publishes succeeded!
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), startsWith("/_template/")), first, otherResponses, exception);
// Since we return a "Not Ready" response on any templates that are not available (instead
// of trying to publish them), we set the expected number of gets to be the first run of successful responses
// plus the first failure
if (successfulFirst) {
expectedGets += successful + 1; // the string of successes, then the last failure.
}
if (successfulFirst && unsuccessful == 0) {
// In this case, there will be only one failed response, and it'll be an exception
expectedResult = null;
} else {
// The first bad response will be either a 404 or a template with an old version
String missingTemplateName = TEMPLATE_NAMES[expectedGets - 1];
expectedResult = new ResourcePublishResult(
false,
"waiting for remote monitoring cluster to install "
+ "appropriate template ["
+ missingTemplateName
+ "] (version mismatch or missing)",
HttpResource.State.DIRTY
);
}
} else {
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), startsWith("/_template/")), exception);
expectedResult = null;
}
assertTrue(resources.isDirty());
awaitCheckAndPublish(resources, expectedResult);
// ensure it didn't magically become not-dirty
assertTrue(resources.isDirty());
verifyVersionCheck();
verifyGetTemplates(expectedGets);
verifyNoMoreInteractions(client);
}
public void testWatcherCheckBlocksAfterSuccessfulTemplatePublish() {
final int successfulGetTemplates = randomIntBetween(0, EXPECTED_TEMPLATES);
final int unsuccessfulGetTemplates = EXPECTED_TEMPLATES - successfulGetTemplates;
final Exception exception = failureGetException();
whenValidVersionResponse();
whenGetTemplates(EXPECTED_TEMPLATES);
// there's only one check
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), is("/_xpack")), exception);
assertTrue(resources.isDirty());
awaitCheckAndPublish(null);
// ensure it didn't magically become not-dirty
assertTrue(resources.isDirty());
verifyVersionCheck();
verifyGetTemplates(EXPECTED_TEMPLATES);
verifyWatcherCheck();
verifyNoMoreInteractions(client);
}
public void testWatchCheckBlocksAfterSuccessfulWatcherCheck() {
final Exception exception = validLicense ? failureGetException() : failureDeleteException();
final boolean firstSucceeds = randomBoolean();
int expectedGets = 1;
int expectedPuts = 0;
whenValidVersionResponse();
whenGetTemplates(EXPECTED_TEMPLATES);
whenWatcherCanBeUsed(validLicense);
// failure in the middle of various watches being checked/published; suggests a node dropped
if (firstSucceeds) {
// getting _and_ putting watches
if (validLicense) {
final boolean successfulFirst = randomBoolean();
// -2 from one success + a necessary failure after it!
final int extraPasses = randomIntBetween(0, EXPECTED_WATCHES - 2);
final int successful = randomIntBetween(0, extraPasses);
final int unsuccessful = extraPasses - successful;
final String watchId = watchNames.get(0);
final Response first = successfulFirst ? successfulGetWatchResponse(watchId) : unsuccessfulGetWatchResponse(watchId);
final List<Response> otherResponses = getWatcherResponses(1, successful, unsuccessful);
// last check fails implies that N - 2 publishes succeeded!
whenPerformRequestAsyncWith(
client,
new RequestMatcher(is("GET"), startsWith("/_watcher/watch/")),
first,
otherResponses,
exception
);
whenSuccessfulPutWatches(otherResponses.size() + 1);
// +1 for the "first"
expectedGets += 1 + successful + unsuccessful;
expectedPuts = (successfulFirst ? 0 : 1) + unsuccessful;
} else {
// deleting watches
// - 1 from necessary failure after it!
final int successful = randomIntBetween(1, EXPECTED_WATCHES - 1);
// there is no form of an unsuccessful delete; only success or error
final List<Response> responses = successfulDeleteResponses(successful);
whenPerformRequestAsyncWith(
client,
new RequestMatcher(is("DELETE"), startsWith("/_watcher/watch/")),
responses.get(0),
responses.subList(1, responses.size()),
exception
);
expectedGets += successful;
}
} else {
final String method = validLicense ? "GET" : "DELETE";
whenPerformRequestAsyncWith(client, new RequestMatcher(is(method), startsWith("/_watcher/watch/")), exception);
}
assertTrue(resources.isDirty());
awaitCheckAndPublish(null);
// ensure it didn't magically become not-dirty
assertTrue(resources.isDirty());
verifyVersionCheck();
verifyGetTemplates(EXPECTED_TEMPLATES);
verifyWatcherCheck();
if (validLicense) {
verifyGetWatches(expectedGets);
verifyPutWatches(expectedPuts);
} else {
verifyDeleteWatches(expectedGets);
}
verifyNoMoreInteractions(client);
}
public void testWatchPublishBlocksAfterSuccessfulWatcherCheck() {
final Exception exception = failurePutException();
final boolean firstSucceeds = randomBoolean();
int expectedGets = 1;
int expectedPuts = 1;
whenValidVersionResponse();
whenGetTemplates(EXPECTED_TEMPLATES);
// license needs to be valid, otherwise we'll do DELETEs, which are tested earlier
whenWatcherCanBeUsed(true);
// failure in the middle of various watches being checked/published; suggests a node dropped
if (firstSucceeds) {
final Response firstSuccess = successfulPutResponse();
// -2 from one success + a necessary failure after it!
final int extraPasses = randomIntBetween(0, EXPECTED_WATCHES - 2);
final int successful = randomIntBetween(0, extraPasses);
final int unsuccessful = extraPasses - successful;
final List<Response> otherResponses = successfulPutResponses(unsuccessful);
// first one passes for sure, so we need an extra "unsuccessful" GET
whenGetWatches(successful, unsuccessful + 2);
// previous publishes must have succeeded
whenPerformRequestAsyncWith(
client,
new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/")),
firstSuccess,
otherResponses,
exception
);
// GETs required for each PUT attempt (first is guaranteed "unsuccessful")
expectedGets += successful + unsuccessful + 1;
// unsuccessful are PUT attempts + the guaranteed successful PUT (first)
expectedPuts += unsuccessful + 1;
} else {
// fail the check so that it has to attempt the PUT
whenGetWatches(0, 1);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/")), exception);
}
assertTrue(resources.isDirty());
awaitCheckAndPublish(null);
// ensure it didn't magically become not-dirty
assertTrue(resources.isDirty());
verifyVersionCheck();
verifyGetTemplates(EXPECTED_TEMPLATES);
verifyWatcherCheck();
verifyGetWatches(expectedGets);
verifyPutWatches(expectedPuts);
verifyNoMoreInteractions(client);
}
public void testDeployClusterAlerts() {
final Exception exception = failurePutException();
whenValidVersionResponse();
whenGetTemplates(EXPECTED_TEMPLATES);
// license needs to be valid, otherwise we'll do DELETEs, which are tested earlier
whenWatcherCanBeUsed(true);
// a number of watches are mocked as present
final int existingWatches = randomIntBetween(0, EXPECTED_WATCHES);
// For completeness's sake. GET/PUT watches wont be called by the resources.
// Instead it tries to DELETE the watches ignoring them not existing.
whenGetWatches(existingWatches, EXPECTED_WATCHES - existingWatches);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/")), exception);
whenPerformRequestAsyncWith(
client,
new RequestMatcher(is("DELETE"), startsWith("/_watcher/watch/")),
successfulDeleteResponses(EXPECTED_WATCHES)
);
// Create resources that are configured to remove all watches
Settings removalExporterSettings = Settings.builder()
.put(exporterSettings)
.put("xpack.monitoring.migration.decommission_alerts", true)
.build();
MultiHttpResource overrideResource = HttpExporter.createResources(
new Exporter.Config("_http", "http", removalExporterSettings, clusterService, licenseState)
).allResources;
assertTrue(overrideResource.isDirty());
awaitCheckAndPublish(overrideResource, true);
// Should proceed
assertFalse(overrideResource.isDirty());
verifyVersionCheck();
verifyGetTemplates(EXPECTED_TEMPLATES);
verifyWatcherCheck();
verifyGetWatches(0);
verifyPutWatches(0);
verifyDeleteWatches(EXPECTED_WATCHES);
verifyNoMoreInteractions(client);
assertWarnings(
"[xpack.monitoring.migration.decommission_alerts] setting was deprecated in Elasticsearch and will be "
+ "removed in a future release. See the deprecation documentation for the next major version.",
"[xpack.monitoring.exporters._http.cluster_alerts.management.enabled] setting was deprecated in Elasticsearch and "
+ "will be removed in a future release. See the deprecation documentation for the next major version."
);
}
public void testSuccessfulChecksOnElectedMasterNode() {
final int successfulGetWatches = randomIntBetween(0, EXPECTED_WATCHES);
final int unsuccessfulGetWatches = EXPECTED_WATCHES - successfulGetWatches;
whenValidVersionResponse();
whenGetTemplates(EXPECTED_TEMPLATES);
if (remoteClusterHasWatcher) {
whenWatcherCanBeUsed(validLicense);
if (validLicense) {
whenGetWatches(successfulGetWatches, unsuccessfulGetWatches);
whenSuccessfulPutWatches(unsuccessfulGetWatches);
} else {
whenSuccessfulDeleteWatches(EXPECTED_WATCHES);
}
} else {
whenWatcherCannotBeUsed();
}
assertTrue(resources.isDirty());
// it should be able to proceed!
awaitCheckAndPublish(true);
assertFalse(resources.isDirty());
verifyVersionCheck();
verifyGetTemplates(EXPECTED_TEMPLATES);
verifyWatcherCheck();
if (remoteClusterHasWatcher) {
if (validLicense) {
verifyGetWatches(EXPECTED_WATCHES);
verifyPutWatches(unsuccessfulGetWatches);
} else {
verifyDeleteWatches(EXPECTED_WATCHES);
}
}
verifyNoMoreInteractions(client);
}
/**
* If the node is not the elected master node, then it should never check Watcher or send Watches (Cluster Alerts).
*/
public void testSuccessfulChecksIfNotElectedMasterNode() {
final ClusterState mockState = mockClusterState(false);
final ClusterService mockClusterService = mockClusterService(mockState);
final MultiHttpResource allResources = HttpExporter.createResources(
new Exporter.Config("_http", "http", exporterSettings, mockClusterService, licenseState)
).allResources;
whenValidVersionResponse();
whenGetTemplates(EXPECTED_TEMPLATES);
assertTrue(allResources.isDirty());
// it should be able to proceed! (note: we are not using the instance "resources" here)
allResources.checkAndPublish(client, wrapMockListener(publishListener));
verifyPublishListener(ResourcePublishResult.ready());
assertFalse(allResources.isDirty());
verifyVersionCheck();
verifyGetTemplates(EXPECTED_TEMPLATES);
verifyNoMoreInteractions(client);
assertWarnings(
"[xpack.monitoring.exporters._http.cluster_alerts.management.enabled] setting was deprecated in Elasticsearch "
+ "and will be removed in a future release. See the deprecation documentation for the next major version."
);
}
private Exception failureGetException() {
final ResponseException responseException = responseException("GET", "/_get_something", failedCheckStatus());
return randomFrom(new IOException("expected"), new RuntimeException("expected"), responseException);
}
private Exception failurePutException() {
final ResponseException responseException = responseException("PUT", "/_put_something", failedPublishStatus());
return randomFrom(new IOException("expected"), new RuntimeException("expected"), responseException);
}
private Exception failureDeleteException() {
final ResponseException responseException = responseException("DELETE", "/_delete_something", failedCheckStatus());
return randomFrom(new IOException("expected"), new RuntimeException("expected"), responseException);
}
private Response unsuccessfulGetResponse() {
return response("GET", "/_get_something", notFoundCheckStatus());
}
private Response successfulGetWatchResponse(final String watchId) {
final HttpEntity goodEntity = entityForClusterAlert(true, ClusterAlertsUtil.LAST_UPDATED_VERSION);
return response("GET", "/_watcher/watch/" + watchId, successfulCheckStatus(), goodEntity);
}
private Response unsuccessfulGetWatchResponse(final String watchId) {
if (randomBoolean()) {
final HttpEntity badEntity = entityForClusterAlert(false, ClusterAlertsUtil.LAST_UPDATED_VERSION);
return response("GET", "/_watcher/watch/" + watchId, successfulCheckStatus(), badEntity);
}
return unsuccessfulGetResponse();
}
private Response successfulGetResourceResponse(final String resourcePath, final String resourceName) {
final HttpEntity goodEntity = entityForResource(true, resourceName, MonitoringTemplateUtils.LAST_UPDATED_VERSION);
if (logger.isTraceEnabled()) {
try {
logger.trace("Generated HTTP response for resource [{}]: [{}]", resourceName, EntityUtils.toString(goodEntity));
} catch (IOException e) {
logger.warn("Generated HTTP response for resource [" + resourceName + "] that cannot be deserialized!", e);
}
}
return response("GET", resourcePath + resourceName, successfulCheckStatus(), goodEntity);
}
private Response unsuccessfulGetResourceResponse(final String resourcePath, final String resourceName) {
if (randomBoolean()) {
final HttpEntity badEntity = entityForResource(false, resourceName, MonitoringTemplateUtils.LAST_UPDATED_VERSION);
if (logger.isTraceEnabled()) {
try {
logger.trace("Generated bad HTTP entity for resource [{}]: [{}]", resourceName, EntityUtils.toString(badEntity));
} catch (IOException e) {
logger.warn("Generated bad HTTP response for resource [" + resourceName + "] that cannot be deserialized!", e);
}
}
return response("GET", resourcePath + resourceName, successfulCheckStatus(), badEntity);
}
logger.trace("Generated NOT FOUND response for resource [{}]", resourceName);
return unsuccessfulGetResponse();
}
private List<Response> getResourceResponses(
final String resourcePath,
final List<String> resourceNames,
final int skip,
final int successful,
final int unsuccessful
) {
final List<Response> responses = new ArrayList<>(successful + unsuccessful);
for (int i = 0; i < successful; ++i) {
responses.add(successfulGetResourceResponse(resourcePath, resourceNames.get(i + skip)));
}
for (int i = 0; i < unsuccessful; ++i) {
responses.add(unsuccessfulGetResourceResponse(resourcePath, resourceNames.get(i + successful + skip)));
}
return responses;
}
private List<Response> getTemplateResponses(final int skip, final int successful, final int unsuccessful) {
return getResourceResponses("/_template/", templateNames, skip, successful, unsuccessful);
}
private List<Response> getWatcherResponses(final int skip, final int successful, final int unsuccessful) {
final List<Response> responses = new ArrayList<>(successful + unsuccessful);
for (int i = 0; i < successful; ++i) {
responses.add(successfulGetWatchResponse(watchNames.get(i + skip)));
}
for (int i = 0; i < unsuccessful; ++i) {
responses.add(unsuccessfulGetWatchResponse(watchNames.get(i + successful + skip)));
}
return responses;
}
private Response successfulPutResponse() {
final Response response = mock(Response.class);
final StatusLine statusLine = mock(StatusLine.class);
when(response.getStatusLine()).thenReturn(statusLine);
when(statusLine.getStatusCode()).thenReturn(randomFrom(RestStatus.OK, RestStatus.CREATED).getStatus());
return response;
}
private List<Response> successfulPutResponses(final int successful) {
final List<Response> responses = new ArrayList<>(successful);
for (int i = 0; i < successful; ++i) {
responses.add(successfulPutResponse());
}
return responses;
}
private Response successfulDeleteResponse() {
final RestStatus status = randomFrom(successfulCheckStatus(), notFoundCheckStatus());
return response("DELETE", "/_delete_something", status);
}
private List<Response> successfulDeleteResponses(final int successful) {
final List<Response> responses = new ArrayList<>(successful);
for (int i = 0; i < successful; ++i) {
responses.add(successfulDeleteResponse());
}
return responses;
}
private void whenValidVersionResponse() {
final HttpEntity entity = new StringEntity("{\"version\":{\"number\":\"" + Version.CURRENT + "\"}}", ContentType.APPLICATION_JSON);
when(versionResponse.getEntity()).thenReturn(entity);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), is("/")), versionResponse);
}
private void whenGetTemplates(final int successful) {
final List<Response> gets = getTemplateResponses(0, successful, 0);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), startsWith("/_template/")), gets);
}
private void whenWatcherCanBeUsed(final boolean validLicenseToReturn) {
final Metadata metadata = mock(Metadata.class);
when(state.metadata()).thenReturn(metadata);
when(metadata.clusterUUID()).thenReturn("the_clusters_uuid");
when(licenseState.isAllowed(Monitoring.MONITORING_CLUSTER_ALERTS_FEATURE)).thenReturn(validLicenseToReturn);
final HttpEntity entity = new StringEntity(
"{\"features\":{\"watcher\":{\"enabled\":true,\"available\":true}}}",
ContentType.APPLICATION_JSON
);
final Response successfulGet = response("GET", "_xpack", successfulCheckStatus(), entity);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), is("/_xpack")), successfulGet);
}
private void whenWatcherCannotBeUsed() {
final Response response;
if (randomBoolean()) {
final HttpEntity entity = randomFrom(
new StringEntity("""
{"features":{"watcher":{"enabled":false,"available":true}}}""", ContentType.APPLICATION_JSON),
new StringEntity("""
{"features":{"watcher":{"enabled":true,"available":false}}}""", ContentType.APPLICATION_JSON),
new StringEntity("{}", ContentType.APPLICATION_JSON)
);
response = response("GET", "_xpack", successfulCheckStatus(), entity);
} else {
response = response("GET", "_xpack", notFoundCheckStatus());
}
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), is("/_xpack")), response);
}
private void whenGetWatches(final int successful, final int unsuccessful) {
final List<Response> gets = getWatcherResponses(0, successful, unsuccessful);
whenPerformRequestAsyncWith(client, new RequestMatcher(is("GET"), startsWith("/_watcher/watch/")), gets);
}
private void whenSuccessfulPutWatches(final int successful) {
final List<Response> successfulPuts = successfulPutResponses(successful);
// empty is possible if they all exist
whenPerformRequestAsyncWith(client, new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/")), successfulPuts);
}
private void whenSuccessfulDeleteWatches(final int successful) {
final List<Response> successfulDeletes = successfulDeleteResponses(successful);
// empty is possible if they all exist
whenPerformRequestAsyncWith(client, new RequestMatcher(is("DELETE"), startsWith("/_watcher/watch/")), successfulDeletes);
}
private void verifyVersionCheck() {
verify(client).performRequestAsync(argThat(new RequestMatcher(is("GET"), is("/"))::matches), any(ResponseListener.class));
}
private void verifyGetTemplates(final int called) {
verify(client, times(called)).performRequestAsync(
argThat(new RequestMatcher(is("GET"), startsWith("/_template/"))::matches),
any(ResponseListener.class)
);
}
private void verifyWatcherCheck() {
verify(client).performRequestAsync(argThat(new RequestMatcher(is("GET"), is("/_xpack"))::matches), any(ResponseListener.class));
}
private void verifyDeleteWatches(final int called) {
verify(client, times(called)).performRequestAsync(
argThat(new RequestMatcher(is("DELETE"), startsWith("/_watcher/watch/"))::matches),
any(ResponseListener.class)
);
}
private void verifyGetWatches(final int called) {
verify(client, times(called)).performRequestAsync(
argThat(new RequestMatcher(is("GET"), startsWith("/_watcher/watch/"))::matches),
any(ResponseListener.class)
);
}
private void verifyPutWatches(final int called) {
verify(client, times(called)).performRequestAsync(
argThat(new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/"))::matches),
any(ResponseListener.class)
);
}
private ClusterService mockClusterService(final ClusterState clusterState) {
final ClusterService mockClusterService = mock(ClusterService.class);
when(mockClusterService.state()).thenReturn(clusterState);
return mockClusterService;
}
private ClusterState mockClusterState(final boolean electedMaster) {
final ClusterState mockState = mock(ClusterState.class);
final DiscoveryNodes nodes = mock(DiscoveryNodes.class);
when(mockState.nodes()).thenReturn(nodes);
when(nodes.isLocalNodeElectedMaster()).thenReturn(electedMaster);
return mockState;
}
private static | HttpExporterResourceTests |
java | spring-projects__spring-security | test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java | {
"start": 11285,
"end": 11840
} | class ____ extends AuthenticationMatcher<UnAuthenticatedMatcher> {
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private UnAuthenticatedMatcher() {
}
@Override
public void match(MvcResult result) {
SecurityContext context = load(result);
Authentication authentication = context.getAuthentication();
AssertionErrors.assertTrue("Expected anonymous Authentication got " + context,
authentication == null || this.trustResolver.isAnonymous(authentication));
}
}
}
| UnAuthenticatedMatcher |
java | elastic__elasticsearch | modules/data-streams/src/test/java/org/elasticsearch/datastreams/lifecycle/downsampling/DeleteSourceAndAddDownsampleIndexExecutorTests.java | {
"start": 1099,
"end": 2801
} | class ____ extends ESTestCase {
public void testExecutorNotifiesListenerAndReroutesAllocationService() {
final var projectId = randomUniqueProjectId();
String dataStreamName = randomAlphaOfLengthBetween(10, 100);
String sourceIndex = randomAlphaOfLengthBetween(10, 100);
String downsampleIndex = randomAlphaOfLengthBetween(10, 100);
AllocationService allocationService = mock(AllocationService.class);
DeleteSourceAndAddDownsampleIndexExecutor executor = new DeleteSourceAndAddDownsampleIndexExecutor(allocationService);
AtomicBoolean taskListenerCalled = new AtomicBoolean(false);
executor.taskSucceeded(
new DeleteSourceAndAddDownsampleToDS(
Settings.EMPTY,
projectId,
dataStreamName,
sourceIndex,
downsampleIndex,
new ActionListener<>() {
@Override
public void onResponse(Void unused) {
taskListenerCalled.set(true);
}
@Override
public void onFailure(Exception e) {
logger.error(e.getMessage(), e);
fail("unexpected exception: " + e.getMessage());
}
}
),
null
);
assertThat(taskListenerCalled.get(), is(true));
ClusterState state = ClusterState.EMPTY_STATE;
executor.afterBatchExecution(state, true);
verify(allocationService).reroute(state, "deleted indices", rerouteCompletionIsNotRequired());
}
}
| DeleteSourceAndAddDownsampleIndexExecutorTests |
java | google__dagger | javatests/dagger/functional/multipackage/moduleconstructor/ModuleWithInaccessibleConstructor.java | {
"start": 750,
"end": 972
} | class ____ {
private final int i;
/* intentionally package private */ModuleWithInaccessibleConstructor() {
i = new Random().nextInt();
}
@Provides
int i() {
return i;
}
}
| ModuleWithInaccessibleConstructor |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufDecoder.java | {
"start": 2962,
"end": 7051
} | class ____ extends ProtobufCodecSupport implements Decoder<Message> {
/** The default max size for aggregating messages. */
protected static final int DEFAULT_MESSAGE_MAX_SIZE = 256 * 1024;
private static final ConcurrentMap<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>();
private final ExtensionRegistry extensionRegistry;
private int maxMessageSize = DEFAULT_MESSAGE_MAX_SIZE;
/**
* Construct a new {@code ProtobufDecoder}.
*/
public ProtobufDecoder() {
this(ExtensionRegistry.newInstance());
}
/**
* Construct a new {@code ProtobufDecoder} with an initializer that allows the
* registration of message extensions.
* @param extensionRegistry a message extension registry
*/
public ProtobufDecoder(ExtensionRegistry extensionRegistry) {
Assert.notNull(extensionRegistry, "ExtensionRegistry must not be null");
this.extensionRegistry = extensionRegistry;
}
/**
* The max size allowed per message.
* <p>By default, this is set to 256K.
* @param maxMessageSize the max size per message, or -1 for unlimited
*/
public void setMaxMessageSize(int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
/**
* Return the {@link #setMaxMessageSize configured} message size limit.
* @since 5.1.11
*/
public int getMaxMessageSize() {
return this.maxMessageSize;
}
@Override
public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) {
return Message.class.isAssignableFrom(elementType.toClass()) && supportsMimeType(mimeType);
}
@Override
public Flux<Message> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
MessageDecoderFunction decoderFunction =
new MessageDecoderFunction(elementType, this.maxMessageSize, initMessageSizeReader());
return Flux.from(inputStream)
.flatMapIterable(decoderFunction)
.doOnTerminate(decoderFunction::discard);
}
/**
* Return a reader for message size information encoded in the input stream.
* @since 7.0
*/
protected MessageSizeReader initMessageSizeReader() {
return new DefaultMessageSizeReader();
}
@Override
public Mono<Message> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
return DataBufferUtils.join(inputStream, this.maxMessageSize)
.map(dataBuffer -> decode(dataBuffer, elementType, mimeType, hints));
}
@Override
public Message decode(DataBuffer dataBuffer, ResolvableType targetType,
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) throws DecodingException {
try {
Message.Builder builder = getMessageBuilder(targetType.toClass());
merge(dataBuffer, builder);
return builder.build();
}
catch (IOException ex) {
throw new DecodingException("I/O error while parsing input stream", ex);
}
catch (Exception ex) {
throw new DecodingException("Could not read Protobuf message: " + ex.getMessage(), ex);
}
finally {
DataBufferUtils.release(dataBuffer);
}
}
/**
* Use merge methods on {@link Message.Builder} to read a single message
* from the given {@code DataBuffer}.
* @since 7.0
*/
protected void merge(DataBuffer dataBuffer, Message.Builder builder) throws IOException {
ByteBuffer byteBuffer = ByteBuffer.allocate(dataBuffer.readableByteCount());
dataBuffer.toByteBuffer(byteBuffer);
builder.mergeFrom(CodedInputStream.newInstance(byteBuffer), this.extensionRegistry);
}
/**
* Create a new {@code Message.Builder} instance for the given class.
* <p>This method uses a ConcurrentHashMap for caching method lookups.
*/
private static Message.Builder getMessageBuilder(Class<?> clazz) throws Exception {
Method method = methodCache.get(clazz);
if (method == null) {
method = clazz.getMethod("newBuilder");
methodCache.put(clazz, method);
}
return (Message.Builder) method.invoke(clazz);
}
@Override
public List<MimeType> getDecodableMimeTypes() {
return getMimeTypes();
}
private | ProtobufDecoder |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java | {
"start": 69947,
"end": 70119
} | class ____ {
@Target(ElementType.METHOD)
@Retention(RUNTIME)
@ParameterizedTest(quoteTextArguments = false, name = "{arguments}")
@MethodSource
@ | MethodSourceTestCase |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeOnErrorReturn.java | {
"start": 1592,
"end": 3160
} | class ____<T> implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super T> downstream;
final Function<? super Throwable, ? extends T> itemSupplier;
Disposable upstream;
OnErrorReturnMaybeObserver(MaybeObserver<? super T> actual,
Function<? super Throwable, ? extends T> valueSupplier) {
this.downstream = actual;
this.itemSupplier = valueSupplier;
}
@Override
public void dispose() {
upstream.dispose();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
downstream.onSuccess(value);
}
@Override
public void onError(Throwable e) {
T v;
try {
v = Objects.requireNonNull(itemSupplier.apply(e), "The itemSupplier returned a null value");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
downstream.onError(new CompositeException(e, ex));
return;
}
downstream.onSuccess(v);
}
@Override
public void onComplete() {
downstream.onComplete();
}
}
}
| OnErrorReturnMaybeObserver |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/framework/ProxyProcessorSupport.java | {
"start": 4405,
"end": 4552
} | interface ____ found for a given bean, it will get
* proxied with its full target class, assuming that as the user's intention.
* @param ifc the | is |
java | grpc__grpc-java | util/src/test/java/io/grpc/util/MutableHandlerRegistryTest.java | {
"start": 1586,
"end": 8175
} | class ____ {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
private MutableHandlerRegistry registry = new MutableHandlerRegistry();
@Mock
private Marshaller<String> requestMarshaller;
@Mock
private Marshaller<Integer> responseMarshaller;
@Mock
private ServerCallHandler<String, Integer> flowHandler;
@Mock
private ServerCallHandler<String, Integer> coupleHandler;
@Mock
private ServerCallHandler<String, Integer> fewHandler;
private ServerServiceDefinition basicServiceDefinition;
private ServerServiceDefinition multiServiceDefinition;
@SuppressWarnings("rawtypes")
private ServerMethodDefinition flowMethodDefinition;
@Before
public void setUp() throws Exception {
MethodDescriptor<String, Integer> flowMethod = MethodDescriptor.<String, Integer>newBuilder()
.setType(MethodType.UNKNOWN)
.setFullMethodName("basic/flow")
.setRequestMarshaller(requestMarshaller)
.setResponseMarshaller(responseMarshaller)
.build();
basicServiceDefinition = ServerServiceDefinition.builder(
new ServiceDescriptor("basic", flowMethod))
.addMethod(flowMethod, flowHandler)
.build();
MethodDescriptor<String, Integer> coupleMethod =
flowMethod.toBuilder().setFullMethodName("multi/couple").build();
MethodDescriptor<String, Integer> fewMethod =
flowMethod.toBuilder().setFullMethodName("multi/few").build();
multiServiceDefinition = ServerServiceDefinition.builder(
new ServiceDescriptor("multi", coupleMethod, fewMethod))
.addMethod(coupleMethod, coupleHandler)
.addMethod(fewMethod, fewHandler)
.build();
flowMethodDefinition = getOnlyElement(basicServiceDefinition.getMethods());
}
/** Final checks for all tests. */
@After
public void makeSureMocksUnused() {
Mockito.verifyNoInteractions(requestMarshaller);
Mockito.verifyNoInteractions(responseMarshaller);
Mockito.verifyNoMoreInteractions(flowHandler);
Mockito.verifyNoMoreInteractions(coupleHandler);
Mockito.verifyNoMoreInteractions(fewHandler);
}
@Test
public void simpleLookup() {
assertNull(registry.addService(basicServiceDefinition));
ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/flow");
assertSame(flowMethodDefinition, method);
assertNull(registry.lookupMethod("/basic/flow"));
assertNull(registry.lookupMethod("basic/basic"));
assertNull(registry.lookupMethod("flow/flow"));
assertNull(registry.lookupMethod("completely/random"));
}
@Test
public void simpleLookupWithBindable() {
BindableService bindableService =
new BindableService() {
@Override
public ServerServiceDefinition bindService() {
return basicServiceDefinition;
}
};
assertNull(registry.addService(bindableService));
ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/flow");
assertSame(flowMethodDefinition, method);
}
@Test
public void multiServiceLookup() {
assertNull(registry.addService(basicServiceDefinition));
assertNull(registry.addService(multiServiceDefinition));
ServerCallHandler<?, ?> handler = registry.lookupMethod("basic/flow").getServerCallHandler();
assertSame(flowHandler, handler);
handler = registry.lookupMethod("multi/couple").getServerCallHandler();
assertSame(coupleHandler, handler);
handler = registry.lookupMethod("multi/few").getServerCallHandler();
assertSame(fewHandler, handler);
}
@Test
public void removeAndLookup() {
assertNull(registry.addService(multiServiceDefinition));
assertNotNull(registry.lookupMethod("multi/couple"));
assertNotNull(registry.lookupMethod("multi/few"));
assertTrue(registry.removeService(multiServiceDefinition));
assertNull(registry.lookupMethod("multi/couple"));
assertNull(registry.lookupMethod("multi/few"));
}
@Test
public void replaceAndLookup() {
assertNull(registry.addService(basicServiceDefinition));
assertNotNull(registry.lookupMethod("basic/flow"));
MethodDescriptor<String, Integer> anotherMethod = MethodDescriptor.<String, Integer>newBuilder()
.setType(MethodType.UNKNOWN)
.setFullMethodName("basic/another")
.setRequestMarshaller(requestMarshaller)
.setResponseMarshaller(responseMarshaller)
.build();
ServerServiceDefinition replaceServiceDefinition = ServerServiceDefinition.builder(
new ServiceDescriptor("basic", anotherMethod))
.addMethod(anotherMethod, flowHandler).build();
ServerMethodDefinition<?, ?> anotherMethodDefinition =
replaceServiceDefinition.getMethod("basic/another");
assertSame(basicServiceDefinition, registry.addService(replaceServiceDefinition));
assertNull(registry.lookupMethod("basic/flow"));
ServerMethodDefinition<?, ?> method = registry.lookupMethod("basic/another");
assertSame(anotherMethodDefinition, method);
}
@Test
public void removeSameSucceeds() {
assertNull(registry.addService(basicServiceDefinition));
assertTrue(registry.removeService(basicServiceDefinition));
}
@Test
public void doubleRemoveFails() {
assertNull(registry.addService(basicServiceDefinition));
assertTrue(registry.removeService(basicServiceDefinition));
assertFalse(registry.removeService(basicServiceDefinition));
}
@Test
public void removeMissingFails() {
assertFalse(registry.removeService(basicServiceDefinition));
}
@Test
public void removeMissingNameConflictFails() {
assertNull(registry.addService(basicServiceDefinition));
assertFalse(registry.removeService(ServerServiceDefinition.builder(
new ServiceDescriptor("basic")).build()));
}
@Test
public void initialAddReturnsNull() {
assertNull(registry.addService(basicServiceDefinition));
assertNull(registry.addService(multiServiceDefinition));
}
@Test
public void missingMethodLookupReturnsNull() {
assertNull(registry.lookupMethod("bad"));
}
@Test
public void addAfterRemoveReturnsNull() {
assertNull(registry.addService(basicServiceDefinition));
assertTrue(registry.removeService(basicServiceDefinition));
assertNull(registry.addService(basicServiceDefinition));
}
@Test
public void addReturnsPrevious() {
assertNull(registry.addService(basicServiceDefinition));
assertSame(basicServiceDefinition,
registry.addService(ServerServiceDefinition.builder(
new ServiceDescriptor("basic")).build()));
}
}
| MutableHandlerRegistryTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/MetamodelTest.java | {
"start": 2777,
"end": 2974
} | class ____ {
@Id
@GeneratedValue
private Long id;
@ManyToMany
private Set<ElementOfCollection2> collection2;
}
@Entity(name = "ElementOfCollection2")
public static | EntityWithCollection2 |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/array/ArrayTest.java | {
"start": 631,
"end": 1224
} | class ____ {
@Test
public void testArrayJoinFetch(SessionFactoryScope scope) {
A a = new A();
scope.inTransaction(
session -> {
B b = new B();
a.setBs( new B[] { b } );
session.persist( a );
}
);
scope.inTransaction(
session -> {
A retrieved = session.find( A.class, a.getId() );
assertNotNull( retrieved );
assertNotNull( retrieved.getBs() );
assertEquals( 1, retrieved.getBs().length );
assertNotNull( retrieved.getBs()[0] );
session.remove( retrieved );
session.remove( retrieved.getBs()[0] );
}
);
}
}
| ArrayTest |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/resume/ConsumerListener.java | {
"start": 1176,
"end": 2319
} | interface ____<C, P> {
/**
* This sets the predicate responsible for evaluating whether the processing can resume or not. Such predicate
* should return true if the consumption can resume, or false otherwise. The exact point of when the predicate is
* called is dependent on the component, and it may be called on either one of the available events. Implementations
* should not assume the predicate to be called at any specific point.
*/
void setResumableCheck(Predicate<?> afterConsumeEval);
/**
* This is an event that runs after data consumption if and only if the consumer has been paused.
*
* @param consumePayload the resume payload if any
* @return true if the consumer should continue processing or false otherwise.
*/
boolean afterConsume(C consumePayload);
/**
* This is an event that runs after data processing.
*
* @param processingPayload the resume payload if any
* @return true if the consumer should continue or false otherwise.
*/
boolean afterProcess(P processingPayload);
}
| ConsumerListener |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scripting/MessengerScrambler.java | {
"start": 839,
"end": 1042
} | class ____ {
public String scramble(ProceedingJoinPoint pjp) throws Throwable {
String message = (String) pjp.proceed();
return new StringBuilder(message).reverse().toString();
}
}
| MessengerScrambler |
java | apache__flink | flink-clients/src/test/java/org/apache/flink/client/cli/ClientOptionsTest.java | {
"start": 1058,
"end": 1832
} | class ____ {
@Test
void testGetClientTimeout() {
Configuration configuration = new Configuration();
configuration.set(ClientOptions.CLIENT_TIMEOUT, Duration.ofSeconds(10));
assertThat(configuration.get(ClientOptions.CLIENT_TIMEOUT))
.isEqualTo(Duration.ofSeconds(10));
configuration = new Configuration();
configuration.set(ClientOptions.CLIENT_TIMEOUT, Duration.ofSeconds(20));
assertThat(configuration.get(ClientOptions.CLIENT_TIMEOUT))
.isEqualTo(Duration.ofSeconds(20));
configuration = new Configuration();
assertThat(configuration.get(ClientOptions.CLIENT_TIMEOUT))
.isEqualTo(ClientOptions.CLIENT_TIMEOUT.defaultValue());
}
}
| ClientOptionsTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/snapshots/IndexShardSnapshotStatus.java | {
"start": 2176,
"end": 12784
} | enum ____ {
/**
* The shard snapshot got past the stage where an abort or pause could have occurred, and is either complete or on its way to
* completion.
*/
NO_ABORT,
/**
* The shard snapshot stopped before completion, either because the whole snapshot was aborted or because this node is to be
* removed.
*/
ABORTED
}
private final AtomicReference<Stage> stage;
private final AtomicReference<ShardGeneration> generation;
private final AtomicReference<ShardSnapshotResult> shardSnapshotResult; // only set in stage DONE
private long startTimeMillis;
private long totalTimeMillis;
private int incrementalFileCount;
private int totalFileCount;
private int processedFileCount;
private long totalSize;
private long incrementalSize;
private long processedSize;
private String failure;
private final SubscribableListener<AbortStatus> abortListeners = new SubscribableListener<>();
private volatile String statusDescription;
private IndexShardSnapshotStatus(
final Stage stage,
final long startTimeMillis,
final long totalTimeMillis,
final int incrementalFileCount,
final int totalFileCount,
final int processedFileCount,
final long incrementalSize,
final long totalSize,
final long processedSize,
final String failure,
final ShardGeneration generation,
final String statusDescription
) {
this.stage = new AtomicReference<>(Objects.requireNonNull(stage));
this.generation = new AtomicReference<>(generation);
this.shardSnapshotResult = new AtomicReference<>();
this.startTimeMillis = startTimeMillis;
this.totalTimeMillis = totalTimeMillis;
this.incrementalFileCount = incrementalFileCount;
this.totalFileCount = totalFileCount;
this.processedFileCount = processedFileCount;
this.totalSize = totalSize;
this.processedSize = processedSize;
this.incrementalSize = incrementalSize;
this.failure = failure;
updateStatusDescription(statusDescription);
}
public synchronized Copy moveToStarted(
final long startTimeMillis,
final int incrementalFileCount,
final int totalFileCount,
final long incrementalSize,
final long totalSize
) {
if (stage.compareAndSet(Stage.INIT, Stage.STARTED)) {
this.startTimeMillis = startTimeMillis;
this.incrementalFileCount = incrementalFileCount;
this.totalFileCount = totalFileCount;
this.incrementalSize = incrementalSize;
this.totalSize = totalSize;
} else {
ensureNotAborted();
assert false : "Should not try to move stage [" + stage.get() + "] to [STARTED]";
throw new IllegalStateException(
"Unable to move the shard snapshot status to [STARTED]: " + "expecting [INIT] but got [" + stage.get() + "]"
);
}
return asCopy();
}
public synchronized Copy moveToFinalize() {
final var prevStage = stage.compareAndExchange(Stage.STARTED, Stage.FINALIZE);
return switch (prevStage) {
case STARTED -> {
abortListeners.onResponse(AbortStatus.NO_ABORT);
yield asCopy();
}
case ABORTED -> throw new AbortedSnapshotException();
case PAUSING -> throw new PausedSnapshotException();
default -> {
final var message = Strings.format(
"Unable to move the shard snapshot status to [FINALIZE]: expecting [STARTED] but got [%s]",
prevStage
);
assert false : message;
throw new IllegalStateException(message);
}
};
}
public synchronized void moveToDone(final long endTimeMillis, final ShardSnapshotResult shardSnapshotResult) {
assert shardSnapshotResult != null;
assert shardSnapshotResult.getGeneration() != null;
if (stage.compareAndSet(Stage.FINALIZE, Stage.DONE)) {
this.totalTimeMillis = Math.max(0L, endTimeMillis - startTimeMillis);
this.shardSnapshotResult.set(shardSnapshotResult);
this.generation.set(shardSnapshotResult.getGeneration());
} else {
assert false : "Should not try to move stage [" + stage.get() + "] to [DONE]";
throw new IllegalStateException(
"Unable to move the shard snapshot status to [DONE]: " + "expecting [FINALIZE] but got [" + stage.get() + "]"
);
}
}
public Stage getStage() {
return stage.get();
}
public long getTotalTimeMillis() {
return totalTimeMillis;
}
public void addAbortListener(ActionListener<AbortStatus> listener) {
abortListeners.addListener(listener);
}
public void abortIfNotCompleted(final String failure, Consumer<ActionListener<Releasable>> notifyRunner) {
abortAndMoveToStageIfNotCompleted(Stage.ABORTED, failure, notifyRunner);
}
public void pauseIfNotCompleted(Consumer<ActionListener<Releasable>> notifyRunner) {
abortAndMoveToStageIfNotCompleted(Stage.PAUSING, "paused for removal of node holding primary", notifyRunner);
}
private synchronized void abortAndMoveToStageIfNotCompleted(
final Stage newStage,
final String failure,
final Consumer<ActionListener<Releasable>> notifyRunner
) {
assert newStage == Stage.ABORTED || newStage == Stage.PAUSING : newStage;
if (stage.compareAndSet(Stage.INIT, newStage) || stage.compareAndSet(Stage.STARTED, newStage)) {
this.failure = failure;
notifyRunner.accept(abortListeners.map(r -> {
Releasables.closeExpectNoException(r);
return AbortStatus.ABORTED;
}));
}
}
public synchronized SnapshotsInProgress.ShardState moveToUnsuccessful(final Stage newStage, final String failure, final long endTime) {
assert newStage == Stage.PAUSED || newStage == Stage.FAILURE : newStage;
if (newStage == Stage.PAUSED && stage.compareAndSet(Stage.PAUSING, Stage.PAUSED)) {
this.totalTimeMillis = Math.max(0L, endTime - startTimeMillis);
this.failure = failure;
return SnapshotsInProgress.ShardState.PAUSED_FOR_NODE_REMOVAL;
}
moveToFailed(endTime, failure);
return SnapshotsInProgress.ShardState.FAILED;
}
public synchronized void moveToFailed(final long endTime, final String failure) {
if (stage.getAndSet(Stage.FAILURE) != Stage.FAILURE) {
abortListeners.onResponse(AbortStatus.NO_ABORT);
this.totalTimeMillis = Math.max(0L, endTime - startTimeMillis);
this.failure = failure;
}
}
public ShardGeneration generation() {
return generation.get();
}
public ShardSnapshotResult getShardSnapshotResult() {
assert stage.get() == Stage.DONE : stage.get();
return shardSnapshotResult.get();
}
public void ensureNotAborted() {
ensureNotAborted(stage.get());
}
public static void ensureNotAborted(Stage shardSnapshotStage) {
switch (shardSnapshotStage) {
case ABORTED -> throw new AbortedSnapshotException();
case PAUSING -> throw new PausedSnapshotException();
}
}
public boolean isPaused() {
return stage.get() == Stage.PAUSED;
}
/**
* Increments number of processed files
*/
public synchronized void addProcessedFile(long size) {
processedFileCount++;
processedSize += size;
}
public synchronized void addProcessedFiles(int count, long totalSize) {
processedFileCount += count;
processedSize += totalSize;
}
/**
* Updates the string explanation for what the snapshot is actively doing right now.
*/
public void updateStatusDescription(String statusString) {
assert statusString != null;
assert statusString.isEmpty() == false;
this.statusDescription = statusString;
}
/**
* Returns a copy of the current {@link IndexShardSnapshotStatus}. This method is
* intended to be used when a coherent state of {@link IndexShardSnapshotStatus} is needed.
*
* @return a {@link IndexShardSnapshotStatus.Copy}
*/
public synchronized IndexShardSnapshotStatus.Copy asCopy() {
return new IndexShardSnapshotStatus.Copy(
stage.get(),
startTimeMillis,
totalTimeMillis,
incrementalFileCount,
totalFileCount,
processedFileCount,
incrementalSize,
totalSize,
processedSize,
failure,
statusDescription
);
}
public static IndexShardSnapshotStatus newInitializing(ShardGeneration generation) {
return new IndexShardSnapshotStatus(Stage.INIT, 0L, 0L, 0, 0, 0, 0, 0, 0, null, generation, "initializing");
}
public static IndexShardSnapshotStatus.Copy newFailed(final String failure) {
assert failure != null : "expecting non null failure for a failed IndexShardSnapshotStatus";
if (failure == null) {
throw new IllegalArgumentException("A failure description is required for a failed IndexShardSnapshotStatus");
}
return new IndexShardSnapshotStatus(Stage.FAILURE, 0L, 0L, 0, 0, 0, 0, 0, 0, failure, null, "initialized as failed").asCopy();
}
public static IndexShardSnapshotStatus.Copy newDone(
final long startTime,
final long totalTime,
final int incrementalFileCount,
final int fileCount,
final long incrementalSize,
final long size,
ShardGeneration generation
) {
// The snapshot is done which means the number of processed files is the same as total
return new IndexShardSnapshotStatus(
Stage.DONE,
startTime,
totalTime,
incrementalFileCount,
fileCount,
incrementalFileCount,
incrementalSize,
size,
incrementalSize,
null,
generation,
"initialized as done"
).asCopy();
}
/**
* Returns an immutable state of {@link IndexShardSnapshotStatus} at a given point in time.
*/
public static | AbortStatus |
java | netty__netty | handler/src/main/java/io/netty/handler/traffic/GlobalChannelTrafficCounter.java | {
"start": 2111,
"end": 4722
} | class ____ implements Runnable {
/**
* The associated TrafficShapingHandler
*/
private final GlobalChannelTrafficShapingHandler trafficShapingHandler1;
/**
* The associated TrafficCounter
*/
private final TrafficCounter counter;
/**
* @param trafficShapingHandler The parent handler to which this task needs to callback to for accounting.
* @param counter The parent TrafficCounter that we need to reset the statistics for.
*/
MixedTrafficMonitoringTask(
GlobalChannelTrafficShapingHandler trafficShapingHandler,
TrafficCounter counter) {
trafficShapingHandler1 = trafficShapingHandler;
this.counter = counter;
}
@Override
public void run() {
if (!counter.monitorActive) {
return;
}
long newLastTime = milliSecondFromNano();
counter.resetAccounting(newLastTime);
for (PerChannel perChannel : trafficShapingHandler1.channelQueues.values()) {
perChannel.channelTrafficCounter.resetAccounting(newLastTime);
}
trafficShapingHandler1.doAccounting(counter);
}
}
/**
* Start the monitoring process.
*/
@Override
public synchronized void start() {
if (monitorActive) {
return;
}
lastTime.set(milliSecondFromNano());
long localCheckInterval = checkInterval.get();
if (localCheckInterval > 0) {
monitorActive = true;
monitor = new MixedTrafficMonitoringTask((GlobalChannelTrafficShapingHandler) trafficShapingHandler, this);
scheduledFuture =
executor.scheduleAtFixedRate(monitor, 0, localCheckInterval, TimeUnit.MILLISECONDS);
}
}
/**
* Stop the monitoring process.
*/
@Override
public synchronized void stop() {
if (!monitorActive) {
return;
}
monitorActive = false;
resetAccounting(milliSecondFromNano());
trafficShapingHandler.doAccounting(this);
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
}
@Override
public void resetCumulativeTime() {
for (PerChannel perChannel :
((GlobalChannelTrafficShapingHandler) trafficShapingHandler).channelQueues.values()) {
perChannel.channelTrafficCounter.resetCumulativeTime();
}
super.resetCumulativeTime();
}
}
| MixedTrafficMonitoringTask |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java | {
"start": 29480,
"end": 29910
} | class ____ {
private final AtomicIntegerArray actual = new AtomicIntegerArray(0);
@Test
void should_run_test_when_assumption_passes() {
thenCode(() -> given(actual).isEmpty()).doesNotThrowAnyException();
}
@Test
void should_ignore_test_when_assumption_fails() {
expectAssumptionNotMetException(() -> given(actual).isNotEmpty());
}
}
@Nested
| BDDAssumptions_given_AtomicIntegerArray_Test |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/api/async/RedisJsonAsyncCommands.java | {
"start": 866,
"end": 30707
} | interface ____<K, V> {
/**
* Append the JSON values into the array at a given {@link JsonPath} after the last element in a said array.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param values one or more {@link JsonValue} to be appended.
* @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrappend(K key, JsonPath jsonPath, JsonValue... values);
/**
* Append the JSON values into the array at the {@link JsonPath#ROOT_PATH} after the last element in a said array.
*
* @param key the key holding the JSON document.
* @param values one or more {@link JsonValue} to be appended.
* @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrappend(K key, JsonValue... values);
/**
* Append the JSON string values into the array at the {@link JsonPath#ROOT_PATH} after the last element in a said array.
*
* @param key the key holding the JSON document.
* @param jsonStrings one or more JSON strings to be appended.
* @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist.
* @since 6.8
*/
RedisFuture<List<Long>> jsonArrappend(K key, String... jsonStrings);
/**
* Append the JSON string values into the array at a given {@link JsonPath} after the last element in a said array.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param jsonStrings one or more JSON strings to be appended.
* @return Long the resulting size of the arrays after the new data was appended, or null if the path does not exist.
* @since 6.8
*/
RedisFuture<List<Long>> jsonArrappend(K key, JsonPath jsonPath, String... jsonStrings);
/**
* Search for the first occurrence of a {@link JsonValue} in an array at a given {@link JsonPath} and return its index.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param value the {@link JsonValue} to search for.
* @param range the {@link JsonRangeArgs} to search within.
* @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrindex(K key, JsonPath jsonPath, JsonValue value, JsonRangeArgs range);
/**
* Search for the first occurrence of a {@link JsonValue} in an array at a given {@link JsonPath} and return its index. This
* method uses defaults for the start and end indexes, see {@link JsonRangeArgs#DEFAULT_START_INDEX} and
* {@link JsonRangeArgs#DEFAULT_END_INDEX}.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param value the {@link JsonValue} to search for.
* @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrindex(K key, JsonPath jsonPath, JsonValue value);
/**
* Search for the first occurrence of a JSON string in an array at a given {@link JsonPath} and return its index. This
* method uses defaults for the start and end indexes, see {@link JsonRangeArgs#DEFAULT_START_INDEX} and
* {@link JsonRangeArgs#DEFAULT_END_INDEX}.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param jsonString the JSON string to search for.
* @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array.
* @since 6.8
*/
RedisFuture<List<Long>> jsonArrindex(K key, JsonPath jsonPath, String jsonString);
/**
* Search for the first occurrence of a JSON string in an array at a given {@link JsonPath} and return its index.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param jsonString the JSON string to search for.
* @param range the {@link JsonRangeArgs} to search within.
* @return Long the index hosting the searched element, -1 if not found or null if the specified path is not an array.
* @since 6.8
*/
RedisFuture<List<Long>> jsonArrindex(K key, JsonPath jsonPath, String jsonString, JsonRangeArgs range);
/**
* Insert the {@link JsonValue}s into the array at a given {@link JsonPath} before the provided index, shifting the existing
* elements to the right
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param index the index before which the new elements will be inserted.
* @param values one or more {@link JsonValue}s to be inserted.
* @return Long the resulting size of the arrays after the new data was inserted, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrinsert(K key, JsonPath jsonPath, int index, JsonValue... values);
/**
* Insert the JSON string values into the array at a given {@link JsonPath} before the provided index.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param index the index before which the new elements will be inserted.
* @param jsonStrings one or more JSON strings to be inserted.
* @return Long the resulting size of the arrays after the new data was inserted, or null if the path does not exist.
* @since 6.8
*/
RedisFuture<List<Long>> jsonArrinsert(K key, JsonPath jsonPath, int index, String... jsonStrings);
/**
* Report the length of the JSON array at a given {@link JsonPath}
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @return the size of the arrays, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrlen(K key, JsonPath jsonPath);
/**
* Report the length of the JSON array at a the {@link JsonPath#ROOT_PATH}
*
* @param key the key holding the JSON document.
* @return the size of the arrays, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrlen(K key);
/**
* Remove and return {@link JsonValue} at a given index in the array at a given {@link JsonPath}
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param index the index of the element to be removed. Default is -1, meaning the last element. Out-of-range indexes round
* to their respective array ends. Popping an empty array returns null.
* @return List<JsonValue> the removed element, or null if the specified path is not an array.
* @since 6.5
*/
RedisFuture<List<JsonValue>> jsonArrpop(K key, JsonPath jsonPath, int index);
/**
* Remove and return the JSON value at a given index in the array at a given {@link JsonPath} as raw JSON strings.
* <p>
* Behaves like {@link #jsonArrpop(Object, JsonPath, int)} but returns {@code List<String>} with raw JSON instead of
* {@link JsonValue} wrappers.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param index the index of the element to be removed. Default is -1, meaning the last element. Out-of-range indexes round
* to their respective array ends. Popping an empty array returns null.
* @return List<String> the removed element, or null if the specified path is not an array.
* @since 7.0
*/
RedisFuture<List<String>> jsonArrpopRaw(K key, JsonPath jsonPath, int index);
/**
* Remove and return {@link JsonValue} at index -1 (last element) in the array at a given {@link JsonPath}
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @return List<JsonValue> the removed element, or null if the specified path is not an array.
* @since 6.5
*/
RedisFuture<List<JsonValue>> jsonArrpop(K key, JsonPath jsonPath);
/**
* Remove and return the JSON value at index -1 (last element) in the array at a given {@link JsonPath} as raw JSON strings.
* <p>
* Behaves like {@link #jsonArrpop(Object, JsonPath)} but returns {@code List<String>} with raw JSON instead of
* {@link JsonValue} wrappers.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @return List<String> the removed element, or null if the specified path is not an array.
* @since 7.0
*/
RedisFuture<List<String>> jsonArrpopRaw(K key, JsonPath jsonPath);
/**
* Remove and return {@link JsonValue} at index -1 (last element) in the array at the {@link JsonPath#ROOT_PATH}
*
* @param key the key holding the JSON document.
* @return List<JsonValue> the removed element, or null if the specified path is not an array.
* @since 6.5
*/
RedisFuture<List<JsonValue>> jsonArrpop(K key);
/**
* Remove and return the JSON value at index -1 (last element) in the array at the {@link JsonPath#ROOT_PATH} as raw JSON
* strings.
* <p>
* Behaves like {@link #jsonArrpop(Object)} but returns {@code List<String>} with raw JSON instead of {@link JsonValue}
* wrappers.
*
* @param key the key holding the JSON document.
* @return List<String> the removed element, or null if the specified path is not an array.
* @since 7.0
*/
RedisFuture<List<String>> jsonArrpopRaw(K key);
/**
* Trim an array at a given {@link JsonPath} so that it contains only the specified inclusive range of elements. All
* elements with indexes smaller than the start range and all elements with indexes bigger than the end range are trimmed.
* <p>
* Behavior as of RedisJSON v2.0:
* <ul>
* <li>If start is larger than the array's size or start > stop, returns 0 and an empty array.</li>
* <li>If start is < 0, then start from the end of the array.</li>
* <li>If stop is larger than the end of the array, it is treated like the last element.</li>
* </ul>
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the array inside the document.
* @param range the {@link JsonRangeArgs} to trim by.
* @return Long the resulting size of the arrays after the trimming, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonArrtrim(K key, JsonPath jsonPath, JsonRangeArgs range);
/**
* Clear container values (arrays/objects) and set numeric values to 0
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value to clear.
* @return Long the number of values removed plus all the matching JSON numerical values that are zeroed.
* @since 6.5
*/
RedisFuture<Long> jsonClear(K key, JsonPath jsonPath);
/**
* Clear container values (arrays/objects) and set numeric values to 0 at the {@link JsonPath#ROOT_PATH}
*
* @param key the key holding the JSON document.
* @return Long the number of values removed plus all the matching JSON numerical values that are zeroed.
* @since 6.5
*/
RedisFuture<Long> jsonClear(K key);
/**
* Deletes a value inside the JSON document at a given {@link JsonPath}
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value to clear.
* @return Long the number of values removed (0 or more).
* @since 6.5
*/
RedisFuture<Long> jsonDel(K key, JsonPath jsonPath);
/**
* Deletes a value inside the JSON document at the {@link JsonPath#ROOT_PATH}
*
* @param key the key holding the JSON document.
* @return Long the number of values removed (0 or more).
* @since 6.5
*/
RedisFuture<Long> jsonDel(K key);
/**
* Return the value at the specified path in JSON serialized form.
* <p>
* When using a single JSONPath, the root of the matching values is a JSON string with a top-level array of serialized JSON
* value. In contrast, a legacy path returns a single value.
* <p>
* When using multiple JSONPath arguments, the root of the matching values is a JSON string with a top-level object, with
* each object value being a top-level array of serialized JSON value. In contrast, if all paths are legacy paths, each
* object value is a single serialized JSON value. If there are multiple paths that include both legacy path and JSONPath,
* the returned value conforms to the JSONPath version (an array of values).
*
* @param key the key holding the JSON document.
* @param options the {@link JsonGetArgs} to use.
* @param jsonPaths the {@link JsonPath}s to use to identify the values to get.
* @return JsonValue the value at path in JSON serialized form, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<JsonValue>> jsonGet(K key, JsonGetArgs options, JsonPath... jsonPaths);
/**
* Return the value at the specified path in JSON serialized form as raw strings.
* <p>
* Behaves like {@link #jsonGet(Object, JsonGetArgs, JsonPath...)} but returns {@code List<String>} with raw JSON instead of
* {@link JsonValue} wrappers.
*
* @param key the key holding the JSON document.
* @param options the {@link JsonGetArgs} to use.
* @param jsonPaths the {@link JsonPath}s to use to identify the values to get.
* @return List<String> the value at path in JSON serialized form, or null if the path does not exist.
* @since 7.0
*/
RedisFuture<List<String>> jsonGetRaw(K key, JsonGetArgs options, JsonPath... jsonPaths);
/**
* Return the value at the specified path in JSON serialized form. Uses defaults for the {@link JsonGetArgs}.
* <p>
* When using a single JSONPath, the root of the matching values is a JSON string with a top-level array of serialized JSON
* value. In contrast, a legacy path returns a single value.
* <p>
* When using multiple JSONPath arguments, the root of the matching values is a JSON string with a top-level object, with
* each object value being a top-level array of serialized JSON value. In contrast, if all paths are legacy paths, each
* object value is a single serialized JSON value. If there are multiple paths that include both legacy path and JSONPath,
* the returned value conforms to the JSONPath version (an array of values).
*
* @param key the key holding the JSON document.
* @param jsonPaths the {@link JsonPath}s to use to identify the values to get.
* @return JsonValue the value at path in JSON serialized form, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<JsonValue>> jsonGet(K key, JsonPath... jsonPaths);
/**
* Return the value at the specified path in JSON serialized form as raw strings. Uses defaults for the {@link JsonGetArgs}.
* <p>
* Behaves like {@link #jsonGet(Object, JsonPath...)} but returns {@code List<String>} with raw JSON instead of
* {@link JsonValue} wrappers.
*
* @param key the key holding the JSON document.
* @param jsonPaths the {@link JsonPath}s to use to identify the values to get.
* @return List<String> the value at path in JSON serialized form, or null if the path does not exist.
* @since 7.0
*/
RedisFuture<List<String>> jsonGetRaw(K key, JsonPath... jsonPaths);
/**
* Merge a given {@link JsonValue} with the value matching {@link JsonPath}. Consequently, JSON values at matching paths are
* updated, deleted, or expanded with new children.
* <p>
* Merging is done according to the following rules per JSON value in the value argument while considering the corresponding
* original value if it exists:
* <ul>
* <li>merging an existing object key with a null value deletes the key</li>
* <li>merging an existing object key with non-null value updates the value</li>
* <li>merging a non-existing object key adds the key and value</li>
* <li>merging an existing array with any merged value, replaces the entire array with the value</li>
* </ul>
* <p>
* This command complies with RFC7396 "Json Merge Patch"
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value to merge.
* @param value the {@link JsonValue} to merge.
* @return String "OK" if the set was successful, error if the operation failed.
* @since 6.5
* @see <A href="https://tools.ietf.org/html/rfc7396">RFC7396</a>
*/
RedisFuture<String> jsonMerge(K key, JsonPath jsonPath, JsonValue value);
/**
* Merge a given JSON string with the value matching {@link JsonPath}.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value to merge.
* @param jsonString the JSON string to merge.
* @return String "OK" if the merge was successful, error if the operation failed.
* @since 6.8
*/
RedisFuture<String> jsonMerge(K key, JsonPath jsonPath, String jsonString);
/**
* Return the values at the specified path from multiple key arguments.
*
* @param jsonPath the {@link JsonPath} pointing to the value to fetch.
* @param keys the keys holding the {@link JsonValue}s to fetch.
* @return List<JsonValue> the values at path, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<JsonValue>> jsonMGet(JsonPath jsonPath, K... keys);
/**
* Return the values at the specified path from multiple key arguments as raw JSON strings.
* <p>
* Behaves like {@link #jsonMGet(JsonPath, Object[])} but returns {@code List<String>} with raw JSON instead of
* {@link JsonValue} wrappers.
*
* @param jsonPath the {@link JsonPath} pointing to the value to fetch.
* @param keys the keys holding the values to fetch.
* @return List<String> the values at path, or null if the path does not exist.
* @since 7.0
*/
RedisFuture<List<String>> jsonMGetRaw(JsonPath jsonPath, K... keys);
/**
* Set or update one or more JSON values according to the specified {@link JsonMsetArgs}
* <p>
* JSON.MSET is atomic, hence, all given additions or updates are either applied or not. It is not possible for clients to
* see that some keys were updated while others are unchanged.
* <p>
* A JSON value is a hierarchical structure. If you change a value in a specific path - nested values are affected.
*
* @param arguments the {@link JsonMsetArgs} specifying the values to change.
* @return "OK" if the operation was successful, error otherwise
* @since 6.5
*/
RedisFuture<String> jsonMSet(List<JsonMsetArgs<K, V>> arguments);
/**
* Increment the number value stored at the specified {@link JsonPath} in the JSON document by the provided increment.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value to increment.
* @param number the increment value.
* @return a {@link List} of the new values after the increment.
* @since 6.5
*/
RedisFuture<List<Number>> jsonNumincrby(K key, JsonPath jsonPath, Number number);
/**
* Return the keys in the JSON document that are referenced by the given {@link JsonPath}
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) whose key(s) we want.
* @return List<V> the keys in the JSON document that are referenced by the given {@link JsonPath}.
* @since 6.5
*/
RedisFuture<List<V>> jsonObjkeys(K key, JsonPath jsonPath);
/**
* Return the keys in the JSON document that are referenced by the {@link JsonPath#ROOT_PATH}
*
* @param key the key holding the JSON document.
* @return List<V> the keys in the JSON document that are referenced by the given {@link JsonPath}.
* @since 6.5
*/
RedisFuture<List<V>> jsonObjkeys(K key);
/**
* Report the number of keys in the JSON object at the specified {@link JsonPath} and for the provided key
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) whose key(s) we want to count
* @return Long the number of keys in the JSON object at the specified path, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonObjlen(K key, JsonPath jsonPath);
/**
* Report the number of keys in the JSON object at the {@link JsonPath#ROOT_PATH} and for the provided key
*
* @param key the key holding the JSON document.
* @return Long the number of keys in the JSON object at the specified path, or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonObjlen(K key);
/**
* Sets the JSON value at a given {@link JsonPath} in the JSON document.
* <p>
* For new Redis keys, the path must be the root. For existing keys, when the entire path exists, the value that it contains
* is replaced with the JSON value. For existing keys, when the path exists, except for the last element, a new child is
* added with the JSON value.
* <p>
* Adds a key (with its respective value) to a JSON Object (in a RedisJSON data type key) only if it is the last child in
* the path, or it is the parent of a new child being added in the path. Optional arguments NX and XX modify this behavior
* for both new RedisJSON data type keys and the JSON Object keys in them.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value.
* @param value the {@link JsonValue} to set.
* @param options the {@link JsonSetArgs} the options for setting the value.
* @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met.
* @since 6.5
*/
RedisFuture<String> jsonSet(K key, JsonPath jsonPath, JsonValue value, JsonSetArgs options);
/**
* Sets the JSON value at a given {@link JsonPath} in the JSON document using defaults for the {@link JsonSetArgs}.
* <p>
* For new Redis keys the path must be the root. For existing keys, when the entire path exists, the value that it contains
* is replaced with the JSON value. For existing keys, when the path exists, except for the last element, a new child is
* added with the JSON value.
* <p>
* Adds a key (with its respective value) to a JSON Object (in a RedisJSON data type key) only if it is the last child in
* the path, or it is the parent of a new child being added in the path. Optional arguments NX and XX modify this behavior
* for both new RedisJSON data type keys and the JSON Object keys in them.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value.
* @param value the {@link JsonValue} to set.
* @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met.
* @since 6.5
*/
RedisFuture<String> jsonSet(K key, JsonPath jsonPath, JsonValue value);
/**
* Sets the JSON value at a given {@link JsonPath} in the JSON document using defaults for the {@link JsonSetArgs}.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value.
* @param jsonString the JSON string to set.
* @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met.
* @since 6.8
*/
RedisFuture<String> jsonSet(K key, JsonPath jsonPath, String jsonString);
/**
* Sets the JSON value at a given {@link JsonPath} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to set the value.
* @param jsonString the JSON string to set.
* @param options the {@link JsonSetArgs} the options for setting the value.
* @return String "OK" if the set was successful, null if the {@link JsonSetArgs} conditions are not met.
* @since 6.8
*/
RedisFuture<String> jsonSet(K key, JsonPath jsonPath, String jsonString, JsonSetArgs options);
/**
* Append the json-string values to the string at the provided {@link JsonPath} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to append the value.
* @param value the {@link JsonValue} to append.
* @return Long the new length of the string, or null if the matching JSON value is not a string.
* @since 6.5
*/
RedisFuture<List<Long>> jsonStrappend(K key, JsonPath jsonPath, JsonValue value);
/**
* Append the json-string values to the string at the {@link JsonPath#ROOT_PATH} in the JSON document.
*
* @param key the key holding the JSON document.
* @param value the {@link JsonValue} to append.
* @return Long the new length of the string, or null if the matching JSON value is not a string.
* @since 6.5
*/
RedisFuture<List<Long>> jsonStrappend(K key, JsonValue value);
/**
* Append the JSON string to the string at the {@link JsonPath#ROOT_PATH} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonString the JSON string to append.
* @return Long the new length of the string, or null if the matching JSON value is not a string.
* @since 6.8
*/
RedisFuture<List<Long>> jsonStrappend(K key, String jsonString);
/**
* Append the JSON string to the string at the provided {@link JsonPath} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s) where we want to append the value.
* @param jsonString the JSON string to append.
* @return Long the new length of the string, or null if the matching JSON value is not a string.
* @since 6.8
*/
RedisFuture<List<Long>> jsonStrappend(K key, JsonPath jsonPath, String jsonString);
/**
* Report the length of the JSON String at the provided {@link JsonPath} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s).
* @return Long (in recursive descent) the length of the JSON String at the provided {@link JsonPath}, or null if the value
* ath the desired path is not a string.
* @since 6.5
*/
RedisFuture<List<Long>> jsonStrlen(K key, JsonPath jsonPath);
/**
* Report the length of the JSON String at the {@link JsonPath#ROOT_PATH} in the JSON document.
*
* @param key the key holding the JSON document.
* @return Long (in recursive descent) the length of the JSON String at the provided {@link JsonPath}, or null if the value
* ath the desired path is not a string.
* @since 6.5
*/
RedisFuture<List<Long>> jsonStrlen(K key);
/**
* Toggle a Boolean value stored at the provided {@link JsonPath} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s).
* @return List<Long> the new value after the toggle, 0 for false, 1 for true or null if the path does not exist.
* @since 6.5
*/
RedisFuture<List<Long>> jsonToggle(K key, JsonPath jsonPath);
/**
* Report the type of JSON value at the provided {@link JsonPath} in the JSON document.
*
* @param key the key holding the JSON document.
* @param jsonPath the {@link JsonPath} pointing to the value(s).
* @return List<JsonType> the type of JSON value at the provided {@link JsonPath}
* @since 6.5
*/
RedisFuture<List<JsonType>> jsonType(K key, JsonPath jsonPath);
/**
* Report the type of JSON value at the {@link JsonPath#ROOT_PATH} in the JSON document.
*
* @param key the key holding the JSON document.
* @return List<JsonType> the type of JSON value at the provided {@link JsonPath}
* @since 6.5
*/
RedisFuture<List<JsonType>> jsonType(K key);
}
| RedisJsonAsyncCommands |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/flush/TestFlushModeWithIdentitySelfReferenceTest.java | {
"start": 1358,
"end": 4904
} | class ____ {
@AfterEach
void tearDown(SessionFactoryScope factoryScope) {
factoryScope.dropData();
}
@Test
public void testFlushModeCommit(SessionFactoryScope factoryScope) {
factoryScope.inSession( (session) -> {
session.setHibernateFlushMode( FlushMode.COMMIT );
loadAndAssert( session, createAndInsertEntity( session ) );
loadAndInsert( session, createAndInsertEntityEmbeddable( session ) );
} );
}
@Test
public void testFlushModeManual(SessionFactoryScope factoryScope) {
factoryScope.inSession( (session) -> {
session.setHibernateFlushMode( FlushMode.MANUAL );
loadAndAssert( session, createAndInsertEntity( session ) );
loadAndInsert( session, createAndInsertEntityEmbeddable( session ) );
} );
}
@Test
public void testFlushModeAuto(SessionFactoryScope factoryScope) {
factoryScope.inSession( (session) -> {
session.setHibernateFlushMode( FlushMode.AUTO );
loadAndAssert( session, createAndInsertEntity( session ) );
loadAndInsert( session, createAndInsertEntityEmbeddable( session ) );
} );
}
private SelfRefEntity createAndInsertEntity(Session session) {
try {
session.getTransaction().begin();
SelfRefEntity entity = new SelfRefEntity();
entity.setSelfRefEntity( entity );
entity.setData( "test" );
entity = (SelfRefEntity) session.merge( entity );
// only during manual flush do we want to force a flush prior to commit
if ( session.getHibernateFlushMode().equals( FlushMode.MANUAL ) ) {
session.flush();
}
session.getTransaction().commit();
return entity;
}
catch ( Exception e ) {
if ( session.getTransaction().isActive() ) {
session.getTransaction().rollback();
}
throw e;
}
}
private SelfRefEntityWithEmbeddable createAndInsertEntityEmbeddable(Session session) {
try {
session.getTransaction().begin();
SelfRefEntityWithEmbeddable entity = new SelfRefEntityWithEmbeddable();
entity.setData( "test" );
SelfRefEntityInfo info = new SelfRefEntityInfo();
info.setSeflRefEntityEmbedded( entity );
entity.setInfo( info );
entity = (SelfRefEntityWithEmbeddable) session.merge( entity );
// only during manual flush do we want to force a flush prior to commit
if ( session.getHibernateFlushMode().equals( FlushMode.MANUAL ) ) {
session.flush();
}
session.getTransaction().commit();
return entity;
}
catch ( Exception e ) {
if ( session.getTransaction().isActive() ) {
session.getTransaction().rollback();
}
throw e;
}
}
private void loadAndAssert(Session session, SelfRefEntity mergedEntity) {
final SelfRefEntity loadedEntity = session.find( SelfRefEntity.class, mergedEntity.getId() );
Assertions.assertNotNull( loadedEntity, "Expected to find the merged entity but did not." );
Assertions.assertEquals( "test", loadedEntity.getData() );
Assertions.assertNotNull( loadedEntity.getSelfRefEntity(), "Expected a non-null self reference" );
}
private void loadAndInsert(Session session, SelfRefEntityWithEmbeddable mergedEntity) {
final SelfRefEntityWithEmbeddable loadedEntity = session.find( SelfRefEntityWithEmbeddable.class, mergedEntity.getId() );
Assertions.assertNotNull( loadedEntity, "Expected to find the merged entity but did not." );
Assertions.assertEquals( "test", loadedEntity.getData() );
Assertions.assertNotNull( loadedEntity.getInfo().getSeflRefEntityEmbedded(),
"Expected a non-null self reference in embeddable" );
}
@Entity(name = "SelfRefEntity")
public static | TestFlushModeWithIdentitySelfReferenceTest |
java | processing__processing4 | java/src/processing/mode/java/debug/Debugger.java | {
"start": 29807,
"end": 29918
} | class ____ of the current this object in a suspended thread.
* @param t a suspended thread
* @return the | name |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/timelineservice/reader/TimelineEntityReader.java | {
"start": 1581,
"end": 2232
} | class ____ implements MessageBodyReader<TimelineEntity> {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return type == TimelineEntity.class;
}
@Override
public TimelineEntity readFrom(Class<TimelineEntity> type, Type genericType,
Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
return objectMapper.readValue(entityStream, TimelineEntity.class);
}
}
| TimelineEntityReader |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-jsonb/deployment/src/test/java/io/quarkus/resteasy/reactive/jsonb/deployment/test/VertxJsonTest.java | {
"start": 399,
"end": 1760
} | class ____ {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(VertxJsonEndpoint.class);
}
});
@Test
public void testJsonObject() {
RestAssured.with()
.body("{\"name\": \"Bob\"}")
.contentType("application/json")
.post("/vertx/jsonObject")
.then()
.statusCode(200)
.contentType("application/json")
.body("name", Matchers.equalTo("Bob"))
.body("age", Matchers.equalTo(50))
.body("nested.foo", Matchers.equalTo("bar"))
.body("bools[0]", Matchers.equalTo(true));
}
@Test
public void testJsonArray() {
RestAssured.with()
.body("[\"first\"]")
.contentType("application/json")
.post("/vertx/jsonArray")
.then()
.statusCode(200)
.contentType("application/json")
.body("[0]", Matchers.equalTo("first"))
.body("[1]", Matchers.equalTo("last"));
}
}
| VertxJsonTest |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java | {
"start": 5254,
"end": 5430
} | class ____ implements InvocationListener {
public void reportInvocation(MethodInvocationReport methodInvocationReport) {
// nop
}
}
}
| CustomListener |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/mistral/embeddings/MistralEmbeddingsServiceSettings.java | {
"start": 1932,
"end": 7371
} | class ____ extends FilteredXContentObject implements ServiceSettings {
public static final String NAME = "mistral_embeddings_service_settings";
private final String model;
private final Integer dimensions;
private final SimilarityMeasure similarity;
private final Integer maxInputTokens;
private final RateLimitSettings rateLimitSettings;
// default for Mistral is 5 requests / sec
// setting this to 240 (4 requests / sec) is a sane default for us
protected static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(240);
public static MistralEmbeddingsServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) {
ValidationException validationException = new ValidationException();
String model = extractRequiredString(map, MODEL_FIELD, ModelConfigurations.SERVICE_SETTINGS, validationException);
SimilarityMeasure similarity = extractSimilarity(map, ModelConfigurations.SERVICE_SETTINGS, validationException);
Integer maxInputTokens = extractOptionalPositiveInteger(
map,
MAX_INPUT_TOKENS,
ModelConfigurations.SERVICE_SETTINGS,
validationException
);
RateLimitSettings rateLimitSettings = RateLimitSettings.of(
map,
DEFAULT_RATE_LIMIT_SETTINGS,
validationException,
MistralService.NAME,
context
);
Integer dims = extractOptionalPositiveInteger(map, DIMENSIONS, ModelConfigurations.SERVICE_SETTINGS, validationException);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return new MistralEmbeddingsServiceSettings(model, dims, maxInputTokens, similarity, rateLimitSettings);
}
public MistralEmbeddingsServiceSettings(StreamInput in) throws IOException {
this.model = in.readString();
this.dimensions = in.readOptionalVInt();
this.similarity = in.readOptionalEnum(SimilarityMeasure.class);
this.maxInputTokens = in.readOptionalVInt();
this.rateLimitSettings = new RateLimitSettings(in);
}
public MistralEmbeddingsServiceSettings(
String model,
@Nullable Integer dimensions,
@Nullable Integer maxInputTokens,
@Nullable SimilarityMeasure similarity,
@Nullable RateLimitSettings rateLimitSettings
) {
this.model = model;
this.dimensions = dimensions;
this.similarity = similarity;
this.maxInputTokens = maxInputTokens;
this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_15_0;
}
@Override
public String modelId() {
return this.model;
}
@Override
public Integer dimensions() {
return this.dimensions;
}
public Integer maxInputTokens() {
return this.maxInputTokens;
}
@Override
public SimilarityMeasure similarity() {
return this.similarity;
}
@Override
public DenseVectorFieldMapper.ElementType elementType() {
return DenseVectorFieldMapper.ElementType.FLOAT;
}
public RateLimitSettings rateLimitSettings() {
return this.rateLimitSettings;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(model);
out.writeOptionalVInt(dimensions);
out.writeOptionalEnum(SimilarityMeasure.translateSimilarity(similarity, out.getTransportVersion()));
out.writeOptionalVInt(maxInputTokens);
rateLimitSettings.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
this.toXContentFragmentOfExposedFields(builder, params);
builder.endObject();
return builder;
}
@Override
protected XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException {
builder.field(MODEL_FIELD, this.model);
if (dimensions != null) {
builder.field(DIMENSIONS, dimensions);
}
if (similarity != null) {
builder.field(SIMILARITY, similarity);
}
if (this.maxInputTokens != null) {
builder.field(MAX_INPUT_TOKENS, this.maxInputTokens);
}
rateLimitSettings.toXContent(builder, params);
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MistralEmbeddingsServiceSettings that = (MistralEmbeddingsServiceSettings) o;
return Objects.equals(model, that.model)
&& Objects.equals(dimensions, that.dimensions)
&& Objects.equals(maxInputTokens, that.maxInputTokens)
&& Objects.equals(similarity, that.similarity)
&& Objects.equals(rateLimitSettings, that.rateLimitSettings);
}
@Override
public int hashCode() {
return Objects.hash(model, dimensions, maxInputTokens, similarity, rateLimitSettings);
}
}
| MistralEmbeddingsServiceSettings |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/cat/RestAliasAction.java | {
"start": 1396,
"end": 4737
} | class ____ extends AbstractCatAction {
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_cat/aliases"), new Route(GET, "/_cat/aliases/{alias}"));
}
@Override
public String getName() {
return "cat_alias_action";
}
@Override
public boolean allowSystemIndexAccessByDefault() {
return true;
}
@Override
protected RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
final var masterNodeTimeout = RestUtils.getMasterNodeTimeout(request);
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(
masterNodeTimeout,
Strings.commaDelimitedListToStringArray(request.param("alias"))
);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
return channel -> new RestCancellableNodeClient(client, request.getHttpChannel()).admin()
.indices()
.getAliases(getAliasesRequest, new RestResponseListener<>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response) throws Exception {
Table tab = buildTable(request, response);
return RestTable.buildResponse(tab, channel);
}
});
}
@Override
protected void documentation(StringBuilder sb) {
sb.append("/_cat/aliases\n");
sb.append("/_cat/aliases/{alias}\n");
}
@Override
protected Table getTableWithHeader(RestRequest request) {
final Table table = new Table();
table.startHeaders();
table.addCell("alias", "alias:a;desc:alias name");
table.addCell("index", "alias:i,idx;desc:index alias points to");
table.addCell("filter", "alias:f,fi;desc:filter");
table.addCell("routing.index", "alias:ri,routingIndex;desc:index routing");
table.addCell("routing.search", "alias:rs,routingSearch;desc:search routing");
table.addCell("is_write_index", "alias:w,isWriteIndex;desc:write index");
table.endHeaders();
return table;
}
private Table buildTable(RestRequest request, GetAliasesResponse response) {
Table table = getTableWithHeader(request);
for (Map.Entry<String, List<AliasMetadata>> cursor : response.getAliases().entrySet()) {
String indexName = cursor.getKey();
for (AliasMetadata aliasMetadata : cursor.getValue()) {
table.startRow();
table.addCell(aliasMetadata.alias());
table.addCell(indexName);
table.addCell(aliasMetadata.filteringRequired() ? "*" : "-");
String indexRouting = Strings.hasLength(aliasMetadata.indexRouting()) ? aliasMetadata.indexRouting() : "-";
table.addCell(indexRouting);
String searchRouting = Strings.hasLength(aliasMetadata.searchRouting()) ? aliasMetadata.searchRouting() : "-";
table.addCell(searchRouting);
String isWriteIndex = aliasMetadata.writeIndex() == null ? "-" : aliasMetadata.writeIndex().toString();
table.addCell(isWriteIndex);
table.endRow();
}
}
return table;
}
}
| RestAliasAction |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.