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 | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/api/AssertEqualsAssertionsTests.java | {
"start": 1045,
"end": 18763
} | class ____ {
@Test
void assertEqualsByte() {
byte expected = 1;
byte actual = 1;
assertEquals(expected, actual);
assertEquals(expected, actual, "message");
assertEquals(expected, actual, () -> "message");
}
@Test
void assertEqualsByteWithUnequalValues() {
byte expected = 1;
byte actual = 2;
try {
assertEquals(expected, actual);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, expected, actual);
}
}
@Test
void assertEqualsByteWithUnequalValuesAndMessage() {
byte expected = 1;
byte actual = 2;
try {
assertEquals(expected, actual, "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, expected, actual);
}
}
@Test
void assertEqualsByteWithUnequalValuesAndMessageSupplier() {
byte expected = 1;
byte actual = 2;
try {
assertEquals(expected, actual, () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, expected, actual);
}
}
@Test
void assertEqualsShort() {
short expected = 1;
short actual = 1;
assertEquals(expected, actual);
assertEquals(expected, actual, "message");
assertEquals(expected, actual, () -> "message");
}
@Test
void assertEqualsShortWithUnequalValues() {
short expected = 1;
short actual = 2;
try {
assertEquals(expected, actual);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, expected, actual);
}
}
@Test
void assertEqualsShortWithUnequalValuesAndMessage() {
short expected = 1;
short actual = 2;
try {
assertEquals(expected, actual, "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, expected, actual);
}
}
@Test
void assertEqualsShortWithUnequalValuesAndMessageSupplier() {
short expected = 1;
short actual = 2;
try {
assertEquals(expected, actual, () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, expected, actual);
}
}
@Test
void assertEqualsInt() {
assertEquals(1, 1);
assertEquals(1, 1, "message");
assertEquals(1, 1, () -> "message");
}
@Test
void assertEqualsIntWithUnequalValues() {
try {
assertEquals(1, 2);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, 1, 2);
}
}
@Test
void assertEqualsIntWithUnequalValuesAndMessage() {
try {
assertEquals(1, 2, "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, 1, 2);
}
}
@Test
void assertEqualsIntWithUnequalValuesAndMessageSupplier() {
try {
assertEquals(1, 2, () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, 1, 2);
}
}
@Test
void assertEqualsLong() {
assertEquals(1L, 1L);
assertEquals(1L, 1L, "message");
assertEquals(1L, 1L, () -> "message");
}
@Test
void assertEqualsLongWithUnequalValues() {
try {
assertEquals(1L, 2L);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, 1L, 2L);
}
}
@Test
void assertEqualsLongWithUnequalValuesAndMessage() {
try {
assertEquals(1L, 2L, "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, 1L, 2L);
}
}
@Test
void assertEqualsLongWithUnequalValuesAndMessageSupplier() {
try {
assertEquals(1L, 2L, () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1> but was: <2>");
assertExpectedAndActualValues(ex, 1L, 2L);
}
}
@Test
void assertEqualsChar() {
assertEquals('a', 'a');
assertEquals('a', 'a', "message");
assertEquals('a', 'a', () -> "message");
}
@Test
void assertEqualsCharWithUnequalValues() {
try {
assertEquals('a', 'b');
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <a> but was: <b>");
assertExpectedAndActualValues(ex, 'a', 'b');
}
}
@Test
void assertEqualsCharWithUnequalValuesAndMessage() {
try {
assertEquals('a', 'b', "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <a> but was: <b>");
assertExpectedAndActualValues(ex, 'a', 'b');
}
}
@Test
void assertEqualsCharWithUnequalValuesAndMessageSupplier() {
try {
assertEquals('a', 'b', () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <a> but was: <b>");
assertExpectedAndActualValues(ex, 'a', 'b');
}
}
@Test
void assertEqualsFloat() {
assertEquals(1.0f, 1.0f);
assertEquals(1.0f, 1.0f, "message");
assertEquals(1.0f, 1.0f, () -> "message");
assertEquals(Float.NaN, Float.NaN);
assertEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
assertEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY);
assertEquals(Float.MIN_VALUE, Float.MIN_VALUE);
assertEquals(Float.MAX_VALUE, Float.MAX_VALUE);
assertEquals(Float.MIN_NORMAL, Float.MIN_NORMAL);
assertEquals(Double.NaN, Float.NaN);
}
@Test
void assertEqualsFloatWithUnequalValues() {
try {
assertEquals(1.0f, 1.1f);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <1.0> but was: <1.1>");
assertExpectedAndActualValues(ex, 1.0f, 1.1f);
}
}
@Test
void assertEqualsFloatWithUnequalValuesAndMessage() {
try {
assertEquals(1.0f, 1.1f, "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1.0> but was: <1.1>");
assertExpectedAndActualValues(ex, 1.0f, 1.1f);
}
}
@Test
void assertEqualsFloatWithUnequalValuesAndMessageSupplier() {
try {
assertEquals(1.0f, 1.1f, () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1.0> but was: <1.1>");
assertExpectedAndActualValues(ex, 1.0f, 1.1f);
}
}
@Test
void assertEqualsFloatWithDelta() {
assertEquals(0.0f, 0.0f, 0.1f);
assertEquals(0.0f, 0.0f, 0.1f, "message");
assertEquals(0.0f, 0.0f, 0.1f, () -> "message");
assertEquals(0.56f, 0.6f, 0.05f);
assertEquals(0.01f, 0.011f, 0.002f);
assertEquals(Float.NaN, Float.NaN, 0.5f);
assertEquals(0.1f, 0.1f, 0.0f);
}
@Test
void assertEqualsFloatWithIllegalDelta() {
AssertionFailedError e1 = assertThrows(AssertionFailedError.class, () -> assertEquals(0.1f, 0.2f, -0.9f));
assertMessageEndsWith(e1, "positive delta expected but was: <-0.9>");
AssertionFailedError e2 = assertThrows(AssertionFailedError.class, () -> assertEquals(.0f, .0f, -10.5f));
assertMessageEndsWith(e2, "positive delta expected but was: <-10.5>");
AssertionFailedError e3 = assertThrows(AssertionFailedError.class, () -> assertEquals(4.5f, 4.6f, Float.NaN));
assertMessageEndsWith(e3, "positive delta expected but was: <NaN>");
}
@Test
void assertEqualsFloatWithDeltaWithUnequalValues() {
AssertionFailedError e1 = assertThrows(AssertionFailedError.class, () -> assertEquals(0.5f, 0.2f, 0.2f));
assertMessageEndsWith(e1, "expected: <0.5> but was: <0.2>");
AssertionFailedError e2 = assertThrows(AssertionFailedError.class, () -> assertEquals(0.1f, 0.2f, 0.000001f));
assertMessageEndsWith(e2, "expected: <0.1> but was: <0.2>");
AssertionFailedError e3 = assertThrows(AssertionFailedError.class, () -> assertEquals(100.0f, 50.0f, 10.0f));
assertMessageEndsWith(e3, "expected: <100.0> but was: <50.0>");
AssertionFailedError e4 = assertThrows(AssertionFailedError.class, () -> assertEquals(-3.5f, -3.3f, 0.01f));
assertMessageEndsWith(e4, "expected: <-3.5> but was: <-3.3>");
AssertionFailedError e5 = assertThrows(AssertionFailedError.class, () -> assertEquals(+0.0f, -0.001f, .00001f));
assertMessageEndsWith(e5, "expected: <0.0> but was: <-0.001>");
}
@Test
void assertEqualsFloatWithDeltaWithUnequalValuesAndMessage() {
Executable assertion = () -> assertEquals(0.5f, 0.45f, 0.03f, "message");
AssertionFailedError e = assertThrows(AssertionFailedError.class, assertion);
assertMessageStartsWith(e, "message");
assertMessageEndsWith(e, "expected: <0.5> but was: <0.45>");
assertExpectedAndActualValues(e, 0.5f, 0.45f);
}
@Test
void assertEqualsFloatWithDeltaWithUnequalValuesAndMessageSupplier() {
Executable assertion = () -> assertEquals(0.5f, 0.45f, 0.03f, () -> "message");
AssertionFailedError e = assertThrows(AssertionFailedError.class, assertion);
assertMessageStartsWith(e, "message");
assertMessageEndsWith(e, "expected: <0.5> but was: <0.45>");
assertExpectedAndActualValues(e, 0.5f, 0.45f);
}
@Test
void assertEqualsDouble() {
assertEquals(1.0d, 1.0d);
assertEquals(1.0d, 1.0d, "message");
assertEquals(1.0d, 1.0d, () -> "message");
assertEquals(Double.NaN, Double.NaN);
assertEquals(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
assertEquals(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
assertEquals(Double.MIN_VALUE, Double.MIN_VALUE);
assertEquals(Double.MAX_VALUE, Double.MAX_VALUE);
assertEquals(Double.MIN_NORMAL, Double.MIN_NORMAL);
}
@Test
void assertEqualsDoubleWithUnequalValues() {
try {
assertEquals(1.0d, 1.1d);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <1.0> but was: <1.1>");
assertExpectedAndActualValues(ex, 1.0d, 1.1d);
}
}
@Test
void assertEqualsDoubleWithUnequalValuesAndMessage() {
try {
assertEquals(1.0d, 1.1d, "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1.0> but was: <1.1>");
assertExpectedAndActualValues(ex, 1.0d, 1.1d);
}
}
@Test
void assertEqualsDoubleWithUnequalValuesAndMessageSupplier() {
try {
assertEquals(1.0d, 1.1d, () -> "message");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "message");
assertMessageEndsWith(ex, "expected: <1.0> but was: <1.1>");
assertExpectedAndActualValues(ex, 1.0d, 1.1d);
}
}
@Test
void assertEqualsDoubleWithDelta() {
assertEquals(0.0d, 0.0d, 0.1d);
assertEquals(0.0d, 0.0d, 0.1d, "message");
assertEquals(0.0d, 0.0d, 0.1d, () -> "message");
assertEquals(0.42d, 0.24d, 0.19d);
assertEquals(0.02d, 0.011d, 0.01d);
assertEquals(Double.NaN, Double.NaN, 0.2d);
assertEquals(0.001d, 0.001d, 0.0d);
}
@Test
void assertEqualsDoubleWithIllegalDelta() {
AssertionFailedError e1 = assertThrows(AssertionFailedError.class, () -> assertEquals(1.1d, 1.11d, -0.5d));
assertMessageEndsWith(e1, "positive delta expected but was: <-0.5>");
AssertionFailedError e2 = assertThrows(AssertionFailedError.class, () -> assertEquals(.55d, .56d, -10.5d));
assertMessageEndsWith(e2, "positive delta expected but was: <-10.5>");
AssertionFailedError e3 = assertThrows(AssertionFailedError.class, () -> assertEquals(1.1d, 1.1d, Double.NaN));
assertMessageEndsWith(e3, "positive delta expected but was: <NaN>");
}
@Test
void assertEqualsDoubleWithDeltaWithUnequalValues() {
AssertionFailedError e1 = assertThrows(AssertionFailedError.class, () -> assertEquals(9.9d, 9.7d, 0.1d));
assertMessageEndsWith(e1, "expected: <9.9> but was: <9.7>");
assertExpectedAndActualValues(e1, 9.9d, 9.7d);
AssertionFailedError e2 = assertThrows(AssertionFailedError.class, () -> assertEquals(0.1d, 0.05d, 0.001d));
assertMessageEndsWith(e2, "expected: <0.1> but was: <0.05>");
assertExpectedAndActualValues(e2, 0.1d, 0.05d);
AssertionFailedError e3 = assertThrows(AssertionFailedError.class, () -> assertEquals(17.11d, 15.11d, 1.1d));
assertMessageEndsWith(e3, "expected: <17.11> but was: <15.11>");
assertExpectedAndActualValues(e3, 17.11d, 15.11d);
AssertionFailedError e4 = assertThrows(AssertionFailedError.class, () -> assertEquals(-7.2d, -5.9d, 1.1d));
assertMessageEndsWith(e4, "expected: <-7.2> but was: <-5.9>");
assertExpectedAndActualValues(e4, -7.2d, -5.9d);
AssertionFailedError e5 = assertThrows(AssertionFailedError.class, () -> assertEquals(+0.0d, -0.001d, .00001d));
assertMessageEndsWith(e5, "expected: <0.0> but was: <-0.001>");
assertExpectedAndActualValues(e5, +0.0d, -0.001d);
}
@Test
void assertEqualsDoubleWithDeltaWithUnequalValuesAndMessage() {
Executable assertion = () -> assertEquals(42.42d, 42.4d, 0.001d, "message");
AssertionFailedError e = assertThrows(AssertionFailedError.class, assertion);
assertMessageStartsWith(e, "message");
assertMessageEndsWith(e, "expected: <42.42> but was: <42.4>");
assertExpectedAndActualValues(e, 42.42d, 42.4d);
}
@Test
void assertEqualsDoubleWithDeltaWithUnequalValuesAndMessageSupplier() {
Executable assertion = () -> assertEquals(0.9d, 10.12d, 5.001d, () -> "message");
AssertionFailedError e = assertThrows(AssertionFailedError.class, assertion);
assertMessageStartsWith(e, "message");
assertMessageEndsWith(e, "expected: <0.9> but was: <10.12>");
assertExpectedAndActualValues(e, 0.9d, 10.12d);
}
@Test
void assertEqualsWithNullReferences() {
Object null1 = null;
Object null2 = null;
assertEquals(null1, null);
assertEquals(null, null2);
assertEquals(null1, null2);
}
@Test
void assertEqualsWithSameObject() {
Object foo = new Object();
assertEquals(foo, foo);
assertEquals(foo, foo, "message");
assertEquals(foo, foo, () -> "message");
}
@Test
void assertEqualsWithEquivalentStrings() {
assertEquals(new String("foo"), new String("foo"));
}
@Test
void assertEqualsWithNullVsObject() {
try {
assertEquals(null, "foo");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <null> but was: <foo>");
assertExpectedAndActualValues(ex, null, "foo");
}
}
@Test
void assertEqualsWithObjectVsNull() {
try {
assertEquals("foo", null);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageEquals(ex, "expected: <foo> but was: <null>");
assertExpectedAndActualValues(ex, "foo", null);
}
}
@Test
void assertEqualsWithObjectWithNullStringReturnedFromToStringVsNull() {
try {
assertEquals("null", null);
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "expected: java.lang.String@");
assertMessageEndsWith(ex, "<null> but was: <null>");
assertExpectedAndActualValues(ex, "null", null);
}
}
@Test
void assertEqualsWithNullVsObjectWithNullStringReturnedFromToString() {
try {
assertEquals(null, "null");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "expected: <null> but was: java.lang.String@");
assertMessageEndsWith(ex, "<null>");
assertExpectedAndActualValues(ex, null, "null");
}
}
@Test
void assertEqualsWithNullVsObjectAndMessageSupplier() {
try {
assertEquals(null, "foo", () -> "test");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "test");
assertMessageEndsWith(ex, "expected: <null> but was: <foo>");
assertExpectedAndActualValues(ex, null, "foo");
}
}
@Test
void assertEqualsWithObjectVsNullAndMessageSupplier() {
try {
assertEquals("foo", null, () -> "test");
expectAssertionFailedError();
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "test");
assertMessageEndsWith(ex, "expected: <foo> but was: <null>");
assertExpectedAndActualValues(ex, "foo", null);
}
}
@Test
void assertEqualsInvokesEqualsMethodForIdenticalObjects() {
Object obj = new EqualsThrowsException();
assertThrows(NumberFormatException.class, () -> assertEquals(obj, obj));
}
@Test
void assertEqualsWithUnequalObjectWhoseToStringImplementationThrowsAnException() {
try {
assertEquals(new ToStringThrowsException(), "foo");
}
catch (AssertionFailedError ex) {
assertMessageStartsWith(ex, "expected: <" + ToStringThrowsException.class.getName() + "@");
assertMessageEndsWith(ex, "but was: <foo>");
}
}
// -------------------------------------------------------------------------
@Nested
| AssertEqualsAssertionsTests |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/logging/logback/AbstractStructuredLoggingTests.java | {
"start": 1846,
"end": 4009
} | class ____ {
static final Instant EVENT_TIME = Instant.ofEpochSecond(1719910193L);
private static final JsonMapper JSON_MAPPER = new JsonMapper();
private ThrowableProxyConverter throwableProxyConverter;
private BasicMarkerFactory markerFactory;
@Mock
@SuppressWarnings("NullAway.Init")
StructuredLoggingJsonMembersCustomizer<?> customizer;
MockStructuredLoggingJsonMembersCustomizerBuilder<?> customizerBuilder = new MockStructuredLoggingJsonMembersCustomizerBuilder<>(
() -> this.customizer);
@BeforeEach
void setUp() {
this.markerFactory = new BasicMarkerFactory();
this.throwableProxyConverter = new ThrowableProxyConverter();
this.throwableProxyConverter.start();
}
@AfterEach
void tearDown() {
this.throwableProxyConverter.stop();
}
protected Marker getMarker(String name) {
return this.markerFactory.getDetachedMarker(name);
}
protected ThrowableProxyConverter getThrowableProxyConverter() {
return this.throwableProxyConverter;
}
protected Map<String, Object> map(Object... values) {
assertThat(values.length).isEven();
Map<String, Object> result = new HashMap<>();
for (int i = 0; i < values.length; i += 2) {
result.put(values[i].toString(), values[i + 1]);
}
return result;
}
protected List<KeyValuePair> keyValuePairs(Object... values) {
assertThat(values.length).isEven();
List<KeyValuePair> result = new ArrayList<>();
for (int i = 0; i < values.length; i += 2) {
result.add(new KeyValuePair(values[i].toString(), values[i + 1]));
}
return result;
}
protected static LoggingEvent createEvent() {
return createEvent(null);
}
protected static LoggingEvent createEvent(@Nullable Throwable thrown) {
LoggingEvent event = new LoggingEvent();
event.setInstant(EVENT_TIME);
event.setLevel(Level.INFO);
event.setThreadName("main");
event.setLoggerName("org.example.Test");
event.setMessage("message");
if (thrown != null) {
event.setThrowableProxy(new ThrowableProxy(thrown));
}
return event;
}
protected Map<String, Object> deserialize(String json) {
return JSON_MAPPER.readValue(json, new TypeReference<>() {
});
}
}
| AbstractStructuredLoggingTests |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/urls/Urls_assertHasNoHost_Test.java | {
"start": 1176,
"end": 2263
} | class ____ extends UrlsBaseTest {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
URL actual = null;
// WHEN
var assertionError = expectAssertionError(() -> urls.assertHasNoHost(info, actual));
// THEN
then(assertionError).hasMessage(actualIsNull());
}
@Test
void should_fail_if_host_present() throws MalformedURLException {
// GIVEN
URL actual = new URL("https://example.com");
// WHEN
var assertionError = expectAssertionError(() -> urls.assertHasNoHost(info, actual));
// THEN
then(assertionError).hasMessage(shouldHaveNoHost(actual).create());
}
@ParameterizedTest
@MethodSource("urls_with_no_host")
void should_pass_if_host_is_not_present(URL actual) {
// WHEN/THEN
urls.assertHasNoHost(info, actual);
}
private static Stream<URL> urls_with_no_host() throws MalformedURLException {
return Stream.of(new URL("file:///etc/lsb-release"),
new URL("file", "", "/etc/lsb-release"),
new URL("file", null, "/etc/lsb-release"));
}
}
| Urls_assertHasNoHost_Test |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/ExpressionListComparator.java | {
"start": 1151,
"end": 1790
} | class ____ implements Comparator<Exchange> {
private final List<Expression> expressions;
public ExpressionListComparator(List<Expression> expressions) {
this.expressions = expressions;
}
@Override
public int compare(Exchange e1, Exchange e2) {
for (Expression expression : expressions) {
Object o1 = expression.evaluate(e1, Object.class);
Object o2 = expression.evaluate(e2, Object.class);
int answer = ObjectHelper.compare(o1, o2);
if (answer != 0) {
return answer;
}
}
return 0;
}
}
| ExpressionListComparator |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/bugs/injection/Issue353InjectionMightNotHappenInCertainConfigurationTest.java | {
"start": 1337,
"end": 1540
} | class ____ {
Map<String, Integer> stringInteger_field = new HashMap<String, Integer>();
Map<String, String> stringString_that_matches_field = new HashMap<String, String>();
}
}
| FooService |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/doris/ast/DorisExprTableSource.java | {
"start": 335,
"end": 1560
} | class ____ extends SQLExprTableSource implements DorisObject {
protected List<SQLExpr> tablets;
protected SQLExpr repeatable;
public void addTablet(SQLExpr tablet) {
if (tablets == null) {
tablets = new ArrayList<>(2);
}
if (tablet != null) {
tablet.setParent(this);
tablets.add(tablet);
}
}
public List<SQLExpr> getTablets() {
if (tablets == null) {
tablets = new ArrayList<>(2);
}
return tablets;
}
public SQLExpr getRepeatable() {
return repeatable;
}
public void setRepeatable(SQLExpr repeatable) {
if (repeatable != null) {
repeatable.setParent(this);
}
this.repeatable = repeatable;
}
@Override
public void accept0(SQLASTVisitor v) {
if (v instanceof DorisASTVisitor) {
accept0((DorisASTVisitor) v);
} else {
super.accept0(v);
}
}
@Override
public void accept0(DorisASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, this.tablets);
acceptChild(visitor, this.repeatable);
}
}
}
| DorisExprTableSource |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/EmptyMetaStoreFactory.java | {
"start": 1075,
"end": 1869
} | class ____ implements TableMetaStoreFactory {
private final Path path;
public EmptyMetaStoreFactory(Path path) {
this.path = path;
}
@Override
public TableMetaStore createTableMetaStore() {
return new TableMetaStore() {
@Override
public Path getLocationPath() {
return path;
}
@Override
public Optional<Path> getPartition(LinkedHashMap<String, String> partitionSpec) {
return Optional.empty();
}
@Override
public void createOrAlterPartition(
LinkedHashMap<String, String> partitionSpec, Path partitionPath) {}
@Override
public void close() {}
};
}
}
| EmptyMetaStoreFactory |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/ContainerRuntimeStatusBuildItem.java | {
"start": 1014,
"end": 1380
} | interface ____ check the container runtime status
*/
protected ContainerRuntimeStatusBuildItem(IsContainerRuntimeWorking isContainerRuntimeWorking) {
this.isContainerRuntimeWorking = isContainerRuntimeWorking;
}
/**
* Checks if the container runtime is available.
* <p>
* This method uses the {@link IsContainerRuntimeWorking} | to |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/data/binary/BinarySegmentUtilsTest.java | {
"start": 1381,
"end": 8577
} | class ____ {
@Test
void testCopy() {
// test copy the content of the latter Seg
MemorySegment[] segments = new MemorySegment[2];
segments[0] = MemorySegmentFactory.wrap(new byte[] {0, 2, 5});
segments[1] = MemorySegmentFactory.wrap(new byte[] {6, 12, 15});
byte[] bytes = BinarySegmentUtils.copyToBytes(segments, 4, 2);
assertThat(bytes).isEqualTo(new byte[] {12, 15});
}
@Test
void testEquals() {
// test copy the content of the latter Seg
MemorySegment[] segments1 = new MemorySegment[3];
segments1[0] = MemorySegmentFactory.wrap(new byte[] {0, 2, 5});
segments1[1] = MemorySegmentFactory.wrap(new byte[] {6, 12, 15});
segments1[2] = MemorySegmentFactory.wrap(new byte[] {1, 1, 1});
MemorySegment[] segments2 = new MemorySegment[2];
segments2[0] = MemorySegmentFactory.wrap(new byte[] {6, 0, 2, 5});
segments2[1] = MemorySegmentFactory.wrap(new byte[] {6, 12, 15, 18});
assertThat(BinarySegmentUtils.equalsMultiSegments(segments1, 0, segments2, 0, 0)).isTrue();
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 1, 3)).isTrue();
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 1, 6)).isTrue();
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 1, 7)).isFalse();
}
@Test
void testBoundaryByteArrayEquals() {
byte[] bytes1 = new byte[5];
bytes1[3] = 81;
byte[] bytes2 = new byte[100];
bytes2[3] = 81;
bytes2[4] = 81;
assertThat(BinaryRowDataUtil.byteArrayEquals(bytes1, bytes2, 4)).isTrue();
assertThat(BinaryRowDataUtil.byteArrayEquals(bytes1, bytes2, 5)).isFalse();
assertThat(BinaryRowDataUtil.byteArrayEquals(bytes1, bytes2, 0)).isTrue();
}
@Test
void testBoundaryEquals() {
BinaryRowData row24 = DataFormatTestUtil.get24BytesBinaryRow();
BinaryRowData row160 = DataFormatTestUtil.get160BytesBinaryRow();
BinaryRowData varRow160 = DataFormatTestUtil.getMultiSeg160BytesBinaryRow(row160);
BinaryRowData varRow160InOne = DataFormatTestUtil.getMultiSeg160BytesInOneSegRow(row160);
assertThat(varRow160InOne).isEqualTo(row160);
assertThat(varRow160InOne).isEqualTo(varRow160);
assertThat(varRow160).isEqualTo(row160);
assertThat(varRow160).isEqualTo(varRow160InOne);
assertThat(row160).isNotEqualTo(row24);
assertThat(varRow160).isNotEqualTo(row24);
assertThat(varRow160InOne).isNotEqualTo(row24);
assertThat(BinarySegmentUtils.equals(row24.getSegments(), 0, row160.getSegments(), 0, 0))
.isTrue();
assertThat(BinarySegmentUtils.equals(row24.getSegments(), 0, varRow160.getSegments(), 0, 0))
.isTrue();
// test var segs
MemorySegment[] segments1 = new MemorySegment[2];
segments1[0] = MemorySegmentFactory.wrap(new byte[32]);
segments1[1] = MemorySegmentFactory.wrap(new byte[32]);
MemorySegment[] segments2 = new MemorySegment[3];
segments2[0] = MemorySegmentFactory.wrap(new byte[16]);
segments2[1] = MemorySegmentFactory.wrap(new byte[16]);
segments2[2] = MemorySegmentFactory.wrap(new byte[16]);
segments1[0].put(9, (byte) 1);
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 14, 14)).isFalse();
segments2[1].put(7, (byte) 1);
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 14, 14)).isTrue();
assertThat(BinarySegmentUtils.equals(segments1, 2, segments2, 16, 14)).isTrue();
assertThat(BinarySegmentUtils.equals(segments1, 2, segments2, 16, 16)).isTrue();
segments2[2].put(7, (byte) 1);
assertThat(BinarySegmentUtils.equals(segments1, 2, segments2, 32, 14)).isTrue();
}
@Test
void testBoundaryCopy() {
MemorySegment[] segments1 = new MemorySegment[2];
segments1[0] = MemorySegmentFactory.wrap(new byte[32]);
segments1[1] = MemorySegmentFactory.wrap(new byte[32]);
segments1[0].put(15, (byte) 5);
segments1[1].put(15, (byte) 6);
{
byte[] bytes = new byte[64];
MemorySegment[] segments2 = new MemorySegment[] {MemorySegmentFactory.wrap(bytes)};
BinarySegmentUtils.copyToBytes(segments1, 0, bytes, 0, 64);
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 0, 64)).isTrue();
}
{
byte[] bytes = new byte[64];
MemorySegment[] segments2 = new MemorySegment[] {MemorySegmentFactory.wrap(bytes)};
BinarySegmentUtils.copyToBytes(segments1, 32, bytes, 0, 14);
assertThat(BinarySegmentUtils.equals(segments1, 32, segments2, 0, 14)).isTrue();
}
{
byte[] bytes = new byte[64];
MemorySegment[] segments2 = new MemorySegment[] {MemorySegmentFactory.wrap(bytes)};
BinarySegmentUtils.copyToBytes(segments1, 34, bytes, 0, 14);
assertThat(BinarySegmentUtils.equals(segments1, 34, segments2, 0, 14)).isTrue();
}
}
@Test
void testCopyToUnsafe() {
MemorySegment[] segments1 = new MemorySegment[2];
segments1[0] = MemorySegmentFactory.wrap(new byte[32]);
segments1[1] = MemorySegmentFactory.wrap(new byte[32]);
segments1[0].put(15, (byte) 5);
segments1[1].put(15, (byte) 6);
{
byte[] bytes = new byte[64];
MemorySegment[] segments2 = new MemorySegment[] {MemorySegmentFactory.wrap(bytes)};
BinarySegmentUtils.copyToUnsafe(segments1, 0, bytes, BYTE_ARRAY_BASE_OFFSET, 64);
assertThat(BinarySegmentUtils.equals(segments1, 0, segments2, 0, 64)).isTrue();
}
{
byte[] bytes = new byte[64];
MemorySegment[] segments2 = new MemorySegment[] {MemorySegmentFactory.wrap(bytes)};
BinarySegmentUtils.copyToUnsafe(segments1, 32, bytes, BYTE_ARRAY_BASE_OFFSET, 14);
assertThat(BinarySegmentUtils.equals(segments1, 32, segments2, 0, 14)).isTrue();
}
{
byte[] bytes = new byte[64];
MemorySegment[] segments2 = new MemorySegment[] {MemorySegmentFactory.wrap(bytes)};
BinarySegmentUtils.copyToUnsafe(segments1, 34, bytes, BYTE_ARRAY_BASE_OFFSET, 14);
assertThat(BinarySegmentUtils.equals(segments1, 34, segments2, 0, 14)).isTrue();
}
}
@Test
void testFind() {
MemorySegment[] segments1 = new MemorySegment[2];
segments1[0] = MemorySegmentFactory.wrap(new byte[32]);
segments1[1] = MemorySegmentFactory.wrap(new byte[32]);
MemorySegment[] segments2 = new MemorySegment[3];
segments2[0] = MemorySegmentFactory.wrap(new byte[16]);
segments2[1] = MemorySegmentFactory.wrap(new byte[16]);
segments2[2] = MemorySegmentFactory.wrap(new byte[16]);
assertThat(BinarySegmentUtils.find(segments1, 34, 0, segments2, 0, 0)).isEqualTo(34);
assertThat(BinarySegmentUtils.find(segments1, 34, 0, segments2, 0, 15)).isEqualTo(-1);
}
}
| BinarySegmentUtilsTest |
java | apache__camel | core/camel-cloud/src/main/java/org/apache/camel/impl/cloud/DefaultServiceDiscovery.java | {
"start": 1197,
"end": 1865
} | class ____
extends ServiceSupport
implements ServiceDiscovery, CamelContextAware {
private CamelContext camelContext;
@Override
public List<ServiceDefinition> getServices(String name) {
return Collections.emptyList();
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
protected void doStart() throws Exception {
// nop
}
@Override
protected void doStop() throws Exception {
// nop
}
}
| DefaultServiceDiscovery |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/main/java/io/quarkus/rest/client/reactive/deployment/MicroProfileRestClientEnricher.java | {
"start": 63257,
"end": 63426
} | class ____ meant to parse the values in {@link org.eclipse.microprofile.rest.client.annotation.ClientHeaderParam}
* into a list of supported types
*/
static | is |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RedundantControlFlowTest.java | {
"start": 1534,
"end": 2000
} | class ____ {
void test(Iterable<String> xs) {
for (String x : xs) {
if (x.equals("foo")) {
// BUG: Diagnostic contains:
continue;
}
}
}
}
""")
.doTest();
}
@Test
public void onlyStatementInNestedIf() {
helper
.addSourceLines(
"Test.java",
"""
| Test |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/gen/src/main/java/org/elasticsearch/compute/gen/AggregatorFunctionSupplierImplementer.java | {
"start": 1816,
"end": 4096
} | class ____ {
private final TypeElement declarationType;
private final AggregatorImplementer aggregatorImplementer;
private final GroupingAggregatorImplementer groupingAggregatorImplementer;
private final boolean hasWarnings;
private final List<Parameter> createParameters;
private final ClassName implementation;
public AggregatorFunctionSupplierImplementer(
Elements elements,
TypeElement declarationType,
AggregatorImplementer aggregatorImplementer,
GroupingAggregatorImplementer groupingAggregatorImplementer,
boolean hasWarnings
) {
this.declarationType = declarationType;
this.aggregatorImplementer = aggregatorImplementer;
this.groupingAggregatorImplementer = groupingAggregatorImplementer;
this.hasWarnings = hasWarnings;
Set<Parameter> createParameters = new LinkedHashSet<>();
if (aggregatorImplementer != null) {
createParameters.addAll(aggregatorImplementer.createParameters());
}
if (groupingAggregatorImplementer != null) {
createParameters.addAll(groupingAggregatorImplementer.createParameters());
}
this.createParameters = new ArrayList<>(createParameters);
this.implementation = ClassName.get(
elements.getPackageOf(declarationType).toString(),
(declarationType.getSimpleName() + "AggregatorFunctionSupplier").replace("AggregatorAggregator", "Aggregator")
);
}
public JavaFile sourceFile() {
JavaFile.Builder builder = JavaFile.builder(implementation.packageName(), type());
builder.addFileComment("""
Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
or more contributor license agreements. Licensed under the Elastic License
2.0; you may not use this file except in compliance with the Elastic License
2.0.""");
return builder.build();
}
private TypeSpec type() {
TypeSpec.Builder builder = TypeSpec.classBuilder(implementation);
builder.addJavadoc("{@link $T} implementation for {@link $T}.\n", AGGREGATOR_FUNCTION_SUPPLIER, declarationType);
builder.addJavadoc("This | AggregatorFunctionSupplierImplementer |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4544ActiveComponentCollectionThreadSafeTest.java | {
"start": 1131,
"end": 1997
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that concurrent access to active component collections is thread-safe.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-4544");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/thread.properties");
assertEquals(0, Integer.parseInt(props.getProperty("exceptions")));
assertEquals(2, Integer.parseInt(props.getProperty("components")));
}
}
| MavenITmng4544ActiveComponentCollectionThreadSafeTest |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxGroupJoin.java | {
"start": 14003,
"end": 15803
} | class ____
implements InnerConsumer<Object>, Disposable {
final JoinSupport<?> parent;
final boolean isLeft;
@SuppressWarnings("NotNullFieldNotInitialized") // initialized in onSubscribe
volatile Subscription subscription;
// https://github.com/uber/NullAway/issues/1157
@SuppressWarnings({"rawtypes", "DataFlowIssue"})
final static AtomicReferenceFieldUpdater<LeftRightSubscriber, @Nullable Subscription>
SUBSCRIPTION =
AtomicReferenceFieldUpdater.newUpdater(LeftRightSubscriber.class,
Subscription.class,
"subscription");
LeftRightSubscriber(JoinSupport<?> parent, boolean isLeft) {
this.parent = parent;
this.isLeft = isLeft;
}
@Override
public void dispose() {
Operators.terminate(SUBSCRIPTION, this);
}
@Override
public Context currentContext() {
CoreSubscriber<?> actual = parent.actual();
assert actual != null : "actual subscriber can not be null in inner consumer";
return actual.currentContext();
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.PARENT) return subscription;
if (key == Attr.ACTUAL ) return parent;
if (key == Attr.CANCELLED) return isDisposed();
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
@Override
public boolean isDisposed() {
return Operators.cancelledSubscription() == subscription;
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.setOnce(SUBSCRIPTION, this, s)) {
s.request(Long.MAX_VALUE);
}
}
@Override
public void onNext(Object t) {
parent.innerValue(isLeft, t);
}
@Override
public void onError(Throwable t) {
parent.innerError(t);
}
@Override
public void onComplete() {
parent.innerComplete(this);
}
}
static final | LeftRightSubscriber |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/metamodel/Company.java | {
"start": 321,
"end": 833
} | class ____ implements Serializable {
@Id
private long id = System.nanoTime();
@Column(nullable = false)
private String name;
@Embedded
private Address address = new Address();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
| Company |
java | resilience4j__resilience4j | resilience4j-timelimiter/src/test/java/io/github/resilience4j/timelimiter/internal/TimeLimiterImplTest.java | {
"start": 462,
"end": 1157
} | class ____ {
private static final String NAME = "name";
private TimeLimiterConfig timeLimiterConfig;
private TimeLimiter timeLimiter;
@Before
public void init() {
timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ZERO)
.build();
TimeLimiterImpl testTimeout = new TimeLimiterImpl("name", timeLimiterConfig);
timeLimiter = spy(testTimeout);
}
@Test
public void configPropagation() {
then(timeLimiter.getTimeLimiterConfig()).isEqualTo(timeLimiterConfig);
}
@Test
public void namePropagation() {
then(timeLimiter.getName()).isEqualTo(NAME);
}
}
| TimeLimiterImplTest |
java | google__guava | android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java | {
"start": 11774,
"end": 12403
} | class ____ method
@Override
public boolean remove(@Nullable Object o) {
Monitor monitor = this.monitor;
monitor.enter();
try {
return q.remove(o);
} finally {
monitor.leave();
}
}
/**
* Returns {@code true} if this queue contains the specified element. More formally, returns
* {@code true} if and only if this queue contains at least one element {@code e} such that {@code
* o.equals(e)}.
*
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
*/
@CanIgnoreReturnValue // pushed down from | to |
java | quarkusio__quarkus | independent-projects/qute/core/src/test/java/io/quarkus/qute/ExpressionTest.java | {
"start": 463,
"end": 8072
} | class ____ {
@Test
public void testExpressions() throws InterruptedException, ExecutionException {
verify("data:name.value", "data", null, name("name", "data:name"), name("value", "value"));
verify("data:getName('value')", "data", null, virtualMethod("getName", ExpressionImpl.from("'value'")));
// ignore adjacent separators
verify("name..value", null, null, name("name"), name("value"));
verify("0", null, CompletedStage.of(Integer.valueOf(0)), name("0", "|java.lang.Integer|"));
verify("false", null, CompletedStage.of(Boolean.FALSE), name("false", "|java.lang.Boolean|"));
verify("null", null, CompletedStage.of(null), name("null"));
verify("name.orElse('John')", null, null, name("name"), virtualMethod("orElse", ExpressionImpl.from("'John'")));
verify("name or 'John'", null, null, name("name"), virtualMethod("or", ExpressionImpl.from("'John'")));
verify("item.name or 'John'", null, null, name("item"), name("name"),
virtualMethod("or", ExpressionImpl.from("'John'")));
verify("name.func('John', 1)", null, null, name("name"),
virtualMethod("func", ExpressionImpl.literalFrom(-1, "'John'"), ExpressionImpl.literalFrom(-1, "1")));
verify("name ?: 'John Bug'", null, null, name("name"),
virtualMethod("?:", ExpressionImpl.literalFrom(-1, "'John Bug'")));
verify("name ? 'John' : 'Bug'", null, null, name("name"), virtualMethod("?", ExpressionImpl.literalFrom(-1, "'John'")),
virtualMethod(":", ExpressionImpl.literalFrom(-1, "'Bug'")));
verify("name.func(data:foo)", null, null, name("name"), virtualMethod("func", ExpressionImpl.from("data:foo")));
verify("this.getList(5).size", null, null, name("this"), virtualMethod("getList", ExpressionImpl.literalFrom(-1, "5")),
name("size"));
verify("foo.call(bar.baz)", null, null, name("foo"), virtualMethod("call", ExpressionImpl.from("bar.baz")));
verify("foo.call(bar.call(1))", null, null, name("foo"), virtualMethod("call", ExpressionImpl.from("bar.call(1)")));
verify("foo.call(bar.alpha(1),bar.alpha('ping'))", null, null, name("foo"),
virtualMethod("call", ExpressionImpl.from("bar.alpha(1)"), ExpressionImpl.from("bar.alpha('ping')")));
verify("'foo:bar'", null, CompletedStage.of("foo:bar"), name("'foo:bar'", "|java.lang.String|"));
// bracket notation
// ignore adjacent separators
verify("name[['value']", null, null, name("name"), name("value"));
verify("name[false]]", null, null, name("name"), name("false"));
verify("name[1l]", null, null, name("name"), name("1"));
assertThatExceptionOfType(TemplateException.class)
.isThrownBy(() -> verify("name['value'][1][null]", null, null))
.withMessageContaining("Null value");
assertThatExceptionOfType(TemplateException.class)
.isThrownBy(() -> verify("name[value]", null, null))
.withMessageContaining("Non-literal value");
verify("name[1l]['foo']", null, null, name("name"), name("1"), name("foo"));
verify("foo[\"name.dot\"].value", null, null, name("foo"), name("name.dot"), name("value"));
verify("list[100] or 'NOT_FOUND'", null, null, name("list"), name("100"),
virtualMethod("or", ExpressionImpl.literalFrom(-1, "'NOT_FOUND'")));
verify("hero.name.isBlank ? hulk.name : hero.name", null, null, name("hero"), name("name"), name("isBlank"),
virtualMethod("?", ExpressionImpl.from("hulk.name")),
virtualMethod(":", ExpressionImpl.from("hero.name")));
verify("hero.name.isBlank ? 'Hulk' : hero.name", null, null, name("hero"), name("name"), name("isBlank"),
virtualMethod("?", ExpressionImpl.literalFrom(-1, "'Hulk'")),
virtualMethod(":", ExpressionImpl.from("hero.name")));
verify("hero.name??", null, null, name("hero"), name("name"),
virtualMethod("or", ExpressionImpl.literalFrom(-1, "null")));
}
@Test
public void testInfixNotationRedundantSpace() throws InterruptedException, ExecutionException {
verify("name or 'John'", null, null, name("name"), virtualMethod("or", ExpressionImpl.from("'John'")));
verify("name or 'John'", null, null, name("name"), virtualMethod("or", ExpressionImpl.from("'John'")));
verify("name or 'John'", null, null, name("name"), virtualMethod("or", ExpressionImpl.from("'John'")));
verify("name or 'John' or 1", null, null, name("name"), virtualMethod("or", ExpressionImpl.from("'John'")),
virtualMethod("or", ExpressionImpl.literalFrom(-1, "1")));
verify("name or 'John' or 1", null, null, name("name"), virtualMethod("or", ExpressionImpl.from("'John'")),
virtualMethod("or", ExpressionImpl.literalFrom(-1, "1")));
}
@Test
public void testNestedVirtualMethods() {
assertNestedVirtualMethod(ExpressionImpl.from("movie.findServices(movie.name,movie.toNumber(movie.getName))"));
assertNestedVirtualMethod(ExpressionImpl.from("movie.findServices(movie.name, movie.toNumber(movie.getName) )"));
}
private void assertNestedVirtualMethod(Expression exp) {
assertNull(exp.getNamespace());
List<Expression.Part> parts = exp.getParts();
assertEquals(2, parts.size());
assertEquals("movie", parts.get(0).getName());
Expression.VirtualMethodPart findServicesPart = parts.get(1).asVirtualMethod();
List<Expression> findServicesParams = findServicesPart.getParameters();
assertEquals(2, findServicesParams.size());
Expression findServicesParam2 = findServicesParams.get(1);
parts = findServicesParam2.getParts();
assertEquals(2, parts.size());
Expression.VirtualMethodPart toNumberPart = parts.get(1).asVirtualMethod();
List<Expression> toNumberParams = toNumberPart.getParameters();
assertEquals(1, toNumberParams.size());
Expression movieGetName = toNumberParams.get(0);
parts = movieGetName.getParts();
assertEquals(2, parts.size());
assertEquals("movie", parts.get(0).getName());
assertEquals("getName", parts.get(1).getName());
}
@Test
public void testTypeInfo() {
List<String> parts = Expressions.splitTypeInfoParts("|org.acme.Foo|.call(|java.util.List<org.acme.Label>|,bar)");
assertEquals(2, parts.size());
assertEquals("|org.acme.Foo|", parts.get(0));
assertEquals("call(|java.util.List<org.acme.Label>|,bar)", parts.get(1));
}
private void verify(String value, String namespace, CompletedStage<Object> literalValue, Part... parts) {
ExpressionImpl exp = ExpressionImpl.from(value);
assertEquals(namespace, exp.getNamespace());
assertEquals(Arrays.asList(parts), exp.getParts());
if (literalValue == null) {
assertNull(exp.getLiteral());
} else {
assertNotNull(exp.getLiteralValue());
assertEquals(literalValue.get(), exp.getLiteral());
}
}
private Part name(String name) {
return name(name, null);
}
private Part name(String name, String typeInfo) {
return new ExpressionImpl.PartImpl(name, typeInfo);
}
private Part virtualMethod(String name, Expression... params) {
return new ExpressionImpl.VirtualMethodPartImpl(name, Arrays.asList(params), null);
}
}
| ExpressionTest |
java | spring-projects__spring-boot | core/spring-boot-test/src/main/java/org/springframework/boot/test/json/Jackson2Tester.java | {
"start": 3160,
"end": 6690
} | class ____ to load resources
* @param type the type under test
* @param objectMapper the Jackson object mapper
* @param view the JSON view
*/
public Jackson2Tester(Class<?> resourceLoadClass, ResolvableType type, ObjectMapper objectMapper,
@Nullable Class<?> view) {
super(resourceLoadClass, type);
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this.objectMapper = objectMapper;
this.view = view;
}
@Override
protected JsonContent<T> getJsonContent(String json) {
Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonProvider(this.objectMapper))
.mappingProvider(new JacksonMappingProvider(this.objectMapper))
.build();
Class<?> resourceLoadClass = getResourceLoadClass();
Assert.state(resourceLoadClass != null, "'resourceLoadClass' must not be null");
return new JsonContent<>(resourceLoadClass, getType(), json, configuration);
}
@Override
protected T readObject(InputStream inputStream, ResolvableType type) throws IOException {
return getObjectReader(type).readValue(inputStream);
}
@Override
protected T readObject(Reader reader, ResolvableType type) throws IOException {
return getObjectReader(type).readValue(reader);
}
private ObjectReader getObjectReader(ResolvableType type) {
ObjectReader objectReader = this.objectMapper.readerFor(getType(type));
if (this.view != null) {
return objectReader.withView(this.view);
}
return objectReader;
}
@Override
protected String writeObject(T value, ResolvableType type) throws IOException {
return getObjectWriter(type).writeValueAsString(value);
}
private ObjectWriter getObjectWriter(ResolvableType type) {
ObjectWriter objectWriter = this.objectMapper.writerFor(getType(type));
if (this.view != null) {
return objectWriter.withView(this.view);
}
return objectWriter;
}
private JavaType getType(ResolvableType type) {
return this.objectMapper.constructType(type.getType());
}
/**
* Utility method to initialize {@link Jackson2Tester} fields. See
* {@link Jackson2Tester class-level documentation} for example usage.
* @param testInstance the test instance
* @param objectMapper the JSON mapper
* @see #initFields(Object, ObjectMapper)
*/
public static void initFields(Object testInstance, ObjectMapper objectMapper) {
new Jackson2FieldInitializer().initFields(testInstance, objectMapper);
}
/**
* Utility method to initialize {@link Jackson2Tester} fields. See
* {@link Jackson2Tester class-level documentation} for example usage.
* @param testInstance the test instance
* @param objectMapperFactory a factory to create the object mapper
* @see #initFields(Object, ObjectMapper)
*/
public static void initFields(Object testInstance, ObjectFactory<ObjectMapper> objectMapperFactory) {
new Jackson2FieldInitializer().initFields(testInstance, objectMapperFactory);
}
/**
* Returns a new instance of {@link Jackson2Tester} with the view that should be used
* for json serialization/deserialization.
* @param view the view class
* @return the new instance
*/
public Jackson2Tester<T> forView(Class<?> view) {
Class<?> resourceLoadClass = getResourceLoadClass();
ResolvableType type = getType();
Assert.state(resourceLoadClass != null, "'resourceLoadClass' must not be null");
Assert.state(type != null, "'type' must not be null");
return new Jackson2Tester<>(resourceLoadClass, type, this.objectMapper, view);
}
/**
* {@link FieldInitializer} for Jackson.
*/
private static | used |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/tree/SqmJoinType.java | {
"start": 347,
"end": 2231
} | enum ____ {
/**
* Represents an inner join.
*/
INNER,
/**
* Represents a left outer join.
*/
LEFT,
/**
* Represents a right outer join.
*/
RIGHT,
/**
* Represents a cross join (aka a cartesian product).
*/
CROSS,
/**
* Represents a full join.
*/
FULL;
@Override
public String toString() {
return getText();
}
public String getText() {
return switch (this) {
case RIGHT -> "right outer";
case LEFT -> "left outer";
case INNER -> "inner";
case FULL -> "full";
case CROSS -> "cross";
};
}
public SqlAstJoinType getCorrespondingSqlJoinType() {
return switch (this) {
case RIGHT -> SqlAstJoinType.RIGHT;
case LEFT -> SqlAstJoinType.LEFT;
case INNER -> SqlAstJoinType.INNER;
case FULL -> SqlAstJoinType.FULL;
case CROSS -> SqlAstJoinType.CROSS;
};
}
public jakarta.persistence.criteria.JoinType getCorrespondingJpaJoinType() {
return switch (this) {
case RIGHT -> jakarta.persistence.criteria.JoinType.RIGHT;
case LEFT -> jakarta.persistence.criteria.JoinType.LEFT;
case INNER -> jakarta.persistence.criteria.JoinType.INNER;
default -> throw new IllegalArgumentException( "Join type has no JPA join type mapping: " + this );
};
}
public JoinType getCorrespondingJoinType() {
return switch (this) {
case RIGHT -> JoinType.RIGHT;
case LEFT -> JoinType.LEFT;
case INNER -> JoinType.INNER;
case FULL -> JoinType.FULL;
case CROSS -> JoinType.CROSS;
};
}
public static SqmJoinType from(JoinType joinType) {
return switch ( joinType ) {
case INNER -> INNER;
case LEFT -> LEFT;
case RIGHT -> RIGHT;
case CROSS -> CROSS;
case FULL -> FULL;
};
}
public static SqmJoinType from(jakarta.persistence.criteria.JoinType jpaJoinType) {
return switch ( jpaJoinType ) {
case INNER -> INNER;
case LEFT -> LEFT;
case RIGHT -> RIGHT;
};
}
}
| SqmJoinType |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/jdk8/OptionalTest.java | {
"start": 303,
"end": 2773
} | class ____ extends TestCase {
public void test_optional() throws Exception {
Optional<Integer> val = Optional.of(3);
String text = JSON.toJSONString(val);
Assert.assertEquals("3", text);
Optional<Integer> val2 = JSON.parseObject(text, new TypeReference<Optional<Integer>>() {});
Assert.assertEquals(val.get(), val2.get());
}
public void test_optionalInt_present() throws Exception {
String text = JSON.toJSONString(OptionalInt.empty());
Assert.assertEquals("null", text);
}
public void test_optionalInt() throws Exception {
OptionalInt val = OptionalInt.of(3);
String text = JSON.toJSONString(val);
Assert.assertEquals("3", text);
OptionalInt val2 = JSON.parseObject(text, OptionalInt.class);
Assert.assertEquals(val.getAsInt(), val2.getAsInt());
}
public void test_optionalLong_present() throws Exception {
String text = JSON.toJSONString(OptionalLong.empty());
Assert.assertEquals("null", text);
}
public void test_optionalLong() throws Exception {
OptionalLong val = OptionalLong.of(3);
String text = JSON.toJSONString(val);
Assert.assertEquals("3", text);
OptionalLong val2 = JSON.parseObject(text, OptionalLong.class);
Assert.assertEquals(val.getAsLong(), val2.getAsLong());
}
public void test_optionalDouble_present() throws Exception {
String text = JSON.toJSONString(OptionalDouble.empty());
Assert.assertEquals("null", text);
}
public void test_optionalDouble() throws Exception {
OptionalDouble val = OptionalDouble.of(3.1D);
String text = JSON.toJSONString(val);
Assert.assertEquals("3.1", text);
OptionalDouble val2 = JSON.parseObject(text, OptionalDouble.class);
Assert.assertEquals(Double.toString(val.getAsDouble()), Double.toString(val2.getAsDouble()));
}
public void test_optional_parseNull() throws Exception {
assertSame(Optional.empty()
, JSON.parseObject("null", Optional.class));
}
public void test_optional_parseNull_2() throws Exception {
assertSame(Optional.empty()
, JSON.parseObject("null", new TypeReference<Optional<Integer>>() {}));
}
}
| OptionalTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/replication/ReplicationResponse.java | {
"start": 2204,
"end": 8951
} | class ____ implements Writeable, ToXContentObject {
// cache the most commonly used instances where all shard operations succeeded to save allocations on the transport layer
private static final ShardInfo[] COMMON_INSTANCES = IntStream.range(0, 10)
.mapToObj(i -> new ShardInfo(i, i, NO_FAILURES))
.toArray(ShardInfo[]::new);
public static final ShardInfo EMPTY = COMMON_INSTANCES[0];
private static final String TOTAL = "total";
private static final String SUCCESSFUL = "successful";
private static final String FAILED = "failed";
private static final String FAILURES = "failures";
private final int total;
private final int successful;
private final Failure[] failures;
public static ShardInfo readFrom(StreamInput in) throws IOException {
int total = in.readVInt();
int successful = in.readVInt();
int size = in.readVInt();
final Failure[] failures;
if (size > 0) {
failures = new Failure[size];
for (int i = 0; i < size; i++) {
failures[i] = new Failure(in);
}
} else {
failures = NO_FAILURES;
}
return ShardInfo.of(total, successful, failures);
}
public static ShardInfo allSuccessful(int total) {
if (total < COMMON_INSTANCES.length) {
return COMMON_INSTANCES[total];
}
return new ShardInfo(total, total, NO_FAILURES);
}
public static ShardInfo of(int total, int successful) {
if (total == successful) {
return allSuccessful(total);
}
return new ShardInfo(total, successful, ReplicationResponse.NO_FAILURES);
}
public static ShardInfo of(int total, int successful, Failure[] failures) {
if (failures.length == 0) {
return of(total, successful);
}
return new ShardInfo(total, successful, failures);
}
private ShardInfo(int total, int successful, Failure[] failures) {
assert total >= 0 && successful >= 0;
this.total = total;
this.successful = successful;
this.failures = failures;
}
/**
* @return the total number of shards the write should go to (replicas and primaries). This includes relocating shards, so this
* number can be higher than the number of shards.
*/
public int getTotal() {
return total;
}
/**
* @return the total number of shards the write succeeded on (replicas and primaries). This includes relocating shards, so this
* number can be higher than the number of shards.
*/
public int getSuccessful() {
return successful;
}
/**
* @return The total number of replication failures.
*/
public int getFailed() {
return failures.length;
}
/**
* @return The replication failures that have been captured in the case writes have failed on replica shards.
*/
public Failure[] getFailures() {
return failures;
}
public RestStatus status() {
RestStatus status = RestStatus.OK;
for (Failure failure : failures) {
if (failure.primary() && failure.status().getStatus() > status.getStatus()) {
status = failure.status();
}
}
return status;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(total);
out.writeVInt(successful);
out.writeArray(failures);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(TOTAL, total);
builder.field(SUCCESSFUL, successful);
builder.field(FAILED, getFailed());
if (failures.length > 0) {
builder.startArray(FAILURES);
for (Failure failure : failures) {
failure.toXContent(builder, params);
}
builder.endArray();
}
builder.endObject();
return builder;
}
public static ShardInfo fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser);
int total = 0, successful = 0;
List<Failure> failuresList = null;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (TOTAL.equals(currentFieldName)) {
total = parser.intValue();
} else if (SUCCESSFUL.equals(currentFieldName)) {
successful = parser.intValue();
} else {
parser.skipChildren();
}
} else if (token == XContentParser.Token.START_ARRAY) {
if (FAILURES.equals(currentFieldName)) {
failuresList = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
failuresList.add(Failure.fromXContent(parser));
}
} else {
parser.skipChildren(); // skip potential inner arrays for forward compatibility
}
} else if (token == XContentParser.Token.START_OBJECT) {
parser.skipChildren(); // skip potential inner arrays for forward compatibility
}
}
Failure[] failures = ReplicationResponse.NO_FAILURES;
if (failuresList != null) {
failures = failuresList.toArray(ReplicationResponse.NO_FAILURES);
}
return new ShardInfo(total, successful, failures);
}
@Override
public String toString() {
return "ShardInfo{" + "total=" + total + ", successful=" + successful + ", failures=" + Arrays.toString(failures) + '}';
}
public static | ShardInfo |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_457.java | {
"start": 386,
"end": 714
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
ParserConfig.global.putDeserializer(MyEnum.class, new MyEnumDeser());
VO entity = JSON.parseObject("{\"myEnum\":\"AA\"}", VO.class);
Assert.assertEquals(MyEnum.A, entity.myEnum);
}
public static | Bug_for_issue_457 |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindyComplexCsvUnmarshallUnwrapSingleInstanceTest.java | {
"start": 2383,
"end": 2636
} | class ____ extends RouteBuilder {
@Override
public void configure() {
from("direct:start")
.unmarshal().bindy(BindyType.Csv, TYPE, false)
.to("mock:result");
}
}
}
| ContextConfig |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/transport/DockerEngineExceptionTests.java | {
"start": 1110,
"end": 5512
} | class ____ {
private static final String HOST = "docker://localhost/";
private static final URI URI;
static {
try {
URI = new URI("example");
}
catch (URISyntaxException ex) {
throw new IllegalStateException(ex);
}
}
private static final Errors NO_ERRORS = new Errors(Collections.emptyList());
private static final Errors ERRORS = new Errors(Collections.singletonList(new Errors.Error("code", "message")));
private static final Message NO_MESSAGE = new Message(null);
private static final Message MESSAGE = new Message("response message");
@Test
@SuppressWarnings("NullAway") // Test null check
void createWhenHostIsNullThrowsException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DockerEngineException(null, null, 404, null, NO_ERRORS, NO_MESSAGE, null))
.withMessage("'host' must not be null");
}
@Test
@SuppressWarnings("NullAway") // Test null check
void createWhenUriIsNullThrowsException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DockerEngineException(HOST, null, 404, null, NO_ERRORS, NO_MESSAGE, null))
.withMessage("'uri' must not be null");
}
@Test
void create() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 404, "missing", ERRORS, MESSAGE, null);
assertThat(exception.getMessage()).isEqualTo(
"Docker API call to 'docker://localhost/example' failed with status code 404 \"missing\" and message \"response message\" [code: message]");
assertThat(exception.getStatusCode()).isEqualTo(404);
assertThat(exception.getReasonPhrase()).isEqualTo("missing");
assertThat(exception.getErrors()).isSameAs(ERRORS);
assertThat(exception.getResponseMessage()).isSameAs(MESSAGE);
}
@Test
void createWhenReasonPhraseIsNull() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 404, null, ERRORS, MESSAGE, null);
assertThat(exception.getMessage()).isEqualTo(
"Docker API call to 'docker://localhost/example' failed with status code 404 and message \"response message\" [code: message]");
assertThat(exception.getStatusCode()).isEqualTo(404);
assertThat(exception.getReasonPhrase()).isNull();
assertThat(exception.getErrors()).isSameAs(ERRORS);
assertThat(exception.getResponseMessage()).isSameAs(MESSAGE);
}
@Test
void createWhenErrorsIsNull() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 404, "missing", null, MESSAGE, null);
assertThat(exception.getMessage()).isEqualTo(
"Docker API call to 'docker://localhost/example' failed with status code 404 \"missing\" and message \"response message\"");
assertThat(exception.getErrors()).isNull();
}
@Test
void createWhenErrorsIsEmpty() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 404, "missing", NO_ERRORS, MESSAGE,
null);
assertThat(exception.getMessage()).isEqualTo(
"Docker API call to 'docker://localhost/example' failed with status code 404 \"missing\" and message \"response message\"");
assertThat(exception.getStatusCode()).isEqualTo(404);
assertThat(exception.getReasonPhrase()).isEqualTo("missing");
assertThat(exception.getErrors()).isSameAs(NO_ERRORS);
}
@Test
void createWhenMessageIsNull() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 404, "missing", ERRORS, null, null);
assertThat(exception.getMessage()).isEqualTo(
"Docker API call to 'docker://localhost/example' failed with status code 404 \"missing\" [code: message]");
assertThat(exception.getResponseMessage()).isNull();
}
@Test
void createWhenMessageIsEmpty() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 404, "missing", ERRORS, NO_MESSAGE,
null);
assertThat(exception.getMessage()).isEqualTo(
"Docker API call to 'docker://localhost/example' failed with status code 404 \"missing\" [code: message]");
assertThat(exception.getResponseMessage()).isSameAs(NO_MESSAGE);
}
@Test
void createWhenProxyAuthFailureWithTextContent() {
DockerEngineException exception = new DockerEngineException(HOST, URI, 407, "Proxy Authentication Required",
null, null, "Badness".getBytes(StandardCharsets.UTF_8));
assertThat(exception.getMessage())
.isEqualTo("Docker API call to 'docker://localhost/example' failed with status code 407 "
+ "\"Proxy Authentication Required\" and content \"Badness\"");
}
}
| DockerEngineExceptionTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/TemplatingTest.java | {
"start": 27361,
"end": 28437
} | class ____ {",
" public void example(int[] array) {",
" int sum = 0;",
" for (int value : array) {",
" sum += value;",
" }",
" }",
"}");
assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
.isEqualTo(
BlockTemplate.create(
ImmutableMap.of("array", UArrayType.create(UPrimitiveType.INT)),
UVariableDecl.create("sum", UPrimitiveTypeTree.INT, ULiteral.intLit(0)),
UEnhancedForLoop.create(
UVariableDecl.create("value", UPrimitiveTypeTree.INT),
UFreeIdent.create("array"),
UBlock.create(
UExpressionStatement.create(
UAssignOp.create(
ULocalVarIdent.create("sum"),
Kind.PLUS_ASSIGNMENT,
ULocalVarIdent.create("value")))))));
}
@Test
public void synchronizd() {
compile(
" | ForEachExample |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/AroundInvokeOnTargetClassAndManySuperclassesWithOverridesTest.java | {
"start": 448,
"end": 857
} | class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(MyBean.class);
@Test
public void test() {
ArcContainer arc = Arc.container();
MyBean bean = arc.instance(MyBean.class).get();
assertEquals("super-intercepted: intercepted: foobar", bean.doSomething(42));
}
static | AroundInvokeOnTargetClassAndManySuperclassesWithOverridesTest |
java | elastic__elasticsearch | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/BucketArrayIterator.java | {
"start": 1022,
"end": 2384
} | class ____ implements CopyableBucketIterator {
private final int scale;
private final long[] bucketCounts;
private final long[] bucketIndices;
private int currentSlot;
private final int limit;
BucketArrayIterator(int scale, long[] bucketCounts, long[] bucketIndices, int startSlot, int limit) {
this.scale = scale;
this.bucketCounts = bucketCounts;
this.bucketIndices = bucketIndices;
this.currentSlot = startSlot;
this.limit = limit;
}
@Override
public boolean hasNext() {
return currentSlot < limit;
}
@Override
public long peekCount() {
ensureEndNotReached();
return bucketCounts[currentSlot];
}
@Override
public long peekIndex() {
ensureEndNotReached();
return bucketIndices[currentSlot];
}
@Override
public void advance() {
ensureEndNotReached();
currentSlot++;
}
@Override
public int scale() {
return scale;
}
@Override
public CopyableBucketIterator copy() {
return new BucketArrayIterator(scale, bucketCounts, bucketIndices, currentSlot, limit);
}
private void ensureEndNotReached() {
if (hasNext() == false) {
throw new IllegalStateException("Iterator has no more buckets");
}
}
}
| BucketArrayIterator |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/RestAuthenticateAction.java | {
"start": 1342,
"end": 2807
} | class ____ extends SecurityBaseRestHandler {
private final SecurityContext securityContext;
public RestAuthenticateAction(Settings settings, SecurityContext securityContext, XPackLicenseState licenseState) {
super(settings, licenseState);
this.securityContext = securityContext;
}
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_security/_authenticate"));
}
@Override
public String getName() {
return "security_authenticate_action";
}
@Override
public RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException {
final User user = securityContext.getUser();
if (user == null) {
return restChannel -> { throw new IllegalStateException("we should never have a null user and invoke this consumer"); };
}
return channel -> client.execute(
AuthenticateAction.INSTANCE,
AuthenticateRequest.INSTANCE,
new RestBuilderListener<AuthenticateResponse>(channel) {
@Override
public RestResponse buildResponse(AuthenticateResponse authenticateResponse, XContentBuilder builder) throws Exception {
authenticateResponse.toXContent(builder, ToXContent.EMPTY_PARAMS);
return new RestResponse(RestStatus.OK, builder);
}
}
);
}
}
| RestAuthenticateAction |
java | quarkusio__quarkus | extensions/devui/runtime/src/main/java/io/quarkus/devui/runtime/logstream/LogStreamRecorder.java | {
"start": 256,
"end": 759
} | class ____ {
private final LogBuildTimeConfig logBuildTimeConfig;
public LogStreamRecorder(final LogBuildTimeConfig logBuildTimeConfig) {
this.logBuildTimeConfig = logBuildTimeConfig;
}
public RuntimeValue<Optional<MutinyLogHandler>> mutinyLogHandler(String srcMainJava, List<String> knownClasses) {
return new RuntimeValue<>(
Optional.of(new MutinyLogHandler(logBuildTimeConfig.decorateStacktraces(), srcMainJava, knownClasses)));
}
}
| LogStreamRecorder |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/ECChunk.java | {
"start": 1051,
"end": 2953
} | class ____ {
private ByteBuffer chunkBuffer;
// TODO: should be in a more general flags
private boolean allZero = false;
/**
* Wrapping a ByteBuffer
* @param buffer buffer to be wrapped by the chunk
*/
public ECChunk(ByteBuffer buffer) {
this.chunkBuffer = buffer;
}
public ECChunk(ByteBuffer buffer, int offset, int len) {
ByteBuffer tmp = buffer.duplicate();
tmp.position(offset);
tmp.limit(offset + len);
this.chunkBuffer = tmp.slice();
}
/**
* Wrapping a bytes array
* @param buffer buffer to be wrapped by the chunk
*/
public ECChunk(byte[] buffer) {
this.chunkBuffer = ByteBuffer.wrap(buffer);
}
public ECChunk(byte[] buffer, int offset, int len) {
this.chunkBuffer = ByteBuffer.wrap(buffer, offset, len);
}
public boolean isAllZero() {
return allZero;
}
public void setAllZero(boolean allZero) {
this.allZero = allZero;
}
/**
* Convert to ByteBuffer
* @return ByteBuffer
*/
public ByteBuffer getBuffer() {
return chunkBuffer;
}
/**
* Convert an array of this chunks to an array of ByteBuffers
* @param chunks chunks to convert into buffers
* @return an array of ByteBuffers
*/
public static ByteBuffer[] toBuffers(ECChunk[] chunks) {
ByteBuffer[] buffers = new ByteBuffer[chunks.length];
ECChunk chunk;
for (int i = 0; i < chunks.length; i++) {
chunk = chunks[i];
if (chunk == null) {
buffers[i] = null;
} else {
buffers[i] = chunk.getBuffer();
}
}
return buffers;
}
/**
* Convert to a bytes array, just for test usage.
* @return bytes array
*/
public byte[] toBytesArray() {
byte[] bytesArr = new byte[chunkBuffer.remaining()];
// Avoid affecting the original one
chunkBuffer.mark();
chunkBuffer.get(bytesArr);
chunkBuffer.reset();
return bytesArr;
}
}
| ECChunk |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_843/TagMapper.java | {
"start": 442,
"end": 656
} | interface ____ {
TagMapper INSTANCE = Mappers.getMapper( TagMapper.class );
@Mapping(target = "date", source = "gitlabTag.commit.authoredDate")
TagInfo gitlabTagToTagInfo(GitlabTag gitlabTag);
}
| TagMapper |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/common/util/BinarySearcherTests.java | {
"start": 772,
"end": 3434
} | class ____ extends ESTestCase {
private BigArrays randombigArrays() {
return new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService());
}
private BigArrays bigArrays;
@Before
public void init() {
bigArrays = randombigArrays();
}
public void testDoubleBinarySearch() throws Exception {
final int size = randomIntBetween(50, 10000);
DoubleArray bigArray = new BigDoubleArray(size, bigArrays, false);
double[] array = new double[size];
// Fill array with sorted values
double currentValue = randomDoubleBetween(-100, 100, true);
for (int i = 0; i < size; ++i) {
bigArray.set(i, currentValue);
array[i] = currentValue;
currentValue += randomDoubleBetween(0, 30, false);
}
// Pick a number to search for
int index = randomIntBetween(0, size - 1);
double searchFor = bigArray.get(index);
if (randomBoolean()) {
// Pick a number where there is no exact match, but that is closest to array.get(index)
if (randomBoolean()) {
// Pick a number above array.get(index)
if (index < size - 1) {
// Divide by 3 so that it's closer to array.get(index) than to array.get(index + 1)
searchFor += (bigArray.get(index + 1) - bigArray.get(index)) / 3;
} else {
// There is nothing about index
searchFor += 0.1;
}
} else {
// Pick one below array.get(index)
if (index > 0) {
searchFor -= (bigArray.get(index) - bigArray.get(index - 1)) / 3;
} else {
// There is nothing below index
searchFor -= 0.1;
}
}
}
BigArrays.DoubleBinarySearcher searcher = new BigArrays.DoubleBinarySearcher(bigArray);
assertEquals(index, searcher.search(0, size - 1, searchFor));
// Sanity check: confirm that ArrayUtils.binarySearch() returns the same index
int arraysIndex = Arrays.binarySearch(array, searchFor);
if (arraysIndex < 0) {
// Arrays.binarySearch didn't find an exact match
arraysIndex = -(arraysIndex + 1);
}
// Arrays.binarySearch always rounds down whereas BinarySearcher rounds to the closest index
// So sometimes they will be off by 1
assertEquals(Math.abs(index - arraysIndex) <= 1, true);
Releasables.close(bigArray);
}
| BinarySearcherTests |
java | apache__camel | components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/internal/AvailablePhoneNumberCountryTollFreeApiMethod.java | {
"start": 708,
"end": 1932
} | enum ____ implements ApiMethod {
READER(
com.twilio.rest.api.v2010.account.availablephonenumbercountry.TollFreeReader.class,
"reader",
arg("pathCountryCode", String.class)),
READER_1(
com.twilio.rest.api.v2010.account.availablephonenumbercountry.TollFreeReader.class,
"reader",
arg("pathAccountSid", String.class),
arg("pathCountryCode", String.class));
private final ApiMethod apiMethod;
AvailablePhoneNumberCountryTollFreeApiMethod(Class<?> resultType, String name, ApiMethodArg... args) {
this.apiMethod = new ApiMethodImpl(TollFree.class, resultType, name, args);
}
@Override
public String getName() { return apiMethod.getName(); }
@Override
public Class<?> getResultType() { return apiMethod.getResultType(); }
@Override
public List<String> getArgNames() { return apiMethod.getArgNames(); }
@Override
public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); }
@Override
public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); }
@Override
public Method getMethod() { return apiMethod.getMethod(); }
}
| AvailablePhoneNumberCountryTollFreeApiMethod |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataImporter.java | {
"start": 1373,
"end": 6348
} | class ____ {
private final Log logger;
private final ConfigDataLocationResolvers resolvers;
private final ConfigDataLoaders loaders;
private final ConfigDataNotFoundAction notFoundAction;
private final Set<ConfigDataResource> loaded = new HashSet<>();
private final Set<ConfigDataLocation> loadedLocations = new HashSet<>();
private final Set<ConfigDataLocation> optionalLocations = new HashSet<>();
/**
* Create a new {@link ConfigDataImporter} instance.
* @param logFactory the log factory
* @param notFoundAction the action to take when a location cannot be found
* @param resolvers the config data location resolvers
* @param loaders the config data loaders
*/
ConfigDataImporter(DeferredLogFactory logFactory, ConfigDataNotFoundAction notFoundAction,
ConfigDataLocationResolvers resolvers, ConfigDataLoaders loaders) {
this.logger = logFactory.getLog(getClass());
this.resolvers = resolvers;
this.loaders = loaders;
this.notFoundAction = notFoundAction;
}
/**
* Resolve and load the given list of locations, filtering any that have been
* previously loaded.
* @param activationContext the activation context
* @param locationResolverContext the location resolver context
* @param loaderContext the loader context
* @param locations the locations to resolve
* @return a map of the loaded locations and data
*/
Map<ConfigDataResolutionResult, ConfigData> resolveAndLoad(@Nullable ConfigDataActivationContext activationContext,
ConfigDataLocationResolverContext locationResolverContext, ConfigDataLoaderContext loaderContext,
List<ConfigDataLocation> locations) {
try {
Profiles profiles = (activationContext != null) ? activationContext.getProfiles() : null;
List<ConfigDataResolutionResult> resolved = resolve(locationResolverContext, profiles, locations);
return load(loaderContext, resolved);
}
catch (IOException ex) {
throw new IllegalStateException("IO error on loading imports from " + locations, ex);
}
}
private List<ConfigDataResolutionResult> resolve(ConfigDataLocationResolverContext locationResolverContext,
@Nullable Profiles profiles, List<ConfigDataLocation> locations) {
List<ConfigDataResolutionResult> resolved = new ArrayList<>(locations.size());
for (ConfigDataLocation location : locations) {
resolved.addAll(resolve(locationResolverContext, profiles, location));
}
return Collections.unmodifiableList(resolved);
}
private List<ConfigDataResolutionResult> resolve(ConfigDataLocationResolverContext locationResolverContext,
@Nullable Profiles profiles, ConfigDataLocation location) {
try {
return this.resolvers.resolve(locationResolverContext, location, profiles);
}
catch (ConfigDataNotFoundException ex) {
handle(ex, location, null);
return Collections.emptyList();
}
}
private Map<ConfigDataResolutionResult, ConfigData> load(ConfigDataLoaderContext loaderContext,
List<ConfigDataResolutionResult> candidates) throws IOException {
Map<ConfigDataResolutionResult, ConfigData> result = new LinkedHashMap<>();
for (int i = candidates.size() - 1; i >= 0; i--) {
ConfigDataResolutionResult candidate = candidates.get(i);
ConfigDataLocation location = candidate.getLocation();
ConfigDataResource resource = candidate.getResource();
this.logger.trace(LogMessage.format("Considering resource %s from location %s", resource, location));
if (resource.isOptional()) {
this.optionalLocations.add(location);
}
if (this.loaded.contains(resource)) {
this.logger
.trace(LogMessage.format("Already loaded resource %s ignoring location %s", resource, location));
this.loadedLocations.add(location);
}
else {
try {
ConfigData loaded = this.loaders.load(loaderContext, resource);
if (loaded != null) {
this.logger.trace(LogMessage.format("Loaded resource %s from location %s", resource, location));
this.loaded.add(resource);
this.loadedLocations.add(location);
result.put(candidate, loaded);
}
}
catch (ConfigDataNotFoundException ex) {
handle(ex, location, resource);
}
}
}
return Collections.unmodifiableMap(result);
}
private void handle(ConfigDataNotFoundException ex, ConfigDataLocation location,
@Nullable ConfigDataResource resource) {
if (ex instanceof ConfigDataResourceNotFoundException notFoundException) {
ex = notFoundException.withLocation(location);
}
getNotFoundAction(location, resource).handle(this.logger, ex);
}
private ConfigDataNotFoundAction getNotFoundAction(ConfigDataLocation location,
@Nullable ConfigDataResource resource) {
if (location.isOptional() || (resource != null && resource.isOptional())) {
return ConfigDataNotFoundAction.IGNORE;
}
return this.notFoundAction;
}
Set<ConfigDataLocation> getLoadedLocations() {
return this.loadedLocations;
}
Set<ConfigDataLocation> getOptionalLocations() {
return this.optionalLocations;
}
}
| ConfigDataImporter |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/AsyncCalcITCase.java | {
"start": 17063,
"end": 17425
} | class ____
extends AsyncFuncMoreGeneric<CompletableFuture<Long[]>> {
@Override
void finish(CompletableFuture<Long[]> future, int param) {
Long[] result = new Long[1];
result[0] = 10L + param;
future.complete(result);
}
}
/** Test function. */
public static | LongAsyncFuncMoreGeneric |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/checkpointing/StreamCheckpointingITCase.java | {
"start": 4746,
"end": 7384
} | class ____ extends RichSourceFunction<String>
implements ParallelSourceFunction<String>, ListCheckpointed<Integer> {
private final long numElements;
private final Random rnd = new Random();
private final StringBuilder stringBuilder = new StringBuilder();
private int index;
private int step;
private volatile boolean isRunning = true;
static long[] counts = new long[PARALLELISM];
@Override
public void close() throws IOException {
counts[getRuntimeContext().getTaskInfo().getIndexOfThisSubtask()] = index;
}
StringGeneratingSourceFunction(long numElements) {
this.numElements = numElements;
}
@Override
public void open(OpenContext openContext) throws IOException {
step = getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks();
if (index == 0) {
index = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask();
}
}
@Override
public void run(SourceContext<String> ctx) throws Exception {
final Object lockingObject = ctx.getCheckpointLock();
while (isRunning && index < numElements) {
char first = (char) ((index % 40) + 40);
stringBuilder.setLength(0);
stringBuilder.append(first);
String result = randomString(stringBuilder, rnd);
synchronized (lockingObject) {
index += step;
ctx.collect(result);
}
}
}
@Override
public void cancel() {
isRunning = false;
}
private static String randomString(StringBuilder bld, Random rnd) {
final int len = rnd.nextInt(10) + 5;
for (int i = 0; i < len; i++) {
char next = (char) (rnd.nextInt(20000) + 33);
bld.append(next);
}
return bld.toString();
}
@Override
public List<Integer> snapshotState(long checkpointId, long timestamp) throws Exception {
return Collections.singletonList(this.index);
}
@Override
public void restoreState(List<Integer> state) throws Exception {
if (state.isEmpty() || state.size() > 1) {
throw new RuntimeException(
"Test failed due to unexpected recovered state size " + state.size());
}
this.index = state.get(0);
}
}
private static | StringGeneratingSourceFunction |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_513/TargetValue.java | {
"start": 233,
"end": 701
} | class ____ {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) throws MappingException, MappingValueException {
if ( MappingValueException.class.getSimpleName().equals( value ) ) {
throw new MappingValueException();
}
else if ( MappingException.class.getSimpleName().equals( value ) ) {
throw new MappingException();
}
}
}
| TargetValue |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageExecutionIntervalUnconstrained.java | {
"start": 1742,
"end": 3153
} | class ____ implements
StageExecutionInterval {
@Override
public ReservationInterval computeExecutionInterval(Plan plan,
ReservationDefinition reservation,
ReservationRequest currentReservationStage, boolean allocateLeft,
RLESparseResourceAllocation allocations) {
Long stageArrival = reservation.getArrival();
Long stageDeadline = reservation.getDeadline();
ReservationRequestInterpreter jobType =
reservation.getReservationRequests().getInterpreter();
// Left to right
if (allocateLeft) {
// If ORDER job, change the stage arrival time
if ((jobType == ReservationRequestInterpreter.R_ORDER)
|| (jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP)) {
Long allocationEndTime = allocations.getLatestNonNullTime();
if (allocationEndTime != -1) {
stageArrival = allocationEndTime;
}
}
// Right to left
} else {
// If ORDER job, change the stage deadline
if ((jobType == ReservationRequestInterpreter.R_ORDER)
|| (jobType == ReservationRequestInterpreter.R_ORDER_NO_GAP)) {
Long allocationStartTime = allocations.getEarliestStartTime();
if (allocationStartTime != -1) {
stageDeadline = allocationStartTime;
}
}
}
return new ReservationInterval(stageArrival, stageDeadline);
}
}
| StageExecutionIntervalUnconstrained |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java | {
"start": 35373,
"end": 35981
} | class ____ {
String @Nullable [] getMessage(boolean b, String[] s) {
return b ? s : null;
}
}
""")
.doTest();
}
@Test
public void negativeCases_alreadyTypeAnnotatedMemberSelect() {
createAggressiveCompilationTestHelper()
.addSourceLines(
"com/google/errorprone/bugpatterns/nullness/LiteralNullReturnTest.java",
"""
package com.google.errorprone.bugpatterns.nullness;
import org.checkerframework.checker.nullness.qual.Nullable;
public | LiteralNullReturnTest |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/cmdb/pojo/Label.java | {
"start": 751,
"end": 1349
} | class ____ {
private String name;
private Set<String> values;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getValues() {
return values;
}
public void setValues(Set<String> values) {
this.values = values;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| Label |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/HarFileSystem.java | {
"start": 28179,
"end": 28343
} | class ____ extends FSDataInputStream {
/**
* Create an input stream that fakes all the reads/positions/seeking.
*/
private static | HarFSDataInputStream |
java | elastic__elasticsearch | modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LatvianAnalyzerProvider.java | {
"start": 883,
"end": 1453
} | class ____ extends AbstractIndexAnalyzerProvider<LatvianAnalyzer> {
private final LatvianAnalyzer analyzer;
LatvianAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(name);
analyzer = new LatvianAnalyzer(
Analysis.parseStopWords(env, settings, LatvianAnalyzer.getDefaultStopSet()),
Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)
);
}
@Override
public LatvianAnalyzer get() {
return this.analyzer;
}
}
| LatvianAnalyzerProvider |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/quarkus/JakartaDataBookRepository.java | {
"start": 356,
"end": 573
} | interface ____ extends CrudRepository<PanacheBook, Long> {
@Find
public List<PanacheBook> findBook(String isbn);
@Query("WHERE isbn = :isbn")
public List<PanacheBook> hqlBook(String isbn);
}
| JakartaDataBookRepository |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/VariableLengthRowBasedKeyValueBatch.java | {
"start": 1452,
"end": 6473
} | class ____ extends RowBasedKeyValueBatch {
// full addresses for key rows and value rows
private final long[] keyOffsets;
/**
* Append a key value pair.
* It copies data into the backing MemoryBlock.
* Returns an UnsafeRow pointing to the value if succeeds, otherwise returns null.
*/
@Override
public UnsafeRow appendRow(Object kbase, long koff, int klen,
Object vbase, long voff, int vlen) {
int uaoSize = UnsafeAlignedOffset.getUaoSize();
final long recordLength = 2L * uaoSize + klen + vlen + 8L;
// if run out of max supported rows or page size, return null
if (numRows >= capacity || page == null || page.size() - pageCursor < recordLength) {
return null;
}
long offset = page.getBaseOffset() + pageCursor;
final long recordOffset = offset;
UnsafeAlignedOffset.putSize(base, offset, klen + vlen + uaoSize);
UnsafeAlignedOffset.putSize(base, offset + uaoSize, klen);
offset += 2L * uaoSize;
Platform.copyMemory(kbase, koff, base, offset, klen);
offset += klen;
Platform.copyMemory(vbase, voff, base, offset, vlen);
offset += vlen;
Platform.putLong(base, offset, 0);
pageCursor += recordLength;
keyOffsets[numRows] = recordOffset + 2L * uaoSize;
keyRowId = numRows;
keyRow.pointTo(base, recordOffset + 2L * uaoSize, klen);
valueRow.pointTo(base, recordOffset + 2L * uaoSize + klen, vlen);
numRows++;
return valueRow;
}
/**
* Returns the key row in this batch at `rowId`. Returned key row is reused across calls.
*/
@Override
public UnsafeRow getKeyRow(int rowId) {
assert(rowId >= 0);
assert(rowId < numRows);
if (keyRowId != rowId) { // if keyRowId == rowId, desired keyRow is already cached
long offset = keyOffsets[rowId];
int klen = UnsafeAlignedOffset.getSize(base, offset - UnsafeAlignedOffset.getUaoSize());
keyRow.pointTo(base, offset, klen);
// set keyRowId so we can check if desired row is cached
keyRowId = rowId;
}
return keyRow;
}
/**
* Returns the value row by two steps:
* 1) looking up the key row with the same id (skipped if the key row is cached)
* 2) retrieve the value row by reusing the metadata from step 1)
* In most times, 1) is skipped because `getKeyRow(id)` is often called before `getValueRow(id)`.
*/
@Override
public UnsafeRow getValueFromKey(int rowId) {
if (keyRowId != rowId) {
getKeyRow(rowId);
}
assert(rowId >= 0);
int uaoSize = UnsafeAlignedOffset.getUaoSize();
long offset = keyRow.getBaseOffset();
int klen = keyRow.getSizeInBytes();
int vlen = UnsafeAlignedOffset.getSize(base, offset - uaoSize * 2L) - klen - uaoSize;
valueRow.pointTo(base, offset + klen, vlen);
return valueRow;
}
/**
* Returns an iterator to go through all rows
*/
@Override
public org.apache.spark.unsafe.KVIterator<UnsafeRow, UnsafeRow> rowIterator() {
return new org.apache.spark.unsafe.KVIterator<UnsafeRow, UnsafeRow>() {
private final UnsafeRow key = new UnsafeRow(keySchema.length());
private final UnsafeRow value = new UnsafeRow(valueSchema.length());
private long offsetInPage = 0;
private int recordsInPage = 0;
private int currentklen;
private int currentvlen;
private int totalLength;
private boolean initialized = false;
private void init() {
if (page != null) {
offsetInPage = page.getBaseOffset();
recordsInPage = numRows;
}
initialized = true;
}
@Override
public boolean next() {
if (!initialized) init();
//searching for the next non empty page is records is now zero
if (recordsInPage == 0) {
freeCurrentPage();
return false;
}
int uaoSize = UnsafeAlignedOffset.getUaoSize();
totalLength = UnsafeAlignedOffset.getSize(base, offsetInPage) - uaoSize;
currentklen = UnsafeAlignedOffset.getSize(base, offsetInPage + uaoSize);
currentvlen = totalLength - currentklen;
key.pointTo(base, offsetInPage + 2L * uaoSize, currentklen);
value.pointTo(base, offsetInPage + 2L * uaoSize + currentklen, currentvlen);
offsetInPage += 2L * uaoSize + totalLength + 8;
recordsInPage -= 1;
return true;
}
@Override
public UnsafeRow getKey() {
return key;
}
@Override
public UnsafeRow getValue() {
return value;
}
@Override
public void close() {
// do nothing
}
private void freeCurrentPage() {
if (page != null) {
freePage(page);
page = null;
}
}
};
}
VariableLengthRowBasedKeyValueBatch(StructType keySchema, StructType valueSchema,
int maxRows, TaskMemoryManager manager) {
super(keySchema, valueSchema, maxRows, manager);
this.keyOffsets = new long[maxRows];
}
}
| VariableLengthRowBasedKeyValueBatch |
java | grpc__grpc-java | util/src/main/java/io/grpc/util/RandomSubsettingLoadBalancer.java | {
"start": 4415,
"end": 4713
} | class ____ {
public final int subsetSize;
public final Object childConfig;
private RandomSubsettingLoadBalancerConfig(int subsetSize, Object childConfig) {
this.subsetSize = subsetSize;
this.childConfig = childConfig;
}
public static | RandomSubsettingLoadBalancerConfig |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/DocValueFormat.java | {
"start": 15046,
"end": 16307
} | class ____ implements DocValueFormat {
public static final DocValueFormat INSTANCE = new BooleanDocValueFormat();
private BooleanDocValueFormat() {}
@Override
public String getWriteableName() {
return "bool";
}
@Override
public void writeTo(StreamOutput out) {}
@Override
public Boolean format(long value) {
return value != 0;
}
@Override
public Boolean format(double value) {
return value != 0;
}
@Override
public long parseLong(String value, boolean roundUp, LongSupplier now) {
switch (value) {
case "false":
return 0;
case "true":
return 1;
}
throw new IllegalArgumentException("Cannot parse boolean [" + value + "], expected either [true] or [false]");
}
@Override
public double parseDouble(String value, boolean roundUp, LongSupplier now) {
return parseLong(value, roundUp, now);
}
};
IpDocValueFormat IP = IpDocValueFormat.INSTANCE;
/**
* Stateless, singleton formatter for IP address data
*/
| BooleanDocValueFormat |
java | playframework__playframework | documentation/manual/releases/release24/migration24/code24/MyComponent.java | {
"start": 298,
"end": 604
} | class ____ implements MyComponent {
@Inject
public MyComponentImpl(ApplicationLifecycle lifecycle) {
// previous contents of Plugin.onStart
lifecycle.addStopHook( () -> {
// previous contents of Plugin.onStop
return F.Promise.pure(null);
});
}
}
//#components-decl
| MyComponentImpl |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmanager/DefaultExecutionPlanStore.java | {
"start": 2293,
"end": 16825
} | class ____<R extends ResourceVersion<R>>
implements ExecutionPlanStore, ExecutionPlanStore.ExecutionPlanListener {
private static final Logger LOG = LoggerFactory.getLogger(DefaultExecutionPlanStore.class);
/** Lock to synchronize with the {@link ExecutionPlanListener}. */
private final Object lock = new Object();
/** The set of IDs of all added execution plans. */
@GuardedBy("lock")
private final Set<JobID> addedExecutionPlans = new HashSet<>();
/** Submitted execution plans handle store. */
private final StateHandleStore<ExecutionPlan, R> executionPlanStateHandleStore;
@GuardedBy("lock")
private final ExecutionPlanStoreWatcher executionPlanStoreWatcher;
private final ExecutionPlanStoreUtil executionPlanStoreUtil;
/** The external listener to be notified on races. */
@GuardedBy("lock")
private ExecutionPlanListener executionPlanListener;
/** Flag indicating whether this instance is running. */
@GuardedBy("lock")
private volatile boolean running;
public DefaultExecutionPlanStore(
StateHandleStore<ExecutionPlan, R> stateHandleStore,
ExecutionPlanStoreWatcher executionPlanStoreWatcher,
ExecutionPlanStoreUtil executionPlanStoreUtil) {
this.executionPlanStateHandleStore = checkNotNull(stateHandleStore);
this.executionPlanStoreWatcher = checkNotNull(executionPlanStoreWatcher);
this.executionPlanStoreUtil = checkNotNull(executionPlanStoreUtil);
this.running = false;
}
@Override
public void start(ExecutionPlanListener executionPlanListener) throws Exception {
synchronized (lock) {
if (!running) {
this.executionPlanListener = checkNotNull(executionPlanListener);
executionPlanStoreWatcher.start(this);
running = true;
}
}
}
@Override
public void stop() throws Exception {
synchronized (lock) {
if (running) {
running = false;
LOG.info("Stopping DefaultExecutionPlanStore.");
Exception exception = null;
try {
executionPlanStateHandleStore.releaseAll();
} catch (Exception e) {
exception = e;
}
try {
executionPlanStoreWatcher.stop();
} catch (Exception e) {
exception = ExceptionUtils.firstOrSuppressed(e, exception);
}
if (exception != null) {
throw new FlinkException(
"Could not properly stop the DefaultExecutionPlanStore.", exception);
}
}
}
}
@Nullable
@Override
public ExecutionPlan recoverExecutionPlan(JobID jobId) throws Exception {
checkNotNull(jobId, "Job ID");
LOG.debug("Recovering execution plan {} from {}.", jobId, executionPlanStateHandleStore);
final String name = executionPlanStoreUtil.jobIDToName(jobId);
synchronized (lock) {
verifyIsRunning();
boolean success = false;
RetrievableStateHandle<ExecutionPlan> executionPlanRetrievableStateHandle;
try {
try {
executionPlanRetrievableStateHandle =
executionPlanStateHandleStore.getAndLock(name);
} catch (StateHandleStore.NotExistException ignored) {
success = true;
return null;
} catch (Exception e) {
throw new FlinkException(
"Could not retrieve the submitted execution plan state handle "
+ "for "
+ name
+ " from the submitted execution plan store.",
e);
}
ExecutionPlan executionPlan;
try {
executionPlan = executionPlanRetrievableStateHandle.retrieveState();
} catch (ClassNotFoundException cnfe) {
throw new FlinkException(
"Could not retrieve submitted ExecutionPlan from state handle under "
+ name
+ ". This indicates that you are trying to recover from state written by an "
+ "older Flink version which is not compatible. Try cleaning the state handle store.",
cnfe);
} catch (IOException ioe) {
throw new FlinkException(
"Could not retrieve submitted ExecutionPlan from state handle under "
+ name
+ ". This indicates that the retrieved state handle is broken. Try cleaning the state handle "
+ "store.",
ioe);
}
addedExecutionPlans.add(executionPlan.getJobID());
LOG.info("Recovered {}.", executionPlan);
success = true;
return executionPlan;
} finally {
if (!success) {
executionPlanStateHandleStore.release(name);
}
}
}
}
@Override
public void putExecutionPlan(ExecutionPlan executionPlan) throws Exception {
checkNotNull(executionPlan, "Execution Plan");
final JobID jobID = executionPlan.getJobID();
final String name = executionPlanStoreUtil.jobIDToName(jobID);
LOG.debug("Adding execution plan {} to {}.", jobID, executionPlanStateHandleStore);
boolean success = false;
while (!success) {
synchronized (lock) {
verifyIsRunning();
final R currentVersion = executionPlanStateHandleStore.exists(name);
if (!currentVersion.isExisting()) {
try {
executionPlanStateHandleStore.addAndLock(name, executionPlan);
addedExecutionPlans.add(jobID);
success = true;
} catch (StateHandleStore.AlreadyExistException ignored) {
LOG.warn(
"{} already exists in {}.",
executionPlan,
executionPlanStateHandleStore);
}
} else if (addedExecutionPlans.contains(jobID)) {
try {
executionPlanStateHandleStore.replace(name, currentVersion, executionPlan);
LOG.info("Updated {} in {}.", executionPlan, getClass().getSimpleName());
success = true;
} catch (StateHandleStore.NotExistException ignored) {
LOG.warn(
"{} does not exists in {}.",
executionPlan,
executionPlanStateHandleStore);
}
} else {
throw new IllegalStateException(
"Trying to update an execution plan you didn't "
+ "#getAllSubmittedExecutionPlans() or #putExecutionPlan() yourself before.");
}
}
}
LOG.info("Added {} to {}.", executionPlan, executionPlanStateHandleStore);
}
@Override
public void putJobResourceRequirements(
JobID jobId, JobResourceRequirements jobResourceRequirements) throws Exception {
synchronized (lock) {
@Nullable final ExecutionPlan executionPlan = recoverExecutionPlan(jobId);
if (executionPlan == null) {
throw new NoSuchElementException(
String.format(
"ExecutionPlan for job [%s] was not found in ExecutionPlanStore and is needed for attaching JobResourceRequirements.",
jobId));
}
JobResourceRequirements.writeToExecutionPlan(executionPlan, jobResourceRequirements);
putExecutionPlan(executionPlan);
}
}
@Override
public CompletableFuture<Void> globalCleanupAsync(JobID jobId, Executor executor) {
checkNotNull(jobId, "Job ID");
return runAsyncWithLockAssertRunning(
() -> {
LOG.debug(
"Removing execution plan {} from {}.",
jobId,
executionPlanStateHandleStore);
final String name = executionPlanStoreUtil.jobIDToName(jobId);
releaseAndRemoveOrThrowCompletionException(jobId, name);
addedExecutionPlans.remove(jobId);
LOG.info(
"Removed execution plan {} from {}.",
jobId,
executionPlanStateHandleStore);
},
executor);
}
@GuardedBy("lock")
private void releaseAndRemoveOrThrowCompletionException(JobID jobId, String jobName) {
boolean success;
try {
success = executionPlanStateHandleStore.releaseAndTryRemove(jobName);
} catch (Exception e) {
throw new CompletionException(e);
}
if (!success) {
throw new CompletionException(
new FlinkException(
String.format(
"Could not remove execution plan with job id %s from %s.",
jobId, executionPlanStateHandleStore)));
}
}
/**
* Releases the locks on the specified {@link ExecutionPlan}.
*
* <p>Releasing the locks allows that another instance can delete the job from the {@link
* ExecutionPlanStore}.
*
* @param jobId specifying the job to release the locks for
* @param executor the executor being used for the asynchronous execution of the local cleanup.
* @returns The cleanup result future.
*/
@Override
public CompletableFuture<Void> localCleanupAsync(JobID jobId, Executor executor) {
checkNotNull(jobId, "Job ID");
return runAsyncWithLockAssertRunning(
() -> {
LOG.debug(
"Releasing execution plan {} from {}.",
jobId,
executionPlanStateHandleStore);
executionPlanStateHandleStore.release(
executionPlanStoreUtil.jobIDToName(jobId));
addedExecutionPlans.remove(jobId);
LOG.info(
"Released execution plan {} from {}.",
jobId,
executionPlanStateHandleStore);
},
executor);
}
private CompletableFuture<Void> runAsyncWithLockAssertRunning(
ThrowingRunnable<Exception> runnable, Executor executor) {
return CompletableFuture.runAsync(
() -> {
synchronized (lock) {
verifyIsRunning();
try {
runnable.run();
} catch (Exception e) {
throw new CompletionException(e);
}
}
},
executor);
}
@Override
public Collection<JobID> getJobIds() throws Exception {
LOG.debug("Retrieving all stored job ids from {}.", executionPlanStateHandleStore);
final Collection<String> names;
try {
names = executionPlanStateHandleStore.getAllHandles();
} catch (Exception e) {
throw new Exception(
"Failed to retrieve all job ids from " + executionPlanStateHandleStore + ".",
e);
}
final List<JobID> jobIds = new ArrayList<>(names.size());
for (String name : names) {
try {
jobIds.add(executionPlanStoreUtil.nameToJobID(name));
} catch (Exception exception) {
LOG.warn(
"Could not parse job id from {}. This indicates a malformed name.",
name,
exception);
}
}
LOG.info("Retrieved job ids {} from {}", jobIds, executionPlanStateHandleStore);
return jobIds;
}
@Override
public void onAddedExecutionPlan(JobID jobId) {
synchronized (lock) {
if (running) {
if (!addedExecutionPlans.contains(jobId)) {
try {
// This has been added by someone else. Or we were fast to remove it (false
// positive).
executionPlanListener.onAddedExecutionPlan(jobId);
} catch (Throwable t) {
LOG.error(
"Failed to notify execution plan listener onAddedExecutionPlan event for {}",
jobId,
t);
}
}
}
}
}
@Override
public void onRemovedExecutionPlan(JobID jobId) {
synchronized (lock) {
if (running) {
if (addedExecutionPlans.contains(jobId)) {
try {
// Someone else removed one of our execution plans. Mean!
executionPlanListener.onRemovedExecutionPlan(jobId);
} catch (Throwable t) {
LOG.error(
"Failed to notify execution plan listener onRemovedExecutionPlan event for {}",
jobId,
t);
}
}
}
}
}
/** Verifies that the state is running. */
private void verifyIsRunning() {
checkState(running, "Not running. Forgot to call start()?");
}
}
| DefaultExecutionPlanStore |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ser/jdk/MapSerializationSorted4773Test.java | {
"start": 674,
"end": 800
} | class ____ {
public Map<Currency, String> exampleMap = new HashMap<>();
}
public static | IncomparableContainer4773 |
java | apache__spark | sql/core/src/test/java/test/org/apache/spark/sql/connector/JavaOrderAndPartitionAwareDataSource.java | {
"start": 1412,
"end": 3601
} | class ____ extends JavaPartitionAwareDataSource.MyScanBuilder
implements SupportsReportOrdering {
private final Partitioning partitioning;
private final SortOrder[] ordering;
MyScanBuilder(String partitionKeys, String orderKeys) {
if (partitionKeys != null) {
String[] keys = partitionKeys.split(",");
Expression[] clustering = new Transform[keys.length];
for (int i = 0; i < keys.length; i++) {
clustering[i] = Expressions.identity(keys[i]);
}
this.partitioning = new KeyGroupedPartitioning(clustering, 2);
} else {
this.partitioning = new UnknownPartitioning(2);
}
if (orderKeys != null) {
String[] keys = orderKeys.split(",");
this.ordering = new SortOrder[keys.length];
for (int i = 0; i < keys.length; i++) {
this.ordering[i] = new MySortOrder(keys[i]);
}
} else {
this.ordering = new SortOrder[0];
}
}
@Override
public InputPartition[] planInputPartitions() {
InputPartition[] partitions = new InputPartition[2];
partitions[0] = new SpecificInputPartition(new int[]{1, 1, 3}, new int[]{4, 5, 5});
partitions[1] = new SpecificInputPartition(new int[]{2, 4, 4}, new int[]{6, 1, 2});
return partitions;
}
@Override
public Partitioning outputPartitioning() {
return this.partitioning;
}
@Override
public SortOrder[] outputOrdering() {
return this.ordering;
}
}
@Override
public Table getTable(CaseInsensitiveStringMap options) {
return new JavaSimpleBatchTable() {
@Override
public Transform[] partitioning() {
String partitionKeys = options.get("partitionKeys");
if (partitionKeys == null) {
return new Transform[0];
} else {
return (Transform[]) Arrays.stream(partitionKeys.split(","))
.map(Expressions::identity).toArray();
}
}
@Override
public ScanBuilder newScanBuilder(CaseInsensitiveStringMap options) {
return new MyScanBuilder(options.get("partitionKeys"), options.get("orderKeys"));
}
};
}
static | MyScanBuilder |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/protocolPB/RefreshCallQueueProtocolServerSideTranslatorPB.java | {
"start": 1260,
"end": 2015
} | class ____ implements
RefreshCallQueueProtocolPB {
private final RefreshCallQueueProtocol impl;
private final static RefreshCallQueueResponseProto
VOID_REFRESH_CALL_QUEUE_RESPONSE = RefreshCallQueueResponseProto
.newBuilder().build();
public RefreshCallQueueProtocolServerSideTranslatorPB(
RefreshCallQueueProtocol impl) {
this.impl = impl;
}
@Override
public RefreshCallQueueResponseProto refreshCallQueue(
RpcController controller, RefreshCallQueueRequestProto request)
throws ServiceException {
try {
impl.refreshCallQueue();
} catch (IOException e) {
throw new ServiceException(e);
}
return VOID_REFRESH_CALL_QUEUE_RESPONSE;
}
}
| RefreshCallQueueProtocolServerSideTranslatorPB |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/BlockingObservableIterable.java | {
"start": 1583,
"end": 5103
} | class ____<T>
extends AtomicReference<Disposable>
implements io.reactivex.rxjava3.core.Observer<T>, Iterator<T>, Disposable {
private static final long serialVersionUID = 6695226475494099826L;
final SpscLinkedArrayQueue<T> queue;
final Lock lock;
final Condition condition;
volatile boolean done;
volatile Throwable error;
BlockingObservableIterator(int batchSize) {
this.queue = new SpscLinkedArrayQueue<>(batchSize);
this.lock = new ReentrantLock();
this.condition = lock.newCondition();
}
@Override
public boolean hasNext() {
for (;;) {
if (isDisposed()) {
Throwable e = error;
if (e != null) {
throw ExceptionHelper.wrapOrThrow(e);
}
return false;
}
boolean d = done;
boolean empty = queue.isEmpty();
if (d) {
Throwable e = error;
if (e != null) {
throw ExceptionHelper.wrapOrThrow(e);
} else
if (empty) {
return false;
}
}
if (empty) {
try {
BlockingHelper.verifyNonBlocking();
lock.lock();
try {
while (!done && queue.isEmpty() && !isDisposed()) {
condition.await();
}
} finally {
lock.unlock();
}
} catch (InterruptedException ex) {
DisposableHelper.dispose(this);
signalConsumer();
throw ExceptionHelper.wrapOrThrow(ex);
}
} else {
return true;
}
}
}
@Override
public T next() {
if (hasNext()) {
return queue.poll();
}
throw new NoSuchElementException();
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onNext(T t) {
queue.offer(t);
signalConsumer();
}
@Override
public void onError(Throwable t) {
error = t;
done = true;
signalConsumer();
}
@Override
public void onComplete() {
done = true;
signalConsumer();
}
void signalConsumer() {
lock.lock();
try {
condition.signalAll();
} finally {
lock.unlock();
}
}
@Override // otherwise default method which isn't available in Java 7
public void remove() {
throw new UnsupportedOperationException("remove");
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
signalConsumer(); // Just in case it is currently blocking in hasNext.
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
}
}
| BlockingObservableIterator |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/cache/polymorphism/PolymorphicCacheAndBatchingTest.java | {
"start": 1088,
"end": 1465
} | class ____ extends PolymorphicCacheTest {
@Test
public void testMultiLoad(SessionFactoryScope scope) {
final CacheImplementor cache = scope.getSessionFactory().getCache();
assertThat( cache.containsEntity( CachedItem1.class, 1 ) ).isTrue();
assertThat( cache.containsEntity( CachedItem2.class, 2 ) ).isTrue();
// test accessing the wrong | PolymorphicCacheAndBatchingTest |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/GrpcComponentBuilderFactory.java | {
"start": 1823,
"end": 5297
} | interface ____ extends ComponentBuilder<GrpcComponent> {
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default GrpcComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default GrpcComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default GrpcComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
| GrpcComponentBuilder |
java | elastic__elasticsearch | libs/entitlement/src/main/java/org/elasticsearch/entitlement/bootstrap/EntitlementBootstrap.java | {
"start": 1514,
"end": 8209
} | class ____ {
/**
* Main entry point that activates entitlement checking. Once this method returns,
* calls to methods protected by entitlements from classes without a valid
* policy will throw {@link org.elasticsearch.entitlement.runtime.api.NotEntitledException}.
*
* @param serverPolicyPatch additional entitlements to patch the embedded server layer policy
* @param pluginPolicies maps each plugin name to the corresponding {@link Policy}
* @param scopeResolver a functor to map a Java Class to the component and module it belongs to.
* @param settingResolver a functor to resolve a setting name pattern for one or more Elasticsearch settings.
* @param dataDirs data directories for Elasticsearch
* @param sharedDataDir shared data directory for Elasticsearch (deprecated)
* @param sharedRepoDirs shared repository directories for Elasticsearch
* @param configDir the config directory for Elasticsearch
* @param libDir the lib directory for Elasticsearch
* @param modulesDir the directory where Elasticsearch modules are
* @param pluginsDir the directory where plugins are installed for Elasticsearch
* @param pluginSourcePaths maps each plugin name to the location of that plugin's code
* @param tempDir the temp directory for Elasticsearch
* @param logsDir the log directory for Elasticsearch
* @param pidFile path to a pid file for Elasticsearch, or {@code null} if one was not specified
* @param suppressFailureLogPackages packages for which we do not need or want to log Entitlements failures
*/
public static void bootstrap(
Policy serverPolicyPatch,
Map<String, Policy> pluginPolicies,
Function<Class<?>, PolicyManager.PolicyScope> scopeResolver,
Function<String, Stream<String>> settingResolver,
Path[] dataDirs,
Path sharedDataDir,
Path[] sharedRepoDirs,
Path configDir,
Path libDir,
Path modulesDir,
Path pluginsDir,
Map<String, Collection<Path>> pluginSourcePaths,
Path logsDir,
Path tempDir,
@Nullable Path pidFile,
Set<Package> suppressFailureLogPackages
) {
logger.debug("Loading entitlement agent");
if (EntitlementInitialization.initializeArgs != null) {
throw new IllegalStateException("initialization data is already set");
}
PathLookupImpl pathLookup = new PathLookupImpl(
getUserHome(),
configDir,
dataDirs,
sharedDataDir,
sharedRepoDirs,
libDir,
modulesDir,
pluginsDir,
logsDir,
tempDir,
pidFile,
settingResolver
);
EntitlementInitialization.initializeArgs = new EntitlementInitialization.InitializeArgs(
pathLookup,
suppressFailureLogPackages,
createPolicyManager(pluginPolicies, pathLookup, serverPolicyPatch, scopeResolver, pluginSourcePaths)
);
exportInitializationToAgent();
loadAgent(findAgentJar(), EntitlementInitialization.class.getName());
if (EntitlementInitialization.getError() != null) {
throw EntitlementInitialization.getError();
}
}
private static Path getUserHome() {
String userHome = System.getProperty("user.home");
if (userHome == null) {
throw new IllegalStateException("user.home system property is required");
}
return PathUtils.get(userHome);
}
@SuppressForbidden(reason = "The VirtualMachine API is the only way to attach a java agent dynamically")
static void loadAgent(String agentPath, String entitlementInitializationClassName) {
try {
VirtualMachine vm = VirtualMachine.attach(Long.toString(ProcessHandle.current().pid()));
try {
vm.loadAgent(agentPath, entitlementInitializationClassName);
} finally {
vm.detach();
}
} catch (AttachNotSupportedException | IOException | AgentLoadException | AgentInitializationException e) {
throw new IllegalStateException("Unable to attach entitlement agent [" + agentPath + "]", e);
}
}
private static void exportInitializationToAgent() {
String initPkg = EntitlementInitialization.class.getPackageName();
// agent will live in unnamed module
Module unnamedModule = ClassLoader.getSystemClassLoader().getUnnamedModule();
EntitlementInitialization.class.getModule().addExports(initPkg, unnamedModule);
}
static String findAgentJar() {
String propertyName = "es.entitlement.agentJar";
String propertyValue = System.getProperty(propertyName);
if (propertyValue != null) {
return propertyValue;
}
Path esHome = Path.of(System.getProperty("es.path.home"));
Path dir = esHome.resolve("lib/entitlement-agent");
if (Files.exists(dir) == false) {
throw new IllegalStateException("Directory for entitlement jar does not exist: " + dir);
}
try (var s = Files.list(dir)) {
var candidates = s.limit(2).toList();
if (candidates.size() != 1) {
throw new IllegalStateException("Expected one jar in " + dir + "; found " + candidates.size());
}
return candidates.get(0).toString();
} catch (IOException e) {
throw new IllegalStateException("Failed to list entitlement jars in: " + dir, e);
}
}
private static PolicyManager createPolicyManager(
Map<String, Policy> pluginPolicies,
PathLookup pathLookup,
Policy serverPolicyPatch,
Function<Class<?>, PolicyManager.PolicyScope> scopeResolver,
Map<String, Collection<Path>> pluginSourcePathsResolver
) {
FilesEntitlementsValidation.validate(pluginPolicies, pathLookup);
return new PolicyManager(
HardcodedEntitlements.serverPolicy(pathLookup.pidFile(), serverPolicyPatch),
HardcodedEntitlements.agentEntitlements(),
pluginPolicies,
scopeResolver,
pluginSourcePathsResolver::get,
pathLookup
);
}
private static final Logger logger = LogManager.getLogger(EntitlementBootstrap.class);
}
| EntitlementBootstrap |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/inject/annotation/EnvironmentOptionalValuesMap.java | {
"start": 1051,
"end": 2893
} | class ____<V> extends OptionalValuesMap<V> {
/**
* @param type The type
* @param values A map of values
* @param environment The environment
*/
EnvironmentOptionalValuesMap(Class<?> type, Map<CharSequence, ?> values, Environment environment) {
super(type, resolveValues(environment, values));
}
@SuppressWarnings("unchecked")
private static Map<CharSequence, ?> resolveValues(Environment environment, Map<CharSequence, ?> values) {
PropertyPlaceholderResolver placeholderResolver = environment.getPlaceholderResolver();
return values.entrySet().stream().map((Function<Map.Entry<CharSequence, ?>, Map.Entry<CharSequence, ?>>) entry -> {
Object value = entry.getValue();
if (value instanceof CharSequence) {
value = placeholderResolver.resolveRequiredPlaceholders(value.toString());
} else if (value instanceof String[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = placeholderResolver.resolveRequiredPlaceholders(a[i]);
}
}
Object finalValue = value;
return new Map.Entry<CharSequence, Object>() {
Object val = finalValue;
@Override
public CharSequence getKey() {
return entry.getKey();
}
@Override
public Object getValue() {
return val;
}
@Override
public Object setValue(Object value) {
Object old = val;
val = value;
return old;
}
};
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}
| EnvironmentOptionalValuesMap |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java | {
"start": 2881,
"end": 3451
} | class ____ element in the {@code Mono}
* @param <T> the element type
* @return a mono containing the body of the given type {@code T}
*/
<T> Mono<T> bodyToMono(Class<? extends T> elementClass);
/**
* Extract the body to a {@code Mono}.
* @param elementTypeRef the type reference of element in the {@code Mono}
* @param <T> the element type
* @return a mono containing the body of the given type {@code T}
*/
<T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef);
/**
* Extract the body to a {@code Flux}.
* @param elementClass the | of |
java | spring-projects__spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixin.java | {
"start": 1127,
"end": 1872
} | class ____ used to serialize/deserialize
* {@link OAuth2AuthenticationException}.
*
* @author Dennis Neufeld
* @author Steve Riesenberg
* @since 5.3.4
* @see OAuth2AuthenticationException
* @see OAuth2ClientJackson2Module
* @deprecated as of 7.0 in favor of
* {@code org.springframework.security.oauth2.client.jackson.OAuth2AuthenticationExceptionMixin}
* based on Jackson 3
*/
@Deprecated(forRemoval = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true, value = { "cause", "stackTrace", "suppressedExceptions" })
abstract | is |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/SystemUtils.java | {
"start": 44119,
"end": 44639
} | class ____ loaded.
* </p>
*
* @since 3.13.0
*/
public static final boolean IS_JAVA_20 = getJavaVersionMatches("20");
/**
* The constant {@code true} if this is Java version 21 (also 21.x versions).
* <p>
* The result depends on the value of the {@link #JAVA_SPECIFICATION_VERSION} constant.
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_SPECIFICATION_VERSION} is {@code null}.
* </p>
* <p>
* This value is initialized when the | is |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/EmbeddedAnyTest.java | {
"start": 3473,
"end": 3925
} | class ____ {
@Any
@AnyDiscriminator( DiscriminatorType.STRING )
@AnyDiscriminatorValue( discriminator = "1", entity = Bar1.class )
@AnyDiscriminatorValue( discriminator = "2", entity = Bar2.class )
@Column(name = "bar_type")
@AnyKeyJavaClass( Integer.class )
@JoinColumn(name = "bar_id")
private BarInt bar;
public BarInt getBar() {
return bar;
}
public void setBar(BarInt bar) {
this.bar = bar;
}
}
public | FooEmbeddable |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/compressor/Compressor.java | {
"start": 1435,
"end": 2130
} | interface ____ extends MessageEncoding {
Compressor NONE = Identity.IDENTITY;
static Compressor getCompressor(FrameworkModel frameworkModel, String compressorStr) {
if (null == compressorStr) {
return null;
}
if (compressorStr.equals(Identity.MESSAGE_ENCODING)) {
return NONE;
}
return frameworkModel.getExtensionLoader(Compressor.class).getExtension(compressorStr);
}
/**
* compress payload
*
* @param payloadByteArr payload byte array
* @return compressed payload byte array
*/
byte[] compress(byte[] payloadByteArr);
OutputStream decorate(OutputStream outputStream);
}
| Compressor |
java | quarkusio__quarkus | integration-tests/spring-data-jpa/src/main/java/io/quarkus/it/spring/data/jpa/CarRepository.java | {
"start": 244,
"end": 540
} | interface ____ extends JpaRepository<Car, Long> {
List<Car> findByBrand(String brand);
Car findByBrandAndModel(String brand, String model);
@Query("SELECT m.model FROM MotorCar m WHERE m.brand = :brand")
List<String> findModelsByBrand(@Param("brand") String brand);
}
| CarRepository |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/jdbc/env/internal/BlobAndClobCreator.java | {
"start": 762,
"end": 6577
} | class ____ extends AbstractLobCreator implements LobCreator {
/**
* Callback for performing contextual BLOB creation
*/
public static final LobCreationContext.Callback<Blob> CREATE_BLOB_CALLBACK = Connection::createBlob;
/**
* Callback for performing contextual CLOB creation
*/
public static final LobCreationContext.Callback<Clob> CREATE_CLOB_CALLBACK = Connection::createClob;
/**
* Callback for performing contextual NCLOB creation
*/
public static final LobCreationContext.Callback<NClob> CREATE_NCLOB_CALLBACK = Connection::createNClob;
protected final LobCreationContext lobCreationContext;
protected final boolean useConnectionToCreateLob;
BlobAndClobCreator(LobCreationContext lobCreationContext, boolean useConnectionToCreateLob) {
this.lobCreationContext = lobCreationContext;
this.useConnectionToCreateLob = useConnectionToCreateLob;
}
/**
* Create the basic contextual BLOB reference.
*
* @return The created BLOB reference.
*/
Blob createBlob() {
return lobCreationContext.fromContext( CREATE_BLOB_CALLBACK );
}
/**
* Create a {@link Blob} object after reading a {@code byte[]}
* array from a JDBC {@link ResultSet}.
*/
@Override
public Blob createBlob(byte[] bytes) {
final Blob blob = createBlob();
try {
blob.setBytes( 1, bytes );
return blob;
}
catch ( SQLException e ) {
throw new JDBCException( "Unable to set BLOB bytes after creation", e );
}
}
/**
* Create a {@link Blob} object after reading an {@link InputStream}
* from a JDBC {@link ResultSet}.
*
* @implNote
* It's very inefficient to use JDBC LOB locator creation to create
* a LOB with the contents of the given stream, since that requires
* reading the whole stream. So instead just wrap the given stream,
* just like what {@link NonContextualLobCreator} does.
*/
@Override
public Blob createBlob(InputStream stream, long length) {
return NonContextualLobCreator.INSTANCE.createBlob( stream, length );
}
/**
* Create the basic contextual CLOB reference.
*
* @return The created CLOB reference.
*/
Clob createClob() {
return lobCreationContext.fromContext( CREATE_CLOB_CALLBACK );
}
/**
* Create the basic contextual NCLOB reference.
*
* @return The created NCLOB reference.
*/
NClob createNClob() {
return lobCreationContext.fromContext( CREATE_NCLOB_CALLBACK );
}
/**
* Create a {@link Clob} object after reading a {@code String}
* from a JDBC {@link ResultSet}.
*/
@Override
public Clob createClob(String string) {
try {
final Clob clob = createClob();
clob.setString( 1, string );
return clob;
}
catch ( SQLException e ) {
throw new JDBCException( "Unable to set CLOB string after creation", e );
}
}
/**
* Create a {@link Clob} object after reading an {@link InputStream}
* from a JDBC {@link ResultSet}.
*
* @implNote
* It's very inefficient to use JDBC LOB locator creation to create
* a LOB with the contents of the given stream, since that requires
* reading the whole stream. So instead just wrap the given stream,
* just like what {@link NonContextualLobCreator} does.
*/
@Override
public Clob createClob(Reader reader, long length) {
return NonContextualLobCreator.INSTANCE.createClob( reader, length );
}
@Override
public NClob createNClob(String string) {
return NonContextualLobCreator.INSTANCE.createNClob( string );
}
@Override
public NClob createNClob(Reader reader, long length) {
return NonContextualLobCreator.INSTANCE.createNClob( reader, length );
}
/**
* Obtain a {@link Blob} instance which can be written to a JDBC
* {@link java.sql.PreparedStatement} using
* {@link java.sql.PreparedStatement#setBlob(int, Blob)}.
*/
@Override
public Blob toJdbcBlob(Blob blob) {
try {
if ( useConnectionToCreateLob ) {
// final Blob jdbcBlob = createBlob();
// blob.getBinaryStream().transferTo( jdbcBlob.setBinaryStream(1) );
// return jdbcBlob;
return createBlob( blob.getBytes( 1, (int) blob.length() ) );
}
else {
return super.toJdbcBlob( blob );
}
}
catch (SQLException e) {
throw new JDBCException( "Could not create JDBC Blob", e );
}
// catch (IOException e) {
// throw new HibernateException( "Could not create JDBC Blob", e );
// }
}
/**
* Obtain a {@link Clob} instance which can be written to a JDBC
* {@link java.sql.PreparedStatement} using
* {@link java.sql.PreparedStatement#setClob(int, Clob)}.
*/
@Override
public Clob toJdbcClob(Clob clob) {
try {
if ( useConnectionToCreateLob ) {
// final Clob jdbcClob = createClob();
// clob.getCharacterStream().transferTo( jdbcClob.setCharacterStream(1) );
// return jdbcClob;
return createClob( clob.getSubString( 1, (int) clob.length() ) );
}
else {
return super.toJdbcClob( clob );
}
}
catch (SQLException e) {
throw new JDBCException( "Could not create JDBC Clob", e );
}
// catch (IOException e) {
// throw new HibernateException( "Could not create JDBC Clob", e );
// }
}
/**
* Obtain an {@link NClob} instance which can be written to a JDBC
* {@link java.sql.PreparedStatement} using
* {@link java.sql.PreparedStatement#setNClob(int, NClob)}.
*/
@Override
public NClob toJdbcNClob(NClob clob) {
try {
if ( useConnectionToCreateLob ) {
// final NClob jdbcClob = createNClob();
// clob.getCharacterStream().transferTo( jdbcClob.setCharacterStream(1) );
// return jdbcClob;
return createNClob( clob.getSubString( 1, (int) clob.length() ) );
}
else {
return super.toJdbcNClob( clob );
}
}
catch (SQLException e) {
throw new JDBCException( "Could not create JDBC NClob", e );
}
// catch (IOException e) {
// throw new HibernateException( "Could not create JDBC NClob", e );
// }
}
}
| BlobAndClobCreator |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java | {
"start": 35617,
"end": 36292
} | class ____ {
private final Object actual = new ByteArrayInputStream("stream".getBytes());
@Test
void createAssert() {
// WHEN
AbstractInputStreamAssert<?, ?> result = INPUT_STREAM.createAssert(actual);
// THEN
result.hasContent("stream");
}
@Test
void createAssert_with_ValueProvider() {
// GIVEN
ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual);
// WHEN
AbstractInputStreamAssert<?, ?> result = INPUT_STREAM.createAssert(valueProvider);
// THEN
result.hasContent("stream");
verify(valueProvider).apply(InputStream.class);
}
}
@Nested
| InputStream_Factory |
java | quarkusio__quarkus | test-framework/junit5-component/src/test/java/io/quarkus/test/component/declarative/AnnotationsTransformerTest.java | {
"start": 733,
"end": 1049
} | class ____ {
@Inject
NotABean bean;
@InjectMock
Charlie charlie;
@Test
public void testPing() {
Mockito.when(charlie.ping()).thenReturn("foo");
assertEquals("foo", bean.ping());
}
// @Singleton should be added automatically
public static | AnnotationsTransformerTest |
java | apache__dubbo | dubbo-metadata/dubbo-metadata-processor/src/main/java/org/apache/dubbo/metadata/annotation/processing/builder/ArrayTypeDefinitionBuilder.java | {
"start": 1301,
"end": 2103
} | class ____ implements TypeBuilder<ArrayType> {
@Override
public boolean accept(ProcessingEnvironment processingEnv, TypeMirror type) {
return isArrayType(type);
}
@Override
public TypeDefinition build(
ProcessingEnvironment processingEnv, ArrayType type, Map<String, TypeDefinition> typeCache) {
TypeDefinition typeDefinition = new TypeDefinition(type.toString());
TypeMirror componentType = type.getComponentType();
TypeDefinition subTypeDefinition = TypeDefinitionBuilder.build(processingEnv, componentType, typeCache);
typeDefinition.getItems().add(subTypeDefinition.getType());
return typeDefinition;
}
@Override
public int getPriority() {
return MIN_PRIORITY - 4;
}
}
| ArrayTypeDefinitionBuilder |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/jsontype/JsonTypeInfoCustomResolver2811Test.java | {
"start": 625,
"end": 740
} | class ____ implements Vehicle {
public int wheels;
public String bicycleType;
}
static | Bicycle |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/notfound/OptionalEagerRefNonPKNotFoundTest.java | {
"start": 19502,
"end": 20115
} | class ____ extends Person {
@Id
private Long id;
@OneToOne(cascade = CascadeType.PERSIST)
@MapsId
@JoinColumn(
name = "cityName",
referencedColumnName = "name",
foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)
)
@Fetch(FetchMode.SELECT)
private City city;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public City getCity() {
return city;
}
@Override
public void setCity(City city) {
this.city = city;
}
}
@Entity
@Table(name = "PersonMapsIdColumnSelectIgnore")
public static | PersonMapsIdColumnSelectException |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/util/function/Tuple8.java | {
"start": 1387,
"end": 6354
} | class ____<T1, T2, T3, T4, T5, T6, T7, T8> extends
Tuple7<T1, T2, T3, T4, T5, T6, T7> {
private static final long serialVersionUID = -8746796646535446242L;
final T8 t8;
Tuple8(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8) {
super(t1, t2, t3, t4, t5, t6, t7);
this.t8 = Objects.requireNonNull(t8, "t8");
}
/**
* Type-safe way to get the eighth object of this {@link Tuples}.
*
* @return The eighth object
*/
public T8 getT8() {
return t8;
}
/**
* Map the 1st part (T1) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T1 part
* @param <R> the new type for the T1 part
* @return a new {@link Tuple8} with a different T1 value
*/
public <R> Tuple8<R, T2, T3, T4, T5, T6, T7, T8> mapT1(Function<T1, R> mapper) {
return new Tuple8<>(mapper.apply(t1), t2, t3, t4, t5, t6, t7, t8);
}
/**
* Map the 2nd part (T2) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T2 part
* @param <R> the new type for the T2 part
* @return a new {@link Tuple8} with a different T2 value
*/
public <R> Tuple8<T1, R, T3, T4, T5, T6, T7, T8> mapT2(Function<T2, R> mapper) {
return new Tuple8<>(t1, mapper.apply(t2), t3, t4, t5, t6, t7, t8);
}
/**
* Map the 3rd part (T3) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T3 part
* @param <R> the new type for the T3 part
* @return a new {@link Tuple8} with a different T3 value
*/
public <R> Tuple8<T1, T2, R, T4, T5, T6, T7, T8> mapT3(Function<T3, R> mapper) {
return new Tuple8<>(t1, t2, mapper.apply(t3), t4, t5, t6, t7, t8);
}
/**
* Map the 4th part (T4) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T4 part
* @param <R> the new type for the T4 part
* @return a new {@link Tuple8} with a different T4 value
*/
public <R> Tuple8<T1, T2, T3, R, T5, T6, T7, T8> mapT4(Function<T4, R> mapper) {
return new Tuple8<>(t1, t2, t3, mapper.apply(t4), t5, t6, t7, t8);
}
/**
* Map the 5th part (T5) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T5 part
* @param <R> the new type for the T5 part
* @return a new {@link Tuple8} with a different T5 value
*/
public <R> Tuple8<T1, T2, T3, T4, R, T6, T7, T8> mapT5(Function<T5, R> mapper) {
return new Tuple8<>(t1, t2, t3, t4, mapper.apply(t5), t6, t7, t8);
}
/**
* Map the 6th part (T6) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T6 part
* @param <R> the new type for the T6 part
* @return a new {@link Tuple8} with a different T6 value
*/
public <R> Tuple8<T1, T2, T3, T4, T5, R, T7, T8> mapT6(Function<T6, R> mapper) {
return new Tuple8<>(t1, t2, t3, t4, t5, mapper.apply(t6), t7, t8);
}
/**
* Map the 7th part (T7) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T7 part
* @param <R> the new type for the T7 part
* @return a new {@link Tuple8} with a different T7 value
*/
public <R> Tuple8<T1, T2, T3, T4, T5, T6, R, T8> mapT7(Function<T7, R> mapper) {
return new Tuple8<>(t1, t2, t3, t4, t5, t6, mapper.apply(t7), t8);
}
/**
* Map the 8th part (t8) of this {@link Tuple8} into a different value and type,
* keeping the other parts.
*
* @param mapper the mapping {@link Function} for the T8 part
* @param <R> the new type for the T8 part
* @return a new {@link Tuple8} with a different T8 value
*/
public <R> Tuple8<T1, T2, T3, T4, T5, T6, T7, R> mapT8(Function<T8, R> mapper) {
return new Tuple8<>(t1, t2, t3, t4, t5, t6, t7, mapper.apply(t8));
}
@Override
public @Nullable Object get(int index) {
switch (index) {
case 0:
return t1;
case 1:
return t2;
case 2:
return t3;
case 3:
return t4;
case 4:
return t5;
case 5:
return t6;
case 6:
return t7;
case 7:
return t8;
default:
return null;
}
}
@Override
public Object[] toArray() {
return new Object[]{t1, t2, t3, t4, t5, t6, t7, t8};
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) return true;
if (!(o instanceof Tuple8)) return false;
if (!super.equals(o)) return false;
@SuppressWarnings("rawtypes")
Tuple8 tuple8 = (Tuple8) o;
return t8.equals(tuple8.t8);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + t8.hashCode();
return result;
}
@Override
public int size() {
return 8;
}
}
| Tuple8 |
java | quarkusio__quarkus | extensions/panache/hibernate-reactive-panache-kotlin/runtime/src/main/kotlin/io/quarkus/hibernate/reactive/panache/Panache.java | {
"start": 1020,
"end": 1098
} | class ____ be removed in the future.
*/
@Deprecated(since = "3.30.0")
public | will |
java | google__gson | gson/src/main/java/com/google/gson/stream/JsonWriter.java | {
"start": 5820,
"end": 27050
} | class ____ implements Closeable, Flushable {
// Syntax as defined by https://datatracker.ietf.org/doc/html/rfc8259#section-6
private static final Pattern VALID_JSON_NUMBER_PATTERN =
Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?");
/*
* From RFC 8259, "All Unicode characters may be placed within the
* quotation marks except for the characters that must be escaped:
* quotation mark, reverse solidus, and the control characters
* (U+0000 through U+001F)."
*
* We also escape '\u2028' and '\u2029', which JavaScript interprets as
* newline characters. This prevents eval() from failing with a syntax
* error. http://code.google.com/p/google-gson/issues/detail?id=341
*/
private static final String[] REPLACEMENT_CHARS;
private static final String[] HTML_SAFE_REPLACEMENT_CHARS;
static {
REPLACEMENT_CHARS = new String[128];
for (int i = 0; i <= 0x1f; i++) {
REPLACEMENT_CHARS[i] = String.format("\\u%04x", i);
}
REPLACEMENT_CHARS['"'] = "\\\"";
REPLACEMENT_CHARS['\\'] = "\\\\";
REPLACEMENT_CHARS['\t'] = "\\t";
REPLACEMENT_CHARS['\b'] = "\\b";
REPLACEMENT_CHARS['\n'] = "\\n";
REPLACEMENT_CHARS['\r'] = "\\r";
REPLACEMENT_CHARS['\f'] = "\\f";
HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone();
HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c";
HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e";
HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026";
HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d";
HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027";
}
/** The JSON output destination */
private final Writer out;
private int[] stack = new int[32];
private int stackSize = 0;
{
push(EMPTY_DOCUMENT);
}
private FormattingStyle formattingStyle;
// These fields cache data derived from the formatting style, to avoid having to
// re-evaluate it every time something is written
private String formattedColon;
private String formattedComma;
private boolean usesEmptyNewlineAndIndent;
private Strictness strictness = Strictness.LEGACY_STRICT;
private boolean htmlSafe;
private String deferredName;
private boolean serializeNulls = true;
/**
* Creates a new instance that writes a JSON-encoded stream to {@code out}. For best performance,
* ensure {@link Writer} is buffered; wrapping in {@link java.io.BufferedWriter BufferedWriter} if
* necessary.
*/
public JsonWriter(Writer out) {
this.out = Objects.requireNonNull(out, "out == null");
setFormattingStyle(FormattingStyle.COMPACT);
}
/**
* Sets the indentation string to be repeated for each level of indentation in the encoded
* document. If {@code indent.isEmpty()} the encoded document will be compact. Otherwise the
* encoded document will be more human-readable.
*
* <p>This is a convenience method which overwrites any previously {@linkplain
* #setFormattingStyle(FormattingStyle) set formatting style} with either {@link
* FormattingStyle#COMPACT} if the given indent string is empty, or {@link FormattingStyle#PRETTY}
* with the given indent if not empty.
*
* @param indent a string containing only whitespace.
*/
public final void setIndent(String indent) {
if (indent.isEmpty()) {
setFormattingStyle(FormattingStyle.COMPACT);
} else {
setFormattingStyle(FormattingStyle.PRETTY.withIndent(indent));
}
}
/**
* Sets the formatting style to be used in the encoded document.
*
* <p>The formatting style specifies for example the indentation string to be repeated for each
* level of indentation, or the newline style, to accommodate various OS styles.
*
* @param formattingStyle the formatting style to use, must not be {@code null}.
* @see #getFormattingStyle()
* @since 2.11.0
*/
public final void setFormattingStyle(FormattingStyle formattingStyle) {
this.formattingStyle = Objects.requireNonNull(formattingStyle);
this.formattedComma = ",";
if (this.formattingStyle.usesSpaceAfterSeparators()) {
this.formattedColon = ": ";
// Only add space if no newline is written
if (this.formattingStyle.getNewline().isEmpty()) {
this.formattedComma = ", ";
}
} else {
this.formattedColon = ":";
}
this.usesEmptyNewlineAndIndent =
this.formattingStyle.getNewline().isEmpty() && this.formattingStyle.getIndent().isEmpty();
}
/**
* Returns the pretty printing style used by this writer.
*
* @return the {@code FormattingStyle} that will be used.
* @see #setFormattingStyle(FormattingStyle)
* @since 2.11.0
*/
public final FormattingStyle getFormattingStyle() {
return formattingStyle;
}
/**
* Sets the strictness of this writer.
*
* @deprecated Please use {@link #setStrictness(Strictness)} instead. {@code
* JsonWriter.setLenient(true)} should be replaced by {@code
* JsonWriter.setStrictness(Strictness.LENIENT)} and {@code JsonWriter.setLenient(false)}
* should be replaced by {@code JsonWriter.setStrictness(Strictness.LEGACY_STRICT)}.<br>
* However, if you used {@code setLenient(false)} before, you might prefer {@link
* Strictness#STRICT} now instead.
* @param lenient whether this writer should be lenient. If true, the strictness is set to {@link
* Strictness#LENIENT}. If false, the strictness is set to {@link Strictness#LEGACY_STRICT}.
* @see #setStrictness(Strictness)
*/
@Deprecated
// Don't specify @InlineMe, so caller with `setLenient(false)` becomes aware of new
// Strictness.STRICT
@SuppressWarnings("InlineMeSuggester")
public final void setLenient(boolean lenient) {
setStrictness(lenient ? Strictness.LENIENT : Strictness.LEGACY_STRICT);
}
/**
* Returns true if the {@link Strictness} of this writer is equal to {@link Strictness#LENIENT}.
*
* @see #getStrictness()
*/
public boolean isLenient() {
return strictness == Strictness.LENIENT;
}
/**
* Configures how strict this writer is with regard to the syntax rules specified in <a
* href="https://www.ietf.org/rfc/rfc8259.txt">RFC 8259</a>. By default, {@link
* Strictness#LEGACY_STRICT} is used.
*
* <dl>
* <dt>{@link Strictness#STRICT} & {@link Strictness#LEGACY_STRICT}
* <dd>The behavior of these is currently identical. In these strictness modes, the writer only
* writes JSON in accordance with RFC 8259.
* <dt>{@link Strictness#LENIENT}
* <dd>This mode relaxes the behavior of the writer to allow the writing of {@link
* Double#isNaN() NaNs} and {@link Double#isInfinite() infinities}. It also allows writing
* multiple top level values.
* </dl>
*
* @param strictness the new strictness of this writer. May not be {@code null}.
* @see #getStrictness()
* @since 2.11.0
*/
public final void setStrictness(Strictness strictness) {
this.strictness = Objects.requireNonNull(strictness);
}
/**
* Returns the {@linkplain Strictness strictness} of this writer.
*
* @see #setStrictness(Strictness)
* @since 2.11.0
*/
public final Strictness getStrictness() {
return strictness;
}
/**
* Configures this writer to emit JSON that's safe for direct inclusion in HTML and XML documents.
* This escapes the HTML characters {@code <}, {@code >}, {@code &}, {@code =} and {@code '}
* before writing them to the stream. Without this setting, your XML/HTML encoder should replace
* these characters with the corresponding escape sequences.
*
* @see #isHtmlSafe()
*/
public final void setHtmlSafe(boolean htmlSafe) {
this.htmlSafe = htmlSafe;
}
/**
* Returns true if this writer writes JSON that's safe for inclusion in HTML and XML documents.
*
* @see #setHtmlSafe(boolean)
*/
public final boolean isHtmlSafe() {
return htmlSafe;
}
/**
* Sets whether object members are serialized when their value is null. This has no impact on
* array elements. The default is true.
*
* @see #getSerializeNulls()
*/
public final void setSerializeNulls(boolean serializeNulls) {
this.serializeNulls = serializeNulls;
}
/**
* Returns true if object members are serialized when their value is null. This has no impact on
* array elements. The default is true.
*
* @see #setSerializeNulls(boolean)
*/
public final boolean getSerializeNulls() {
return serializeNulls;
}
/**
* Begins encoding a new array. Each call to this method must be paired with a call to {@link
* #endArray}.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter beginArray() throws IOException {
writeDeferredName();
return openScope(EMPTY_ARRAY, '[');
}
/**
* Ends encoding the current array.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter endArray() throws IOException {
return closeScope(EMPTY_ARRAY, NONEMPTY_ARRAY, ']');
}
/**
* Begins encoding a new object. Each call to this method must be paired with a call to {@link
* #endObject}.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter beginObject() throws IOException {
writeDeferredName();
return openScope(EMPTY_OBJECT, '{');
}
/**
* Ends encoding the current object.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter endObject() throws IOException {
return closeScope(EMPTY_OBJECT, NONEMPTY_OBJECT, '}');
}
/** Enters a new scope by appending any necessary whitespace and the given bracket. */
@CanIgnoreReturnValue
private JsonWriter openScope(int empty, char openBracket) throws IOException {
beforeValue();
push(empty);
out.write(openBracket);
return this;
}
/** Closes the current scope by appending any necessary whitespace and the given bracket. */
@CanIgnoreReturnValue
private JsonWriter closeScope(int empty, int nonempty, char closeBracket) throws IOException {
int context = peek();
if (context != nonempty && context != empty) {
throw new IllegalStateException("Nesting problem.");
}
if (deferredName != null) {
throw new IllegalStateException("Dangling name: " + deferredName);
}
stackSize--;
if (context == nonempty) {
newline();
}
out.write(closeBracket);
return this;
}
private void push(int newTop) {
if (stackSize == stack.length) {
stack = Arrays.copyOf(stack, stackSize * 2);
}
stack[stackSize++] = newTop;
}
/** Returns the value on the top of the stack. */
private int peek() {
if (stackSize == 0) {
throw new IllegalStateException("JsonWriter is closed.");
}
return stack[stackSize - 1];
}
/** Replace the value on the top of the stack with the given value. */
private void replaceTop(int topOfStack) {
stack[stackSize - 1] = topOfStack;
}
/**
* Encodes the property name.
*
* @param name the name of the forthcoming value. May not be {@code null}.
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter name(String name) throws IOException {
Objects.requireNonNull(name, "name == null");
if (deferredName != null) {
throw new IllegalStateException("Already wrote a name, expecting a value.");
}
int context = peek();
if (context != EMPTY_OBJECT && context != NONEMPTY_OBJECT) {
throw new IllegalStateException("Please begin an object before writing a name.");
}
deferredName = name;
return this;
}
private void writeDeferredName() throws IOException {
if (deferredName != null) {
beforeName();
string(deferredName);
deferredName = null;
}
}
/**
* Encodes {@code value}.
*
* @param value the literal string value, or null to encode a null literal.
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter value(String value) throws IOException {
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue();
string(value);
return this;
}
/**
* Encodes {@code value}.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter value(boolean value) throws IOException {
writeDeferredName();
beforeValue();
out.write(value ? "true" : "false");
return this;
}
/**
* Encodes {@code value}.
*
* @return this writer.
* @since 2.7
*/
@CanIgnoreReturnValue
public JsonWriter value(Boolean value) throws IOException {
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue();
out.write(value ? "true" : "false");
return this;
}
/**
* Encodes {@code value}.
*
* @param value a finite value, or if {@link #setStrictness(Strictness) lenient}, also {@link
* Float#isNaN() NaN} or {@link Float#isInfinite() infinity}.
* @return this writer.
* @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link
* #setStrictness(Strictness) lenient}.
* @since 2.9.1
*/
@CanIgnoreReturnValue
public JsonWriter value(float value) throws IOException {
writeDeferredName();
if (strictness != Strictness.LENIENT && (Float.isNaN(value) || Float.isInfinite(value))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue();
out.append(Float.toString(value));
return this;
}
/**
* Encodes {@code value}.
*
* @param value a finite value, or if {@link #setStrictness(Strictness) lenient}, also {@link
* Double#isNaN() NaN} or {@link Double#isInfinite() infinity}.
* @return this writer.
* @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link
* #setStrictness(Strictness) lenient}.
*/
@CanIgnoreReturnValue
public JsonWriter value(double value) throws IOException {
writeDeferredName();
if (strictness != Strictness.LENIENT && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue();
out.append(Double.toString(value));
return this;
}
/**
* Encodes {@code value}.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter value(long value) throws IOException {
writeDeferredName();
beforeValue();
out.write(Long.toString(value));
return this;
}
/**
* Encodes {@code value}. The value is written by directly writing the {@link Number#toString()}
* result to JSON. Implementations must make sure that the result represents a valid JSON number.
*
* @param value a finite value, or if {@link #setStrictness(Strictness) lenient}, also {@link
* Double#isNaN() NaN} or {@link Double#isInfinite() infinity}.
* @return this writer.
* @throws IllegalArgumentException if the value is NaN or Infinity and this writer is not {@link
* #setStrictness(Strictness) lenient}; or if the {@code toString()} result is not a valid
* JSON number.
*/
@CanIgnoreReturnValue
public JsonWriter value(Number value) throws IOException {
if (value == null) {
return nullValue();
}
writeDeferredName();
String string = value.toString();
Class<? extends Number> numberClass = value.getClass();
if (!alwaysCreatesValidJsonNumber(numberClass)) {
// Validate that string is valid before writing it directly to JSON output
if (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN")) {
if (strictness != Strictness.LENIENT) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + string);
}
} else if (numberClass != Float.class
&& numberClass != Double.class
&& !VALID_JSON_NUMBER_PATTERN.matcher(string).matches()) {
throw new IllegalArgumentException(
"String created by " + numberClass + " is not a valid JSON number: " + string);
}
}
beforeValue();
out.append(string);
return this;
}
/**
* Encodes {@code null}.
*
* @return this writer.
*/
@CanIgnoreReturnValue
public JsonWriter nullValue() throws IOException {
if (deferredName != null) {
if (serializeNulls) {
writeDeferredName();
} else {
deferredName = null;
return this; // skip the name and the value
}
}
beforeValue();
out.write("null");
return this;
}
/**
* Writes {@code value} directly to the writer without quoting or escaping. This might not be
* supported by all implementations, if not supported an {@code UnsupportedOperationException} is
* thrown.
*
* @param value the literal string value, or null to encode a null literal.
* @return this writer.
* @throws UnsupportedOperationException if this writer does not support writing raw JSON values.
* @since 2.4
*/
@CanIgnoreReturnValue
public JsonWriter jsonValue(String value) throws IOException {
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue();
out.append(value);
return this;
}
/**
* Ensures all buffered data is written to the underlying {@link Writer} and flushes that writer.
*/
@Override
public void flush() throws IOException {
if (stackSize == 0) {
throw new IllegalStateException("JsonWriter is closed.");
}
out.flush();
}
/**
* Flushes and closes this writer and the underlying {@link Writer}.
*
* @throws IOException if the JSON document is incomplete.
*/
@Override
public void close() throws IOException {
out.close();
int size = stackSize;
if (size > 1 || (size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT)) {
throw new IOException("Incomplete document");
}
stackSize = 0;
}
/** Returns whether the {@code toString()} of {@code c} will always return a valid JSON number. */
private static boolean alwaysCreatesValidJsonNumber(Class<? extends Number> c) {
// Does not include Float or Double because their value can be NaN or Infinity
// Does not include LazilyParsedNumber because it could contain a malformed string
return c == Integer.class
|| c == Long.class
|| c == Byte.class
|| c == Short.class
|| c == BigDecimal.class
|| c == BigInteger.class
|| c == AtomicInteger.class
|| c == AtomicLong.class;
}
private void string(String value) throws IOException {
String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
out.write('\"');
int last = 0;
int length = value.length();
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
String replacement;
if (c < 128) {
replacement = replacements[c];
if (replacement == null) {
continue;
}
} else if (c == '\u2028') {
replacement = "\\u2028";
} else if (c == '\u2029') {
replacement = "\\u2029";
} else {
continue;
}
if (last < i) {
out.write(value, last, i - last);
}
out.write(replacement);
last = i + 1;
}
if (last < length) {
out.write(value, last, length - last);
}
out.write('\"');
}
private void newline() throws IOException {
if (usesEmptyNewlineAndIndent) {
return;
}
out.write(formattingStyle.getNewline());
for (int i = 1, size = stackSize; i < size; i++) {
out.write(formattingStyle.getIndent());
}
}
/**
* Inserts any necessary separators and whitespace before a name. Also adjusts the stack to expect
* the name's value.
*/
private void beforeName() throws IOException {
int context = peek();
if (context == NONEMPTY_OBJECT) { // first in object
out.write(formattedComma);
} else if (context != EMPTY_OBJECT) { // not in an object!
throw new IllegalStateException("Nesting problem.");
}
newline();
replaceTop(DANGLING_NAME);
}
/**
* Inserts any necessary separators and whitespace before a literal value, inline array, or inline
* object. Also adjusts the stack to expect either a closing bracket or another element.
*/
@SuppressWarnings("fallthrough")
private void beforeValue() throws IOException {
switch (peek()) {
case NONEMPTY_DOCUMENT:
if (strictness != Strictness.LENIENT) {
throw new IllegalStateException("JSON must have only one top-level value.");
}
// fall-through
case EMPTY_DOCUMENT: // first in document
replaceTop(NONEMPTY_DOCUMENT);
break;
case EMPTY_ARRAY: // first in array
replaceTop(NONEMPTY_ARRAY);
newline();
break;
case NONEMPTY_ARRAY: // another in array
out.append(formattedComma);
newline();
break;
case DANGLING_NAME: // value for name
out.append(formattedColon);
replaceTop(NONEMPTY_OBJECT);
break;
default:
throw new IllegalStateException("Nesting problem.");
}
}
}
| JsonWriter |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/conditional/basic/ErroneousSourceParameterConditionalWithTargetTypeMapper.java | {
"start": 382,
"end": 713
} | interface ____ {
BasicEmployee map(BasicEmployeeDto employee);
@Condition(appliesTo = ConditionStrategy.SOURCE_PARAMETERS)
default boolean isNotBlank(String value, @TargetType Class<?> targetClass) {
return value != null && !value.trim().isEmpty();
}
}
| ErroneousSourceParameterConditionalWithTargetTypeMapper |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerStringConcatenationTest.java | {
"start": 5480,
"end": 5994
} | class ____ {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public void method(String hello, String world) {
logger.atInfo().log("message is %s %s", hello, world);
}
}
""")
.doTest();
}
@Test
public void negativeNoArgs() {
compilationHelper
.addSourceLines(
"in/Test.java",
"""
import com.google.common.flogger.FluentLogger;
| Test |
java | elastic__elasticsearch | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/IDGenerator.java | {
"start": 683,
"end": 3718
} | class ____ {
private static final byte[] NULL_VALUE = "__NULL_VALUE__".getBytes(StandardCharsets.UTF_8);
private static final byte[] EMPTY_VALUE = "__EMPTY_VALUE__".getBytes(StandardCharsets.UTF_8);
private static final byte DELIM = '$';
private static final long SEED = 19;
private static final int MAX_FIRST_BYTES = 5;
private final TreeMap<String, Object> objectsForIDGeneration = new TreeMap<>();
public IDGenerator() {}
/**
* Add a value to the generator
* @param key object identifier, to be used for consistent sorting
* @param value the value
*/
public void add(String key, Object value) {
if (objectsForIDGeneration.containsKey(key)) {
throw new IllegalArgumentException("Keys must be unique");
}
objectsForIDGeneration.put(key, value);
}
/**
* Create a document id based on the input objects
*
* @return a document id as string
*/
public String getID() {
if (objectsForIDGeneration.size() == 0) {
throw new RuntimeException("Add at least 1 object before generating the ID");
}
BytesRefBuilder buffer = new BytesRefBuilder();
BytesRefBuilder hashedBytes = new BytesRefBuilder();
for (Object value : objectsForIDGeneration.values()) {
byte[] v = getBytes(value);
if (v.length == 0) {
v = EMPTY_VALUE;
}
buffer.append(v, 0, v.length);
buffer.append(DELIM);
// keep the 1st byte of every object
if (hashedBytes.length() <= MAX_FIRST_BYTES) {
hashedBytes.append(v[0]);
}
}
MurmurHash3.Hash128 hasher = MurmurHash3.hash128(buffer.bytes(), 0, buffer.length(), SEED, new MurmurHash3.Hash128());
hashedBytes.append(Numbers.longToBytes(hasher.h1), 0, 8);
hashedBytes.append(Numbers.longToBytes(hasher.h2), 0, 8);
return Strings.BASE_64_NO_PADDING_URL_ENCODER.encodeToString(hashedBytes.bytes());
}
/**
* Turns objects into byte arrays, only supporting types returned groupBy
*
* @param value the value as object
* @return a byte representation of the input object
*/
private static byte[] getBytes(Object value) {
if (value == null) {
return NULL_VALUE;
} else if (value instanceof String) {
return ((String) value).getBytes(StandardCharsets.UTF_8);
} else if (value instanceof Long) {
return Numbers.longToBytes((Long) value);
} else if (value instanceof Double) {
return Numbers.doubleToBytes((Double) value);
} else if (value instanceof Integer) {
return Numbers.intToBytes((Integer) value);
} else if (value instanceof Boolean) {
return new byte[] { (Boolean) value ? (byte) 1 : (byte) 0 };
}
throw new IllegalArgumentException("Value of type [" + value.getClass() + "] is not supported");
}
}
| IDGenerator |
java | quarkusio__quarkus | test-framework/security-jwt/src/main/java/io/quarkus/test/security/jwt/JwtTestSecurityIdentityAugmentorProducer.java | {
"start": 261,
"end": 458
} | class ____ {
@Produces
@Unremovable
public TestSecurityIdentityAugmentor produce() {
return new JwtTestSecurityIdentityAugmentor();
}
}
| JwtTestSecurityIdentityAugmentorProducer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/JUnit3TestNotRunTest.java | {
"start": 941,
"end": 1632
} | class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(JUnit3TestNotRun.class, getClass());
private final BugCheckerRefactoringTestHelper refactorHelper =
BugCheckerRefactoringTestHelper.newInstance(JUnit3TestNotRun.class, getClass());
@Test
public void positiveCases() {
compilationHelper
.addSourceLines(
"JUnit3TestNotRunPositiveCases.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import junit.framework.TestCase;
/**
* @author rburny@google.com (Radoslaw Burny)
*/
public | JUnit3TestNotRunTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/InvalidJavaTimeConstantTest.java | {
"start": 1380,
"end": 2047
} | class ____ {
// BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): 0
private static final LocalDateTime LDT0 = LocalDateTime.of(0, 0, 0, 0, 0);
private static final LocalDateTime LDT1 = LocalDateTime.of(0, 1, 1, 0, 0);
private static final LocalTime LT = LocalTime.ofNanoOfDay(12345678);
}
""")
.doTest();
}
@Test
public void localDate_areOk() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"package test;",
"import java.time.LocalDate;",
"import java.time.Month;",
"public | TestCase |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchGeneratedAssociationTest.java | {
"start": 1264,
"end": 2082
} | class ____ {
@Test
public void test(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final Long interpretationVersion = 111L;
final Interpretation interpretation = new Interpretation();
interpretation.uuid = 1L;
final InterpretationData interpretationData = new InterpretationData();
interpretationData.interpretationVersion = new InterpretationVersion(
interpretationVersion,
interpretation.uuid
);
interpretationData.name = "TEST_NAME";
session.persist( interpretationData );
interpretation.interpretationData = interpretationData;
interpretation.interpretationVersion = interpretationVersion;
session.persist( interpretation );
} );
}
@Entity( name = "Interpretation" )
@Table( name = "interpretations" )
public static | BatchGeneratedAssociationTest |
java | apache__flink | flink-table/flink-table-code-splitter/src/test/resources/declaration/expected/TestRewriteLocalVariableInForLoop2.java | {
"start": 7,
"end": 251
} | class ____ {
int sum;
int local$0;
public void myFun(int[] arr) {
sum = 0;
for (int item : arr) {local$0 = item;
sum += local$0;
}
System.out.println(sum);
}
}
| TestRewriteLocalVariableInForLoop2 |
java | quarkusio__quarkus | extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/binder/mpmetrics/CountedInterceptor.java | {
"start": 479,
"end": 1645
} | class ____ {
// Micrometer meter registry
final MetricRegistryAdapter mpRegistry;
CountedInterceptor(MetricRegistryAdapter mpRegistry) {
this.mpRegistry = mpRegistry;
}
@AroundConstruct
Object countedConstructor(ArcInvocationContext context) throws Exception {
return increment(context, context.getConstructor().getDeclaringClass().getSimpleName());
}
@AroundInvoke
Object countedMethod(ArcInvocationContext context) throws Exception {
return increment(context, context.getMethod().getName());
}
Object increment(ArcInvocationContext context, String methodName) throws Exception {
Counted annotation = context.findIterceptorBinding(Counted.class);
if (annotation != null) {
MpMetadata metadata = new MpMetadata(annotation.name().replace("<method>", methodName),
annotation.description().replace("<method>", methodName),
annotation.unit(),
MetricType.COUNTER);
mpRegistry.interceptorCounter(metadata, annotation.tags()).inc();
}
return context.proceed();
}
}
| CountedInterceptor |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/AbstractBeanResolutionContext.java | {
"start": 40322,
"end": 41754
} | class ____<B, T> extends AbstractSegment<B, T> implements CallableInjectionPoint<B> {
/**
* @param declaringClass The declaring class
* @param eventType The argument
*/
EventListenerSegment(
BeanDefinition<B> declaringClass,
Argument<T> eventType) {
super(declaringClass, null, eventType.getName(), eventType);
}
@Override
public String toConsoleString(boolean ansiSupported) {
if (ansiSupported) {
String event = getArgument().getTypeString(TypeFormat.ANSI_SIMPLE);
return event + " ➡️ " +
getDeclaringBean().getBeanDescription(TypeFormat.ANSI_SHORTENED);
} else {
String event = getArgument().getTypeString(TypeFormat.SIMPLE);
return event + " -> " +
getDeclaringBean().getBeanDescription(TypeFormat.SHORTENED);
}
}
@Override
public InjectionPoint<B> getInjectionPoint() {
return this;
}
@Override
public Argument<?>[] getArguments() {
return new Argument[]{getArgument()};
}
@Override
public BeanDefinition<B> getDeclaringBean() {
return getDeclaringType();
}
}
/**
* A segment that represents a method.
*/
public static | EventListenerSegment |
java | quarkusio__quarkus | extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/validation/MyLazyChildEntity.java | {
"start": 416,
"end": 1477
} | interface ____ {
}
public static final String ENTITY_NAME_TOO_LONG = "entity name too long";
private long id;
// Use a non-default validation group so that validation won't trigger an exception on persist:
@Size(max = 5, message = ENTITY_NAME_TOO_LONG, groups = { SomeGroup.class })
private String name;
private MyLazyEntity parent;
public MyLazyChildEntity() {
}
public MyLazyChildEntity(String name) {
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
public MyLazyEntity getParent() {
return parent;
}
public void setParent(MyLazyEntity parent) {
this.parent = parent;
}
@Override
public String toString() {
return "MyLazyChildEntity:" + name;
}
}
| SomeGroup |
java | apache__camel | components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/consumer/integration/configmaps/KubernetesConfigMapsConsumerResourceNameIT.java | {
"start": 1611,
"end": 2498
} | class ____ extends KubernetesConsumerTestSupport {
@Test
public void resourceNameTest() throws Exception {
result.expectedBodiesReceived("ConfigMap " + WATCH_RESOURCE_NAME + " " + ns2 + " ADDED");
createConfigMap(ns1, WATCH_RESOURCE_NAME, null);
createConfigMap(ns2, WATCH_RESOURCE_NAME, null);
result.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
fromF("kubernetes-config-maps://%s?oauthToken=%s&resourceName=%s&namespace=%s", host, authToken,
WATCH_RESOURCE_NAME,
ns2)
.process(new KubernetesProcessor())
.to(result);
}
};
}
}
| KubernetesConfigMapsConsumerResourceNameIT |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RGeoRx.java | {
"start": 893,
"end": 15039
} | interface ____<V> extends RScoredSortedSetRx<V> {
/**
* Adds geospatial member.
*
* @param longitude - longitude of object
* @param latitude - latitude of object
* @param member - object itself
* @return number of elements added to the sorted set,
* not including elements already existing for which
* the score was updated
*/
Single<Long> add(double longitude, double latitude, V member);
/**
* Adds geospatial members.
*
* @param entries - objects
* @return number of elements added to the sorted set,
* not including elements already existing for which
* the score was updated
*/
Single<Long> add(GeoEntry... entries);
/**
* Adds geospatial member only if it's already exists.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param longitude - longitude of object
* @param latitude - latitude of object
* @param member - object itself
* @return number of elements added to the sorted set
*/
Single<Long> addIfExists(double longitude, double latitude, V member);
/**
* Adds geospatial members only if it's already exists.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param entries - objects
* @return number of elements added to the sorted set
*/
Single<Long> addIfExists(GeoEntry... entries);
/**
* Adds geospatial member only if has not been added before.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param longitude - longitude of object
* @param latitude - latitude of object
* @param member - object itself
* @return number of elements added to the sorted set
*/
Single<Boolean> tryAdd(double longitude, double latitude, V member);
/**
* Adds geospatial members only if has not been added before.
* <p>
* Requires <b>Redis 6.2.0 and higher.</b>
*
* @param entries - objects
* @return number of elements added to the sorted set
*/
Single<Long> tryAdd(GeoEntry... entries);
/**
* Returns distance between members in <code>GeoUnit</code> units.
*
* @param firstMember - first object
* @param secondMember - second object
* @param geoUnit - geo unit
* @return distance
*/
Single<Double> dist(V firstMember, V secondMember, GeoUnit geoUnit);
/**
* Returns 11 characters Geohash string mapped by defined member.
*
* @param members - objects
* @return hash mapped by object
*/
Single<Map<V, String>> hash(V... members);
/**
* Returns geo-position mapped by defined member.
*
* @param members - objects
* @return geo position mapped by object
*/
Single<Map<V, GeoPosition>> pos(V... members);
/**
* Returns the members of a sorted set, which are within the
* borders of specified search conditions.
* <p>
* Usage examples:
* <pre>
* List objects = geo.search(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* List objects = geo.search(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
* <p>
* Requires <b>Redis 3.2.10 and higher.</b>
*
* @param args - search conditions object
* @return list of memebers
*/
Single<List<V>> search(GeoSearchArgs args);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Returns the distance mapped by member of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Usage examples:
* <pre>
* Map objects = geo.searchWithDistance(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* Map objects = geo.searchWithDistance(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
* <p>
* Requires <b>Redis 3.2.10 and higher.</b>
*
* @param args - search conditions object
* @return distance mapped by object
*/
Single<Map<V, Double>> searchWithDistance(GeoSearchArgs args);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Returns the position mapped by member of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Usage examples:
* <pre>
* Map objects = geo.searchWithPosition(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* Map objects = geo.searchWithPosition(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
* <p>
* Requires <b>Redis 3.2.10 and higher.</b>
*
* @param args - search conditions object
* @return position mapped by object
*/
Single<Map<V, GeoPosition>> searchWithPosition(GeoSearchArgs args);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(V member, double radius, GeoUnit geoUnit);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(V member, double radius, GeoUnit geoUnit, int count);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use search() method instead
*
*/
@Deprecated
Single<List<V>> radius(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithDistance() method instead
*
*/
@Deprecated
Single<Map<V, Double>> radiusWithDistance(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit, int count);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder);
/*
* Use searchWithPosition() method instead
*
*/
@Deprecated
Single<Map<V, GeoPosition>> radiusWithPosition(V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Finds the members of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Stores result to <code>destName</code>.
* <p>
* Usage examples:
* <pre>
* long count = geo.storeSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* long count = geo.storeSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
*
* @param args - search conditions object
* @return length of result
*/
Single<Long> storeSearchTo(String destName, GeoSearchArgs args);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreTo(String destName, V member, double radius, GeoUnit geoUnit);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreTo(String destName, V member, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreTo(String destName, V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/**
* Finds the members of a sorted set,
* which are within the borders of specified search conditions.
* <p>
* Stores result to <code>destName</code> sorted by distance.
* <p>
* Usage examples:
* <pre>
* long count = geo.storeSortedSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)
* .order(GeoOrder.ASC)
* .count(1)));
* </pre>
* <pre>
* long count = geo.storeSortedSearchTo(GeoSearchArgs.from(15, 37)
* .radius(200, GeoUnit.KILOMETERS)));
* </pre>
*
* @param args - search conditions object
* @return length of result
*/
RFuture<Long> storeSortedSearchTo(String destName, GeoSearchArgs args);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreSortedTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreSortedTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreSortedTo(String destName, double longitude, double latitude, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreSortedTo(String destName, V member, double radius, GeoUnit geoUnit);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreSortedTo(String destName, V member, double radius, GeoUnit geoUnit, int count);
/*
* Use storeSortedSearchTo() method instead
*
*/
@Deprecated
Single<Long> radiusStoreSortedTo(String destName, V member, double radius, GeoUnit geoUnit, GeoOrder geoOrder, int count);
}
| RGeoRx |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/issues/AdviceWithWeaveByTypeCBRTest.java | {
"start": 1118,
"end": 2131
} | class ____ extends ContextTestSupport {
@Test
public void testWeaveByType() throws Exception {
AdviceWith.adviceWith(context.getRouteDefinitions().get(0), context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
weaveByType(ChoiceDefinition.class).replace().to("mock:baz");
}
});
getMockEndpoint("mock:baz").expectedMessageCount(1);
template.sendBody("direct:start", "World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").transform(simple("Hello ${body}")).log("Got ${body}").to("mock:result").choice()
.when(header("foo").isEqualTo("bar")).to("mock:resultA")
.otherwise().to("mock:resultB");
}
};
}
}
| AdviceWithWeaveByTypeCBRTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/test/java/org/apache/hadoop/yarn/service/component/TestComponentDecommissionInstances.java | {
"start": 2003,
"end": 5624
} | class ____ extends ServiceTestUtils {
private static final Logger LOG =
LoggerFactory.getLogger(TestComponentDecommissionInstances.class);
private static final String APP_NAME = "test-decommission";
private static final String COMPA = "compa";
@BeforeEach
public void setup() throws Exception {
File tmpYarnDir = new File("target", "tmp");
FileUtils.deleteQuietly(tmpYarnDir);
}
@AfterEach
public void tearDown() throws IOException {
shutdown();
}
@Test
public void testDecommissionInstances() throws Exception {
setupInternal(3);
ServiceClient client = createClient(getConf());
Service exampleApp = new Service();
exampleApp.setName(APP_NAME);
exampleApp.setVersion("v1");
Component comp = createComponent(COMPA, 6L, "sleep 1000");
exampleApp.addComponent(comp);
client.actionCreate(exampleApp);
waitForServiceToBeStable(client, exampleApp);
checkInstances(client, COMPA + "-0", COMPA + "-1", COMPA + "-2",
COMPA + "-3", COMPA + "-4", COMPA + "-5");
client.actionDecommissionInstances(APP_NAME, Arrays.asList(COMPA + "-1",
COMPA + "-5"));
waitForNumInstances(client, 4);
checkInstances(client, COMPA + "-0", COMPA + "-2", COMPA + "-3",
COMPA + "-4");
// Stop and start service
client.actionStop(APP_NAME);
waitForServiceToBeInState(client, exampleApp, ServiceState.STOPPED);
client.actionStart(APP_NAME);
waitForServiceToBeStable(client, exampleApp);
checkInstances(client, COMPA + "-0", COMPA + "-2", COMPA + "-3",
COMPA + "-4");
Map<String, String> compCounts = new HashMap<>();
compCounts.put(COMPA, "5");
client.actionFlex(APP_NAME, compCounts);
waitForNumInstances(client, 5);
checkInstances(client, COMPA + "-0", COMPA + "-2", COMPA + "-3",
COMPA + "-4", COMPA + "-6");
client.actionDecommissionInstances(APP_NAME, Arrays.asList(COMPA + "-0."
+ APP_NAME + "." + RegistryUtils.currentUser()));
waitForNumInstances(client, 4);
checkInstances(client, COMPA + "-2", COMPA + "-3",
COMPA + "-4", COMPA + "-6");
}
private static void waitForNumInstances(ServiceClient client, int
expectedInstances) throws TimeoutException, InterruptedException {
GenericTestUtils.waitFor(() -> {
try {
Service retrievedApp = client.getStatus(APP_NAME);
return retrievedApp.getComponent(COMPA).getContainers().size() ==
expectedInstances && retrievedApp.getState() == ServiceState.STABLE;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}, 2000, 200000);
}
private static void checkInstances(ServiceClient client, String... instances)
throws IOException, YarnException {
Service service = client.getStatus(APP_NAME);
Component component = service.getComponent(COMPA);
assertEquals(ServiceState.STABLE,
service.getState(), "Service state should be STABLE");
assertEquals(instances.length, component.getContainers().size(),
instances.length + " containers are expected to be running");
Set<String> existingInstances = new HashSet<>();
for (Container cont : component.getContainers()) {
existingInstances.add(cont.getComponentInstanceName());
}
assertEquals(instances.length, existingInstances.size(),
instances.length + " instances are expected to be running");
for (String instance : instances) {
assertTrue(existingInstances.contains(instance),
"Expected instance did not exist " + instance);
}
}
}
| TestComponentDecommissionInstances |
java | spring-projects__spring-boot | core/spring-boot-test/src/main/java/org/springframework/boot/test/system/OutputCaptureExtension.java | {
"start": 1870,
"end": 2002
} | class ____, test method, or lifecycle methods:
*
* <pre class="code">
* @ExtendWith(OutputCaptureExtension.class)
* | constructor |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DynamicRouterComponentBuilderFactory.java | {
"start": 2072,
"end": 4202
} | interface ____ extends ComponentBuilder<DynamicRouterComponent> {
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default DynamicRouterComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default DynamicRouterComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
}
| DynamicRouterComponentBuilder |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/read/NextNameWithMatcherTest.java | {
"start": 369,
"end": 5270
} | class ____
extends JacksonCoreTestBase
{
private final JsonFactory JSON_F = new JsonFactory();
private final List<String> NAMES_1 = Arrays.asList("enabled", "a", "longerName", "otherStuff3");
private final List<String> NAMES_1_CASE_MISMATCH = Arrays.asList("ENABLED", "A", "LongerName", "otherStuff3");
private final List<Named> NAMED_LIST_1 = namedFromStrings(NAMES_1);
private final PropertyNameMatcher MATCHER_CS_1 = JSON_F.constructNameMatcher(NAMED_LIST_1, true);
private final PropertyNameMatcher MATCHER_CI_1 = JSON_F.constructCINameMatcher(NAMED_LIST_1, true,
new Locale("en", "US"));
private final String DOC_1 = a2q(
"{ 'a' : 4, 'enabled' : true, 'longerName' : 'Billy-Bob Burger', 'extra' : [ 0], 'otherStuff3' : 0.25 }"
);
private final String DOC_1_CASE_MISMATCH = a2q(
"{ 'A' : 4, 'ENABLED' : true, 'LongerName' : 'Billy-Bob Burger', 'extra' : [0 ], 'otherStuff3' : 0.25 }");
public void testSimpleCaseSensitive() throws Exception
{
_testSimpleCaseSensitive(MODE_INPUT_STREAM);
_testSimpleCaseSensitive(MODE_INPUT_STREAM_THROTTLED);
_testSimpleCaseSensitive(MODE_DATA_INPUT);
_testSimpleCaseSensitive(MODE_READER);
}
private void _testSimpleCaseSensitive(int mode) throws Exception
{
_verifyDoc1(createParser(mode, DOC_1), MATCHER_CS_1, NAMES_1);
}
public void testSimpleCaseInsensitive() throws Exception
{
_testSimpleCaseInsensitive(MODE_INPUT_STREAM);
_testSimpleCaseInsensitive(MODE_INPUT_STREAM_THROTTLED);
_testSimpleCaseInsensitive(MODE_DATA_INPUT);
_testSimpleCaseInsensitive(MODE_READER);
}
public void _testSimpleCaseInsensitive(int mode) throws Exception
{
// First, should still pass regular case-matching doc
_verifyDoc1(createParser(mode, DOC_1), MATCHER_CI_1, NAMES_1);
// but then mis-cased one too:
_verifyDoc1(createParser(mode, DOC_1_CASE_MISMATCH), MATCHER_CI_1, NAMES_1_CASE_MISMATCH);
}
private void _verifyDoc1(JsonParser p, PropertyNameMatcher matcher,
List<String> names) throws Exception
{
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.START_OBJECT, p.currentToken());
assertEquals(1, p.nextNameMatch(matcher)); // ("enabled", "a", "longerName", "otherStuff3")
assertEquals(names.get(1), p.currentName());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.VALUE_NUMBER_INT, p.currentToken());
assertEquals(4, p.getIntValue());
assertEquals(0, p.nextNameMatch(matcher)); // ("enabled", "a", "longerName", "otherStuff3")
assertEquals(names.get(0), p.currentName());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.VALUE_TRUE, p.currentToken());
assertEquals(2, p.nextNameMatch(matcher)); // ("enabled", "a", "longerName", "otherStuff3")
assertEquals(names.get(2), p.currentName());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.VALUE_STRING, p.currentToken());
assertEquals("Billy-Bob Burger", p.getString());
assertEquals(PropertyNameMatcher.MATCH_UNKNOWN_NAME, p.nextNameMatch(matcher));
assertEquals("extra", p.currentName());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.START_ARRAY, p.currentToken());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.VALUE_NUMBER_INT, p.currentToken());
assertEquals(0, p.getIntValue());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.END_ARRAY, p.currentToken());
assertEquals(3, p.nextNameMatch(matcher)); // ("enabled", "a", "longerName", "otherStuff3")
assertEquals(names.get(3), p.currentName());
assertEquals(PropertyNameMatcher.MATCH_ODD_TOKEN, p.nextNameMatch(matcher));
assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.currentToken());
assertEquals(0.25, p.getDoubleValue());
assertEquals(PropertyNameMatcher.MATCH_END_OBJECT, p.nextNameMatch(matcher));
assertToken(JsonToken.END_OBJECT, p.currentToken());
p.close();
}
static List<Named> namedFromStrings(Collection<String> input) {
ArrayList<Named> result = new ArrayList<>(input.size());
for (String str : input) {
result.add(Named.fromString(str));
}
return result;
}
static List<Named> namedFromStrings(String... input) {
return namedFromStrings(Arrays.asList(input));
}
}
| NextNameWithMatcherTest |
java | apache__camel | components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyServerBootstrapConfiguration.java | {
"start": 1314,
"end": 5786
} | class ____ implements Cloneable {
public static final String DEFAULT_ENABLED_PROTOCOLS = "TLSv1.2,TLSv1.3";
@UriPath(enums = "tcp,udp", description = "The protocol to use which can be tcp or udp")
@Metadata(required = true)
protected String protocol;
@UriPath
@Metadata(required = true,
description = "The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to.")
protected String host;
@UriPath
@Metadata(required = true, description = "The host port number")
protected int port;
@UriParam(label = "consumer,advanced", description = "Setting to choose Multicast over UDP")
protected boolean broadcast;
@UriParam(label = "advanced", defaultValue = "65536",
description = "The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes.")
protected int sendBufferSize = 65536;
@UriParam(label = "advanced", defaultValue = "65536",
description = "The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes.")
protected int receiveBufferSize = 65536;
@UriParam(label = "advanced",
description = "Configures the buffer size predictor. See details at Jetty documentation and this mail thread.")
protected int receiveBufferSizePredictor;
@UriParam(label = "consumer,advanced", defaultValue = "1",
description = "When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty")
protected int bossCount = 1;
@UriParam(label = "advanced",
description = "When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty.")
protected int workerCount;
@UriParam(defaultValue = "true", description = "Setting to ensure socket is not closed due to inactivity")
protected boolean keepAlive = true;
@UriParam(defaultValue = "true", description = "Setting to improve TCP protocol performance")
protected boolean tcpNoDelay = true;
@UriParam(defaultValue = "true", description = "Setting to facilitate socket multiplexing")
protected boolean reuseAddress = true;
@UriParam(label = "producer", defaultValue = "10000",
description = "Time to wait for a socket connection to be available. Value is in milliseconds.")
protected int connectTimeout = 10000;
@UriParam(label = "consumer,advanced",
description = "Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on"
+ " the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the \"accept\" queue"
+ " can be If this option is not configured, then the backlog depends on OS setting.")
protected int backlog;
@UriParam(label = "consumer,advanced", description = "To use a custom ServerInitializerFactory")
protected ServerInitializerFactory serverInitializerFactory;
@UriParam(label = "consumer,advanced", description = "To use a custom NettyServerBootstrapFactory")
protected NettyServerBootstrapFactory nettyServerBootstrapFactory;
@UriParam(label = "advanced", prefix = "option.", multiValue = true,
description = "Allows to configure additional netty options using option. as prefix."
+ " For example option.child.keepAlive=false. See the Netty documentation for possible options that can be used.")
protected Map<String, Object> options;
// SSL options is also part of the server bootstrap as the server listener on port X is either plain or SSL
@UriParam(label = "security", description = "Setting to specify whether SSL encryption is applied to this endpoint")
protected boolean ssl;
@UriParam(label = "security",
description = "When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having"
+ " information about the client certificate such as subject name, issuer name, serial number, and the valid date range.")
protected boolean sslClientCertHeaders;
@UriParam(label = "security", description = "Reference to a | NettyServerBootstrapConfiguration |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/cache/SerializedCacheTest.java | {
"start": 1999,
"end": 2525
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
int x;
public CachingObject(int x) {
this.x = x;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CachingObject obj = (CachingObject) o;
return x == obj.x;
}
@Override
public int hashCode() {
return Objects.hash(x);
}
}
static | CachingObject |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/TinyIntType.java | {
"start": 1158,
"end": 2782
} | class ____ extends LogicalType {
private static final long serialVersionUID = 1L;
public static final int PRECISION = 3;
private static final String FORMAT = "TINYINT";
private static final Set<String> NULL_OUTPUT_CONVERSION = conversionSet(Byte.class.getName());
private static final Set<String> NOT_NULL_INPUT_OUTPUT_CONVERSION =
conversionSet(Byte.class.getName(), byte.class.getName());
private static final Class<?> DEFAULT_CONVERSION = Byte.class;
public TinyIntType(boolean isNullable) {
super(isNullable, LogicalTypeRoot.TINYINT);
}
public TinyIntType() {
this(true);
}
@Override
public LogicalType copy(boolean isNullable) {
return new TinyIntType(isNullable);
}
@Override
public String asSerializableString() {
return withNullability(FORMAT);
}
@Override
public boolean supportsInputConversion(Class<?> clazz) {
return NOT_NULL_INPUT_OUTPUT_CONVERSION.contains(clazz.getName());
}
@Override
public boolean supportsOutputConversion(Class<?> clazz) {
if (isNullable()) {
return NULL_OUTPUT_CONVERSION.contains(clazz.getName());
}
return NOT_NULL_INPUT_OUTPUT_CONVERSION.contains(clazz.getName());
}
@Override
public Class<?> getDefaultConversion() {
return DEFAULT_CONVERSION;
}
@Override
public List<LogicalType> getChildren() {
return Collections.emptyList();
}
@Override
public <R> R accept(LogicalTypeVisitor<R> visitor) {
return visitor.visit(this);
}
}
| TinyIntType |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobView.java | {
"start": 999,
"end": 1469
} | interface ____ {
/**
* Copies a blob to a local file.
*
* @param jobId ID of the job this blob belongs to (or <tt>null</tt> if job-unrelated)
* @param blobKey The blob ID
* @param localFile The local file to copy to
* @return whether the file was copied (<tt>true</tt>) or not (<tt>false</tt>)
* @throws IOException If the copy fails
*/
boolean get(JobID jobId, BlobKey blobKey, File localFile) throws IOException;
}
| BlobView |
java | grpc__grpc-java | testing/src/main/java/io/grpc/internal/testing/StatsTestUtils.java | {
"start": 5439,
"end": 6236
} | class ____ extends Tagger {
@Override
public FakeTagContext empty() {
return FakeTagContext.EMPTY;
}
@Override
public TagContext getCurrentTagContext() {
return ContextUtils.getValue(Context.current());
}
@Override
public TagContextBuilder emptyBuilder() {
return new FakeTagContextBuilder(ImmutableMap.<TagKey, TagValue>of());
}
@Override
public FakeTagContextBuilder toBuilder(TagContext tags) {
return new FakeTagContextBuilder(getTags(tags));
}
@Override
public TagContextBuilder currentBuilder() {
throw new UnsupportedOperationException();
}
@Override
public Scope withTagContext(TagContext tags) {
throw new UnsupportedOperationException();
}
}
public static final | FakeTagger |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/PartialConsumePipelinedResultTest.java | {
"start": 4923,
"end": 5464
} | class ____ extends AbstractInvokable {
public SlowBufferSender(Environment environment) {
super(environment);
}
@Override
public void invoke() throws Exception {
final ResultPartitionWriter writer = getEnvironment().getWriter(0);
for (int i = 0; i < 8; i++) {
writer.emitRecord(ByteBuffer.allocate(1024), 0);
Thread.sleep(50);
}
}
}
/** Reads a single buffer and recycles it. */
public static | SlowBufferSender |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/UnrelatedEntitiesTest.java | {
"start": 893,
"end": 2038
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Set<String> names = new HashSet<>();
String name = "Fab";
names.add( name );
EntityA a = new EntityA( "a", names );
EntityB b = new EntityB( name );
session.persist( a );
session.persist( b );
}
);
}
@Test
public void testNoExceptionThrown(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
List<String> resultList = session.createQuery(
"SELECT 'foobar' FROM EntityA a JOIN EntityB b ON b.name = element(a.names) ",
String.class
).getResultList();
assertThat( resultList.size() ).isEqualTo( 1 );
} );
}
@Test
public void testNoExceptionThrown2(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
List<String> resultList = session.createQuery(
"SELECT 'foobar' FROM EntityA a JOIN a.names aName JOIN EntityB b ON b.name = aName",
String.class
).getResultList();
assertThat( resultList.size() ).isEqualTo( 1 );
}
);
}
@Entity(name = "EntityA")
public static | UnrelatedEntitiesTest |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/layout/StringBuilderEncoder.java | {
"start": 1261,
"end": 1743
} | class ____ implements Encoder<StringBuilder> {
/**
* This ThreadLocal uses raw and inconvenient Object[] to store three heterogeneous objects (CharEncoder, CharBuffer
* and ByteBuffer) instead of a custom class, because it needs to contain JDK classes, no custom (Log4j) classes.
* Where possible putting only JDK classes in ThreadLocals is preferable to avoid memory leaks in web containers:
* the Log4j classes may be loaded by a separate | StringBuilderEncoder |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/util/EnumResolver.java | {
"start": 270,
"end": 404
} | class ____ to resolve String values (either JSON Object field
* names or regular String values) into Java Enum instances.
*/
public | used |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.