language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | google__auto | value/src/main/java/com/google/auto/value/processor/JavaScanner.java | {
"start": 1996,
"end": 3967
} | class ____ {
private final String s;
JavaScanner(String s) {
this.s = s.endsWith("\n") ? s : (s + '\n');
// This allows us to avoid checking for the end of the string in most cases.
}
/**
* Returns the string being scanned, which is either the original input string or that string plus
* a newline.
*/
String string() {
return s;
}
/** Returns the position at which this token ends and the next token begins. */
int tokenEnd(int start) {
if (start >= s.length()) {
return s.length();
}
switch (s.charAt(start)) {
case ' ':
case '\n':
return spaceEnd(start);
case '/':
if (s.charAt(start + 1) == '*') {
return blockCommentEnd(start);
} else if (s.charAt(start + 1) == '/') {
return lineCommentEnd(start);
} else {
return start + 1;
}
case '\'':
case '"':
case '`':
return quoteEnd(start);
default:
// Every other character is considered to be its own token.
return start + 1;
}
}
private int spaceEnd(int start) {
assert s.charAt(start) == ' ' || s.charAt(start) == '\n';
int i;
for (i = start + 1; i < s.length() && s.charAt(i) == ' '; i++) {}
return i;
}
private int blockCommentEnd(int start) {
assert s.charAt(start) == '/' && s.charAt(start + 1) == '*';
int i;
for (i = start + 2; s.charAt(i) != '*' || s.charAt(i + 1) != '/'; i++) {}
return i + 2;
}
private int lineCommentEnd(int start) {
assert s.charAt(start) == '/' && s.charAt(start + 1) == '/';
int end = s.indexOf('\n', start + 2);
assert end > 0;
return end;
}
private int quoteEnd(int start) {
char quote = s.charAt(start);
assert quote == '\'' || quote == '"' || quote == '`';
int i;
for (i = start + 1; s.charAt(i) != quote; i++) {
if (s.charAt(i) == '\\') {
i++;
}
}
return i + 1;
}
}
| JavaScanner |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/streaming/ReportsSinkMetrics.java | {
"start": 943,
"end": 1056
} | interface ____ streaming sinks to signal that they can report
* metrics.
*
* @since 3.4.0
*/
@Evolving
public | for |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson/Saml2AuthenticationExceptionMixin.java | {
"start": 1141,
"end": 1653
} | class ____ used to serialize/deserialize {@link Saml2AuthenticationException}.
*
* @author Sebastien Deleuze
* @author Ulrich Grave
* @since 7.0
* @see Saml2AuthenticationException
* @see Saml2JacksonModule
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties({ "cause", "stackTrace", "suppressedExceptions" })
abstract | is |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/PlaceHolderFieldMapper.java | {
"start": 1885,
"end": 4164
} | class ____ extends FieldMapper.Builder {
private final String type;
// Parameters of legacy indices that are not interpreted by the current ES version. We still need to capture them here so that
// they can be preserved in the mapping that is serialized out based on the toXContent method.
// We use LinkedHashMap to preserve the parameter order.
protected final Map<String, Object> unknownParams = new LinkedHashMap<>();
public Builder(String name, String type) {
super(name);
this.type = type;
}
@Override
public FieldMapper.Builder init(FieldMapper initializer) {
assert initializer instanceof PlaceHolderFieldMapper;
unknownParams.putAll(((PlaceHolderFieldMapper) initializer).unknownParams);
return super.init(initializer);
}
@Override
protected void merge(FieldMapper in, Conflicts conflicts, MapperMergeContext mapperMergeContext) {
assert in instanceof PlaceHolderFieldMapper;
unknownParams.putAll(((PlaceHolderFieldMapper) in).unknownParams);
super.merge(in, conflicts, mapperMergeContext);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder = super.toXContent(builder, params);
for (Map.Entry<String, Object> unknownParam : unknownParams.entrySet()) {
builder.field(unknownParam.getKey(), unknownParam.getValue());
}
return builder;
}
@Override
protected void handleUnknownParamOnLegacyIndex(String propName, Object propNode) {
unknownParams.put(propName, propNode);
}
@Override
protected Parameter<?>[] getParameters() {
return EMPTY_PARAMETERS;
}
@Override
public PlaceHolderFieldMapper build(MapperBuilderContext context) {
PlaceHolderFieldType mappedFieldType = new PlaceHolderFieldType(context.buildFullName(leafName()), type, Map.of());
return new PlaceHolderFieldMapper(leafName(), mappedFieldType, builderParams(this, context), unknownParams);
}
}
public static final | Builder |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/introspect/AnnotatedFieldCollector.java | {
"start": 274,
"end": 1935
} | class ____
extends CollectorBase
{
private final MixInResolver _mixInResolver;
private final boolean _collectAnnotations;
// // // Collected state
AnnotatedFieldCollector(MapperConfig<?> config, MixInResolver mixins,
boolean collectAnnotations)
{
super(config);
_mixInResolver = mixins;
_collectAnnotations = collectAnnotations;
}
public static List<AnnotatedField> collectFields(MapperConfig<?> config,
TypeResolutionContext tc, MixInResolver mixins,
JavaType type, Class<?> primaryMixIn, boolean collectAnnotations)
{
return new AnnotatedFieldCollector(config, mixins, collectAnnotations)
.collect(tc, type, primaryMixIn);
}
List<AnnotatedField> collect(TypeResolutionContext tc,
JavaType type, Class<?> primaryMixIn)
{
Map<String,FieldBuilder> foundFields = _findFields(tc, type, primaryMixIn, null);
if (foundFields == null) {
return Collections.emptyList();
}
List<AnnotatedField> result = new ArrayList<>(foundFields.size());
for (FieldBuilder b : foundFields.values()) {
result.add(b.build());
}
return result;
}
private Map<String,FieldBuilder> _findFields(TypeResolutionContext tc,
JavaType type, Class<?> mixin,
Map<String,FieldBuilder> fields)
{
// First, a quick test: we only care for regular classes (not interfaces,
//primitive types etc), except for Object.class. A simple check to rule out
// other cases is to see if there is a super | AnnotatedFieldCollector |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/server/reactive/ChannelSendOperatorTests.java | {
"start": 7551,
"end": 8292
} | class ____ implements Subscriber<String> {
private Subscription subscription;
private final Subscriber<? super Void> subscriber;
WriteSubscriber(Subscriber<? super Void> subscriber) {
this.subscriber = subscriber;
}
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(1);
}
@Override
public void onNext(String item) {
items.add(item);
this.subscription.request(1);
}
@Override
public void onError(Throwable ex) {
error = ex;
this.subscriber.onError(ex);
}
@Override
public void onComplete() {
completed = true;
this.subscriber.onComplete();
}
}
}
private static | WriteSubscriber |
java | hibernate__hibernate-orm | hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/CollectionMappedByResolver.java | {
"start": 886,
"end": 1011
} | class ____ provides a way to resolve the {@code mappedBy} attribute for collections.
*
* @author Chris Cranford
*/
public | that |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotationSelectors.java | {
"start": 1088,
"end": 2209
} | class ____ {
private static final MergedAnnotationSelector<?> NEAREST = new Nearest();
private static final MergedAnnotationSelector<?> FIRST_DIRECTLY_DECLARED = new FirstDirectlyDeclared();
private MergedAnnotationSelectors() {
}
/**
* Select the nearest annotation, i.e. the one with the lowest distance.
* @return a selector that picks the annotation with the lowest distance
*/
@SuppressWarnings("unchecked")
public static <A extends Annotation> MergedAnnotationSelector<A> nearest() {
return (MergedAnnotationSelector<A>) NEAREST;
}
/**
* Select the first directly declared annotation when possible. If no direct
* annotations are declared then the nearest annotation is selected.
* @return a selector that picks the first directly declared annotation whenever possible
*/
@SuppressWarnings("unchecked")
public static <A extends Annotation> MergedAnnotationSelector<A> firstDirectlyDeclared() {
return (MergedAnnotationSelector<A>) FIRST_DIRECTLY_DECLARED;
}
/**
* {@link MergedAnnotationSelector} to select the nearest annotation.
*/
private static | MergedAnnotationSelectors |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/enums/EnumDeserializationTest.java | {
"start": 16075,
"end": 30136
} | enum ____...");
} catch (InvalidFormatException jex) {
verifyException(jex, "Cannot deserialize Map key of type `tools.jackson.databind.deser");
verifyException(jex, "EnumDeserializationTest$TestEnum`");
}
}
// [databind#141]: allow mapping of empty String into null
@Test
public void testEnumsWithEmpty() throws Exception
{
final ObjectMapper mapper = jsonMapperBuilder()
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
.build();
TestEnum result = mapper.readValue("\"\"", TestEnum.class);
assertNull(result);
}
@Test
public void testGenericEnumDeserialization() throws Exception
{
SimpleModule module = new SimpleModule("foobar");
module.addDeserializer(Enum.class, new LcEnumDeserializer());
final ObjectMapper mapper = jsonMapperBuilder()
.addModule(module)
.build();
// not sure this is totally safe but...
assertEquals(TestEnum.JACKSON, mapper.readValue(q("jackson"), TestEnum.class));
}
// [databind#381]
@Test
public void testUnwrappedEnum() throws Exception {
assertEquals(TestEnum.JACKSON,
MAPPER.readerFor(TestEnum.class)
.with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.readValue("[" + q("JACKSON") + "]"));
}
@Test
public void testUnwrappedEnumException() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.build();
try {
Object v = mapper.readValue("[" + q("JACKSON") + "]",
TestEnum.class);
fail("Exception was not thrown on deserializing a single array element of type enum; instead got: "+v);
} catch (MismatchedInputException exp) {
//exception as thrown correctly
verifyException(exp, "Cannot deserialize");
}
}
// [databind#149]: 'stringified' indexes for enums
@Test
public void testIndexAsString() throws Exception
{
// first, regular index ought to work fine
TestEnum en = MAPPER.readValue("2", TestEnum.class);
assertSame(TestEnum.values()[2], en);
// but also with qd Strings
en = MAPPER.readValue(q("1"), TestEnum.class);
assertSame(TestEnum.values()[1], en);
// [databind#1690]: unless prevented
try {
en = jsonMapperBuilder()
.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)
.build()
.readerFor(TestEnum.class)
.readValue(q("1"));
fail("Should not pass");
} catch (MismatchedInputException e) {
verifyException(e, "Cannot deserialize value of type");
verifyException(e, "EnumDeserializationTest$TestEnum");
verifyException(e, "value looks like quoted Enum index");
}
}
@Test
public void testEnumWithJsonPropertyRename() throws Exception
{
String json = MAPPER.writeValueAsString(new EnumWithPropertyAnno[] {
EnumWithPropertyAnno.B, EnumWithPropertyAnno.A
});
assertEquals("[\"b\",\"a\"]", json);
// and while not really proper place, let's also verify deser while we're at it
EnumWithPropertyAnno[] result = MAPPER.readValue(json, EnumWithPropertyAnno[].class);
assertNotNull(result);
assertEquals(2, result.length);
assertSame(EnumWithPropertyAnno.B, result[0]);
assertSame(EnumWithPropertyAnno.A, result[1]);
}
@Test
public void testEnumWithJsonPropertyRenameWithToString() throws Exception {
EnumWithPropertyAnno a = MAPPER.readerFor(EnumWithPropertyAnno.class)
.with(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("a"));
assertSame(EnumWithPropertyAnno.A, a);
EnumWithPropertyAnno b = MAPPER.readerFor(EnumWithPropertyAnno.class)
.with(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("b"));
assertSame(EnumWithPropertyAnno.B, b);
EnumWithPropertyAnno bb = MAPPER.readerFor(EnumWithPropertyAnno.class)
.with(EnumFeature.READ_ENUMS_USING_TO_STRING)
.with(EnumFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.readValue(q("bb"));
assertNull(bb);
EnumWithPropertyAnno c = MAPPER.readerFor(EnumWithPropertyAnno.class)
.with(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("cc"));
assertSame(EnumWithPropertyAnno.C, c);
}
/**
* {@link #testEnumWithJsonPropertyRename()}
*/
@Test
public void testEnumWithJsonPropertyRenameMixin() throws Exception
{
ObjectMapper mixinMapper = jsonMapperBuilder()
.addMixIn(EnumWithPropertyAnnoBase.class, EnumWithPropertyAnnoMixin.class)
.build();
String json = mixinMapper.writeValueAsString(new EnumWithPropertyAnnoBase[] {
EnumWithPropertyAnnoBase.B, EnumWithPropertyAnnoBase.A
});
assertEquals("[\"b_mixin\",\"a_mixin\"]", json);
// and while not really proper place, let's also verify deser while we're at it
EnumWithPropertyAnnoBase[] result = mixinMapper.readValue(json, EnumWithPropertyAnnoBase[].class);
assertNotNull(result);
assertEquals(2, result.length);
assertSame(EnumWithPropertyAnnoBase.B, result[0]);
assertSame(EnumWithPropertyAnnoBase.A, result[1]);
}
// [databind#1161], unable to switch READ_ENUMS_USING_TO_STRING
@Test
public void testDeserWithToString1161() throws Exception
{
Enum1161 result = MAPPER.readerFor(Enum1161.class)
.without(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("A"));
assertSame(Enum1161.A, result);
result = MAPPER.readerFor(Enum1161.class)
.with(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("a"));
assertSame(Enum1161.A, result);
// and once again, going back to defaults
result = MAPPER.readerFor(Enum1161.class)
.without(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("A"));
assertSame(Enum1161.A, result);
}
@Test
public void testEnumWithDefaultAnnotation() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(EnumFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
.build();
EnumWithDefaultAnno myEnum = mapper.readValue("\"foo\"", EnumWithDefaultAnno.class);
assertSame(EnumWithDefaultAnno.OTHER, myEnum);
}
@Test
public void testEnumWithDefaultAnnotationUsingIndexInBound1() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(EnumFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
.build();
EnumWithDefaultAnno myEnum = mapper.readValue("1", EnumWithDefaultAnno.class);
assertSame(EnumWithDefaultAnno.B, myEnum);
}
@Test
public void testEnumWithDefaultAnnotationUsingIndexInBound2() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(EnumFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
.build();
EnumWithDefaultAnno myEnum = mapper.readValue("2", EnumWithDefaultAnno.class);
assertSame(EnumWithDefaultAnno.OTHER, myEnum);
}
@Test
public void testEnumWithDefaultAnnotationUsingIndexSameAsLength() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(EnumFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
.build();
EnumWithDefaultAnno myEnum = mapper.readValue("3", EnumWithDefaultAnno.class);
assertSame(EnumWithDefaultAnno.OTHER, myEnum);
}
@Test
public void testEnumWithDefaultAnnotationUsingIndexOutOfBound() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(EnumFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
.build();
EnumWithDefaultAnno myEnum = mapper.readValue("4", EnumWithDefaultAnno.class);
assertSame(EnumWithDefaultAnno.OTHER, myEnum);
}
@Test
public void testEnumWithDefaultAnnotationWithConstructor() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.enable(EnumFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
.build();
EnumWithDefaultAnnoAndConstructor myEnum = mapper.readValue("\"foo\"", EnumWithDefaultAnnoAndConstructor.class);
assertNull(myEnum, "When using a constructor, the default value annotation shouldn't be used.");
}
@Test
public void testExceptionFromCustomEnumKeyDeserializer() throws Exception {
final ObjectMapper mapper = jsonMapperBuilder()
.addModule(new EnumModule())
.build();
try {
mapper.readValue("{\"TWO\": \"dumpling\"}",
new TypeReference<Map<AnEnum, String>>() {});
fail("No exception");
} catch (MismatchedInputException e) {
assertTrue(e.getMessage().contains("Undefined AnEnum"));
}
}
// [databind#2164]
@Test
public void testWrapExceptions() throws Exception
{
// By default, wrap:
try {
MAPPER.readerFor(TestEnum2164.class)
.readValue(q("B"));
fail("Should not pass");
} catch (ValueInstantiationException e) {
verifyException(e, "2164");
}
// But can disable:
try {
MAPPER.readerFor(TestEnum2164.class)
.without(DeserializationFeature.WRAP_EXCEPTIONS)
.readValue(q("B"));
fail("Should not pass");
} catch (DatabindException e) {
fail("Wrong exception, should not wrap, got: "+e);
} catch (IllegalArgumentException e) {
verifyException(e, "2164");
}
}
// [databind#2309]
@Test
public void testEnumToStringNull2309() throws Exception
{
Enum2309 value = MAPPER.readerFor(Enum2309.class)
.with(EnumFeature.READ_ENUMS_USING_TO_STRING)
.readValue(q("NON_NULL"));
assertEquals(Enum2309.NON_NULL, value);
}
// [databind#2873] -- take case-sensitivity into account for Enum-as-Map-keys too
@Test
public void testEnumValuesCaseSensitivity() throws Exception {
try {
MAPPER.readValue("{\"map\":{\"JACkson\":\"val\"}}", ClassWithEnumMapKey.class);
} catch (InvalidFormatException e) {
verifyException(e, "Cannot deserialize Map key of type `tools.jackson.databind.deser.");
verifyException(e, "EnumDeserializationTest$TestEnum");
}
}
// [databind#2873] -- take case-sensitivity into account for Enum-as-Map-keys too
@Test
public void testAllowCaseInsensitiveEnumValues() throws Exception {
ObjectMapper m = jsonMapperBuilder()
.enable(ACCEPT_CASE_INSENSITIVE_ENUMS)
.build();
ClassWithEnumMapKey result = m.readerFor(ClassWithEnumMapKey.class)
.readValue("{\"map\":{\"JACkson\":\"val\"}}");
assertEquals(1, result.map.size());
}
// [databind#3006]
@Test
public void testIssue3006() throws Exception
{
assertEquals(Operation3006.ONE, MAPPER.readValue("1", Operation3006.class));
assertEquals(Operation3006.ONE, MAPPER.readValue(q("1"), Operation3006.class));
assertEquals(Operation3006.THREE, MAPPER.readValue("3", Operation3006.class));
assertEquals(Operation3006.THREE, MAPPER.readValue(q("3"), Operation3006.class));
}
@Test
public void testEnumFeature_EnumIndexAsKey() throws Exception {
ObjectReader reader = MAPPER.reader()
.forType(ClassWithEnumMapKey.class)
.with(EnumFeature.READ_ENUM_KEYS_USING_INDEX);
ClassWithEnumMapKey result = reader.readValue("{\"map\": {\"0\":\"I AM FOR REAL\"}}");
assertEquals(result.map.get(TestEnum.JACKSON), "I AM FOR REAL");
}
@Test
public void testEnumFeature_symmetric_to_writing() throws Exception {
ClassWithEnumMapKey obj = new ClassWithEnumMapKey();
Map<TestEnum, String> objMap = new HashMap<>();
objMap.put(TestEnum.JACKSON, "I AM FOR REAL");
obj.map = objMap;
String deserObj = MAPPER.writer()
.with(EnumFeature.WRITE_ENUM_KEYS_USING_INDEX)
.writeValueAsString(obj);
ClassWithEnumMapKey result = MAPPER.reader()
.forType( ClassWithEnumMapKey.class)
.with(EnumFeature.READ_ENUM_KEYS_USING_INDEX)
.readValue(deserObj);
assertNotSame(obj, result);
assertNotSame(obj.map, result.map);
assertEquals(result.map.get(TestEnum.JACKSON), "I AM FOR REAL");
}
@Test
public void testEnumFeature_READ_ENUM_KEYS_USING_INDEX_isDisabledByDefault() {
ObjectReader READER = MAPPER.reader();
assertFalse(READER.isEnabled(EnumFeature.READ_ENUM_KEYS_USING_INDEX));
assertFalse(READER.without(EnumFeature.READ_ENUM_KEYS_USING_INDEX)
.isEnabled(EnumFeature.READ_ENUM_KEYS_USING_INDEX));
}
// [databind#4896]
@Test
public void testEnumReadFromEmptyString() throws Exception {
// First, regular value
assertEquals(YesOrNoOrEmpty4896.YES,
MAPPER.readerFor(YesOrNoOrEmpty4896.class)
.readValue(q("yes")));
assertEquals(YesOrNoOrEmpty4896.EMPTY,
MAPPER.readerFor(YesOrNoOrEmpty4896.class)
.readValue(q("")));
}
}
| value |
java | alibaba__nacos | common/src/test/java/com/alibaba/nacos/common/remote/client/grpc/GrpcClientTlsTest.java | {
"start": 917,
"end": 4369
} | class ____ extends GrpcClientTest {
@Test
void testGrpcEnableTlsAndTrustPart() throws Exception {
when(tlsConfig.getEnableTls()).thenReturn(true);
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
assertNull(grpcClient.connectToServer(serverInfo));
}
@Test
void testGrpcEnableTlsAndTrustAll() throws Exception {
when(tlsConfig.getEnableTls()).thenReturn(true);
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
when(tlsConfig.getTrustAll()).thenReturn(true);
assertNull(grpcClient.connectToServer(serverInfo));
}
@Test
void testGrpcEnableTlsAndEnableMutualAuth() throws Exception {
when(tlsConfig.getEnableTls()).thenReturn(true);
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
when(tlsConfig.getTrustAll()).thenReturn(true);
when(tlsConfig.getMutualAuthEnable()).thenReturn(true);
when(tlsConfig.getCertPrivateKey()).thenReturn("client-key.pem");
assertNull(grpcClient.connectToServer(serverInfo));
}
@Test
void testGrpcSslProvider() {
when(tlsConfig.getEnableTls()).thenReturn(true);
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("ca-cert.pem");
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
when(tlsConfig.getTrustAll()).thenReturn(true);
when(tlsConfig.getMutualAuthEnable()).thenReturn(true);
when(tlsConfig.getCertPrivateKey()).thenReturn("client-key.pem");
when(tlsConfig.getSslProvider()).thenReturn("JDK");
assertNull(grpcClient.connectToServer(serverInfo));
}
@Test
void testGrpcEmptyTrustCollectionCertFile() {
when(tlsConfig.getEnableTls()).thenReturn(true);
when(tlsConfig.getTrustCollectionCertFile()).thenReturn("");
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
assertNull(grpcClient.connectToServer(serverInfo));
}
@Test
void testGrpcMutualAuth() {
when(tlsConfig.getEnableTls()).thenReturn(true);
when(tlsConfig.getCiphers()).thenReturn("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES256-GCM-SHA384");
when(tlsConfig.getProtocols()).thenReturn("TLSv1.2,TLSv1.3");
when(tlsConfig.getMutualAuthEnable()).thenReturn(true);
when(tlsConfig.getTrustAll()).thenReturn(true);
when(tlsConfig.getCertChainFile()).thenReturn("classpath:test-tls-cert.pem");
when(tlsConfig.getCertPrivateKey()).thenReturn("classpath:test-tls-cert.pem");
assertNull(grpcClient.connectToServer(serverInfo));
}
}
| GrpcClientTlsTest |
java | apache__logging-log4j2 | log4j-core-its/src/test/java/org/apache/logging/log4j/core/async/perftest/IPerfTestRunner.java | {
"start": 865,
"end": 1364
} | interface ____ {
String LINE100 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!\"#$%&'()-=^~|\\@`[]{};:+*,.<>/?_123456";
String THROUGHPUT_MSG = LINE100 + LINE100 + LINE100 + LINE100 + LINE100;
String LATENCY_MSG = "Short msg";
void runThroughputTest(int lines, Histogram histogram);
void runLatencyTest(int samples, Histogram histogram, long nanoTimeCost, int threadCount);
void shutdown();
void log(String finalMessage);
}
| IPerfTestRunner |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MaxPrimaryShardDocsCondition.java | {
"start": 1009,
"end": 2453
} | class ____ extends Condition<Long> {
public static final String NAME = "max_primary_shard_docs";
public MaxPrimaryShardDocsCondition(Long value) {
super(NAME, Type.MAX);
this.value = value;
}
public MaxPrimaryShardDocsCondition(StreamInput in) throws IOException {
super(NAME, Type.MAX);
this.value = in.readLong();
}
@Override
public Result evaluate(Stats stats) {
return new Result(this, this.value <= stats.maxPrimaryShardDocs());
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeLong(value);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.field(NAME, value);
}
public static MaxPrimaryShardDocsCondition fromXContent(XContentParser parser) throws IOException {
if (parser.nextToken() == XContentParser.Token.VALUE_NUMBER) {
return new MaxPrimaryShardDocsCondition(parser.longValue());
} else {
throw new IllegalArgumentException("invalid token when parsing " + NAME + " condition: " + parser.currentToken());
}
}
@Override
boolean includedInVersion(TransportVersion version) {
return version.onOrAfter(TransportVersions.V_8_2_0);
}
}
| MaxPrimaryShardDocsCondition |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/benckmark/sql/StatementConverter.java | {
"start": 455,
"end": 3731
} | class ____ {
// remove 'for update' from 'select ... for update'
public static boolean rewriteSelect(SQLSelectStatement stmt) {
SQLSelectQuery q = stmt.getSelect().getQuery();
if (q instanceof MySqlSelectQueryBlock) {
MySqlSelectQueryBlock qb = (MySqlSelectQueryBlock) q;
if (qb.isForUpdate()) {
qb.setForUpdate(false);
return true;
}
}
return false;
}
// construct a 'select' from other types of dml
public static SQLSelectStatement rewrite(SQLStatement stmt) {
SQLSelectStatement selectStmt;
if (stmt instanceof SQLSelectStatement) {
throw new RuntimeException("please use rewriteSelect which does ast modification instead of construction");
} else if (stmt instanceof SQLUpdateStatement) {
SQLTableSource tableSource = ((SQLUpdateStatement) stmt).getTableSource();
SQLExpr where = ((SQLUpdateStatement) stmt).getWhere();
DbType dbType = ((SQLUpdateStatement) stmt).getDbType();
selectStmt = buildSelect(tableSource, where, dbType);
} else if (stmt instanceof SQLDeleteStatement) {
SQLTableSource tableSource = ((SQLDeleteStatement) stmt).getTableSource();
SQLExpr where = ((SQLDeleteStatement) stmt).getWhere();
DbType dbType = ((SQLDeleteStatement) stmt).getDbType();
selectStmt = buildSelect(tableSource, where, dbType);
} else if (stmt instanceof SQLInsertStatement) {
SQLSelect sqlSelect = ((SQLInsertStatement) stmt).getQuery();
if (sqlSelect != null) {
selectStmt = new SQLSelectStatement();
selectStmt.setSelect(sqlSelect);
} else {
throw new UnsupportedOperationException("only insert..select.. is supported");
}
} else if (stmt instanceof SQLReplaceStatement) {
SQLQueryExpr sqlQueryExpr = ((SQLReplaceStatement) stmt).getQuery();
if (sqlQueryExpr != null) {
SQLSelect sqlSelect = ((SQLReplaceStatement) stmt).getQuery().getSubQuery();
selectStmt = new SQLSelectStatement();
selectStmt.setSelect(sqlSelect);
} else {
throw new UnsupportedOperationException("only replace..select.. is supported");
}
} else {
throw new UnsupportedOperationException("only select/update/delete/insert/replace are supported");
}
return selectStmt;
}
// build 'select * from ...'
static SQLSelectStatement buildSelect(SQLTableSource tableSource, SQLExpr where, DbType dbType) {
SQLSelectQueryBlock sqlSelectQuery = new SQLSelectQueryBlock();
sqlSelectQuery.addSelectItem(new SQLSelectItem(new SQLAllColumnExpr()));
sqlSelectQuery.setWhere(where);
sqlSelectQuery.setFrom(tableSource);
tableSource.setParent(sqlSelectQuery);
SQLSelect sqlSelect = new SQLSelect();
sqlSelect.setQuery(sqlSelectQuery);
SQLSelectStatement selectStmt = new SQLSelectStatement();
selectStmt.setSelect(sqlSelect);
selectStmt.setDbType(dbType);
return selectStmt;
}
}
| StatementConverter |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/ScopedMock.java | {
"start": 291,
"end": 719
} | interface ____ extends AutoCloseable {
/**
* Checks if this mock is closed.
*
* @return {@code true} if this mock is closed.
*/
boolean isClosed();
/**
* Closes this scoped mock and throws an exception if already closed.
*/
@Override
void close();
/**
* Releases this scoped mock and is non-operational if already released.
*/
void closeOnDemand();
}
| ScopedMock |
java | google__dagger | dagger-compiler/main/java/dagger/internal/codegen/writing/SwitchingProviders.java | {
"start": 3177,
"end": 5968
} | class ____ {
/**
* Each switch size is fixed at 100 cases each and put in its own method. This is to limit the
* size of the methods so that we don't reach the "huge" method size limit for Android that will
* prevent it from being AOT compiled in some versions of Android (b/77652521). This generally
* starts to happen around 1500 cases, but we are choosing 100 to be safe.
*/
// TODO(bcorso): Include a proguard_spec in the Dagger library to prevent inlining these methods?
// TODO(ronshapiro): Consider making this configurable via a flag.
private static final int MAX_CASES_PER_SWITCH = 100;
private static final long MAX_CASES_PER_CLASS = MAX_CASES_PER_SWITCH * MAX_CASES_PER_SWITCH;
private static final XTypeName typeVariable = XTypeNames.getTypeVariableName("T");
/**
* Maps a {@link Key} to an instance of a {@link SwitchingProviderBuilder}. Each group of {@code
* MAX_CASES_PER_CLASS} keys will share the same instance.
*/
private final Map<Key, SwitchingProviderBuilder> switchingProviderBuilders =
new LinkedHashMap<>();
private final ShardImplementation shardImplementation;
private final CompilerOptions compilerOptions;
private final XProcessingEnv processingEnv;
SwitchingProviders(
ShardImplementation shardImplementation,
CompilerOptions compilerOptions,
XProcessingEnv processingEnv) {
this.shardImplementation = checkNotNull(shardImplementation);
this.compilerOptions = checkNotNull(compilerOptions);
this.processingEnv = checkNotNull(processingEnv);
}
/** Returns the framework instance creation expression for an inner switching provider class. */
FrameworkInstanceCreationExpression newFrameworkInstanceCreationExpression(
ContributionBinding binding, RequestRepresentation unscopedInstanceRequestRepresentation) {
return new FrameworkInstanceCreationExpression() {
@Override
public XCodeBlock creationExpression() {
return switchingProviderBuilders
.computeIfAbsent(binding.key(), key -> getSwitchingProviderBuilder())
.getNewInstanceCodeBlock(binding, unscopedInstanceRequestRepresentation);
}
};
}
private SwitchingProviderBuilder getSwitchingProviderBuilder() {
if (switchingProviderBuilders.size() % MAX_CASES_PER_CLASS == 0) {
String name = shardImplementation.getUniqueClassName("SwitchingProvider");
SwitchingProviderBuilder switchingProviderBuilder =
new SwitchingProviderBuilder(shardImplementation.name().nestedClass(name));
shardImplementation.addTypeSupplier(switchingProviderBuilder::build);
return switchingProviderBuilder;
}
return getLast(switchingProviderBuilders.values());
}
// TODO(bcorso): Consider just merging this | SwitchingProviders |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/KubernetesConfigMapsComponentBuilderFactory.java | {
"start": 1444,
"end": 2039
} | interface ____ {
/**
* Kubernetes ConfigMap (camel-kubernetes)
* Perform operations on Kubernetes ConfigMaps and get notified on
* ConfigMaps changes.
*
* Category: container,cloud
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-kubernetes
*
* @return the dsl builder
*/
static KubernetesConfigMapsComponentBuilder kubernetesConfigMaps() {
return new KubernetesConfigMapsComponentBuilderImpl();
}
/**
* Builder for the Kubernetes ConfigMap component.
*/
| KubernetesConfigMapsComponentBuilderFactory |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/aot/hint/support/ObjectToObjectConverterRuntimeHints.java | {
"start": 1520,
"end": 2836
} | class ____ implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
ReflectionHints reflectionHints = hints.reflection();
TypeReference sqlDateTypeReference = TypeReference.of("java.sql.Date");
reflectionHints.registerTypeIfPresent(classLoader, sqlDateTypeReference.getName(), hint -> hint
.withMethod("toLocalDate", Collections.emptyList(), ExecutableMode.INVOKE)
.onReachableType(sqlDateTypeReference)
.withMethod("valueOf", List.of(TypeReference.of(LocalDate.class)), ExecutableMode.INVOKE)
.onReachableType(sqlDateTypeReference));
TypeReference sqlTimestampTypeReference = TypeReference.of("java.sql.Timestamp");
reflectionHints.registerTypeIfPresent(classLoader, sqlTimestampTypeReference.getName(), hint -> hint
.withMethod("from", List.of(TypeReference.of(Instant.class)), ExecutableMode.INVOKE)
.onReachableType(sqlTimestampTypeReference));
reflectionHints.registerTypeIfPresent(classLoader, "org.springframework.http.HttpMethod",
builder -> builder.withMethod("valueOf", List.of(TypeReference.of(String.class)), ExecutableMode.INVOKE));
reflectionHints.registerTypeIfPresent(classLoader, "java.net.URI", MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
| ObjectToObjectConverterRuntimeHints |
java | hibernate__hibernate-orm | tooling/hibernate-gradle-plugin/src/main/java/org/hibernate/orm/tooling/gradle/enhance/EnhancementHelper.java | {
"start": 7530,
"end": 7628
} | class ____ file [" + file.getAbsolutePath() + "]", e );
}
}
private EnhancementHelper() {
}
}
| to |
java | apache__avro | lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Foo.java | {
"start": 52955,
"end": 53869
} | class ____ implements org.apache.thrift.TBase<add_result, add_result._Fields>,
java.io.Serializable, Cloneable, Comparable<add_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"add_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(
"success", org.apache.thrift.protocol.TType.I32, (short) 0);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new add_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new add_resultTupleSchemeFactory();
private int success; // required
/**
* The set of fields this struct contains, along with convenience methods for
* finding and manipulating them.
*/
public | add_result |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/connector/source/split/ValuesSourcePartitionSplitSerializer.java | {
"start": 1389,
"end": 3239
} | class ____
implements SimpleVersionedSerializer<ValuesSourcePartitionSplit> {
@Override
public int getVersion() {
return 0;
}
@Override
public byte[] serialize(ValuesSourcePartitionSplit split) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos)) {
Map<String, String> partition = split.getPartition();
out.writeUTF(split.splitId());
out.writeInt(partition.size());
for (Map.Entry<String, String> entry : partition.entrySet()) {
out.writeUTF(entry.getKey());
out.writeUTF(entry.getValue());
}
TerminatingLogic.writeTo(out, split.getTerminatingLogic());
out.flush();
return baos.toByteArray();
}
}
@Override
public ValuesSourcePartitionSplit deserialize(int version, byte[] serialized)
throws IOException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
DataInputStream in = new DataInputStream(bais)) {
Map<String, String> partition = new HashMap<>();
String splitId = in.readUTF();
int size = in.readInt();
for (int i = 0; i < size; ++i) {
String key = in.readUTF();
String value = in.readUTF();
partition.put(key, value);
}
final TerminatingLogic terminatingLogic = TerminatingLogic.readFrom(in);
ValuesSourcePartitionSplit split =
new ValuesSourcePartitionSplit(partition, terminatingLogic);
Preconditions.checkArgument(split.splitId().equals(splitId));
return split;
}
}
}
| ValuesSourcePartitionSplitSerializer |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherTemplateTests.java | {
"start": 1305,
"end": 8072
} | class ____ extends ESTestCase {
private TextTemplateEngine textTemplateEngine;
@Before
public void init() throws Exception {
MustacheScriptEngine engine = new MustacheScriptEngine(Settings.EMPTY);
Map<String, ScriptEngine> engines = Collections.singletonMap(engine.getType(), engine);
Map<String, ScriptContext<?>> contexts = Collections.singletonMap(
Watcher.SCRIPT_TEMPLATE_CONTEXT.name,
Watcher.SCRIPT_TEMPLATE_CONTEXT
);
ScriptService scriptService = new ScriptService(
Settings.EMPTY,
engines,
contexts,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
textTemplateEngine = new TextTemplateEngine(scriptService);
}
public void testEscaping() throws Exception {
XContentType contentType = randomFrom(XContentType.values()).canonical();
if (rarely()) {
contentType = null;
}
Character[] specialChars = new Character[] { '\f', '\n', '\r', '"', '\\', (char) 11, '\t', '\b' };
int iters = scaledRandomIntBetween(100, 1000);
for (int i = 0; i < iters; i++) {
int rounds = scaledRandomIntBetween(1, 20);
StringWriter escaped = new StringWriter(); // This will be escaped as it is constructed
StringWriter unescaped = new StringWriter(); // This will be escaped at the end
for (int j = 0; j < rounds; j++) {
String s = getChars();
unescaped.write(s);
if (contentType == XContentType.JSON) {
escaped.write(JsonStringEncoder.getInstance().quoteAsString(s));
} else {
escaped.write(s);
}
char c = randomFrom(specialChars);
unescaped.append(c);
if (contentType == XContentType.JSON) {
escaped.write(JsonStringEncoder.getInstance().quoteAsString("" + c));
} else {
escaped.append(c);
}
}
if (contentType == XContentType.JSON) {
assertThat(escaped.toString(), equalTo(new String(JsonStringEncoder.getInstance().quoteAsString(unescaped.toString()))));
} else {
assertThat(escaped.toString(), equalTo(unescaped.toString()));
}
String template = prepareTemplate("{{data}}", contentType);
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("data", unescaped.toString());
String renderedTemplate = textTemplateEngine.render(new TextTemplate(template), dataMap);
assertThat(renderedTemplate, notNullValue());
if (contentType == XContentType.JSON) {
if (escaped.toString().equals(renderedTemplate) == false) {
String escapedString = escaped.toString();
for (int l = 0; l < renderedTemplate.length() && l < escapedString.length(); ++l) {
if (renderedTemplate.charAt(l) != escapedString.charAt(l)) {
logger.error("at [{}] expected [{}] but got [{}]", l, renderedTemplate.charAt(l), escapedString.charAt(l));
}
}
}
assertThat(escaped.toString(), equalTo(renderedTemplate));
} else {
assertThat(unescaped.toString(), equalTo(renderedTemplate));
}
}
}
public void testSimpleParameterReplace() {
{
String template = """
__json__::GET _search {"query": {"boosting": {"positive": {"match": {"body": "gift"}},"negative": \
{"term": {"body": {"value": "solr"}}}, "negative_boost": {{boost_val}} } }}""";
Map<String, Object> vars = new HashMap<>();
vars.put("boost_val", "0.3");
String result = textTemplateEngine.render(new TextTemplate(template), vars);
assertEquals("""
GET _search {"query": {"boosting": {"positive": {"match": {"body": "gift"}},"negative": \
{"term": {"body": {"value": "solr"}}}, "negative_boost": 0.3 } }}""", result);
}
{
String template = """
__json__::GET _search {"query": {"boosting": {"positive": {"match": {"body": "gift"}},"negative": \
{"term": {"body": {"value": "{{body_val}}"}}}, "negative_boost": {{boost_val}} } }}""";
Map<String, Object> vars = new HashMap<>();
vars.put("boost_val", "0.3");
vars.put("body_val", "\"quick brown\"");
String result = textTemplateEngine.render(new TextTemplate(template), vars);
assertEquals("""
GET _search {"query": {"boosting": {"positive": {"match": {"body": "gift"}},"negative": \
{"term": {"body": {"value": "\\"quick brown\\""}}}, "negative_boost": 0.3 } }}""", result);
}
}
public void testInvalidPrefixes() throws Exception {
String[] specialStrings = new String[] { "\f", "\n", "\r", "\"", "\\", "\t", "\b", "__::", "__" };
String prefix = randomFrom("", "__", "____::", "___::", "____", "::", "++json__::", "__json__", "+_json__::", "__json__:");
String template = prefix + " {{test_var1}} {{test_var2}}";
Map<String, Object> vars = new HashMap<>();
Writer var1Writer = new StringWriter();
Writer var2Writer = new StringWriter();
for (int i = 0; i < scaledRandomIntBetween(10, 1000); ++i) {
var1Writer.write(randomRealisticUnicodeOfCodepointLengthBetween(0, 10));
var2Writer.write(randomRealisticUnicodeOfCodepointLengthBetween(0, 10));
var1Writer.append(randomFrom(specialStrings));
var2Writer.append(randomFrom(specialStrings));
}
vars.put("test_var1", var1Writer.toString());
vars.put("test_var2", var2Writer.toString());
String s1 = textTemplateEngine.render(new TextTemplate(template), vars);
String s2 = prefix + " " + var1Writer.toString() + " " + var2Writer.toString();
assertThat(s1, equalTo(s2));
}
static String getChars() throws IOException {
return randomRealisticUnicodeOfCodepointLengthBetween(0, 10);
}
static String prepareTemplate(String template, @Nullable XContentType contentType) {
if (contentType == null) {
return template;
}
return new StringBuilder("__").append(contentType.queryParameter().toLowerCase(Locale.ROOT))
.append("__::")
.append(template)
.toString();
}
}
| WatcherTemplateTests |
java | elastic__elasticsearch | x-pack/plugin/sql/sql-client/src/test/java/org/elasticsearch/xpack/sql/client/UriUtilsTests.java | {
"start": 877,
"end": 15422
} | class ____ extends ESTestCase {
public static URI DEFAULT_URI = URI.create("http://localhost:9200/");
public void testHostAndPort() throws Exception {
assertEquals(URI.create("http://server:9200/"), parseURI("server:9200", DEFAULT_URI));
}
public void testJustHost() throws Exception {
assertEquals(URI.create("http://server:9200/"), parseURI("server", DEFAULT_URI));
}
public void testHttpWithPort() throws Exception {
assertEquals(URI.create("http://server:9201/"), parseURI("http://server:9201", DEFAULT_URI));
}
public void testHttpsWithPort() throws Exception {
assertEquals(URI.create("https://server:9201/"), parseURI("https://server:9201", DEFAULT_URI));
}
public void testHttpNoPort() throws Exception {
assertEquals(URI.create("https://server:9200/"), parseURI("https://server", DEFAULT_URI));
}
public void testLocalhostV6() throws Exception {
assertEquals(URI.create("http://[::1]:51082/"), parseURI("[::1]:51082", DEFAULT_URI));
}
public void testUserLocalhostV6() throws Exception {
assertEquals(URI.create("http://user@[::1]:51082/"), parseURI("user@[::1]:51082", DEFAULT_URI));
}
public void testLocalhostV4() throws Exception {
assertEquals(URI.create("http://127.0.0.1:51082/"), parseURI("127.0.0.1:51082", DEFAULT_URI));
}
public void testUserLocalhostV4() throws Exception {
assertEquals(URI.create("http://user@127.0.0.1:51082/"), parseURI("user@127.0.0.1:51082", DEFAULT_URI));
}
public void testNoHost() {
assertEquals(URI.create("http://localhost:9200/path?query"), parseURI("/path?query", DEFAULT_URI));
}
public void testEmpty() {
assertEquals(URI.create("http://localhost:9200/"), parseURI("", DEFAULT_URI));
}
public void testHttpsWithUser() throws Exception {
assertEquals(URI.create("https://user@server:9200/"), parseURI("https://user@server", DEFAULT_URI));
}
public void testUserPassHost() throws Exception {
assertEquals(URI.create("http://user:password@server:9200/"), parseURI("user:password@server", DEFAULT_URI));
}
public void testHttpPath() throws Exception {
assertEquals(URI.create("https://server:9201/some_path"), parseURI("https://server:9201/some_path", DEFAULT_URI));
}
public void testHttpQuery() throws Exception {
assertEquals(URI.create("https://server:9201/?query"), parseURI("https://server:9201/?query", DEFAULT_URI));
}
public void testUnsupportedProtocol() throws Exception {
assertEquals(
"Invalid connection scheme [ftp] configuration: only http and https protocols are supported",
expectThrows(IllegalArgumentException.class, () -> parseURI("ftp://server:9201/", DEFAULT_URI)).getMessage()
);
}
public void testMalformedWhiteSpace() throws Exception {
assertThat(
expectThrows(IllegalArgumentException.class, () -> parseURI(" ", DEFAULT_URI)).getMessage(),
// Use a lenient regex here since later JDKs trim exception message whitespace
matchesPattern("^Invalid connection configuration: Illegal character in authority at index 7: http:// ?")
);
}
public void testNoRedaction() {
assertEquals(
"Invalid connection configuration: Illegal character in fragment at index 16: HTTP://host#frag#ment",
expectThrows(IllegalArgumentException.class, () -> parseURI("HTTP://host#frag#ment", DEFAULT_URI)).getMessage()
);
}
public void testSimpleUriRedaction() {
assertEquals(
"http://*************@host:9200/path?user=****&password=****",
redactCredentialsInConnectionString("http://user:password@host:9200/path?user=user&password=pass")
);
}
public void testSimpleConnectionStringRedaction() {
assertEquals(
"*************@host:9200/path?user=****&password=****",
redactCredentialsInConnectionString("user:password@host:9200/path?user=user&password=pass")
);
}
public void testNoRedactionInvalidHost() {
assertEquals("https://ho%st", redactCredentialsInConnectionString("https://ho%st"));
}
public void testUriRedactionInvalidUserPart() {
assertEquals(
"http://*************@@host:9200/path?user=****&password=****&at=@sign",
redactCredentialsInConnectionString("http://user:password@@host:9200/path?user=user&password=pass&at=@sign")
);
}
public void testUriRedactionInvalidHost() {
assertEquals(
"http://*************@ho%st:9200/path?user=****&password=****&at=@sign",
redactCredentialsInConnectionString("http://user:password@ho%st:9200/path?user=user&password=pass&at=@sign")
);
}
public void testUriRedactionInvalidPort() {
assertEquals(
"http://*************@host:port/path?user=****&password=****&at=@sign",
redactCredentialsInConnectionString("http://user:password@host:port/path?user=user&password=pass&at=@sign")
);
}
public void testUriRedactionInvalidPath() {
assertEquals(
"http://*************@host:9200/pa^th?user=****&password=****",
redactCredentialsInConnectionString("http://user:password@host:9200/pa^th?user=user&password=pass")
);
}
public void testUriRedactionInvalidQuery() {
assertEquals(
"http://*************@host:9200/path?user=****&password=****&invali^d",
redactCredentialsInConnectionString("http://user:password@host:9200/path?user=user&password=pass&invali^d")
);
}
public void testUriRedactionInvalidFragment() {
assertEquals(
"https://host:9200/path?usr=****&passwo=****#ssl=5#",
redactCredentialsInConnectionString("https://host:9200/path?usr=user&passwo=pass#ssl=5#")
);
}
public void testUriRedactionMisspelledUser() {
assertEquals(
"https://host:9200/path?usr=****&password=****",
redactCredentialsInConnectionString("https://host:9200/path?usr=user&password=pass")
);
}
public void testUriRedactionMisspelledUserAndPassword() {
assertEquals(
"https://host:9200/path?usr=****&passwo=****",
redactCredentialsInConnectionString("https://host:9200/path?usr=user&passwo=pass")
);
}
public void testUriRedactionNoScheme() {
assertEquals("host:9200/path?usr=****&passwo=****", redactCredentialsInConnectionString("host:9200/path?usr=user&passwo=pass"));
}
public void testUriRedactionNoPort() {
assertEquals("host/path?usr=****&passwo=****", redactCredentialsInConnectionString("host/path?usr=user&passwo=pass"));
}
public void testUriRedactionNoHost() {
assertEquals("/path?usr=****&passwo=****", redactCredentialsInConnectionString("/path?usr=user&passwo=pass"));
}
public void testUriRedactionNoPath() {
assertEquals("?usr=****&passwo=****", redactCredentialsInConnectionString("?usr=user&passwo=pass"));
}
public void testUriRandomRedact() {
final String scheme = randomFrom("http://", "https://", StringUtils.EMPTY);
final String host = randomFrom("host", "host:" + randomIntBetween(1, 65535), StringUtils.EMPTY);
final String path = randomFrom("", "/", "/path", StringUtils.EMPTY);
final String userVal = randomAlphaOfLengthBetween(1, 2 + randomInt(50));
final String user = "user=" + userVal;
final String passVal = randomAlphaOfLengthBetween(1, 2 + randomInt(50));
final String pass = "password=" + passVal;
final String redactedUser = "user=" + String.valueOf(REDACTION_CHAR).repeat(userVal.length());
final String redactedPass = "password=" + String.valueOf(REDACTION_CHAR).repeat(passVal.length());
String connStr, expectRedact, expectParse, creds = StringUtils.EMPTY;
if (randomBoolean() && host.length() > 0) {
creds = userVal;
if (randomBoolean()) {
creds += ":" + passVal;
}
connStr = scheme + creds + "@" + host + path;
expectRedact = scheme + String.valueOf(REDACTION_CHAR).repeat(creds.length()) + "@" + host + path;
} else {
connStr = scheme + host + path;
expectRedact = scheme + host + path;
}
expectParse = scheme.length() > 0 ? scheme : "http://";
expectParse += creds + (creds.length() > 0 ? "@" : StringUtils.EMPTY);
expectParse += host.length() > 0 ? host : "localhost";
expectParse += (host.indexOf(':') > 0 ? StringUtils.EMPTY : ":" + 9200);
expectParse += path.length() > 0 ? path : "/";
Character sep = '?';
if (randomBoolean()) {
connStr += sep + user;
expectRedact += sep + redactedUser;
expectParse += sep + user;
sep = '&';
}
if (randomBoolean()) {
connStr += sep + pass;
expectRedact += sep + redactedPass;
expectParse += sep + pass;
}
assertEquals(expectRedact, redactCredentialsInConnectionString(connStr));
if ((connStr.equals("http://") || connStr.equals("https://")) == false) { // URI parser expects an authority past a scheme
assertEquals(URI.create(expectParse), parseURI(connStr, DEFAULT_URI));
}
}
public void testUriRedactionMissingSeparatorBetweenUserAndPassword() {
assertEquals(
"https://host:9200/path?user=*****************",
redactCredentialsInConnectionString("https://host:9200/path?user=userpassword=pass")
);
}
public void testUriRedactionMissingSeparatorBeforePassword() {
assertEquals(
"https://host:9200/path?user=****&foo=barpassword=********&bar=foo",
redactCredentialsInConnectionString("https://host:9200/path?user=user&foo=barpassword=password&bar=foo")
);
}
// tests that no other option is "similar" to the credential options and be inadvertently redacted
public void testUriRedactionAllOptions() {
StringBuilder cs = new StringBuilder("https://host:9200/path?");
String[] options = {
"timezone",
"connect.timeout",
"network.timeout",
"page.timeout",
"page.size",
"query.timeout",
"user",
"password",
"ssl",
"ssl.keystore.location",
"ssl.keystore.pass",
"ssl.keystore.type",
"ssl.truststore.location",
"ssl.truststore.pass",
"ssl.truststore.type",
"ssl.protocol",
"proxy.http",
"proxy.socks",
"field.multi.value.leniency",
"index.include.frozen",
"validate.properties" };
Arrays.stream(options).forEach(e -> cs.append(e).append("=").append(e).append("&"));
String connStr = cs.substring(0, cs.length() - 1);
String expected = connStr.replace("user=user", "user=****");
expected = expected.replace("password=password", "password=********");
assertEquals(expected, redactCredentialsInConnectionString(connStr));
}
public void testUriRedactionBrokenHost() {
assertEquals("ho^st", redactCredentialsInConnectionString("ho^st"));
}
public void testUriRedactionDisabled() {
assertEquals(
"HTTPS://host:9200/path?user=user;password=pass",
redactCredentialsInConnectionString("HTTPS://host:9200/path?user=user;password=pass")
);
}
public void testRemoveQuery() throws Exception {
assertEquals(
URI.create("http://server:9100"),
removeQuery(URI.create("http://server:9100?query"), "http://server:9100?query", DEFAULT_URI)
);
}
public void testRemoveQueryTrailingSlash() throws Exception {
assertEquals(
URI.create("http://server:9100/"),
removeQuery(URI.create("http://server:9100/?query"), "http://server:9100/?query", DEFAULT_URI)
);
}
public void testRemoveQueryNoQuery() throws Exception {
assertEquals(URI.create("http://server:9100"), removeQuery(URI.create("http://server:9100"), "http://server:9100", DEFAULT_URI));
}
public void testAppendEmptySegmentToPath() throws Exception {
assertEquals(URI.create("http://server:9100"), appendSegmentToPath(URI.create("http://server:9100"), ""));
}
public void testAppendNullSegmentToPath() throws Exception {
assertEquals(URI.create("http://server:9100"), appendSegmentToPath(URI.create("http://server:9100"), null));
}
public void testAppendSegmentToNullPath() throws Exception {
assertEquals(
"URI must not be null",
expectThrows(IllegalArgumentException.class, () -> appendSegmentToPath(null, "/_sql")).getMessage()
);
}
public void testAppendSegmentToEmptyPath() throws Exception {
assertEquals(URI.create("/_sql"), appendSegmentToPath(URI.create(""), "/_sql"));
}
public void testAppendSlashSegmentToPath() throws Exception {
assertEquals(URI.create("http://server:9100"), appendSegmentToPath(URI.create("http://server:9100"), "/"));
}
public void testAppendSqlSegmentToPath() throws Exception {
assertEquals(URI.create("http://server:9100/_sql"), appendSegmentToPath(URI.create("http://server:9100"), "/_sql"));
}
public void testAppendSqlSegmentNoSlashToPath() throws Exception {
assertEquals(URI.create("http://server:9100/_sql"), appendSegmentToPath(URI.create("http://server:9100"), "_sql"));
}
public void testAppendSegmentToPath() throws Exception {
assertEquals(URI.create("http://server:9100/es_rest/_sql"), appendSegmentToPath(URI.create("http://server:9100/es_rest"), "/_sql"));
}
public void testAppendSegmentNoSlashToPath() throws Exception {
assertEquals(URI.create("http://server:9100/es_rest/_sql"), appendSegmentToPath(URI.create("http://server:9100/es_rest"), "_sql"));
}
public void testAppendSegmentTwoSlashesToPath() throws Exception {
assertEquals(
URI.create("https://server:9100/es_rest/_sql"),
appendSegmentToPath(URI.create("https://server:9100/es_rest/"), "/_sql")
);
}
}
| UriUtilsTests |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/jdbc/ApplicationScopedStatementInspectorTest.java | {
"start": 2234,
"end": 2501
} | class ____ implements StatementInspector {
static List<String> statements = new ArrayList<>();
@Override
public String inspect(String sql) {
statements.add(sql);
return sql;
}
}
}
| ApplicationStatementInspector |
java | apache__camel | dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java | {
"start": 1158973,
"end": 1164543
} | class ____ extends YamlDeserializerBase<TokenizerDefinition> {
public TokenizerDefinitionDeserializer() {
super(TokenizerDefinition.class);
}
@Override
protected TokenizerDefinition newInstance() {
return new TokenizerDefinition();
}
@Override
protected boolean setProperty(TokenizerDefinition target, String propertyKey,
String propertyName, Node node) {
propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey);
switch(propertyKey) {
case "disabled": {
String val = asText(node);
target.setDisabled(val);
break;
}
case "tokenizerImplementation": {
MappingNode val = asMappingNode(node);
setProperties(target, val);
break;
}
case "langChain4jCharacterTokenizer": {
org.apache.camel.model.tokenizer.LangChain4jCharacterTokenizerDefinition val = asType(node, org.apache.camel.model.tokenizer.LangChain4jCharacterTokenizerDefinition.class);
target.setTokenizerImplementation(val);
break;
}
case "langChain4jLineTokenizer": {
org.apache.camel.model.tokenizer.LangChain4jLineTokenizerDefinition val = asType(node, org.apache.camel.model.tokenizer.LangChain4jLineTokenizerDefinition.class);
target.setTokenizerImplementation(val);
break;
}
case "langChain4jParagraphTokenizer": {
org.apache.camel.model.tokenizer.LangChain4jParagraphTokenizerDefinition val = asType(node, org.apache.camel.model.tokenizer.LangChain4jParagraphTokenizerDefinition.class);
target.setTokenizerImplementation(val);
break;
}
case "langChain4jSentenceTokenizer": {
org.apache.camel.model.tokenizer.LangChain4jSentenceTokenizerDefinition val = asType(node, org.apache.camel.model.tokenizer.LangChain4jSentenceTokenizerDefinition.class);
target.setTokenizerImplementation(val);
break;
}
case "langChain4jWordTokenizer": {
org.apache.camel.model.tokenizer.LangChain4jWordTokenizerDefinition val = asType(node, org.apache.camel.model.tokenizer.LangChain4jWordTokenizerDefinition.class);
target.setTokenizerImplementation(val);
break;
}
case "id": {
String val = asText(node);
target.setId(val);
break;
}
case "description": {
String val = asText(node);
target.setDescription(val);
break;
}
case "note": {
String val = asText(node);
target.setNote(val);
break;
}
default: {
return false;
}
}
return true;
}
}
@YamlType(
nodes = "tokenize",
inline = true,
types = org.apache.camel.model.language.TokenizerExpression.class,
order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1,
displayName = "Tokenize",
description = "Tokenize text payloads using delimiter patterns.",
deprecated = false,
properties = {
@YamlProperty(name = "endToken", type = "string", description = "The end token to use as tokenizer if using start/end token pairs. You can use simple language as the token to support dynamic tokens.", displayName = "End Token"),
@YamlProperty(name = "group", type = "string", description = "To group N parts together, for example to split big files into chunks of 1000 lines. You can use simple language as the group to support dynamic group sizes.", displayName = "Group"),
@YamlProperty(name = "groupDelimiter", type = "string", description = "Sets the delimiter to use when grouping. If this has not been set then token will be used as the delimiter.", displayName = "Group Delimiter"),
@YamlProperty(name = "id", type = "string", description = "Sets the id of this node", displayName = "Id"),
@YamlProperty(name = "includeTokens", type = "boolean", defaultValue = "false", description = "Whether to include the tokens in the parts when using pairs. When including tokens then the endToken property must also be configured (to use pair mode). The default value is false", displayName = "Include Tokens"),
@YamlProperty(name = "inheritNamespaceTagName", type = "string", description = "To inherit namespaces from a root/parent tag name when using XML You can use simple language as the tag name to support dynamic names.", displayName = "Inherit Namespace Tag Name"),
@YamlProperty(name = "regex", type = "boolean", defaultValue = "false", description = "If the token is a regular expression pattern. The default value is false", displayName = "Regex"),
@YamlProperty(name = "resultType", type = "string", description = "Sets the | TokenizerDefinitionDeserializer |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpBadLoginConnectionLeakIT.java | {
"start": 3065,
"end": 3994
} | class ____ extends SocketFactory {
@Override
public Socket createSocket(String s, int i) {
return null;
}
@Override
public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) {
return null;
}
@Override
public Socket createSocket(InetAddress inetAddress, int i) {
return null;
}
@Override
public Socket createSocket() {
AuditingSocket socket = new AuditingSocket();
socketAudits.put(System.identityHashCode(socket), new boolean[] { false, false });
return socket;
}
@Override
public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) {
return null;
}
}
/**
* {@link Socket} which counts connect()/close() invocations
*/
private | AuditingSocketFactory |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/resourceplugin/ResourcePluginManager.java | {
"start": 9930,
"end": 10036
} | interface
____ (dpInstance instanceof DevicePluginScheduler) {
// check DevicePluginScheduler | if |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/alias/UserProvider.java | {
"start": 1455,
"end": 3175
} | class ____ extends CredentialProvider {
public static final String SCHEME_NAME = "user";
private final UserGroupInformation user;
private final Credentials credentials;
private UserProvider() throws IOException {
user = UserGroupInformation.getCurrentUser();
credentials = user.getCredentials();
}
@Override
public boolean isTransient() {
return true;
}
@Override
public synchronized CredentialEntry getCredentialEntry(String alias) {
byte[] bytes = credentials.getSecretKey(new Text(alias));
if (bytes == null) {
return null;
}
return new CredentialEntry(
alias, new String(bytes, StandardCharsets.UTF_8).toCharArray());
}
@Override
public synchronized CredentialEntry createCredentialEntry(String name, char[] credential)
throws IOException {
Text nameT = new Text(name);
if (credentials.getSecretKey(nameT) != null) {
throw new IOException("Credential " + name +
" already exists in " + this);
}
credentials.addSecretKey(new Text(name),
new String(credential).getBytes(StandardCharsets.UTF_8));
return new CredentialEntry(name, credential);
}
@Override
public synchronized void deleteCredentialEntry(String name) throws IOException {
byte[] cred = credentials.getSecretKey(new Text(name));
if (cred != null) {
credentials.removeSecretKey(new Text(name));
}
else {
throw new IOException("Credential " + name +
" does not exist in " + this);
}
}
@Override
public String toString() {
return SCHEME_NAME + ":///";
}
@Override
public synchronized void flush() {
user.addCredentials(credentials);
}
public static | UserProvider |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/registration/RegisteredRpcConnection.java | {
"start": 2017,
"end": 10506
} | class ____<
F extends Serializable,
G extends RpcGateway,
S extends RegistrationResponse.Success,
R extends RegistrationResponse.Rejection> {
private static final AtomicReferenceFieldUpdater<RegisteredRpcConnection, RetryingRegistration>
REGISTRATION_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(
RegisteredRpcConnection.class,
RetryingRegistration.class,
"pendingRegistration");
/** The logger for all log messages of this class. */
protected final Logger log;
/** The fencing token fo the remote component. */
private final F fencingToken;
/** The target component Address, for example the ResourceManager Address. */
private final String targetAddress;
/**
* Execution context to be used to execute the on complete action of the
* ResourceManagerRegistration.
*/
private final Executor executor;
/** The Registration of this RPC connection. */
private volatile RetryingRegistration<F, G, S, R> pendingRegistration;
/** The gateway to register, it's null until the registration is completed. */
private volatile G targetGateway;
/** Flag indicating that the RPC connection is closed. */
private volatile boolean closed;
// ------------------------------------------------------------------------
public RegisteredRpcConnection(
Logger log, String targetAddress, F fencingToken, Executor executor) {
this.log = checkNotNull(log);
this.targetAddress = checkNotNull(targetAddress);
this.fencingToken = checkNotNull(fencingToken);
this.executor = checkNotNull(executor);
}
// ------------------------------------------------------------------------
// Life cycle
// ------------------------------------------------------------------------
public void start() {
checkState(!closed, "The RPC connection is already closed");
checkState(
!isConnected() && pendingRegistration == null,
"The RPC connection is already started");
final RetryingRegistration<F, G, S, R> newRegistration = createNewRegistration();
if (REGISTRATION_UPDATER.compareAndSet(this, null, newRegistration)) {
newRegistration.startRegistration();
} else {
// concurrent start operation
newRegistration.cancel();
}
}
/**
* Tries to reconnect to the {@link #targetAddress} by cancelling the pending registration and
* starting a new pending registration.
*
* @return {@code false} if the connection has been closed or a concurrent modification has
* happened; otherwise {@code true}
*/
public boolean tryReconnect() {
checkState(isConnected(), "Cannot reconnect to an unknown destination.");
if (closed) {
return false;
} else {
final RetryingRegistration<F, G, S, R> currentPendingRegistration = pendingRegistration;
if (currentPendingRegistration != null) {
currentPendingRegistration.cancel();
}
final RetryingRegistration<F, G, S, R> newRegistration = createNewRegistration();
if (REGISTRATION_UPDATER.compareAndSet(
this, currentPendingRegistration, newRegistration)) {
newRegistration.startRegistration();
} else {
// concurrent modification
newRegistration.cancel();
return false;
}
// double check for concurrent close operations
if (closed) {
newRegistration.cancel();
return false;
} else {
return true;
}
}
}
/**
* This method generate a specific Registration, for example TaskExecutor Registration at the
* ResourceManager.
*/
protected abstract RetryingRegistration<F, G, S, R> generateRegistration();
/** This method handle the Registration Response. */
protected abstract void onRegistrationSuccess(S success);
/**
* This method handles the Registration rejection.
*
* @param rejection rejection containing additional information about the rejection
*/
protected abstract void onRegistrationRejection(R rejection);
/** This method handle the Registration failure. */
protected abstract void onRegistrationFailure(Throwable failure);
/** Close connection. */
public void close() {
closed = true;
// make sure we do not keep re-trying forever
if (pendingRegistration != null) {
pendingRegistration.cancel();
}
}
public boolean isClosed() {
return closed;
}
// ------------------------------------------------------------------------
// Properties
// ------------------------------------------------------------------------
public F getTargetLeaderId() {
return fencingToken;
}
public String getTargetAddress() {
return targetAddress;
}
/** Gets the RegisteredGateway. This returns null until the registration is completed. */
public G getTargetGateway() {
return targetGateway;
}
public boolean isConnected() {
return targetGateway != null;
}
// ------------------------------------------------------------------------
@Override
public String toString() {
String connectionInfo =
"(ADDRESS: " + targetAddress + " FENCINGTOKEN: " + fencingToken + ")";
if (isConnected()) {
connectionInfo =
"RPC connection to "
+ targetGateway.getClass().getSimpleName()
+ " "
+ connectionInfo;
} else {
connectionInfo = "RPC connection to " + connectionInfo;
}
if (isClosed()) {
connectionInfo += " is closed";
} else if (isConnected()) {
connectionInfo += " is established";
} else {
connectionInfo += " is connecting";
}
return connectionInfo;
}
// ------------------------------------------------------------------------
// Internal methods
// ------------------------------------------------------------------------
private RetryingRegistration<F, G, S, R> createNewRegistration() {
RetryingRegistration<F, G, S, R> newRegistration = checkNotNull(generateRegistration());
CompletableFuture<RetryingRegistration.RetryingRegistrationResult<G, S, R>> future =
newRegistration.getFuture();
future.whenCompleteAsync(
(RetryingRegistration.RetryingRegistrationResult<G, S, R> result,
Throwable failure) -> {
if (failure != null) {
if (failure instanceof CancellationException) {
// we ignore cancellation exceptions because they originate from
// cancelling
// the RetryingRegistration
log.debug(
"Retrying registration towards {} was cancelled.",
targetAddress);
} else {
// this future should only ever fail if there is a bug, not if the
// registration is declined
onRegistrationFailure(failure);
}
} else {
if (result.isSuccess()) {
targetGateway = result.getGateway();
onRegistrationSuccess(result.getSuccess());
} else if (result.isRejection()) {
onRegistrationRejection(result.getRejection());
} else {
throw new IllegalArgumentException(
String.format(
"Unknown retrying registration response: %s.", result));
}
}
},
executor);
return newRegistration;
}
}
| RegisteredRpcConnection |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/search/arguments/FieldArgsTest.java | {
"start": 545,
"end": 669
} | class ____ {
/**
* Concrete implementation of FieldArgs for testing purposes.
*/
private static | FieldArgsTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeSafeSubscribeTest.java | {
"start": 1110,
"end": 7400
} | class ____ {
@Test
public void normalSuccess() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
Maybe.just(1)
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verify(consumer).onSuccess(1);
order.verifyNoMoreInteractions();
assertTrue("" + errors, errors.isEmpty());
});
}
@Test
public void normalError() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
Maybe.<Integer>error(new TestException())
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verify(consumer).onError(any(TestException.class));
order.verifyNoMoreInteractions();
assertTrue("" + errors, errors.isEmpty());
});
}
@Test
public void normalEmpty() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
Maybe.<Integer>empty()
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verify(consumer).onComplete();
order.verifyNoMoreInteractions();
});
}
@Test
public void onSubscribeCrash() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
doThrow(new TestException()).when(consumer).onSubscribe(any());
Disposable d = Disposable.empty();
new Maybe<Integer>() {
@Override
protected void subscribeActual(@NonNull MaybeObserver<? super Integer> observer) {
observer.onSubscribe(d);
// none of the following should arrive at the consumer
observer.onSuccess(1);
observer.onError(new IOException());
observer.onComplete();
}
}
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verifyNoMoreInteractions();
assertTrue(d.isDisposed());
TestHelper.assertUndeliverable(errors, 0, TestException.class);
TestHelper.assertUndeliverable(errors, 1, IOException.class);
});
}
@Test
public void onSuccessCrash() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
doThrow(new TestException()).when(consumer).onSuccess(any());
new Maybe<Integer>() {
@Override
protected void subscribeActual(@NonNull MaybeObserver<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
observer.onSuccess(1);
}
}
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verify(consumer).onSuccess(1);
order.verifyNoMoreInteractions();
TestHelper.assertUndeliverable(errors, 0, TestException.class);
});
}
@Test
public void onErrorCrash() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
doThrow(new TestException()).when(consumer).onError(any());
new Maybe<Integer>() {
@Override
protected void subscribeActual(@NonNull MaybeObserver<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
// none of the following should arrive at the consumer
observer.onError(new IOException());
}
}
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verify(consumer).onError(any(IOException.class));
order.verifyNoMoreInteractions();
TestHelper.assertError(errors, 0, CompositeException.class);
CompositeException compositeException = (CompositeException)errors.get(0);
TestHelper.assertError(compositeException.getExceptions(), 0, IOException.class);
TestHelper.assertError(compositeException.getExceptions(), 1, TestException.class);
});
}
@Test
public void onCompleteCrash() throws Throwable {
TestHelper.withErrorTracking(errors -> {
@SuppressWarnings("unchecked")
MaybeObserver<Integer> consumer = mock(MaybeObserver.class);
doThrow(new TestException()).when(consumer).onComplete();
new Maybe<Integer>() {
@Override
protected void subscribeActual(@NonNull MaybeObserver<? super Integer> observer) {
observer.onSubscribe(Disposable.empty());
// none of the following should arrive at the consumer
observer.onComplete();
}
}
.safeSubscribe(consumer);
InOrder order = inOrder(consumer);
order.verify(consumer).onSubscribe(any(Disposable.class));
order.verify(consumer).onComplete();
order.verifyNoMoreInteractions();
TestHelper.assertUndeliverable(errors, 0, TestException.class);
});
}
}
| MaybeSafeSubscribeTest |
java | apache__flink | flink-python/src/test/java/org/apache/flink/table/runtime/operators/python/aggregate/arrow/batch/BatchArrowPythonGroupAggregateFunctionOperatorTest.java | {
"start": 2467,
"end": 9182
} | class ____
extends AbstractBatchArrowPythonAggregateFunctionOperatorTest {
@Test
void testGroupAggregateFunction() throws Exception {
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
getTestHarness(new Configuration());
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newRow(true, "c1", "c2", 0L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newRow(true, "c1", "c4", 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newRow(true, "c2", "c6", 2L), initialTime + 3));
testHarness.close();
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L)));
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 2L)));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
}
@Test
void testFinishBundleTriggeredByCount() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 2);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newRow(true, "c1", "c2", 0L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newRow(true, "c1", "c2", 1L), initialTime + 2));
assertOutputEquals(
"FinishBundle should not be triggered.", expectedOutput, testHarness.getOutput());
testHarness.processElement(
new StreamRecord<>(newRow(true, "c2", "c6", 2L), initialTime + 2));
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L)));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 2L)));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
}
@Test
void testFinishBundleTriggeredByTime() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10);
conf.set(PythonOptions.MAX_BUNDLE_TIME_MILLS, 1000L);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarness(conf);
long initialTime = 0L;
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.open();
testHarness.processElement(
new StreamRecord<>(newRow(true, "c1", "c2", 0L), initialTime + 1));
testHarness.processElement(
new StreamRecord<>(newRow(true, "c1", "c2", 1L), initialTime + 2));
testHarness.processElement(
new StreamRecord<>(newRow(true, "c2", "c6", 2L), initialTime + 2));
assertOutputEquals(
"FinishBundle should not be triggered.", expectedOutput, testHarness.getOutput());
testHarness.setProcessingTime(1000L);
expectedOutput.add(new StreamRecord<>(newRow(true, "c1", 0L)));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
expectedOutput.add(new StreamRecord<>(newRow(true, "c2", 2L)));
assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput());
}
@Override
public LogicalType[] getOutputLogicalType() {
return new LogicalType[] {
DataTypes.STRING().getLogicalType(), DataTypes.BIGINT().getLogicalType()
};
}
@Override
public RowType getInputType() {
return new RowType(
Arrays.asList(
new RowType.RowField("f1", new VarCharType()),
new RowType.RowField("f2", new VarCharType()),
new RowType.RowField("f3", new BigIntType())));
}
@Override
public RowType getOutputType() {
return new RowType(
Arrays.asList(
new RowType.RowField("f1", new VarCharType()),
new RowType.RowField("f2", new BigIntType())));
}
@Override
public AbstractArrowPythonAggregateFunctionOperator getTestOperator(
Configuration config,
PythonFunctionInfo[] pandasAggregateFunctions,
RowType inputType,
RowType outputType,
int[] groupingSet,
int[] udafInputOffsets) {
RowType udfInputType = (RowType) Projection.of(udafInputOffsets).project(inputType);
RowType udfOutputType =
(RowType)
Projection.range(groupingSet.length, outputType.getFieldCount())
.project(outputType);
return new PassThroughBatchArrowPythonGroupAggregateFunctionOperator(
config,
pandasAggregateFunctions,
inputType,
udfInputType,
udfOutputType,
ProjectionCodeGenerator.generateProjection(
new CodeGeneratorContext(
new Configuration(),
Thread.currentThread().getContextClassLoader()),
"UdafInputProjection",
inputType,
udfInputType,
udafInputOffsets),
ProjectionCodeGenerator.generateProjection(
new CodeGeneratorContext(
new Configuration(),
Thread.currentThread().getContextClassLoader()),
"GroupKey",
inputType,
(RowType) Projection.of(groupingSet).project(inputType),
groupingSet),
ProjectionCodeGenerator.generateProjection(
new CodeGeneratorContext(
new Configuration(),
Thread.currentThread().getContextClassLoader()),
"GroupSet",
inputType,
(RowType) Projection.of(groupingSet).project(inputType),
groupingSet));
}
private static | BatchArrowPythonGroupAggregateFunctionOperatorTest |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/configuration/ClassLoadingConfig.java | {
"start": 814,
"end": 2144
} | class ____ to be loaded by the system ClassLoader. Note that if you
* make a library parent first all its dependencies should generally also be parent first.
* <p>
* Artifacts should be configured as a comma separated list of artifact ids, with the group, artifact-id and optional
* classifier separated by a colon.
* <p>
* WARNING: This config property can only be set in application.properties
*/
Optional<List<String>> parentFirstArtifacts();
/**
* Artifacts that are loaded in the runtime ClassLoader in dev mode, so they will be dropped
* and recreated on change.
* <p>
* This is an advanced option, it should only be used if you have a problem with
* libraries holding stale state between reloads. Note that if you use this any library that depends on the listed libraries
* will also need to be reloadable.
* <p>
* This setting has no impact on production builds.
* <p>
* Artifacts should be configured as a comma separated list of artifact ids, with the group, artifact-id and optional
* classifier separated by a colon.
* <p>
* WARNING: This config property can only be set in application.properties
*/
Optional<String> reloadableArtifacts();
/**
* Artifacts that will never be loaded by the | needs |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/conditional/ClampMaxIntegerEvaluator.java | {
"start": 4884,
"end": 5664
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory field;
private final EvalOperator.ExpressionEvaluator.Factory max;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory field,
EvalOperator.ExpressionEvaluator.Factory max) {
this.source = source;
this.field = field;
this.max = max;
}
@Override
public ClampMaxIntegerEvaluator get(DriverContext context) {
return new ClampMaxIntegerEvaluator(source, field.get(context), max.get(context), context);
}
@Override
public String toString() {
return "ClampMaxIntegerEvaluator[" + "field=" + field + ", max=" + max + "]";
}
}
}
| Factory |
java | google__error-prone | check_api/src/main/java/com/google/errorprone/apply/SourceFile.java | {
"start": 1295,
"end": 1432
} | class ____ not thread-safe.
*
* @author sjnickerson@google.com (Simon Nickerson)
* @author alexeagle@google.com (Alex Eagle)
*/
public | is |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/YearMonthIntervalType.java | {
"start": 3308,
"end": 6946
} | enum ____ {
YEAR,
YEAR_TO_MONTH,
MONTH
}
private final YearMonthResolution resolution;
private final int yearPrecision;
public YearMonthIntervalType(
boolean isNullable, YearMonthResolution resolution, int yearPrecision) {
super(isNullable, LogicalTypeRoot.INTERVAL_YEAR_MONTH);
Preconditions.checkNotNull(resolution);
if (resolution == YearMonthResolution.MONTH && yearPrecision != DEFAULT_PRECISION) {
throw new ValidationException(
String.format(
"Year precision of sub-year intervals must be equal to the default precision %d.",
DEFAULT_PRECISION));
}
if (yearPrecision < MIN_PRECISION || yearPrecision > MAX_PRECISION) {
throw new ValidationException(
String.format(
"Year precision of year-month intervals must be between %d and %d (both inclusive).",
MIN_PRECISION, MAX_PRECISION));
}
this.resolution = resolution;
this.yearPrecision = yearPrecision;
}
public YearMonthIntervalType(YearMonthResolution resolution, int yearPrecision) {
this(true, resolution, yearPrecision);
}
public YearMonthIntervalType(YearMonthResolution resolution) {
this(resolution, DEFAULT_PRECISION);
}
public YearMonthResolution getResolution() {
return resolution;
}
public int getYearPrecision() {
return yearPrecision;
}
@Override
public LogicalType copy(boolean isNullable) {
return new YearMonthIntervalType(isNullable, resolution, yearPrecision);
}
@Override
public String asSerializableString() {
return withNullability(getResolutionFormat(), yearPrecision);
}
@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);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
YearMonthIntervalType that = (YearMonthIntervalType) o;
return yearPrecision == that.yearPrecision && resolution == that.resolution;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), resolution, yearPrecision);
}
// --------------------------------------------------------------------------------------------
private String getResolutionFormat() {
switch (resolution) {
case YEAR:
return YEAR_FORMAT;
case YEAR_TO_MONTH:
return YEAR_TO_MONTH_FORMAT;
case MONTH:
return MONTH_FORMAT;
default:
throw new UnsupportedOperationException();
}
}
}
| YearMonthResolution |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/JsonPointer.java | {
"start": 30681,
"end": 30786
} | class ____ to replace call stack when parsing JsonPointer
* expressions.
*/
private static | used |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java | {
"start": 28191,
"end": 28439
} | class ____ {
@Inject
@TestQualifierWithMultipleAttributes(number=123)
private Person person;
public Person getPerson() {
return this.person;
}
}
@SuppressWarnings("unused")
private static | QualifiedFieldWithMultipleAttributesTestBean |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/syncjob/action/ConnectorSyncJobActionRequest.java | {
"start": 484,
"end": 570
} | class ____ action requests targeting the connector sync job index.
*/
public abstract | for |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/ValidateSimpleRegExpTest.java | {
"start": 894,
"end": 1291
} | class ____ extends ValidateRegExpTest {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").validate().simple("${bodyAs(java.lang.String)} regex '^\\d{2}\\.\\d{2}\\.\\d{4}$'")
.to("mock:result");
}
};
}
}
| ValidateSimpleRegExpTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/testkit/VehicleAssert.java | {
"start": 704,
"end": 1352
} | class ____ extends AbstractAssert<VehicleAssert, Vehicle> {
public VehicleAssert(Vehicle actual) {
super(actual, VehicleAssert.class);
}
public static VehicleAssert assertThat(Vehicle actual) {
return new VehicleAssert(actual);
}
public VehicleAssert hasName(String name) {
// check that actual Vehicle we want to make assertions on is not null.
isNotNull();
// check condition
if (!actual.getName().equals(name)) {
failWithMessage("Expected vehicle's name to be <%s> but was <%s>", name, actual.getName());
}
// return the current assertion for method chaining
return this;
}
}
| VehicleAssert |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/planner/ConstantShardContextIndexedByShardId.java | {
"start": 1052,
"end": 3389
} | class ____ implements IndexedByShardId<EsPhysicalOperationProviders.ShardContext> {
public static final ConstantShardContextIndexedByShardId INSTANCE = new ConstantShardContextIndexedByShardId();
private ConstantShardContextIndexedByShardId() {}
private static final EsPhysicalOperationProviders.ShardContext CONTEXT = new EsPhysicalOperationProviders.ShardContext() {
@Override
public Query toQuery(QueryBuilder queryBuilder) {
throw new UnsupportedOperationException();
}
@Override
public double storedFieldsSequentialProportion() {
throw new UnsupportedOperationException();
}
@Override
public int index() {
return 0;
}
@Override
public IndexSearcher searcher() {
throw new UnsupportedOperationException();
}
@Override
public Optional<SortAndFormats> buildSort(List<SortBuilder<?>> sorts) {
throw new UnsupportedOperationException();
}
@Override
public String shardIdentifier() {
return "ConstantRefCountedIndexedByShardId.CONTEXT";
}
@Override
public SourceLoader newSourceLoader(Set<String> sourcePaths) {
throw new UnsupportedOperationException();
}
@Override
public BlockLoader blockLoader(
String name,
boolean asUnsupportedSource,
MappedFieldType.FieldExtractPreference fieldExtractPreference,
BlockLoaderFunctionConfig blockLoaderFunctionConfig
) {
throw new UnsupportedOperationException();
}
@Override
public MappedFieldType fieldType(String name) {
throw new UnsupportedOperationException();
}
@Override
public void close() {}
};
@Override
public EsPhysicalOperationProviders.ShardContext get(int shardId) {
return CONTEXT;
}
@Override
public Collection<? extends EsPhysicalOperationProviders.ShardContext> collection() {
return List.of(CONTEXT);
}
@Override
public <S> IndexedByShardId<S> map(Function<EsPhysicalOperationProviders.ShardContext, S> mapper) {
throw new UnsupportedOperationException();
}
}
| ConstantShardContextIndexedByShardId |
java | google__guice | core/test/com/google/inject/EagerSingletonTest.java | {
"start": 2821,
"end": 5020
} | class ____ B a bunch of times.
final List<Class<?>> jitBindings = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
jitBindings.add(copyClass(B.class));
}
Guice.createInjector(
Stage.PRODUCTION,
new AbstractModule() {
@Override
protected void configure() {
// create a just-in-time binding for A
getProvider(A.class);
// create a just-in-time binding for C
requestInjection(
new Object() {
@Inject
void inject(final Injector injector) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
@Override
public void run() {
latch.countDown();
for (Class<?> jitBinding : jitBindings) {
// this causes the binding to be created
injector.getProvider(jitBinding);
}
}
}.start();
latch.await(); // make sure the thread is running before returning
}
});
}
});
assertEquals(1, A.instanceCount);
// our thread runs in parallel with eager singleton loading so some there should be some number
// N such that 0<=N <jitBindings.size() and all classes in jitBindings with an index < N will
// have been initialized. Assert that!
int prev = -1;
int index = 0;
for (Class<?> jitBinding : jitBindings) {
int instanceCount = (Integer) jitBinding.getDeclaredField("instanceCount").get(null);
if (instanceCount != 0 && instanceCount != 1) {
fail("Should only have created zero or one instances, got " + instanceCount);
}
if (prev == -1) {
prev = instanceCount;
} else if (prev != instanceCount) {
if (prev != 1 && instanceCount != 0) {
fail("initialized later JIT bindings before earlier ones at index " + index);
}
prev = instanceCount;
}
index++;
}
}
/** Creates a copy of a | for |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/chain/ChainMapContextImpl.java | {
"start": 2001,
"end": 8121
} | class ____<KEYIN, VALUEIN, KEYOUT, VALUEOUT> implements
MapContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {
private RecordReader<KEYIN, VALUEIN> reader;
private RecordWriter<KEYOUT, VALUEOUT> output;
private TaskInputOutputContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> base;
private Configuration conf;
ChainMapContextImpl(
TaskInputOutputContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> base,
RecordReader<KEYIN, VALUEIN> rr, RecordWriter<KEYOUT, VALUEOUT> rw,
Configuration conf) {
this.reader = rr;
this.output = rw;
this.base = base;
this.conf = conf;
}
@Override
public KEYIN getCurrentKey() throws IOException, InterruptedException {
return reader.getCurrentKey();
}
@Override
public VALUEIN getCurrentValue() throws IOException, InterruptedException {
return reader.getCurrentValue();
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
return reader.nextKeyValue();
}
@Override
public InputSplit getInputSplit() {
if (base instanceof MapContext) {
MapContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT> mc =
(MapContext<KEYIN, VALUEIN, KEYOUT, VALUEOUT>) base;
return mc.getInputSplit();
} else {
return null;
}
}
@Override
public Counter getCounter(Enum<?> counterName) {
return base.getCounter(counterName);
}
@Override
public Counter getCounter(String groupName, String counterName) {
return base.getCounter(groupName, counterName);
}
@Override
public OutputCommitter getOutputCommitter() {
return base.getOutputCommitter();
}
@Override
public void write(KEYOUT key, VALUEOUT value) throws IOException,
InterruptedException {
output.write(key, value);
}
@Override
public String getStatus() {
return base.getStatus();
}
@Override
public TaskAttemptID getTaskAttemptID() {
return base.getTaskAttemptID();
}
@Override
public void setStatus(String msg) {
base.setStatus(msg);
}
@Override
public Path[] getArchiveClassPaths() {
return base.getArchiveClassPaths();
}
@Override
public String[] getArchiveTimestamps() {
return base.getArchiveTimestamps();
}
@Override
public URI[] getCacheArchives() throws IOException {
return base.getCacheArchives();
}
@Override
public URI[] getCacheFiles() throws IOException {
return base.getCacheFiles();
}
@Override
public Class<? extends Reducer<?, ?, ?, ?>> getCombinerClass()
throws ClassNotFoundException {
return base.getCombinerClass();
}
@Override
public Configuration getConfiguration() {
return conf;
}
@Override
public Path[] getFileClassPaths() {
return base.getFileClassPaths();
}
@Override
public String[] getFileTimestamps() {
return base.getFileTimestamps();
}
@Override
public RawComparator<?> getCombinerKeyGroupingComparator() {
return base.getCombinerKeyGroupingComparator();
}
@Override
public RawComparator<?> getGroupingComparator() {
return base.getGroupingComparator();
}
@Override
public Class<? extends InputFormat<?, ?>> getInputFormatClass()
throws ClassNotFoundException {
return base.getInputFormatClass();
}
@Override
public String getJar() {
return base.getJar();
}
@Override
public JobID getJobID() {
return base.getJobID();
}
@Override
public String getJobName() {
return base.getJobName();
}
@Override
public boolean getJobSetupCleanupNeeded() {
return base.getJobSetupCleanupNeeded();
}
@Override
public boolean getTaskCleanupNeeded() {
return base.getTaskCleanupNeeded();
}
@Override
public Path[] getLocalCacheArchives() throws IOException {
return base.getLocalCacheArchives();
}
@Override
public Path[] getLocalCacheFiles() throws IOException {
return base.getLocalCacheArchives();
}
@Override
public Class<?> getMapOutputKeyClass() {
return base.getMapOutputKeyClass();
}
@Override
public Class<?> getMapOutputValueClass() {
return base.getMapOutputValueClass();
}
@Override
public Class<? extends Mapper<?, ?, ?, ?>> getMapperClass()
throws ClassNotFoundException {
return base.getMapperClass();
}
@Override
public int getMaxMapAttempts() {
return base.getMaxMapAttempts();
}
@Override
public int getMaxReduceAttempts() {
return base.getMaxReduceAttempts();
}
@Override
public int getNumReduceTasks() {
return base.getNumReduceTasks();
}
@Override
public Class<? extends OutputFormat<?, ?>> getOutputFormatClass()
throws ClassNotFoundException {
return base.getOutputFormatClass();
}
@Override
public Class<?> getOutputKeyClass() {
return base.getMapOutputKeyClass();
}
@Override
public Class<?> getOutputValueClass() {
return base.getOutputValueClass();
}
@Override
public Class<? extends Partitioner<?, ?>> getPartitionerClass()
throws ClassNotFoundException {
return base.getPartitionerClass();
}
@Override
public boolean getProfileEnabled() {
return base.getProfileEnabled();
}
@Override
public String getProfileParams() {
return base.getProfileParams();
}
@Override
public IntegerRanges getProfileTaskRange(boolean isMap) {
return base.getProfileTaskRange(isMap);
}
@Override
public Class<? extends Reducer<?, ?, ?, ?>> getReducerClass()
throws ClassNotFoundException {
return base.getReducerClass();
}
@Override
public RawComparator<?> getSortComparator() {
return base.getSortComparator();
}
@Override
public boolean getSymlink() {
return base.getSymlink();
}
@Override
public String getUser() {
return base.getUser();
}
@Override
public Path getWorkingDirectory() throws IOException {
return base.getWorkingDirectory();
}
@Override
public void progress() {
base.progress();
}
@Override
public Credentials getCredentials() {
return base.getCredentials();
}
@Override
public float getProgress() {
return base.getProgress();
}
}
| ChainMapContextImpl |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/AbstractOuterJoinTaskExternalITCase.java | {
"start": 1790,
"end": 5640
} | class ____
extends BinaryOperatorTestBase<
FlatJoinFunction<
Tuple2<Integer, Integer>,
Tuple2<Integer, Integer>,
Tuple2<Integer, Integer>>,
Tuple2<Integer, Integer>,
Tuple2<Integer, Integer>> {
protected static final long HASH_MEM = 4 * 1024 * 1024;
private static final long SORT_MEM = 3 * 1024 * 1024;
private static final long BNLJN_MEM = 10 * PAGE_SIZE;
private final double bnljn_frac;
@SuppressWarnings("unchecked")
protected final TypeComparator<Tuple2<Integer, Integer>> comparator1 =
new TupleComparator<>(
new int[] {0},
new TypeComparator<?>[] {new IntComparator(true)},
new TypeSerializer<?>[] {IntSerializer.INSTANCE});
@SuppressWarnings("unchecked")
protected final TypeComparator<Tuple2<Integer, Integer>> comparator2 =
new TupleComparator<>(
new int[] {0},
new TypeComparator<?>[] {new IntComparator(true)},
new TypeSerializer<?>[] {IntSerializer.INSTANCE});
@SuppressWarnings("unchecked")
protected final TypeSerializer<Tuple2<Integer, Integer>> serializer =
new TupleSerializer<>(
(Class<Tuple2<Integer, Integer>>) (Class<?>) Tuple2.class,
new TypeSerializer<?>[] {IntSerializer.INSTANCE, IntSerializer.INSTANCE});
protected final CountingOutputCollector<Tuple2<Integer, Integer>> output =
new CountingOutputCollector<>();
AbstractOuterJoinTaskExternalITCase(ExecutionConfig config) {
super(config, HASH_MEM, 2, SORT_MEM);
bnljn_frac = (double) BNLJN_MEM / this.getMemoryManager().getMemorySize();
}
@TestTemplate
void testExternalSortOuterJoinTask() throws Exception {
final int keyCnt1 = 16384 * 4;
final int valCnt1 = 2;
final int keyCnt2 = 8192;
final int valCnt2 = 4 * 2;
final int expCnt = calculateExpectedCount(keyCnt1, valCnt1, keyCnt2, valCnt2);
setOutput(this.output);
addDriverComparator(this.comparator1);
addDriverComparator(this.comparator2);
getTaskConfig().setDriverPairComparator(new RuntimePairComparatorFactory());
getTaskConfig().setDriverStrategy(this.getSortStrategy());
getTaskConfig().setRelativeMemoryDriver(bnljn_frac);
setNumFileHandlesForSort(4);
final AbstractOuterJoinDriver<
Tuple2<Integer, Integer>,
Tuple2<Integer, Integer>,
Tuple2<Integer, Integer>>
testTask = getOuterJoinDriver();
addInputSorted(
new UniformIntTupleGenerator(keyCnt1, valCnt1, false),
serializer,
this.comparator1.duplicate());
addInputSorted(
new UniformIntTupleGenerator(keyCnt2, valCnt2, false),
serializer,
this.comparator2.duplicate());
testDriver(testTask, MockJoinStub.class);
assertThat(this.output.getNumberOfRecords())
.withFailMessage("Wrong result set size.")
.isEqualTo(expCnt);
}
protected abstract int calculateExpectedCount(
int keyCnt1, int valCnt1, int keyCnt2, int valCnt2);
protected abstract AbstractOuterJoinDriver<
Tuple2<Integer, Integer>, Tuple2<Integer, Integer>, Tuple2<Integer, Integer>>
getOuterJoinDriver();
protected abstract DriverStrategy getSortStrategy();
// =================================================================================================
@SuppressWarnings("serial")
public static final | AbstractOuterJoinTaskExternalITCase |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/mapping/Component.java | {
"start": 23333,
"end": 24499
} | class
____ rootClass.getMappedClass();
}
}
private Setter injector(Property property, Class<?> attributeDeclarer) {
return property.getPropertyAccessStrategy( attributeDeclarer )
.buildPropertyAccess( attributeDeclarer, property.getName(), true )
.getSetter();
}
private Class<?> resolveComponentClass() {
try {
return getComponentClass();
}
catch ( Exception e ) {
return null;
}
}
@Internal
public String[] getPropertyNames() {
final String[] propertyNames = new String[properties.size()];
for ( int i = 0; i < properties.size(); i++ ) {
propertyNames[i] = properties.get( i ).getName();
}
return propertyNames;
}
public void clearProperties() {
properties.clear();
}
/**
* Apply a column naming pattern.
*
* @see org.hibernate.annotations.EmbeddedColumnNaming
*/
public void setColumnNamingPattern(String columnNamingPattern) {
this.columnNamingPattern = columnNamingPattern;
}
/**
* Column naming pattern applied to the component
*
* @see org.hibernate.annotations.EmbeddedColumnNaming
*/
public String getColumnNamingPattern() {
return columnNamingPattern;
}
public static | return |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/nativeio/NativeIO.java | {
"start": 17533,
"end": 22466
} | class ____ {
private int ownerId, groupId;
private String owner, group;
private int mode;
// Mode constants - Set by JNI
public static int S_IFMT = -1; /* type of file */
public static int S_IFIFO = -1; /* named pipe (fifo) */
public static int S_IFCHR = -1; /* character special */
public static int S_IFDIR = -1; /* directory */
public static int S_IFBLK = -1; /* block special */
public static int S_IFREG = -1; /* regular */
public static int S_IFLNK = -1; /* symbolic link */
public static int S_IFSOCK = -1; /* socket */
public static int S_ISUID = -1; /* set user id on execution */
public static int S_ISGID = -1; /* set group id on execution */
public static int S_ISVTX = -1; /* save swapped text even after use */
public static int S_IRUSR = -1; /* read permission, owner */
public static int S_IWUSR = -1; /* write permission, owner */
public static int S_IXUSR = -1; /* execute/search permission, owner */
Stat(int ownerId, int groupId, int mode) {
this.ownerId = ownerId;
this.groupId = groupId;
this.mode = mode;
}
Stat(String owner, String group, int mode) {
if (!Shell.WINDOWS) {
this.owner = owner;
} else {
this.owner = stripDomain(owner);
}
if (!Shell.WINDOWS) {
this.group = group;
} else {
this.group = stripDomain(group);
}
this.mode = mode;
}
@Override
public String toString() {
return "Stat(owner='" + owner + "', group='" + group + "'" +
", mode=" + mode + ")";
}
public String getOwner() {
return owner;
}
public String getGroup() {
return group;
}
public int getMode() {
return mode;
}
}
/**
* Returns the file stat for a file descriptor.
*
* @param fd file descriptor.
* @return the file descriptor file stat.
* @throws IOException thrown if there was an IO error while obtaining the file stat.
*/
public static Stat getFstat(FileDescriptor fd) throws IOException {
Stat stat = null;
if (!Shell.WINDOWS) {
stat = fstat(fd);
stat.owner = getName(IdCache.USER, stat.ownerId);
stat.group = getName(IdCache.GROUP, stat.groupId);
} else {
try {
stat = fstat(fd);
} catch (NativeIOException nioe) {
if (nioe.getErrorCode() == 6) {
throw new NativeIOException("The handle is invalid.",
Errno.EBADF);
} else {
LOG.warn(String.format("NativeIO.getFstat error (%d): %s",
nioe.getErrorCode(), nioe.getMessage()));
throw new NativeIOException("Unknown error", Errno.UNKNOWN);
}
}
}
return stat;
}
/**
* Return the file stat for a file path.
*
* @param path file path
* @return the file stat
* @throws IOException thrown if there is an IO error while obtaining the
* file stat
*/
public static Stat getStat(String path) throws IOException {
if (path == null) {
String errMessage = "Path is null";
LOG.warn(errMessage);
throw new IOException(errMessage);
}
Stat stat = null;
try {
if (!Shell.WINDOWS) {
stat = stat(path);
stat.owner = getName(IdCache.USER, stat.ownerId);
stat.group = getName(IdCache.GROUP, stat.groupId);
} else {
stat = stat(path);
}
} catch (NativeIOException nioe) {
LOG.warn("NativeIO.getStat error ({}): {} -- file path: {}",
nioe.getErrorCode(), nioe.getMessage(), path);
throw new PathIOException(path, nioe);
}
return stat;
}
private static String getName(IdCache domain, int id) throws IOException {
Map<Integer, CachedName> idNameCache = (domain == IdCache.USER)
? USER_ID_NAME_CACHE : GROUP_ID_NAME_CACHE;
String name;
CachedName cachedName = idNameCache.get(id);
long now = System.currentTimeMillis();
if (cachedName != null && (cachedName.timestamp + cacheTimeout) > now) {
name = cachedName.name;
} else {
name = (domain == IdCache.USER) ? getUserName(id) : getGroupName(id);
if (LOG.isDebugEnabled()) {
String type = (domain == IdCache.USER) ? "UserName" : "GroupName";
LOG.debug("Got " + type + " " + name + " for ID " + id +
" from the native implementation");
}
cachedName = new CachedName(name, now);
idNameCache.put(id, cachedName);
}
return name;
}
static native String getUserName(int uid) throws IOException;
static native String getGroupName(int uid) throws IOException;
private static | Stat |
java | elastic__elasticsearch | x-pack/plugin/autoscaling/src/main/java/org/elasticsearch/xpack/autoscaling/action/PolicyValidator.java | {
"start": 435,
"end": 657
} | interface ____ {
/**
* Validate the given policy, e.g., check decider names, setting names and values.
* @param policy the policy to validate
*/
void validate(AutoscalingPolicy policy);
}
| PolicyValidator |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/CamelContext.java | {
"start": 50969,
"end": 51092
} | class ____ which may be helpful for running camel in other containers
*
* @return the application CamelContext | loader |
java | apache__maven | compat/maven-model-builder/src/test/java/org/apache/maven/model/building/DefaultModelBuilderTest.java | {
"start": 1353,
"end": 3734
} | class ____ {
private static final String BASE1_ID = "thegroup:base1:pom";
private static final String BASE1_ID2 = "thegroup:base1:1";
private static final String BASE1 = "<project>\n" + " <modelVersion>4.0.0</modelVersion>\n"
+ " <groupId>thegroup</groupId>\n"
+ " <artifactId>base1</artifactId>\n"
+ " <version>1</version>\n"
+ " <packaging>pom</packaging>\n"
+ " <dependencyManagement>\n"
+ " <dependencies>\n"
+ " <dependency>\n"
+ " <groupId>thegroup</groupId>\n"
+ " <artifactId>base2</artifactId>\n"
+ " <version>1</version>\n"
+ " <type>pom</type>\n"
+ " <scope>import</scope>\n"
+ " </dependency>\n"
+ " </dependencies>\n"
+ " </dependencyManagement>\n"
+ "</project>\n";
private static final String BASE2_ID = "thegroup:base2:pom";
private static final String BASE2_ID2 = "thegroup:base2:1";
private static final String BASE2 = "<project>\n" + " <modelVersion>4.0.0</modelVersion>\n"
+ " <groupId>thegroup</groupId>\n"
+ " <artifactId>base2</artifactId>\n"
+ " <version>1</version>\n"
+ " <packaging>pom</packaging>\n"
+ " <dependencyManagement>\n"
+ " <dependencies>\n"
+ " <dependency>\n"
+ " <groupId>thegroup</groupId>\n"
+ " <artifactId>base1</artifactId>\n"
+ " <version>1</version>\n"
+ " <type>pom</type>\n"
+ " <scope>import</scope>\n"
+ " </dependency>\n"
+ " </dependencies>\n"
+ " </dependencyManagement>\n"
+ "</project>\n";
@Test
public void testCycleInImports() throws Exception {
ModelBuilder builder = new DefaultModelBuilderFactory().newInstance();
assertNotNull(builder);
DefaultModelBuildingRequest request = new DefaultModelBuildingRequest();
request.setModelSource(new StringModelSource(BASE1));
request.setModelResolver(new CycleInImportsResolver());
assertThrows(ModelBuildingException.class, () -> builder.build(request));
}
static | DefaultModelBuilderTest |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java | {
"start": 50178,
"end": 50615
} | class ____ {
@TempDirForField
private Path tempDir1;
@Test
void test(@TempDirForParameter Path tempDir2) {
assertThat(tempDir1.getFileName()).asString().startsWith("field");
assertThat(tempDir2.getFileName()).asString().startsWith("parameter");
}
@Target(ANNOTATION_TYPE)
@Retention(RUNTIME)
@TempDir(factory = FactoryWithCustomMetaAnnotationTestCase.Factory.class)
private @ | FactoryWithCustomMetaAnnotationTestCase |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/authorization/EnableMultiFactorAuthenticationFiltersSetTests.java | {
"start": 4836,
"end": 6422
} | class ____ {
@Bean
AuthenticationManager authenticationManager() {
return mock(AuthenticationManager.class);
}
@Bean
static AbstractAuthenticationProcessingFilter authnProcessingFilter(
AuthenticationManager authenticationManager) {
AbstractAuthenticationProcessingFilter result = new AbstractAuthenticationProcessingFilter(
AnyRequestMatcher.INSTANCE, authenticationManager) {
};
result.setAuthenticationConverter(new BasicAuthenticationConverter());
return result;
}
@Bean
static AuthenticationFilter authenticationFilter(AuthenticationManager authenticationManager) {
return new AuthenticationFilter(authenticationManager, new BasicAuthenticationConverter());
}
@Bean
static AbstractPreAuthenticatedProcessingFilter preAuthenticatedProcessingFilter(
AuthenticationManager authenticationManager) {
AbstractPreAuthenticatedProcessingFilter result = new AbstractPreAuthenticatedProcessingFilter() {
@Override
protected @Nullable Object getPreAuthenticatedCredentials(HttpServletRequest request) {
return "password";
}
@Override
protected @Nullable Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
return "user";
}
};
result.setRequiresAuthenticationRequestMatcher(AnyRequestMatcher.INSTANCE);
result.setAuthenticationManager(authenticationManager);
return result;
}
@Bean
static BasicAuthenticationFilter basicAuthenticationFilter(AuthenticationManager authenticationManager) {
return new BasicAuthenticationFilter(authenticationManager);
}
}
}
| Config |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/accumulators/AccumulatorLiveITCase.java | {
"start": 8820,
"end": 10019
} | class ____ extends RichFlatMapFunction<Integer, Integer> {
private static final long serialVersionUID = 1L;
private static final OneShotLatch notifyLatch = new OneShotLatch();
private static final OneShotLatch shutdownLatch = new OneShotLatch();
private final IntCounter counter = new IntCounter();
@Override
public void open(OpenContext openContext) throws Exception {
getRuntimeContext().addAccumulator(ACCUMULATOR_NAME, counter);
}
@Override
public void flatMap(Integer value, Collector<Integer> out) throws Exception {
counter.add(1);
out.collect(value);
LOG.debug("Emitting value {}.", value);
if (counter.getLocalValuePrimitive() == 5) {
notifyLatch.trigger();
}
}
@Override
public void close() throws Exception {
shutdownLatch.await();
}
private static void reset() throws InterruptedException {
notifyLatch.reset();
shutdownLatch.reset();
}
}
/** Outputs format which waits for the previous mapper. */
private static | NotifyingMapper |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/fieldcaps/RequestDispatcherTests.java | {
"start": 42925,
"end": 49537
} | class ____ extends TransportService {
final SetOnce<RequestTracker> requestTracker = new SetOnce<>();
final ThreadPool threadPool;
private TransportInterceptor.AsyncSender interceptor = null;
private TestTransportService(Transport transport, TransportInterceptor.AsyncSender asyncSender, ThreadPool threadPool) {
super(Settings.EMPTY, transport, threadPool, new TransportInterceptor() {
@Override
public AsyncSender interceptSender(AsyncSender sender) {
return asyncSender;
}
}, addr -> newNode("local"), null, Collections.emptySet());
this.threadPool = threadPool;
}
@Override
public Transport.Connection getConnection(DiscoveryNode node) {
final Transport.Connection conn = mock(Transport.Connection.class);
when(conn.getNode()).thenReturn(node);
return conn;
}
static TestTransportService newTestTransportService() {
final TestThreadPool threadPool = new TestThreadPool("test");
TcpTransport transport = new Netty4Transport(
Settings.EMPTY,
TransportVersion.current(),
threadPool,
new NetworkService(Collections.emptyList()),
PageCacheRecycler.NON_RECYCLING_INSTANCE,
new NamedWriteableRegistry(Collections.emptyList()),
new NoneCircuitBreakerService(),
new SharedGroupFactory(Settings.EMPTY)
);
SetOnce<TransportInterceptor.AsyncSender> asyncSenderHolder = new SetOnce<>();
TestTransportService transportService = new TestTransportService(transport, new TransportInterceptor.AsyncSender() {
@Override
public <T extends TransportResponse> void sendRequest(
Transport.Connection connection,
String action,
TransportRequest request,
TransportRequestOptions options,
TransportResponseHandler<T> handler
) {
final TransportInterceptor.AsyncSender asyncSender = asyncSenderHolder.get();
assertNotNull(asyncSender);
asyncSender.sendRequest(connection, action, request, options, handler);
}
}, threadPool);
asyncSenderHolder.set(new TransportInterceptor.AsyncSender() {
@Override
public <T extends TransportResponse> void sendRequest(
Transport.Connection connection,
String action,
TransportRequest request,
TransportRequestOptions options,
TransportResponseHandler<T> handler
) {
final RequestTracker requestTracker = transportService.requestTracker.get();
assertNotNull("Request tracker wasn't set", requestTracker);
requestTracker.verifyAndTrackRequest(connection, action, request);
if (transportService.interceptor != null) {
transportService.interceptor.sendRequest(connection, action, request, options, handler);
} else {
FieldCapabilitiesNodeRequest nodeRequest = (FieldCapabilitiesNodeRequest) request;
Set<String> indices = nodeRequest.shardIds().stream().map(ShardId::getIndexName).collect(Collectors.toSet());
transportService.sendResponse(
handler,
randomNodeResponse(indices, Collections.emptyList(), Collections.emptySet())
);
}
}
});
transportService.start();
return transportService;
}
void setTransportInterceptor(TransportInterceptor.AsyncSender interceptor) {
this.interceptor = interceptor;
}
@Override
protected void doClose() throws IOException {
super.doClose();
threadPool.shutdown();
requestTracker.get().verifyAfterComplete();
}
@SuppressWarnings("unchecked")
<T extends TransportResponse> void sendResponse(TransportResponseHandler<T> handler, TransportResponse resp) {
threadPool.executor(ThreadPool.Names.SEARCH_COORDINATION).submit(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
throw new AssertionError(e);
}
@Override
protected void doRun() {
handler.handleResponse((T) resp);
}
});
}
}
static FieldCapabilitiesRequest randomFieldCapRequest(boolean withFilter) {
final QueryBuilder filter = withFilter ? new RangeQueryBuilder("timestamp").from(randomNonNegativeLong()) : null;
return new FieldCapabilitiesRequest().fields("*").indexFilter(filter);
}
static FieldCapabilitiesNodeResponse randomNodeResponse(
Collection<String> successIndices,
Collection<ShardId> failedShards,
Set<ShardId> unmatchedShards
) {
final Map<ShardId, Exception> failures = new HashMap<>();
for (ShardId shardId : failedShards) {
failures.put(shardId, new IllegalStateException(randomAlphaOfLength(10)));
}
final List<FieldCapabilitiesIndexResponse> indexResponses = new ArrayList<>();
Map<String, List<String>> indicesWithMappingHash = new HashMap<>();
for (String index : successIndices) {
if (randomBoolean()) {
indicesWithMappingHash.computeIfAbsent(index, k -> new ArrayList<>()).add(index);
} else {
indexResponses.add(
new FieldCapabilitiesIndexResponse(
index,
null,
FieldCapabilitiesIndexResponseTests.randomFieldCaps(),
true,
randomFrom(IndexMode.values())
)
);
}
}
indexResponses.addAll(FieldCapabilitiesIndexResponseTests.randomIndexResponsesWithMappingHash(indicesWithMappingHash));
Randomness.shuffle(indexResponses);
return new FieldCapabilitiesNodeResponse(indexResponses, failures, unmatchedShards);
}
static | TestTransportService |
java | google__dagger | javatests/dagger/internal/codegen/ModuleFactoryGeneratorTest.java | {
"start": 41050,
"end": 41419
} | class ____<T1, T2 extends Bar<T1>> {",
" @Provides",
" Map<T1, T2> provideMap(T1 t1) { return null; }",
"}");
Source packagePrivateFoo =
CompilerTests.javaSource(
"test.Foo",
"package test;",
"",
"import javax.inject.Inject;",
"",
" | ParameterizedModule |
java | greenrobot__greendao | DaoCore/src/main/java/org/greenrobot/greendao/test/AbstractDaoTest.java | {
"start": 1072,
"end": 1338
} | class ____ DAO related testing without any tests. Prepares an in-memory DB and DAO.
*
* @author Markus
*
* @param <D>
* DAO class
* @param <T>
* Entity type of the DAO
* @param <K>
* Key type of the DAO
*/
public abstract | for |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/InjectionTargetInfo.java | {
"start": 514,
"end": 610
} | enum ____ {
BEAN,
OBSERVER,
DISPOSER,
INVOKER,
}
}
| TargetKind |
java | quarkusio__quarkus | test-framework/junit5-component/src/test/java/io/quarkus/test/component/declarative/InstanceComponentTest.java | {
"start": 303,
"end": 477
} | class ____ {
@Inject
Instance<SomeBean> instance;
@Test
public void testComponents() {
assertTrue(instance.get().ping());
}
}
| InstanceComponentTest |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/support/descriptor/MethodSource.java | {
"start": 5866,
"end": 6746
} | class ____ be loaded.
*
* @since 1.7
* @see #getClassName()
*/
@API(status = STABLE, since = "1.7")
public Class<?> getJavaClass() {
return lazyLoadJavaClass();
}
/**
* Get the {@linkplain Method Java method} of this source.
*
* <p>If the {@link Method} was not provided, but only the name, this method
* attempts to lazily load the {@code Method} based on its name and throws a
* {@link PreconditionViolationException} if the method cannot be loaded.
*
* @since 1.7
* @see #getMethodName()
*/
@API(status = STABLE, since = "1.7")
public Method getJavaMethod() {
return lazyLoadJavaMethod();
}
private Class<?> lazyLoadJavaClass() {
if (this.javaClass == null) {
// @formatter:off
this.javaClass = ReflectionSupport.tryToLoadClass(this.className).getNonNullOrThrow(
cause -> new PreconditionViolationException("Could not load | cannot |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/validation/CatalogLSResourceResolver.java | {
"start": 1787,
"end": 4900
} | class ____ implements LSInput {
private final InputSource inputSource;
private String publicId;
private final String systemId;
private final String baseURI;
LSInputSource(String namespaceURI, String publicId, String systemId, String baseURI) {
if (publicId == null) {
publicId = namespaceURI;
}
this.publicId = publicId;
this.systemId = systemId;
this.baseURI = baseURI;
if (catalogResolver == null) {
throw new IllegalStateException("catalogResolver must be provided");
}
this.inputSource = catalogResolver.resolveEntity(publicId, systemId);
}
@Override
public Reader getCharacterStream() {
return null;
}
@Override
public void setCharacterStream(Reader characterStream) {
// noop
}
@Override
public InputStream getByteStream() {
return inputSource != null ? inputSource.getByteStream() : null;
}
@Override
public void setByteStream(InputStream byteStream) {
if (inputSource != null) {
inputSource.setByteStream(byteStream);
}
}
@Override
public String getStringData() {
return null;
}
@Override
public void setStringData(String stringData) {
// noop
}
@Override
public String getSystemId() {
if (inputSource != null) {
return inputSource.getSystemId();
}
return systemId;
}
@Override
public void setSystemId(String systemId) {
if (inputSource != null) {
inputSource.setSystemId(systemId);
}
}
@Override
public String getPublicId() {
if (inputSource != null) {
return inputSource.getPublicId();
}
return publicId;
}
@Override
public void setPublicId(String publicId) {
if (inputSource != null) {
inputSource.setPublicId(publicId);
} else {
this.publicId = publicId;
}
}
@Override
public String getBaseURI() {
return baseURI;
}
@Override
public void setBaseURI(String baseURI) {
// noop
}
@Override
public String getEncoding() {
if (inputSource != null) {
return inputSource.getEncoding();
}
return null;
}
@Override
public void setEncoding(String encoding) {
if (inputSource != null) {
inputSource.setEncoding(encoding);
}
}
@Override
public boolean getCertifiedText() {
return true;
}
@Override
public void setCertifiedText(boolean certifiedText) {
// noop
}
}
}
| LSInputSource |
java | apache__logging-log4j2 | log4j-core-test/src/test/java/org/apache/logging/log4j/core/pattern/NamedInstantPatternTest.java | {
"start": 1296,
"end": 2746
} | class ____ {
@ParameterizedTest
@EnumSource(NamedInstantPattern.class)
void compatibilityOfLegacyPattern(NamedInstantPattern namedPattern) {
if (namedPattern == NamedInstantPattern.ISO8601_OFFSET_DATE_TIME_HH) {
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
assumeThat(offset.getTotalSeconds() % 3600 == 0)
.withFailMessage(
"Skipping test: ISO8601_OFFSET_DATE_TIME_HH requires a whole-hour offset, but system offset is %s",
offset)
.isTrue();
}
InstantPatternFormatter legacyFormatter = InstantPatternFormatter.newBuilder()
.setPattern(namedPattern.getLegacyPattern())
.setLegacyFormattersEnabled(true)
.build();
InstantPatternFormatter formatter = InstantPatternFormatter.newBuilder()
.setPattern(namedPattern.getPattern())
.setLegacyFormattersEnabled(false)
.build();
Instant javaTimeInstant = Instant.now();
MutableInstant instant = new MutableInstant();
instant.initFromEpochSecond(javaTimeInstant.getEpochSecond(), javaTimeInstant.getNano());
String legacy = legacyFormatter.format(instant);
String modern = formatter.format(instant);
assertThat(legacy).isEqualTo(modern);
}
}
| NamedInstantPatternTest |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/progress/MockingProgressImplTest.java | {
"start": 3790,
"end": 3863
} | interface ____ extends MockitoListener, AutoCleanableListener {}
}
| MyListener |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/spi/metrics/VertxMetrics.java | {
"start": 934,
"end": 1341
} | interface ____ two purposes, one
* to be called by Vert.x itself for events like verticles deployed, timers created, etc. The other
* to provide Vert.x with other metrics SPI's which will be used for specific components i.e.
* {@link io.vertx.core.http.HttpServer}, {@link io.vertx.core.spi.metrics.EventBusMetrics}, etc.
*
* @author <a href="mailto:nscavell@redhat.com">Nick Scavelli</a>
*/
public | serves |
java | quarkusio__quarkus | extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusPermission.java | {
"start": 613,
"end": 1167
} | class ____<T> extends Permission {
private volatile InstanceHandle<T> bean = null;
/**
* Subclasses can declare constructors that accept permission name and/or arguments of a secured method.
*
* @param permissionName permission name, this matches {@link PermissionChecker#value()}
* @see PermissionsAllowed#params() for more information about additional Permission arguments
*/
protected QuarkusPermission(String permissionName) {
super(permissionName);
}
/**
* @return declaring | QuarkusPermission |
java | spring-projects__spring-security | acl/src/main/java/org/springframework/security/acls/jdbc/AclClassIdUtils.java | {
"start": 5083,
"end": 5459
} | class ____ implements Converter<String, Long> {
@Override
public Long convert(String identifierAsString) {
if (identifierAsString == null) {
throw new ConversionFailedException(TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(Long.class), null, null);
}
return Long.parseLong(identifierAsString);
}
}
private static | StringToLongConverter |
java | apache__flink | flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/api/output/operators/LazyTimerService.java | {
"start": 1282,
"end": 2992
} | class ____ implements TimerService {
private final Supplier<InternalTimerService<VoidNamespace>> supplier;
private final ProcessingTimeService processingTimeService;
private InternalTimerService<VoidNamespace> internalTimerService;
LazyTimerService(
Supplier<InternalTimerService<VoidNamespace>> supplier,
ProcessingTimeService processingTimeService) {
this.supplier = supplier;
this.processingTimeService = processingTimeService;
}
@Override
public long currentProcessingTime() {
return processingTimeService.getCurrentProcessingTime();
}
@Override
public long currentWatermark() {
// The watermark does not advance
// when bootstrapping state.
return Long.MIN_VALUE;
}
@Override
public void registerProcessingTimeTimer(long time) {
ensureInitialized();
internalTimerService.registerProcessingTimeTimer(VoidNamespace.INSTANCE, time);
}
@Override
public void registerEventTimeTimer(long time) {
ensureInitialized();
internalTimerService.registerEventTimeTimer(VoidNamespace.INSTANCE, time);
}
@Override
public void deleteProcessingTimeTimer(long time) {
ensureInitialized();
internalTimerService.deleteProcessingTimeTimer(VoidNamespace.INSTANCE, time);
}
@Override
public void deleteEventTimeTimer(long time) {
ensureInitialized();
internalTimerService.deleteEventTimeTimer(VoidNamespace.INSTANCE, time);
}
private void ensureInitialized() {
if (internalTimerService == null) {
internalTimerService = supplier.get();
}
}
}
| LazyTimerService |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/StoredProcedureAttributeSourceUnitTests.java | {
"start": 15495,
"end": 19450
} | interface ____ {
/**
* Explicitly mapped to a procedure with name "plus1inout" in database.
*/
@Procedure("plus1inout") // DATAJPA-455
Integer explicitlyNamedPlus1inout(Integer arg);
/**
* Explicitly mapped to a procedure with name "plus1inout" in database via alias.
*/
@Procedure(procedureName = "plus1inout") // DATAJPA-455
Integer explicitPlus1inoutViaProcedureNameAlias(Integer arg);
/**
* Explicitly mapped to a procedure with name "plus1inout" in database via alias and explicitly named output
* parameter.
*/
@Procedure(procedureName = "plus1inout", outputParameterName = "res") // DATAJPA-1297
Integer explicitPlus1inoutViaProcedureNameAliasAndOutputParameterName(Integer arg);
/**
* Implicitly mapped to a procedure with name "plus1inout" in database via alias.
*/
@Procedure // DATAJPA-455
Integer plus1inout(Integer arg);
/**
* Explicitly mapped to named stored procedure "User.plus1IO" in {@link EntityManager}.
*/
@Procedure(name = "User.plus1IO") // DATAJPA-455
Integer entityAnnotatedCustomNamedProcedurePlus1IO(@Param("arg") Integer arg);
/**
* Explicitly mapped to named stored procedure "User.plus1IO" in {@link EntityManager} with an outputParameterName.
*/
@Procedure(name = "User.plus1IO", outputParameterName = "override") // DATAJPA-707
Integer entityAnnotatedCustomNamedProcedureOutputParamNamePlus1IO(@Param("arg") Integer arg);
/**
* Explicitly mapped to named stored procedure "User.plus1IO2" in {@link EntityManager}.
*/
@Procedure(name = "User.plus1IO2") // DATAJPA-707
Map<String, Integer> entityAnnotatedCustomNamedProcedurePlus1IO2(@Param("arg") Integer arg);
/**
* Implicitly mapped to named stored procedure "User.plus1" in {@link EntityManager}.
*/
@Procedure // DATAJPA-455
Integer plus1(@Param("arg") Integer arg);
@ComposedProcedureUsingAliasFor(explicitProcedureName = "plus1inout")
Integer plus1inoutWithComposedAnnotationOverridingProcedureName(Integer arg);
@ComposedProcedureUsingAliasFor(emProcedureName = "User.plus1")
Integer plus1inoutWithComposedAnnotationOverridingName(Integer arg);
@Procedure("0_input_1_row_resultset") // DATAJPA-1657
Dummy singleEntityFrom1RowResultSetAndNoInput();
@Procedure("1_input_1_row_resultset") // DATAJPA-1657
Dummy singleEntityFrom1RowResultSetWithInput(Integer arg);
@Procedure("0_input_1_resultset") // DATAJPA-1657
List<Dummy> entityListFromResultSetWithNoInput();
@Procedure("1_input_1_resultset") // DATAJPA-1657
List<Dummy> entityListFromResultSetWithInput(Integer arg);
@Procedure("1_input_1_resultset") // DATAJPA-1657
List<Object[]> genericObjectListFromResultSetWithInput(Integer arg);
@Procedure(value = "1_input_1_resultset", outputParameterName = "dummies") // DATAJPA-1657
List<Dummy> entityListFromResultSetWithInputAndNamedOutput(Integer arg);
@Procedure(value = "1_input_1_resultset", outputParameterName = "dummies", refCursor = true) // DATAJPA-1657
List<Dummy> entityListFromResultSetWithInputAndNamedOutputAndCursor(Integer arg);
@Procedure(name = "InOut.in_in_out")
Map<Object, Object> inInOut(Integer in1, Integer in2);
@Procedure(name = "InOut.inout_in_out")
Map<Object, Object> inoutInOut(Integer inout1, Integer in2);
@Procedure(name = "InOut.inout_out")
Map<Object, Object> inoutOut(Integer inout1);
@Procedure(name = "InOut.out_in_in")
Map<Object, Object> outInIn(Integer in1, Integer in2);
@Procedure(name = "InOut.in_in_inout_out")
Map<Object, Object> inInInoutOut(Integer in1, Integer in2, Integer inout);
@Procedure(name = "InOut.in_inout_in_out")
Map<Object, Object> inInoutInOut(Integer in1, Integer inout, Integer in2);
@Procedure(name = "InOut.in_inout_inout_out")
Map<Object, Object> inInoutInoutOut(Integer in1, Integer inout1, Integer inout2);
}
@SuppressWarnings("unused")
@Procedure
@Retention(RetentionPolicy.RUNTIME)
private @ | DummyRepository |
java | google__gson | gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java | {
"start": 1348,
"end": 2380
} | class ____ {
private static final String DEFAULT_VALUE = "test123";
private static final String SUFFIX = "blah";
private Gson gson;
@Before
public void setUp() throws Exception {
gson =
new GsonBuilder()
.registerTypeAdapter(DataHolder.class, new DataHolderDeserializer())
.create();
}
@Test
public void testDefaultConstructorNotCalledOnObject() {
DataHolder data = new DataHolder(DEFAULT_VALUE);
String json = gson.toJson(data);
DataHolder actual = gson.fromJson(json, DataHolder.class);
assertThat(actual.getData()).isEqualTo(DEFAULT_VALUE + SUFFIX);
}
@Test
public void testDefaultConstructorNotCalledOnField() {
DataHolderWrapper dataWrapper = new DataHolderWrapper(new DataHolder(DEFAULT_VALUE));
String json = gson.toJson(dataWrapper);
DataHolderWrapper actual = gson.fromJson(json, DataHolderWrapper.class);
assertThat(actual.getWrappedData().getData()).isEqualTo(DEFAULT_VALUE + SUFFIX);
}
private static | CustomDeserializerTest |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassUtils.java | {
"start": 16586,
"end": 17399
} | interface ____
types.addAll(getAllInterfaces(type, typeFilters));
return unmodifiableSet(types);
}
/**
* the semantics is same as {@link Class#isAssignableFrom(Class)}
*
* @param superType the super type
* @param targetType the target type
* @return see {@link Class#isAssignableFrom(Class)}
* @since 2.7.6
*/
public static boolean isAssignableFrom(Class<?> superType, Class<?> targetType) {
// any argument is null
if (superType == null || targetType == null) {
return false;
}
// equals
if (Objects.equals(superType, targetType)) {
return true;
}
// isAssignableFrom
return superType.isAssignableFrom(targetType);
}
/**
* Test the specified | classes |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ChainedAssertionLosesContextTest.java | {
"start": 3639,
"end": 4572
} | class ____ {
final String string;
final int integer;
Foo(String string, int integer) {
this.string = string;
this.integer = integer;
}
String string() {
return string;
}
int integer() {
return integer;
}
Foo otherFoo() {
return this;
}
}
}\
""")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"ChainedAssertionLosesContextNegativeCases.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
/**
* @author cpovirk@google.com (Chris Povirk)
*/
public | Foo |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/IdFieldMapper.java | {
"start": 1125,
"end": 3003
} | class ____ extends MetadataFieldMapper {
public static final String NAME = "_id";
public static final String CONTENT_TYPE = "_id";
public static final TypeParser PARSER = new FixedTypeParser(MappingParserContext::idFieldMapper);
private static final Map<String, NamedAnalyzer> ANALYZERS = Map.of(NAME, Lucene.KEYWORD_ANALYZER);
protected IdFieldMapper(MappedFieldType mappedFieldType) {
super(mappedFieldType);
assert mappedFieldType.isSearchable();
}
@Override
public Map<String, NamedAnalyzer> indexAnalyzers() {
return ANALYZERS;
}
@Override
protected final String contentType() {
return CONTENT_TYPE;
}
/**
* Description of the document being parsed used in error messages. Not
* called unless there is an error.
*/
public abstract String documentDescription(DocumentParserContext context);
/**
* Description of the document being indexed used after parsing for things
* like version conflicts.
*/
public abstract String documentDescription(ParsedDocument parsedDocument);
/**
* Build the {@code _id} to use on requests reindexing into indices using
* this {@code _id}.
*/
public abstract String reindexId(String id);
/**
* Create a {@link Field} to store the provided {@code _id} that "stores"
* the {@code _id} so it can be fetched easily from the index.
*/
public static Field standardIdField(String id) {
return new StringField(NAME, Uid.encodeId(id), Field.Store.YES);
}
/**
* Create a {@link Field} corresponding to a synthetic {@code _id} field, which is not indexed but instead resolved at runtime.
*/
public static Field syntheticIdField(String id) {
return new SyntheticIdField(Uid.encodeId(id));
}
protected abstract static | IdFieldMapper |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/BadImportTest.java | {
"start": 1004,
"end": 1599
} | class ____ {
private final CompilationTestHelper compilationTestHelper =
CompilationTestHelper.newInstance(BadImport.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(BadImport.class, getClass());
@Test
public void positive_static_simpleCase() {
compilationTestHelper
.addSourceLines(
"Test.java",
"""
import static com.google.common.collect.ImmutableList.of;
import com.google.common.collect.ImmutableList;
| BadImportTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/RedissonBloomFilter.java | {
"start": 2121,
"end": 16458
} | class ____<T> extends RedissonExpirable implements RBloomFilter<T> {
volatile long size;
volatile int hashIterations;
final CommandAsyncExecutor commandExecutor;
String configName;
protected RedissonBloomFilter(CommandAsyncExecutor commandExecutor, String name) {
super(commandExecutor, name);
this.commandExecutor = commandExecutor;
this.configName = suffixName(getRawName(), "config");
}
protected RedissonBloomFilter(Codec codec, CommandAsyncExecutor commandExecutor, String name) {
super(codec, commandExecutor, name);
this.commandExecutor = commandExecutor;
this.configName = suffixName(getRawName(), "config");
}
private int optimalNumOfHashFunctions(long n, long m) {
return Math.max(1, (int) Math.round((double) m / n * Math.log(2)));
}
private long optimalNumOfBits(long n, double p) {
if (p == 0) {
p = Double.MIN_VALUE;
}
return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2)));
}
private long[] hash(Object object) {
ByteBuf state = encode(object);
try {
return Hash.hash128(state);
} finally {
state.release();
}
}
@Override
public boolean add(T object) {
return add(Arrays.asList(object)) > 0;
}
@Override
public RFuture<Boolean> addAsync(T object) {
CompletionStage<Boolean> f = addAsync(Arrays.asList(object)).thenApply(r -> r > 0);
return new CompletableFutureWrapper<>(f);
}
@Override
public RFuture<Long> addAsync(Collection<T> objects) {
CompletionStage<Void> future = CompletableFuture.completedFuture(null);
if (size == 0) {
future = readConfigAsync();
}
CompletionStage<Long> f = future.thenCompose(r -> {
List<Long> allIndexes = index(objects);
List<Object> params = new ArrayList<>();
params.add(size);
params.add(hashIterations);
int s = allIndexes.size() / objects.size();
params.add(s);
params.addAll(allIndexes);
return commandExecutor.evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_LONG,
"local size = redis.call('hget', KEYS[1], 'size');" +
"local hashIterations = redis.call('hget', KEYS[1], 'hashIterations');" +
"assert(size == ARGV[1] and hashIterations == ARGV[2], 'Bloom filter config has been changed')" +
"local k = 0;" +
"local c = 0;" +
"for i = 4, #ARGV, 1 do " +
"local r = redis.call('setbit', KEYS[2], ARGV[i], 1); " +
"if r == 0 then " +
"k = k + 1;" +
"end; " +
"if ((i - 4) + 1) % ARGV[3] == 0 then " +
"if k > 0 then " +
"c = c + 1;" +
"end; " +
"k = 0; " +
"end; " +
"end; " +
"return c;",
Arrays.asList(configName, getRawName()),
params.toArray());
});
return new CompletableFutureWrapper<>(f);
}
@Override
public long add(Collection<T> objects) {
return get(addAsync(objects));
}
private long[] hash(long hash1, long hash2, int iterations, long size) {
long[] indexes = new long[iterations];
long hash = hash1;
for (int i = 0; i < iterations; i++) {
indexes[i] = (hash & Long.MAX_VALUE) % size;
if (i % 2 == 0) {
hash += hash2;
} else {
hash += hash1;
}
}
return indexes;
}
@Override
public RFuture<Long> containsAsync(Collection<T> objects) {
CompletionStage<Long> f = CompletableFuture.completedFuture(null);
if (size == 0) {
f = readConfigAsync().handle((r, e) -> {
if (e instanceof IllegalArgumentException) {
return 0L;
}
return null;
});
}
f = f.thenCompose(r -> {
if (r != null) {
return CompletableFuture.completedFuture(r);
}
List<Long> allIndexes = index(objects);
List<Object> params = new ArrayList<>();
params.add(size);
params.add(hashIterations);
params.add(objects.size());
params.addAll(allIndexes);
return commandExecutor.evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_LONG,
"local size = redis.call('hget', KEYS[1], 'size');" +
"local hashIterations = redis.call('hget', KEYS[1], 'hashIterations');" +
"if size ~= ARGV[1] or hashIterations ~= ARGV[2] then " +
"return 0;" +
"end;" +
"local k = 0;" +
"local c = 0;" +
"local cc = (#ARGV - 3) / ARGV[3];" +
"for i = 4, #ARGV, 1 do " +
"local r = redis.call('getbit', KEYS[2], ARGV[i]); " +
"if r == 0 then " +
"k = k + 1;" +
"end; " +
"if ((i - 4) + 1) % cc == 0 then " +
"if k > 0 then " +
"c = c + 1;" +
"end; " +
"k = 0; " +
"end; " +
"end; " +
"return ARGV[3] - c;",
Arrays.asList(configName, getRawName()),
params.toArray());
});
return new CompletableFutureWrapper<>(f);
}
@Override
public long contains(Collection<T> objects) {
return get(containsAsync(objects));
}
List<Long> index(Collection<T> objects) {
List<Long> allIndexes = new LinkedList<>();
for (T object : objects) {
long[] hashes = hash(object);
long[] indexes = hash(hashes[0], hashes[1], hashIterations, size);
allIndexes.addAll(Arrays.stream(indexes).boxed().collect(Collectors.toList()));
}
return allIndexes;
}
@Override
public boolean contains(T object) {
return contains(Arrays.asList(object)) > 0;
}
@Override
public RFuture<Boolean> containsAsync(T object) {
CompletionStage<Boolean> f = containsAsync(Arrays.asList(object)).thenApply(r -> r > 0);
return new CompletableFutureWrapper<>(f);
}
@Override
public long count() {
return get(countAsync());
}
@Override
public RFuture<Long> countAsync() {
CompletionStage<Void> f = readConfigAsync();
CompletionStage<Long> res = f.thenCompose(r -> {
RedissonBitSet bs = new RedissonBitSet(commandExecutor, getName());
return bs.cardinalityAsync().thenApply(c -> {
return Math.round(-size / ((double) hashIterations) * Math.log(1 - c / ((double) size)));
});
});
return new CompletableFutureWrapper<>(res);
}
@Override
public RFuture<Boolean> deleteAsync() {
return deleteAsync(getRawName(), configName);
}
@Override
public RFuture<Boolean> copyAsync(List<Object> keys, int database, boolean replace) {
String newName = (String) keys.get(1);
List<Object> kks = Arrays.asList(getRawName(), configName,
newName, suffixName(newName, "config"));
return super.copyAsync(kks, database, replace);
}
@Override
public RFuture<Long> sizeInMemoryAsync() {
List<Object> keys = Arrays.asList(getRawName(), configName);
return super.sizeInMemoryAsync(keys);
}
CompletionStage<Void> readConfigAsync() {
RFuture<Map<String, String>> future = commandExecutor.readAsync(configName, StringCodec.INSTANCE,
new RedisCommand<Map<Object, Object>>("HGETALL", new ObjectMapReplayDecoder()), configName);
return future.thenAccept(config -> {
readConfig(config);
});
}
private void readConfig(Map<String, String> config) {
if (config.get("hashIterations") == null
|| config.get("size") == null) {
throw new IllegalStateException("Bloom filter is not initialized!");
}
size = Long.valueOf(config.get("size"));
hashIterations = Integer.valueOf(config.get("hashIterations"));
}
protected long getMaxSize() {
return Integer.MAX_VALUE*2L;
}
@Override
public boolean tryInit(long expectedInsertions, double falseProbability) {
return get(tryInitAsync(expectedInsertions, falseProbability));
}
@Override
public RFuture<Boolean> tryInitAsync(long expectedInsertions, double falseProbability) {
if (falseProbability > 1) {
throw new IllegalArgumentException("Bloom filter false probability can't be greater than 1");
}
if (falseProbability < 0) {
throw new IllegalArgumentException("Bloom filter false probability can't be negative");
}
size = optimalNumOfBits(expectedInsertions, falseProbability);
if (size == 0) {
throw new IllegalArgumentException("Bloom filter calculated size is " + size);
}
if (size > getMaxSize()) {
throw new IllegalArgumentException("Bloom filter size can't be greater than " + getMaxSize() + ". But calculated size is " + size);
}
hashIterations = optimalNumOfHashFunctions(expectedInsertions, size);
return commandExecutor.evalWriteAsync(configName, StringCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if redis.call('exists', KEYS[1]) == 1 then " +
"return 0;" +
"end; " +
"redis.call('hset', KEYS[1], 'size', ARGV[1]);" +
"redis.call('hset', KEYS[1], 'hashIterations', ARGV[2]);" +
"redis.call('hset', KEYS[1], 'expectedInsertions', ARGV[3]);" +
"redis.call('hset', KEYS[1], 'falseProbability', ARGV[4]);" +
"return 1;",
Arrays.asList(configName),
size, hashIterations, expectedInsertions, falseProbability);
}
@Override
public RFuture<Boolean> expireAsync(long timeToLive, TimeUnit timeUnit, String param, String... keys) {
return super.expireAsync(timeToLive, timeUnit, param, getRawName(), configName);
}
@Override
protected RFuture<Boolean> expireAtAsync(long timestamp, String param, String... keys) {
return super.expireAtAsync(timestamp, param, getRawName(), configName);
}
@Override
public RFuture<Boolean> clearExpireAsync() {
return clearExpireAsync(getRawName(), configName);
}
@Override
public long getExpectedInsertions() {
return get(getExpectedInsertionsAsync());
}
@Override
public RFuture<Long> getExpectedInsertionsAsync() {
return readSettingAsync(RedisCommands.EVAL_LONG, LongCodec.INSTANCE, "expectedInsertions");
}
private <T> RFuture<T> readSettingAsync(RedisCommand<T> evalCommandType, Codec codec, String settingName) {
return commandExecutor.evalReadAsync(configName, codec, evalCommandType,
"if redis.call('exists', KEYS[1]) == 0 then " +
"assert(false, 'Bloom filter is not initialized')" +
"end; " +
"return redis.call('hget', KEYS[1], ARGV[1]);",
Arrays.asList(configName),
settingName);
}
@Override
public double getFalseProbability() {
return get(getFalseProbabilityAsync());
}
@Override
public RFuture<Double> getFalseProbabilityAsync() {
return readSettingAsync(RedisCommands.EVAL_DOUBLE, DoubleCodec.INSTANCE, "falseProbability");
}
@Override
public long getSize() {
return get(getSizeAsync());
}
@Override
public RFuture<Long> getSizeAsync() {
return readSettingAsync(RedisCommands.EVAL_LONG, LongCodec.INSTANCE, "size");
}
@Override
public int getHashIterations() {
return get(getHashIterationsAsync());
}
@Override
public RFuture<Integer> getHashIterationsAsync() {
return readSettingAsync(RedisCommands.EVAL_INTEGER, LongCodec.INSTANCE, "hashIterations");
}
@Override
public RFuture<Boolean> isExistsAsync() {
return commandExecutor.writeAsync(getRawName(), codec, RedisCommands.EXISTS, getRawName(), configName);
}
@Override
public RFuture<Void> renameAsync(String newName) {
String nn = mapName(newName);
String newConfigName = suffixName(nn, "config");
List<Object> kks = Arrays.asList(getRawName(), configName,
nn, newConfigName);
return renameAsync(commandExecutor, kks, () -> {
setName(newName);
this.configName = newConfigName;
});
}
@Override
public RFuture<Boolean> renamenxAsync(String newName) {
String nn = mapName(newName);
String newConfigName = suffixName(nn, "config");
List<Object> kks = Arrays.asList(getRawName(), configName,
nn, newConfigName);
return renamenxAsync(commandExecutor, kks, value -> {
if (value) {
setName(newName);
this.configName = newConfigName;
}
});
}
}
| RedissonBloomFilter |
java | apache__logging-log4j2 | log4j-jul/src/test/java/org/apache/logging/log4j/jul/test/BracketInNotInterpolatedMessageTest.java | {
"start": 1418,
"end": 2301
} | class ____ {
@BeforeAll
static void setUpClass() {
System.setProperty("java.util.logging.manager", LogManager.class.getName());
}
@AfterAll
static void tearDownClass() {
System.clearProperty("java.util.logging.manager");
}
@Test
void noInterpolation() {
final Logger logger = Logger.getLogger("Test");
logger.info("{raw}");
logger.log(
new LogRecord(INFO, "{raw}")); // should lead to the same as previous but was not the case LOG4J2-1251
final List<LogEvent> events =
ListAppender.getListAppender("TestAppender").getEvents();
assertThat(events, hasSize(2));
assertEquals("{raw}", events.get(0).getMessage().getFormattedMessage());
assertEquals("{raw}", events.get(1).getMessage().getFormattedMessage());
}
}
| BracketInNotInterpolatedMessageTest |
java | alibaba__nacos | mcp-registry-adaptor/src/main/java/com/alibaba/nacos/mcpregistry/config/HttpPathConfiguration.java | {
"start": 1338,
"end": 1853
} | class ____ {
@Bean
public TomcatConnectorCustomizer connectorCustomizer() {
return (connector) -> connector.setEncodedSolidusHandling(EncodedSolidusHandling.PASS_THROUGH.getValue());
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
firewall.setAllowUrlEncodedPercent(true);
return (web) -> web.httpFirewall(firewall);
}
}
| HttpPathConfiguration |
java | jhy__jsoup | src/test/java/org/jsoup/nodes/NodeIteratorTest.java | {
"start": 213,
"end": 9688
} | class ____ {
String html = "<div id=1><p>One<p>Two</div><div id=2><p>Three<p>Four</div>";
@Test void canIterateNodes() {
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
assertIterates(it, "#root;html;head;body;div#1;p;One;p;Two;div#2;p;Three;p;Four;");
assertFalse(it.hasNext());
boolean threw = false;
try {
it.next();
} catch (NoSuchElementException e) {
threw = true;
}
assertTrue(threw);
}
@Test void hasNextIsPure() {
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
assertTrue(it.hasNext());
assertTrue(it.hasNext());
assertIterates(it, "#root;html;head;body;div#1;p;One;p;Two;div#2;p;Three;p;Four;");
assertFalse(it.hasNext());
}
@Test void iterateSubTree() {
Document doc = Jsoup.parse(html);
Element div1 = doc.expectFirst("div#1");
NodeIterator<Node> it = NodeIterator.from(div1);
assertIterates(it, "div#1;p;One;p;Two;");
assertFalse(it.hasNext());
Element div2 = doc.expectFirst("div#2");
NodeIterator<Node> it2 = NodeIterator.from(div2);
assertIterates(it2, "div#2;p;Three;p;Four;");
assertFalse(it2.hasNext());
}
@Test void canRestart() {
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
assertIterates(it, "#root;html;head;body;div#1;p;One;p;Two;div#2;p;Three;p;Four;");
it.restart(doc.expectFirst("div#2"));
assertIterates(it, "div#2;p;Three;p;Four;");
}
@Test void canIterateJustOneSibling() {
Document doc = Jsoup.parse(html);
Element p2 = doc.expectFirst("p:contains(Two)");
assertEquals("Two", p2.text());
NodeIterator<Node> it = NodeIterator.from(p2);
assertIterates(it, "p;Two;");
NodeIterator<Element> elIt = new NodeIterator<>(p2, Element.class);
Element found = elIt.next();
assertSame(p2, found);
assertFalse(elIt.hasNext());
}
@Test void canIterateFirstEmptySibling() {
Document doc = Jsoup.parse("<div><p id=1></p><p id=2>.</p><p id=3>..</p>");
Element p1 = doc.expectFirst("p#1");
assertEquals("", p1.ownText());
NodeIterator<Node> it = NodeIterator.from(p1);
assertTrue(it.hasNext());
Node node = it.next();
assertSame(p1, node);
assertFalse(it.hasNext());
}
@Test void canRemoveViaIterator() {
String html = "<div id=out1><div id=1><p>One<p>Two</div><div id=2><p>Three<p>Four</div></div><div id=out2>Out2";
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
StringBuilder seen = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
if (node.attr("id").equals("1"))
it.remove();
trackSeen(node, seen);
}
assertEquals("#root;html;head;body;div#out1;div#1;div#2;p;Three;p;Four;div#out2;Out2;", seen.toString());
assertContents(doc, "#root;html;head;body;div#out1;div#2;p;Three;p;Four;div#out2;Out2;");
it = NodeIterator.from(doc);
seen = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
if (node.attr("id").equals("2"))
it.remove();
trackSeen(node, seen);
}
assertEquals("#root;html;head;body;div#out1;div#2;div#out2;Out2;", seen.toString());
assertContents(doc, "#root;html;head;body;div#out1;div#out2;Out2;");
}
@Test void canRemoveViaNode() {
String html = "<div id=out1><div id=1><p>One<p>Two</div><div id=2><p>Three<p>Four</div></div><div id=out2>Out2";
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
StringBuilder seen = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
if (node.attr("id").equals("1"))
node.remove();
trackSeen(node, seen);
}
assertEquals("#root;html;head;body;div#out1;div#1;div#2;p;Three;p;Four;div#out2;Out2;", seen.toString());
assertContents(doc, "#root;html;head;body;div#out1;div#2;p;Three;p;Four;div#out2;Out2;");
it = NodeIterator.from(doc);
seen = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
if (node.attr("id").equals("2"))
node.remove();
trackSeen(node, seen);
}
assertEquals("#root;html;head;body;div#out1;div#2;div#out2;Out2;", seen.toString());
assertContents(doc, "#root;html;head;body;div#out1;div#out2;Out2;");
}
@Test void canReplace() {
String html = "<div id=out1><div id=1><p>One<p>Two</div><div id=2><p>Three<p>Four</div></div><div id=out2>Out2";
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
StringBuilder seen = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
trackSeen(node, seen);
if (node.attr("id").equals("1")) {
node.replaceWith(new Element("span").text("Foo"));
}
}
assertEquals("#root;html;head;body;div#out1;div#1;span;Foo;div#2;p;Three;p;Four;div#out2;Out2;", seen.toString());
// ^^ we don't see <p>One, do see the replaced in <span>, and the subsequent nodes
assertContents(doc, "#root;html;head;body;div#out1;span;Foo;div#2;p;Three;p;Four;div#out2;Out2;");
it = NodeIterator.from(doc);
seen = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
trackSeen(node, seen);
if (node.attr("id").equals("2")) {
node.replaceWith(new Element("span").text("Bar"));
}
}
assertEquals("#root;html;head;body;div#out1;span;Foo;div#2;span;Bar;div#out2;Out2;", seen.toString());
assertContents(doc, "#root;html;head;body;div#out1;span;Foo;span;Bar;div#out2;Out2;");
}
@Test void canWrap() {
Document doc = Jsoup.parse(html);
NodeIterator<Node> it = NodeIterator.from(doc);
boolean sawInner = false;
while (it.hasNext()) {
Node node = it.next();
if (node.attr("id").equals("1")) {
node.wrap("<div id=outer>");
}
if (node instanceof TextNode && ((TextNode) node).text().equals("One"))
sawInner = true;
}
assertContents(doc, "#root;html;head;body;div#outer;div#1;p;One;p;Two;div#2;p;Three;p;Four;");
assertTrue(sawInner);
}
@Test void canFilterForElements() {
Document doc = Jsoup.parse(html);
NodeIterator<Element> it = new NodeIterator<>(doc, Element.class);
StringBuilder seen = new StringBuilder();
while (it.hasNext()) {
Element el = it.next();
assertNotNull(el);
trackSeen(el, seen);
}
assertEquals("#root;html;head;body;div#1;p;p;div#2;p;p;", seen.toString());
}
@Test void canFilterForTextNodes() {
Document doc = Jsoup.parse(html);
NodeIterator<TextNode> it = new NodeIterator<>(doc, TextNode.class);
StringBuilder seen = new StringBuilder();
while (it.hasNext()) {
TextNode text = it.next();
assertNotNull(text);
trackSeen(text, seen);
}
assertEquals("One;Two;Three;Four;", seen.toString());
assertContents(doc, "#root;html;head;body;div#1;p;One;p;Two;div#2;p;Three;p;Four;");
}
@Test void canModifyFilteredElements() {
Document doc = Jsoup.parse(html);
NodeIterator<Element> it = new NodeIterator<>(doc, Element.class);
StringBuilder seen = new StringBuilder();
while (it.hasNext()) {
Element el = it.next();
if (!el.ownText().isEmpty())
el.text(el.ownText() + "++");
trackSeen(el, seen);
}
assertEquals("#root;html;head;body;div#1;p;p;div#2;p;p;", seen.toString());
assertContents(doc, "#root;html;head;body;div#1;p;One++;p;Two++;div#2;p;Three++;p;Four++;");
}
static <T extends Node> void assertIterates(Iterator<T> it, String expected) {
Node previous = null;
StringBuilder actual = new StringBuilder();
while (it.hasNext()) {
Node node = it.next();
assertNotNull(node);
assertNotSame(previous, node);
trackSeen(node, actual);
previous = node;
}
assertEquals(expected, actual.toString());
}
static void assertContents(Element el, String expected) {
NodeIterator<Node> it = NodeIterator.from(el);
assertIterates(it, expected);
}
public static void trackSeen(Node node, StringBuilder actual) {
if (node instanceof Element) {
Element el = (Element) node;
actual.append(el.tagName());
if (el.hasAttr("id"))
actual.append("#").append(el.id());
}
else if (node instanceof TextNode)
actual.append(((TextNode) node).text());
else
actual.append(node.nodeName());
actual.append(";");
}
}
| NodeIteratorTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/memory/MemoryReservationException.java | {
"start": 944,
"end": 1133
} | class ____ extends Exception {
private static final long serialVersionUID = 1L;
MemoryReservationException(String message) {
super(message);
}
}
| MemoryReservationException |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.java | {
"start": 1158,
"end": 1978
} | class ____ an implementation of the ExporterListenerAdapter abstract class,
* <p>
* which is used to listen for changes to the InjvmExporter instances.
* <p>
* It maintains two ConcurrentHashMaps, one to keep track of the ExporterChangeListeners registered for each service,
* <p>
* and another to keep track of the currently exported services and their associated Exporter instances.
* <p>
* It overrides the exported and unexported methods to add or remove the corresponding Exporter instances to/from
* <p>
* the exporters ConcurrentHashMap, and to notify all registered ExporterChangeListeners of the change.
* <p>
* It also provides methods to add or remove ExporterChangeListeners for a specific service, and to retrieve the
* <p>
* currently exported Exporter instance for a given service.
*/
public | is |
java | spring-projects__spring-framework | spring-jms/src/main/java/org/springframework/jms/core/JmsClient.java | {
"start": 6342,
"end": 9034
} | interface ____ {
/**
* Apply the given timeout to any subsequent receive operations.
* @param receiveTimeout the timeout in milliseconds
* @see JmsTemplate#setReceiveTimeout
*/
OperationSpec withReceiveTimeout(long receiveTimeout);
/**
* Apply the given delivery delay to any subsequent send operations.
* @param deliveryDelay the delay in milliseconds
* @see JmsTemplate#setDeliveryDelay
*/
OperationSpec withDeliveryDelay(long deliveryDelay);
/**
* Set whether message delivery should be persistent or non-persistent.
* @param persistent to choose between delivery mode "PERSISTENT"
* ({@code true}) or "NON_PERSISTENT" ({@code false})
* @see JmsTemplate#setDeliveryPersistent
*/
OperationSpec withDeliveryPersistent(boolean persistent);
/**
* Apply the given priority to any subsequent send operations.
* @param priority the priority value
* @see JmsTemplate#setPriority
*/
OperationSpec withPriority(int priority);
/**
* Apply the given time-to-live to any subsequent send operations.
* @param timeToLive the message lifetime in milliseconds
* @see JmsTemplate#setTimeToLive
*/
OperationSpec withTimeToLive(long timeToLive);
/**
* Send the given {@link Message} to the pre-bound destination.
* @param message the spring-messaging {@link Message} to send
* @see #withDeliveryDelay
* @see #withDeliveryPersistent
* @see #withPriority
* @see #withTimeToLive
*/
void send(Message<?> message) throws MessagingException;
/**
* Send a message with the given payload to the pre-bound destination.
* @param payload the payload to convert into a {@link Message}
* @see #withDeliveryDelay
* @see #withDeliveryPersistent
* @see #withPriority
* @see #withTimeToLive
*/
void send(Object payload) throws MessagingException;
/**
* Send a message with the given payload to the pre-bound destination.
* @param payload the payload to convert into a {@link Message}
* @param headers the message headers to apply to the {@link Message}
* @see #withDeliveryDelay
* @see #withDeliveryPersistent
* @see #withPriority
* @see #withTimeToLive
*/
void send(Object payload, Map<String, Object> headers) throws MessagingException;
/**
* Receive a {@link Message} from the pre-bound destination.
* @return the spring-messaging {@link Message} received,
* or {@link Optional#empty()} if none
* @see #withReceiveTimeout
*/
Optional<Message<?>> receive() throws MessagingException;
/**
* Receive a {@link Message} from the pre-bound destination,
* extracting and converting its payload.
* @param targetClass the | OperationSpec |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/services/ITestAbfsHttpClientRequestExecutor.java | {
"start": 15316,
"end": 16809
} | class ____ {
private long connectTime;
private long readTime;
private long sendTime;
private int sendHeaderInvocation;
private int sendBodyInvocation;
private int receiveResponseInvocation;
private int receiveResponseBodyInvocation;
private void incrementSendHeaderInvocation() {
sendHeaderInvocation++;
}
private void incrementSendBodyInvocation() {
sendBodyInvocation++;
}
private void incrementReceiveResponseInvocation() {
receiveResponseInvocation++;
}
private void incrementReceiveResponseBodyInvocation() {
receiveResponseBodyInvocation++;
}
private void addConnectTime(long connectTime) {
this.connectTime += connectTime;
}
private void addReadTime(long readTime) {
this.readTime += readTime;
}
private void addSendTime(long sendTime) {
this.sendTime += sendTime;
}
private long getConnectTime() {
return connectTime;
}
private long getReadTime() {
return readTime;
}
private long getSendTime() {
return sendTime;
}
private int getSendHeaderInvocation() {
return sendHeaderInvocation;
}
private int getSendBodyInvocation() {
return sendBodyInvocation;
}
private int getReceiveResponseInvocation() {
return receiveResponseInvocation;
}
private int getReceiveResponseBodyInvocation() {
return receiveResponseBodyInvocation;
}
}
}
| ConnectionInfo |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/aop/mapper/InterceptorBeanMapper.java | {
"start": 1257,
"end": 2145
} | class ____ implements TypedAnnotationMapper<InterceptorBean> {
@Override
public Class<InterceptorBean> annotationType() {
return InterceptorBean.class;
}
@Override
public List<AnnotationValue<?>> map(AnnotationValue<InterceptorBean> annotation, VisitorContext visitorContext) {
final AnnotationValueBuilder<Annotation> builder = AnnotationValue.builder(AnnotationUtil.ANN_INTERCEPTOR_BINDINGS);
final AnnotationClassValue<?>[] values = annotation.annotationClassValues("value");
AnnotationValue<?>[] bindings = new AnnotationValue[values.length];
for (int i = 0; i < values.length; i++) {
bindings[i] = AnnotationValue.builder(AnnotationUtil.ANN_INTERCEPTOR_BINDING).value(values[i].getName()).build();
}
return Collections.singletonList(builder.values(bindings).build());
}
}
| InterceptorBeanMapper |
java | quarkusio__quarkus | extensions/quartz/deployment/src/test/java/io/quarkus/quartz/test/PausedMethodExpressionTest.java | {
"start": 1201,
"end": 1650
} | class ____ {
static final CountDownLatch LATCH = new CountDownLatch(1);
@Scheduled(every = "1s", identity = IDENTITY)
void countDownSecond() {
LATCH.countDown();
}
void pause(@Observes @Priority(Interceptor.Priority.PLATFORM_BEFORE - 1) StartupEvent event, Scheduler scheduler) {
// Pause the job before the scheduler starts
scheduler.pause(IDENTITY);
}
}
}
| Jobs |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregationStrategyBeanAdapterWithHeadersAndPropertiesTest.java | {
"start": 1062,
"end": 2249
} | class ____ extends ContextTestSupport {
private final MyBodyAppender appender = new MyBodyAppender();
@Test
public void testAggregate() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("ABC");
getMockEndpoint("mock:result").expectedHeaderReceived("foo", "yesyesyes");
getMockEndpoint("mock:result").expectedPropertyReceived("count", 6);
template.sendBodyAndProperty("direct:start", "A", "count", 1);
template.sendBodyAndProperty("direct:start", "B", "count", 2);
template.sendBodyAndProperty("direct:start", "C", "count", 3);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").setHeader("foo", constant("yes"))
.aggregate(constant(true), AggregationStrategies.bean(appender, "appendWithHeadersAndProperties"))
.completionSize(3).to("mock:result");
}
};
}
public static final | AggregationStrategyBeanAdapterWithHeadersAndPropertiesTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/api/records/TestTaskAttemptReport.java | {
"start": 3419,
"end": 3775
} | class
____ report = Records.newRecord(TaskAttemptReport.class);
// Set raw counters to null
report.setCounters(null);
// Verify properties still null
assertThat(report.getCounters()).isNull();
assertThat(report.getRawCounters()).isNull();
}
@Test
public void testSetNonNullCountersToNull() {
// Create basic | TaskAttemptReport |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/runners/InternalRunner.java | {
"start": 500,
"end": 620
} | interface ____ extends Filterable {
void run(RunNotifier notifier);
Description getDescription();
}
| InternalRunner |
java | apache__hadoop | hadoop-tools/hadoop-gcp/src/main/java/org/apache/hadoop/fs/gs/ListFileOptions.java | {
"start": 881,
"end": 1278
} | class ____ {
static final ListFileOptions OBJECTFIELDS = new ListFileOptions("bucket,name,size,updated");
static final ListFileOptions DELETE_RENAME_LIST_OPTIONS =
new ListFileOptions("bucket,name,generation");
private final String fields;
private ListFileOptions(@Nonnull String fields) {
this.fields = fields;
}
String getFields() {
return fields;
}
}
| ListFileOptions |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/TestNoOverCommitPolicy.java | {
"start": 1725,
"end": 3872
} | class ____ extends BaseSharingPolicyTest {
final static long ONEHOUR = 3600 * 1000;
final static String TWOHOURPERIOD = "7200000";
public void initTestNoOverCommitPolicy(long pDuration,
double pHeight, int pNumSubmissions, String pRecurrenceExpression, Class pExpectedError) {
this.duration = pDuration;
this.height = pHeight;
this.numSubmissions = pNumSubmissions;
this.recurrenceExpression = pRecurrenceExpression;
this.expectedError = pExpectedError;
super.setup();
}
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
// easy fit
{ONEHOUR, 0.25, 1, null, null },
{ONEHOUR, 0.25, 1, TWOHOURPERIOD, null },
// barely fit
{ONEHOUR, 1, 1, null, null },
{ONEHOUR, 1, 1, TWOHOURPERIOD, null },
// overcommit with single reservation
{ONEHOUR, 1.1, 1, null, ResourceOverCommitException.class },
{ONEHOUR, 1.1, 1, TWOHOURPERIOD, ResourceOverCommitException.class },
// barely fit with multiple reservations
{ONEHOUR, 0.25, 4, null, null },
{ONEHOUR, 0.25, 4, TWOHOURPERIOD, null },
// overcommit with multiple reservations
{ONEHOUR, 0.25, 5, null, ResourceOverCommitException.class },
{ONEHOUR, 0.25, 5, TWOHOURPERIOD, ResourceOverCommitException.class }
});
}
@Override
public SharingPolicy getInitializedPolicy() {
String reservationQ =
ReservationSystemTestUtil.getFullReservationQueueName();
conf = new CapacitySchedulerConfiguration();
SharingPolicy policy = new NoOverCommitPolicy();
policy.init(reservationQ, conf);
return policy;
}
@ParameterizedTest(name = "Duration {0}, height {1}," +
" numSubmission {2}, periodic {3})")
@MethodSource("data")
public void testAllocation(long pDuration,
double pHeight, int pNumSubmissions, String pRecurrenceExpression, Class pExpectedError)
throws IOException, PlanningException {
initTestNoOverCommitPolicy(pDuration, pHeight, pNumSubmissions,
pRecurrenceExpression, pExpectedError);
runTest();
}
} | TestNoOverCommitPolicy |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorOperatorEventHandlingTest.java | {
"start": 3007,
"end": 9642
} | class ____ {
@RegisterExtension
private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_EXTENSION =
TestingUtils.defaultExecutorExtension();
private MetricRegistryImpl metricRegistry;
private TestingRpcService rpcService;
@BeforeEach
void setup() {
rpcService = new TestingRpcService();
metricRegistry =
new MetricRegistryImpl(
MetricRegistryTestUtils.defaultMetricRegistryConfiguration());
metricRegistry.startQueryService(rpcService, new ResourceID("mqs"));
}
@AfterEach
void teardown() throws ExecutionException, InterruptedException {
if (rpcService != null) {
rpcService.closeAsync().get();
}
if (metricRegistry != null) {
metricRegistry.closeAsync().get();
}
}
@Test
void eventHandlingInTaskFailureFailsTask() throws Exception {
final JobID jobId = new JobID();
final ExecutionAttemptID eid = createExecutionAttemptId(new JobVertexID(), 3, 0);
try (TaskSubmissionTestEnvironment env =
createExecutorWithRunningTask(jobId, eid, OperatorEventFailingInvokable.class)) {
final TaskExecutorGateway tmGateway = env.getTaskExecutorGateway();
final CompletableFuture<?> resultFuture =
tmGateway.sendOperatorEventToTask(
eid, new OperatorID(), new SerializedValue<>(new TestOperatorEvent()));
assertThat(resultFuture)
.failsWithin(Duration.ofSeconds(10))
.withThrowableOfType(ExecutionException.class)
.withCauseInstanceOf(FlinkException.class);
assertThat(env.getTaskSlotTable().getTask(eid).getExecutionState())
.isEqualTo(ExecutionState.FAILED);
}
}
@Test
void eventToCoordinatorDeliveryFailureFailsTask() throws Exception {
final JobID jobId = new JobID();
final ExecutionAttemptID eid = createExecutionAttemptId(new JobVertexID(), 3, 0);
try (TaskSubmissionTestEnvironment env =
createExecutorWithRunningTask(jobId, eid, OperatorEventSendingInvokable.class)) {
final Task task = env.getTaskSlotTable().getTask(eid);
task.getExecutingThread().join(10_000);
assertThat(task.getExecutionState()).isEqualTo(ExecutionState.FAILED);
}
}
@Test
void requestToCoordinatorDeliveryFailureFailsTask() throws Exception {
final JobID jobId = new JobID();
final ExecutionAttemptID eid = createExecutionAttemptId(new JobVertexID(), 3, 0);
try (TaskSubmissionTestEnvironment env =
createExecutorWithRunningTask(
jobId, eid, CoordinationRequestSendingInvokable.class)) {
final Task task = env.getTaskSlotTable().getTask(eid);
task.getExecutingThread().join(10_000);
assertThat(task.getExecutionState()).isEqualTo(ExecutionState.FAILED);
}
}
// ------------------------------------------------------------------------
// test setup helpers
// ------------------------------------------------------------------------
private TaskSubmissionTestEnvironment createExecutorWithRunningTask(
JobID jobId,
ExecutionAttemptID executionAttemptId,
Class<? extends AbstractInvokable> invokableClass)
throws Exception {
final TaskDeploymentDescriptor tdd =
createTaskDeploymentDescriptor(jobId, executionAttemptId, invokableClass);
final CompletableFuture<Void> taskRunningFuture = new CompletableFuture<>();
final JobMasterId token = JobMasterId.generate();
final TaskSubmissionTestEnvironment env =
new TaskSubmissionTestEnvironment.Builder(jobId)
.setJobMasterId(token)
.setSlotSize(1)
.addTaskManagerActionListener(
executionAttemptId, ExecutionState.RUNNING, taskRunningFuture)
.setMetricQueryServiceAddress(
metricRegistry.getMetricQueryServiceGatewayRpcAddress())
.setJobMasterGateway(
new TestingJobMasterGatewayBuilder()
.setFencingTokenSupplier(() -> token)
.setOperatorEventSender(
(eio, oid, value) -> {
throw new RuntimeException();
})
.setDeliverCoordinationRequestFunction(
(oid, value) -> {
throw new RuntimeException();
})
.build())
.build(EXECUTOR_EXTENSION.getExecutor());
env.getTaskSlotTable()
.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60));
final TaskExecutorGateway tmGateway = env.getTaskExecutorGateway();
tmGateway.submitTask(tdd, env.getJobMasterId(), Duration.ofSeconds(10)).get();
taskRunningFuture.get();
return env;
}
private static TaskDeploymentDescriptor createTaskDeploymentDescriptor(
JobID jobId,
ExecutionAttemptID executionAttemptId,
Class<? extends AbstractInvokable> invokableClass)
throws IOException {
return TaskExecutorSubmissionTest.createTaskDeploymentDescriptor(
jobId,
"test job",
executionAttemptId,
new SerializedValue<>(new ExecutionConfig()),
"test task",
64,
17,
new Configuration(),
new Configuration(),
invokableClass.getName(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList());
}
// ------------------------------------------------------------------------
// test mocks
// ------------------------------------------------------------------------
/** Test invokable that fails when receiving an operator event. */
public static final | TaskExecutorOperatorEventHandlingTest |
java | apache__camel | components/camel-google/camel-google-pubsub-lite/src/main/java/org/apache/camel/component/google/pubsublite/GooglePubsubLiteConsumer.java | {
"start": 1420,
"end": 3433
} | class ____ extends DefaultConsumer {
private Logger localLog;
private final GooglePubsubLiteEndpoint endpoint;
private final Processor processor;
private ExecutorService executor;
private final List<Subscriber> subscribers;
GooglePubsubLiteConsumer(GooglePubsubLiteEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.endpoint = endpoint;
this.processor = processor;
this.subscribers = Collections.synchronizedList(new LinkedList<>());
String loggerId = endpoint.getLoggerId();
if (Strings.isNullOrEmpty(loggerId)) {
loggerId = this.getClass().getName();
}
localLog = LoggerFactory.getLogger(loggerId);
}
@Override
protected void doStart() throws Exception {
super.doStart();
localLog.info("Starting Google PubSub Lite consumer for {}/{}", endpoint.getProjectId(), endpoint.getDestinationName());
executor = endpoint.createExecutor(this);
for (int i = 0; i < endpoint.getConcurrentConsumers(); i++) {
executor.submit(new SubscriberWrapper());
}
}
@Override
protected void doStop() throws Exception {
super.doStop();
localLog.info("Stopping Google PubSub Lite consumer for {}/{}", endpoint.getProjectId(), endpoint.getDestinationName());
synchronized (subscribers) {
if (!subscribers.isEmpty()) {
localLog.info("Stopping subscribers for {}/{}", endpoint.getProjectId(), endpoint.getDestinationName());
subscribers.forEach(Subscriber::stopAsync);
}
}
if (executor != null) {
if (getEndpoint() != null && getEndpoint().getCamelContext() != null) {
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownGraceful(executor);
} else {
executor.shutdownNow();
}
}
executor = null;
}
private | GooglePubsubLiteConsumer |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredFieldValueResolver.java | {
"start": 2137,
"end": 2284
} | class ____ being
* used (typically to support private fields).
*
* @author Phillip Webb
* @author Stephane Nicoll
* @since 6.0
*/
public final | is |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/AotInitializerNotFoundFailureAnalyzerTests.java | {
"start": 1046,
"end": 1315
} | class ____ {
@Test
void shouldAnalyze() {
FailureAnalysis analysis = analyze();
assertThat(analysis).isNotNull();
assertThat(analysis.getDescription()).isEqualTo(
"Startup with AOT mode enabled failed: AOT initializer | AotInitializerNotFoundFailureAnalyzerTests |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/source/abilities/SupportsRowLevelModificationScan.java | {
"start": 2000,
"end": 3749
} | interface ____ {
/**
* Applies the type of row-level modification and the previous {@link
* RowLevelModificationScanContext} returned by previous table source scan, return a new {@link
* RowLevelModificationScanContext}. If the table source is the last one, the {@link
* RowLevelModificationScanContext} will be passed to the table sink. Otherwise, it will be
* passed to the following table source.
*
* <p>Note: For the all tables in the UPDATE/DELETE statement, this method will be involved for
* the corresponding table source scan.
*
* <p>Note: It may have multiple table sources in the case of sub-query. In such case, it will
* return multiple {@link RowLevelModificationScanContext}s. To handle such case, the planner
* will also pass the previous {@link RowLevelModificationScanContext} to the current table
* source scan which is expected to decide what to do with the previous {@link
* RowLevelModificationScanContext}. The order is consistent with the compilation order of the
* table sources. The planer will only pass the last context returned to the sink.
*
* @param previousContext the context returned by previous table source, if there's no previous
* context, it'll be null.
*/
RowLevelModificationScanContext applyRowLevelModificationScan(
RowLevelModificationType rowLevelModificationType,
@Nullable RowLevelModificationScanContext previousContext);
/**
* Type of the row-level modification for table.
*
* <p>Currently, two types are supported:
*
* <ul>
* <li>UPDATE
* <li>DELETE
* </ul>
*/
@PublicEvolving
| SupportsRowLevelModificationScan |
java | apache__camel | components/camel-ai/camel-langchain4j-chat/src/main/java/org/apache/camel/component/langchain4j/chat/LangChain4jChatEndpoint.java | {
"start": 1518,
"end": 2643
} | class ____ extends DefaultEndpoint {
@Metadata(required = true)
@UriPath(description = "The id")
private final String chatId;
@UriParam
private LangChain4jChatConfiguration configuration;
public LangChain4jChatEndpoint(String uri, LangChain4jChatComponent component, String chatId,
LangChain4jChatConfiguration configuration) {
super(uri, component);
this.chatId = chatId;
this.configuration = configuration;
}
@Override
public Producer createProducer() throws Exception {
return new LangChain4jChatProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Consumer not supported");
}
/**
* Chat ID
*
* @return
*/
public String getChatId() {
return chatId;
}
public LangChain4jChatConfiguration getConfiguration() {
return configuration;
}
@Override
protected void doStop() throws Exception {
super.doStop();
}
}
| LangChain4jChatEndpoint |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/NetworkClient.java | {
"start": 3368,
"end": 3426
} | class ____ implements KafkaClient {
private | NetworkClient |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java | {
"start": 99708,
"end": 122963
} | class ____ {
private final Level level; // Intentionally ignoring level for the sake of equality for now
private final String message;
public DeprecationWarning(Level level, String message) {
this.level = level;
this.message = message;
}
@Override
public int hashCode() {
return Objects.hash(message);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeprecationWarning that = (DeprecationWarning) o;
return Objects.equals(message, that.message);
}
@Override
public String toString() {
return Strings.format("%s: %s", level.name(), message);
}
}
/**
* Call method at the beginning of a test to disable its execution
* until a given Lucene version is released and integrated into Elasticsearch
* @param luceneVersionWithFix the lucene release to wait for
* @param message an additional message or link with information on the fix
*/
protected void skipTestWaitingForLuceneFix(org.apache.lucene.util.Version luceneVersionWithFix, String message) {
final boolean currentVersionHasFix = IndexVersion.current().luceneVersion().onOrAfter(luceneVersionWithFix);
assumeTrue("Skipping test as it is waiting on a Lucene fix: " + message, currentVersionHasFix);
fail("Remove call of skipTestWaitingForLuceneFix in " + RandomizedTest.getContext().getTargetMethod());
}
/**
* In non-FIPS mode, get a deterministic SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
* In FIPS mode, get a non-deterministic SecureRandom DEFAULT/BCFIPS instance seeded by deterministic LuceneTestCase.random().
* @return SecureRandom SHA1PRNG instance.
* @throws NoSuchAlgorithmException SHA1PRNG or DEFAULT algorithm not found.
* @throws NoSuchProviderException BCFIPS algorithm not found.
*/
public static SecureRandom secureRandom() throws NoSuchAlgorithmException, NoSuchProviderException {
return secureRandom(randomByteArrayOfLength(32));
}
/**
* In non-FIPS mode, get a deterministic SecureRandom SHA1PRNG/SUN instance seeded by the input value.
* In FIPS mode, get a non-deterministic SecureRandom DEFAULT/BCFIPS instance seeded by the input value.
* @param seed Byte array to use for seeding the SecureRandom instance.
* @return SecureRandom SHA1PRNG or DEFAULT/BCFIPS instance, depending on FIPS mode.
* @throws NoSuchAlgorithmException SHA1PRNG or DEFAULT algorithm not found.
* @throws NoSuchProviderException BCFIPS algorithm not found.
*/
public static SecureRandom secureRandom(final byte[] seed) throws NoSuchAlgorithmException, NoSuchProviderException {
return inFipsJvm() ? secureRandomFips(seed) : secureRandomNonFips(seed);
}
/**
* Returns deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
* @return Deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
* @throws NoSuchAlgorithmException Exception if SHA1PRNG algorithm not found, such as missing SUN provider (unlikely).
*/
protected static SecureRandom secureRandomNonFips() throws NoSuchAlgorithmException {
return secureRandomNonFips(randomByteArrayOfLength(32));
}
/**
* Returns non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.
* @return Non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.
* @throws NoSuchAlgorithmException Exception if DEFAULT algorithm not found, such as missing BCFIPS provider.
*/
protected static SecureRandom secureRandomFips() throws NoSuchAlgorithmException {
return secureRandomFips(randomByteArrayOfLength(32));
}
/**
* Returns deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
* @return Deterministic non-FIPS SecureRandom SHA1PRNG/SUN instance seeded by deterministic LuceneTestCase.random().
* @throws NoSuchAlgorithmException Exception if SHA1PRNG algorithm not found, such as missing SUN provider (unlikely).
*/
protected static SecureRandom secureRandomNonFips(final byte[] seed) throws NoSuchAlgorithmException {
final SecureRandom secureRandomNonFips = SecureRandom.getInstance("SHA1PRNG"); // SHA1PRNG/SUN
secureRandomNonFips.setSeed(seed); // SHA1PRNG/SUN setSeed() is deterministic
return secureRandomNonFips;
}
/**
* Returns non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.
* @return Non-deterministic FIPS SecureRandom DEFAULT/BCFIPS instance. Seeded.
* @throws NoSuchAlgorithmException Exception if DEFAULT algorithm not found, such as missing BCFIPS provider.
*/
protected static SecureRandom secureRandomFips(final byte[] seed) throws NoSuchAlgorithmException {
final SecureRandom secureRandomFips = SecureRandom.getInstance("DEFAULT"); // DEFAULT/BCFIPS
if (WARN_SECURE_RANDOM_FIPS_NOT_DETERMINISTIC.get() == null) {
WARN_SECURE_RANDOM_FIPS_NOT_DETERMINISTIC.set(Boolean.TRUE);
final Provider provider = secureRandomFips.getProvider();
final String providerName = provider.getName();
final Logger logger = LogManager.getLogger(ESTestCase.class);
logger.warn(
"Returning a non-deterministic secureRandom for use with FIPS. "
+ "This may result in difficulty reproducing test failures with from a given a seed."
);
}
secureRandomFips.setSeed(seed); // DEFAULT/BCFIPS setSeed() is non-deterministic
return secureRandomFips;
}
/**
* Various timeouts in various REST APIs default to 30s, and many tests do not care about such timeouts, but must specify some value
* anyway when constructing the corresponding transport/action request instance since we would prefer to avoid having implicit defaults
* in these requests. This constant can be used as a slightly more meaningful way to refer to the 30s default value in tests.
*/
public static final TimeValue TEST_REQUEST_TIMEOUT = TimeValue.THIRTY_SECONDS;
/**
* The timeout used for the various "safe" wait methods such as {@link #safeAwait} and {@link #safeAcquire}. In tests we generally want
* these things to complete almost immediately, but sometimes the CI runner executes things rather slowly so we use {@code 10s} as a
* fairly relaxed definition of "immediately".
* <p>
* A well-designed test should not need to wait for anything close to this duration when run in isolation. If you think you need to do
* so, instead seek a better way to write the test such that it does not need to wait for so long. Tests that take multiple seconds to
* complete are a big drag on CI times which slows everyone down.
* <p>
* For instance, tests which verify things that require the passage of time ought to simulate this (e.g. using a {@link
* org.elasticsearch.common.util.concurrent.DeterministicTaskQueue}). Excessive busy-waits ought to be replaced by blocking waits. For
* instance, use a {@link CountDownLatch} or {@link CyclicBarrier} or similar to continue execution as soon as a condition is satisfied.
* To wait for a particular cluster state, use {@link ClusterServiceUtils#addTemporaryStateListener} rather than busy-waiting on an API.
*/
public static final TimeValue SAFE_AWAIT_TIMEOUT = TimeValue.timeValueSeconds(10);
/**
* Await on the given {@link CyclicBarrier} with a timeout of {@link #SAFE_AWAIT_TIMEOUT}, preserving the thread's interrupt status flag
* and converting all exceptions into an {@link AssertionError} to trigger a test failure.
*/
public static void safeAwait(CyclicBarrier barrier) {
try {
barrier.await(SAFE_AWAIT_TIMEOUT.millis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail(e, "safeAwait: interrupted waiting for CyclicBarrier release");
} catch (Exception e) {
fail(e, "safeAwait: CyclicBarrier did not release within the timeout");
}
}
/**
* Await on the given {@link CountDownLatch} with a timeout of {@link #SAFE_AWAIT_TIMEOUT}, preserving the thread's interrupt status
* flag and asserting that the latch is indeed completed before the timeout.
*/
public static void safeAwait(CountDownLatch countDownLatch) {
safeAwait(countDownLatch, SAFE_AWAIT_TIMEOUT);
}
/**
* Await on the given {@link CountDownLatch} with a supplied timeout, preserving the thread's interrupt status
* flag and asserting that the latch is indeed completed before the timeout.
* <p>
* Prefer {@link #safeAwait(CountDownLatch)} (with the default 10s timeout) wherever possible. It's very unusual to need to block a
* test for more than 10s, and such slow tests are a big problem for overall test suite performance. In almost all cases it's possible
* to find a different way to write the test which doesn't need such a long wait.
*/
public static void safeAwait(CountDownLatch countDownLatch, TimeValue timeout) {
try {
assertTrue(
"safeAwait: CountDownLatch did not reach zero within the timeout",
countDownLatch.await(timeout.millis(), TimeUnit.MILLISECONDS)
);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail(e, "safeAwait: interrupted waiting for CountDownLatch to reach zero");
}
}
/**
* Acquire a single permit from the given {@link Semaphore}, with a timeout of {@link #SAFE_AWAIT_TIMEOUT}, preserving the thread's
* interrupt status flag and asserting that the permit was successfully acquired.
*/
public static void safeAcquire(Semaphore semaphore) {
safeAcquire(1, semaphore);
}
/**
* Acquire the specified number of permits from the given {@link Semaphore}, with a timeout of {@link #SAFE_AWAIT_TIMEOUT}, preserving
* the thread's interrupt status flag and asserting that the permits were all successfully acquired.
*/
public static void safeAcquire(int permits, Semaphore semaphore) {
try {
assertTrue(
"safeAcquire: Semaphore did not acquire permit within the timeout",
semaphore.tryAcquire(permits, SAFE_AWAIT_TIMEOUT.millis(), TimeUnit.MILLISECONDS)
);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail(e, "safeAcquire: interrupted waiting for Semaphore to acquire " + permits + " permit(s)");
}
}
/**
* Wait for the successful completion of the given {@link SubscribableListener}, with a timeout of {@link #SAFE_AWAIT_TIMEOUT},
* preserving the thread's interrupt status flag and converting all exceptions into an {@link AssertionError} to trigger a test failure.
*
* @return The value with which the {@code listener} was completed.
*/
public static <T> T safeAwait(SubscribableListener<T> listener) {
return safeAwait(listener, SAFE_AWAIT_TIMEOUT);
}
/**
* Wait for the successful completion of the given {@link SubscribableListener}, respecting the provided timeout,
* preserving the thread's interrupt status flag and converting all exceptions into an {@link AssertionError} to trigger a test failure.
*
* @return The value with which the {@code listener} was completed.
*/
public static <T> T safeAwait(SubscribableListener<T> listener, TimeValue timeout) {
final var future = new TestPlainActionFuture<T>();
listener.addListener(future);
return safeGet(future, timeout);
}
/**
* Call an async action (a {@link Consumer} of an {@link ActionListener}), wait for it to complete the listener, and then return the
* result. Preserves the thread's interrupt status flag and converts all exceptions into an {@link AssertionError} to trigger a test
* failure.
*
* @return The value with which the consumed listener was completed.
*/
public static <T> T safeAwait(CheckedConsumer<ActionListener<T>, ?> consumer) {
return safeAwait(SubscribableListener.newForked(consumer));
}
/**
* Execute the given {@link ActionRequest} using the given {@link ActionType} and the given {@link ElasticsearchClient}, wait for
* it to complete with a timeout of {@link #SAFE_AWAIT_TIMEOUT}, and then return the result. An exceptional response, timeout or
* interrupt triggers a test failure.
*/
public static <T extends ActionResponse> T safeExecute(ElasticsearchClient client, ActionType<T> action, ActionRequest request) {
return safeAwait(l -> client.execute(action, request, l));
}
/**
* Wait for the successful completion of the given {@link Future}, with a timeout of {@link #SAFE_AWAIT_TIMEOUT}, preserving the
* thread's interrupt status flag and converting all exceptions into an {@link AssertionError} to trigger a test failure.
*
* @return The value with which the {@code future} was completed.
*/
public static <T> T safeGet(Future<T> future) {
return safeGet(future, SAFE_AWAIT_TIMEOUT);
}
/**
* Wait for the successful completion of the given {@link Future}, respecting the provided timeout, preserving the
* thread's interrupt status flag and converting all exceptions into an {@link AssertionError} to trigger a test failure.
*
* @return The value with which the {@code future} was completed.
*/
// NB private because tests should be designed not to need to wait for longer than SAFE_AWAIT_TIMEOUT.
private static <T> T safeGet(Future<T> future, TimeValue timeout) {
try {
return future.get(timeout.millis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError("safeGet: interrupted waiting for SubscribableListener", e);
} catch (ExecutionException e) {
throw new AssertionError("safeGet: listener was completed exceptionally", e);
} catch (TimeoutException e) {
throw new AssertionError("safeGet: listener was not completed within the timeout", e);
}
}
/**
* Call a {@link CheckedSupplier}, converting all exceptions into an {@link AssertionError}. Useful for avoiding
* try/catch boilerplate or cumbersome propagation of checked exceptions around something that <i>should</i> never throw.
*
* @return The value returned by the {@code supplier}.
*/
public static <T> T safeGet(CheckedSupplier<T, ?> supplier) {
try {
return supplier.get();
} catch (Exception e) {
return fail(e);
}
}
/**
* Wait for the exceptional completion of the given {@link SubscribableListener}, with a timeout of {@link #SAFE_AWAIT_TIMEOUT},
* preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into an {@link
* AssertionError} to trigger a test failure.
*
* @return The exception with which the {@code listener} was completed exceptionally.
*/
public static Exception safeAwaitFailure(SubscribableListener<?> listener) {
return safeAwait(exceptionListener -> listener.addListener(ActionTestUtils.assertNoSuccessListener(exceptionListener::onResponse)));
}
/**
* Wait for the exceptional completion of the given async action, with a timeout of {@link #SAFE_AWAIT_TIMEOUT},
* preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into an {@link
* AssertionError} to trigger a test failure.
*
* @return The exception with which the {@code listener} was completed exceptionally.
*/
public static <T> Exception safeAwaitFailure(Consumer<ActionListener<T>> consumer) {
return safeAwait(exceptionListener -> consumer.accept(ActionTestUtils.assertNoSuccessListener(exceptionListener::onResponse)));
}
/**
* Wait for the exceptional completion of the given async action, with a timeout of {@link #SAFE_AWAIT_TIMEOUT},
* preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into an {@link
* AssertionError} to trigger a test failure.
*
* @param responseType Class of listener response type, to aid type inference but otherwise ignored.
*
* @return The exception with which the {@code listener} was completed exceptionally.
*/
public static <T> Exception safeAwaitFailure(@SuppressWarnings("unused") Class<T> responseType, Consumer<ActionListener<T>> consumer) {
return safeAwaitFailure(consumer);
}
/**
* Wait for the exceptional completion of the given async action, with a timeout of {@link #SAFE_AWAIT_TIMEOUT},
* preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into an {@link
* AssertionError} to trigger a test failure.
*
* @param responseType Class of listener response type, to aid type inference but otherwise ignored.
* @param exceptionType Expected exception type. This method throws an {@link AssertionError} if a different type of exception is seen.
*
* @return The exception with which the {@code listener} was completed exceptionally.
*/
public static <Response, ExpectedException extends Exception> ExpectedException safeAwaitFailure(
Class<ExpectedException> exceptionType,
Class<Response> responseType,
Consumer<ActionListener<Response>> consumer
) {
return asInstanceOf(exceptionType, safeAwaitFailure(responseType, consumer));
}
/**
* Wait for the exceptional completion of the given async action, with a timeout of {@link #SAFE_AWAIT_TIMEOUT},
* preserving the thread's interrupt status flag and converting a successful completion, interrupt or timeout into an {@link
* AssertionError} to trigger a test failure. Any layers of {@link ElasticsearchWrapperException} are removed from the thrown exception
* using {@link ExceptionsHelper#unwrapCause}.
*
* @param responseType Class of listener response type, to aid type inference but otherwise ignored.
* @param exceptionType Expected unwrapped exception type. This method throws an {@link AssertionError} if a different type of exception
* is seen.
*
* @return The unwrapped exception with which the {@code listener} was completed exceptionally.
*/
public static <Response, ExpectedException extends Exception> ExpectedException safeAwaitAndUnwrapFailure(
Class<ExpectedException> exceptionType,
Class<Response> responseType,
Consumer<ActionListener<Response>> consumer
) {
return asInstanceOf(exceptionType, ExceptionsHelper.unwrapCause(safeAwaitFailure(responseType, consumer)));
}
/**
* Send the current thread to sleep for the given duration, asserting that the sleep is not interrupted but preserving the thread's
* interrupt status flag in any case.
*/
public static void safeSleep(TimeValue timeValue) {
safeSleep(timeValue.millis());
}
/**
* Send the current thread to sleep for the given number of milliseconds, asserting that the sleep is not interrupted but preserving the
* thread's interrupt status flag in any case.
*/
public static void safeSleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail(e, "safeSleep: interrupted");
}
}
/**
* Wait for all tasks currently running or enqueued on the given executor to complete.
*/
public static void flushThreadPoolExecutor(ThreadPool threadPool, String executorName) {
final var maxThreads = threadPool.info(executorName).getMax();
final var barrier = new CyclicBarrier(maxThreads + 1);
final var executor = threadPool.executor(executorName);
for (int i = 0; i < maxThreads; i++) {
executor.execute(new AbstractRunnable() {
@Override
protected void doRun() {
safeAwait(barrier);
}
@Override
public void onFailure(Exception e) {
fail(e, "unexpected");
}
@Override
public boolean isForceExecution() {
return true;
}
});
}
safeAwait(barrier);
}
protected static boolean isTurkishLocale() {
return Locale.getDefault().getLanguage().equals(new Locale("tr").getLanguage())
|| Locale.getDefault().getLanguage().equals(new Locale("az").getLanguage());
}
/*
* Assert.assertThat (inherited from LuceneTestCase superclass) has been deprecated.
* So make sure that all assertThat references use the non-deprecated version.
*/
public static <T> void assertThat(T actual, Matcher<? super T> matcher) {
MatcherAssert.assertThat(actual, matcher);
}
public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher) {
MatcherAssert.assertThat(reason, actual, matcher);
}
public static <T> T fail(Throwable t, String msg, Object... args) {
throw new AssertionError(org.elasticsearch.common.Strings.format(msg, args), t);
}
public static <T> T fail(Throwable t) {
return fail(t, "unexpected");
}
@SuppressWarnings("unchecked")
public static <T> T asInstanceOf(Class<T> clazz, Object o) {
assertThat(o, Matchers.instanceOf(clazz));
return (T) o;
}
public static <T extends Throwable> T expectThrows(Class<T> expectedType, ActionFuture<? extends RefCounted> future) {
return expectThrows(
expectedType,
"Expected exception " + expectedType.getSimpleName() + " but no exception was thrown",
() -> future.actionGet().decRef() // dec ref if we unexpectedly fail to not leak transport response
);
}
public static <T extends Throwable> T expectThrows(Class<T> expectedType, RequestBuilder<?, ?> builder) {
return expectThrows(
expectedType,
"Expected exception " + expectedType.getSimpleName() + " but no exception was thrown",
() -> builder.get().decRef() // dec ref if we unexpectedly fail to not leak transport response
);
}
/**
* Checks a specific exception | DeprecationWarning |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/runner/bootstrap/StartupActionImpl.java | {
"start": 22863,
"end": 24325
} | class ____ for %s", i.binaryName());
}
}
if (debugSourcesDir != null) {
try {
if (i.getSource() != null) {
File debugPath = new File(debugSourcesDir);
if (!debugPath.exists()) {
debugPath.mkdir();
}
File sourceFile = new File(debugPath, i.internalName() + ".zig");
sourceFile.getParentFile().mkdirs();
Files.writeString(sourceFile.toPath(), i.getSource(), StandardOpenOption.CREATE);
log.infof("Wrote source %s", sourceFile.getAbsolutePath());
} else {
log.infof("Source not available: %s", i.binaryName());
}
} catch (Exception t) {
log.errorf(t, "Failed to write debug source file for %s", i.binaryName());
}
}
}
}
if (applicationClasses) {
for (GeneratedResourceBuildItem i : buildResult.consumeMulti(GeneratedResourceBuildItem.class)) {
if (i.isExcludeFromDevCL()) {
continue;
}
data.put(i.getName(), i.getData());
}
}
return data;
}
}
| file |
java | quarkusio__quarkus | integration-tests/rest-client/src/test/java/io/quarkus/it/rest/client/selfsigned/ExternalSelfSignedTestCase.java | {
"start": 496,
"end": 1290
} | class ____ {
@Test
public void should_accept_self_signed_certs() {
when()
.get("/self-signed/ExternalSelfSignedClient")
.then()
.statusCode(200)
.body(is("Hello self-signed!"));
}
@Test
public void javaxNetSsl() {
given()
.get("/self-signed/HttpClient/javax.net.ssl")
.then()
.statusCode(200)
.body(is("Hello self-signed!"));
}
@Test
public void fakeHost() {
given()
.get("/self-signed/HttpClient/fake-host")
.then()
.statusCode(500)
.body(containsStringIgnoringCase("unable to find valid certification path"));
}
}
| ExternalSelfSignedTestCase |
java | square__retrofit | retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/AsyncTest.java | {
"start": 2005,
"end": 6745
} | interface ____ {
@GET("/")
Completable completable();
}
private Service service;
private final List<Throwable> uncaughtExceptions = new ArrayList<>();
@Before
public void setUp() {
ExecutorService executorService =
Executors.newCachedThreadPool(
r -> {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler((t, e) -> uncaughtExceptions.add(e));
return thread;
});
OkHttpClient client =
new OkHttpClient.Builder().dispatcher(new Dispatcher(executorService)).build();
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
.build();
service = retrofit.create(Service.class);
}
@After
public void tearDown() {
assertTrue("Uncaught exceptions: " + uncaughtExceptions, uncaughtExceptions.isEmpty());
}
@Test
public void success() throws InterruptedException {
TestObserver<Void> observer = new TestObserver<>();
service.completable().subscribe(observer);
assertFalse(observer.await(1, SECONDS));
server.enqueue(new MockResponse());
observer.awaitTerminalEvent(1, SECONDS);
observer.assertComplete();
}
@Test
public void failure() throws InterruptedException {
TestObserver<Void> observer = new TestObserver<>();
service.completable().subscribe(observer);
assertFalse(observer.await(1, SECONDS));
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
observer.awaitTerminalEvent(1, SECONDS);
observer.assertError(IOException.class);
}
@Test
public void throwingInOnCompleteDeliveredToPlugin() throws InterruptedException {
server.enqueue(new MockResponse());
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
latch.countDown();
});
TestObserver<Void> observer = new TestObserver<>();
final RuntimeException e = new RuntimeException();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onComplete() {
throw e;
}
});
latch.await(1, SECONDS);
Throwable error = errorRef.get();
assertThat(error).isInstanceOf(UndeliverableException.class);
assertThat(error).hasCauseThat().isSameInstanceAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() throws InterruptedException {
server.enqueue(new MockResponse().setResponseCode(404));
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!pluginRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
}
latch.countDown();
});
TestObserver<Void> observer = new TestObserver<>();
final RuntimeException e = new RuntimeException();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
errorRef.set(throwable);
throw e;
}
});
latch.await(1, SECONDS);
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) pluginRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void bodyThrowingFatalInOnErrorPropagates() throws InterruptedException {
server.enqueue(new MockResponse().setResponseCode(404));
final CountDownLatch latch = new CountDownLatch(1);
TestObserver<Void> observer = new TestObserver<>();
final Error e = new OutOfMemoryError("Not real");
service
.completable()
.subscribe(
new ForwardingCompletableObserver(observer) {
@Override
public void onError(Throwable throwable) {
throw e;
}
});
latch.await(1, SECONDS);
assertEquals(1, uncaughtExceptions.size());
assertSame(e, uncaughtExceptions.remove(0));
}
}
| Service |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/decorated/DecoratedTest.java | {
"start": 1270,
"end": 1383
} | interface ____<T> {
T convert(T value);
}
@ApplicationScoped
@MyQualifier
static | Converter |
java | quarkusio__quarkus | integration-tests/hibernate-orm-envers/src/main/java/io/quarkus/it/envers/OutputResource.java | {
"start": 262,
"end": 772
} | class ____ {
@GET
@RestStreamElementType(MediaType.APPLICATION_JSON)
@CustomOutput("dummy")
@Path("annotation")
public Multi<Message> sseOut() {
return Multi.createFrom().iterable(List.of(new Message("test"), new Message("test")));
}
@GET
@RestStreamElementType(MediaType.APPLICATION_JSON)
@Path("no-annotation")
public Multi<Message> sseOut2() {
return Multi.createFrom().iterable(List.of(new Message("test"), new Message("test")));
}
}
| OutputResource |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java | {
"start": 20774,
"end": 21257
} | class ____ {
private static final String foo = null, // foo
// BUG: Diagnostic contains:
bar = null;
public static String foo() {
return foo;
}
}
""")
.doTest();
}
@Test
public void utf8Handling() {
helper
.addSourceLines(
"Utf8Handling.java",
"""
package unusedvars;
public | UnusedWithComment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.