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 | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/api/writer/BroadcastRecordWriter.java | {
"start": 1279,
"end": 1856
} | class ____<T extends IOReadableWritable> extends RecordWriter<T> {
BroadcastRecordWriter(ResultPartitionWriter writer, long timeout, String taskName) {
super(writer, timeout, taskName);
}
@Override
public void emit(T record) throws IOException {
broadcastEmit(record);
}
@Override
public void broadcastEmit(T record) throws IOException {
checkErroneous();
targetPartition.broadcastRecord(serializeRecord(serializer, record));
if (flushAlways) {
flushAll();
}
}
}
| BroadcastRecordWriter |
java | micronaut-projects__micronaut-core | core-processor/src/main/java/io/micronaut/inject/ast/annotation/ElementAnnotationMetadata.java | {
"start": 798,
"end": 900
} | interface ____ extends MutableAnnotationMetadataDelegate<AnnotationMetadata> {
}
| ElementAnnotationMetadata |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/visitor/SQLASTParameterizedVisitor.java | {
"start": 1197,
"end": 4913
} | class ____ extends SQLASTVisitorAdapter {
protected DbType dbType;
protected List<Object> parameters;
private int replaceCount;
public SQLASTParameterizedVisitor(DbType dbType) {
this.dbType = dbType;
}
public int getReplaceCount() {
return this.replaceCount;
}
public void incrementReplaceCunt() {
replaceCount++;
}
public DbType getDbType() {
return dbType;
}
public SQLASTParameterizedVisitor(DbType dbType, List<Object> parameters) {
this.dbType = dbType;
this.parameters = parameters;
}
public List<Object> getParameters() {
return parameters;
}
public void setParameters(List<Object> parameters) {
this.parameters = parameters;
}
@Override
public boolean visit(SQLTimestampExpr x) {
parameterizeAndExportPara(x);
return false;
}
public void parameterizeAndExportPara(SQLExpr x) {
SQLVariantRefExpr variantRefExpr = new SQLVariantRefExpr("?");
variantRefExpr.setIndex(this.replaceCount);
SQLUtils.replaceInParent(x, variantRefExpr);
incrementReplaceCunt();
ExportParameterVisitorUtils.exportParameter(this.parameters, x);
}
public void parameterize(SQLExpr x) {
SQLVariantRefExpr variantRefExpr = new SQLVariantRefExpr("?");
variantRefExpr.setIndex(this.replaceCount);
SQLUtils.replaceInParent(x, variantRefExpr);
incrementReplaceCunt();
}
@Override
public boolean visit(SQLCharExpr x) {
parameterizeAndExportPara(x);
return false;
}
@Override
public boolean visit(SQLIntegerExpr x) {
SQLObject parent = x.getParent();
if (parent instanceof SQLSelectGroupByClause || parent instanceof SQLSelectOrderByItem) {
return false;
}
parameterizeAndExportPara(x);
return false;
}
@Override
public boolean visit(SQLMethodInvokeExpr x) {
List<SQLExpr> arguments = x.getArguments();
if (x.methodNameHashCode64() == FnvHash.Constants.TRIM
&& arguments.size() == 1
&& arguments.get(0) instanceof SQLCharExpr && x.getTrimOption() == null && x.getFrom() == null) {
parameterizeAndExportPara(x);
if (this.parameters != null) {
SQLCharExpr charExpr = (SQLCharExpr) arguments.get(0);
this.parameters.add(charExpr.getText().trim());
}
replaceCount++;
return false;
}
return true;
}
@Override
public boolean visit(SQLNCharExpr x) {
parameterizeAndExportPara(x);
return false;
}
@Override
public boolean visit(SQLNullExpr x) {
SQLObject parent = x.getParent();
if (parent instanceof SQLInsertStatement || parent instanceof ValuesClause || parent instanceof SQLInListExpr ||
(parent instanceof SQLBinaryOpExpr && ((SQLBinaryOpExpr) parent).getOperator() == SQLBinaryOperator.Equality)) {
parameterize(x);
if (this.parameters != null) {
if (parent instanceof SQLBinaryOpExpr) {
ExportParameterVisitorUtils.exportParameter(parameters, x);
} else {
this.parameters.add(null);
}
}
return false;
}
return false;
}
@Override
public boolean visit(SQLNumberExpr x) {
parameterizeAndExportPara(x);
return false;
}
@Override
public boolean visit(SQLHexExpr x) {
parameterizeAndExportPara(x);
return false;
}
}
| SQLASTParameterizedVisitor |
java | micronaut-projects__micronaut-core | router/src/main/java/io/micronaut/web/router/exceptions/UnsatisfiedPathVariableRouteException.java | {
"start": 902,
"end": 1458
} | class ____ extends UnsatisfiedRouteException {
private final String name;
/**
* @param name The name of the path variable
* @param argument The {@link Argument}
*/
public UnsatisfiedPathVariableRouteException(String name, Argument<?> argument) {
super("Required PathVariable [" + name + "] not specified", argument);
this.name = name;
}
/**
* @return The name of the path variable
*/
public String getPathVariableName() {
return name;
}
}
| UnsatisfiedPathVariableRouteException |
java | dropwizard__dropwizard | dropwizard-auth/src/test/java/io/dropwizard/auth/CustomAuthExceptionTest.java | {
"start": 979,
"end": 1099
} | class ____ extends JerseyTest {
static {
BootstrapLogging.bootstrap();
}
static | CustomAuthExceptionTest |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/stubbing/answers/CallsRealMethods.java | {
"start": 1654,
"end": 2286
} | class ____ implements Answer<Object>, ValidableAnswer, Serializable {
private static final long serialVersionUID = 9057165148930624087L;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (Modifier.isAbstract(invocation.getMethod().getModifiers())) {
return RETURNS_DEFAULTS.answer(invocation);
}
return invocation.callRealMethod();
}
@Override
public void validateFor(InvocationOnMock invocation) {
if (new InvocationInfo(invocation).isAbstract()) {
throw cannotCallAbstractRealMethod();
}
}
}
| CallsRealMethods |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/lazy/LazyIgnoralForNumbers3730Test.java | {
"start": 807,
"end": 1251
} | class ____ {
private final String s;
private final int i;
@JsonCreator
public ExtractFieldsNoDefaultConstructor3730(@JsonProperty("s") String s, @JsonProperty("i") int i) {
this.s = s;
this.i = i;
}
public String getS() {
return s;
}
public int getI() {
return i;
}
}
// Another | ExtractFieldsNoDefaultConstructor3730 |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeMergeArray.java | {
"start": 2197,
"end": 8045
} | class ____<T>
extends BasicIntQueueSubscription<T> implements MaybeObserver<T> {
private static final long serialVersionUID = -660395290758764731L;
final Subscriber<? super T> downstream;
final CompositeDisposable set;
final AtomicLong requested;
final SimpleQueueWithConsumerIndex<Object> queue;
final AtomicThrowable errors;
final int sourceCount;
volatile boolean cancelled;
boolean outputFused;
long consumed;
MergeMaybeObserver(Subscriber<? super T> actual, int sourceCount, SimpleQueueWithConsumerIndex<Object> queue) {
this.downstream = actual;
this.sourceCount = sourceCount;
this.set = new CompositeDisposable();
this.requested = new AtomicLong();
this.errors = new AtomicThrowable();
this.queue = queue;
}
@Override
public int requestFusion(int mode) {
if ((mode & ASYNC) != 0) {
outputFused = true;
return ASYNC;
}
return NONE;
}
@Nullable
@SuppressWarnings("unchecked")
@Override
public T poll() {
for (;;) {
Object o = queue.poll();
if (o != NotificationLite.COMPLETE) {
return (T)o;
}
}
}
@Override
public boolean isEmpty() {
return queue.isEmpty();
}
@Override
public void clear() {
queue.clear();
}
@Override
public void request(long n) {
if (SubscriptionHelper.validate(n)) {
BackpressureHelper.add(requested, n);
drain();
}
}
@Override
public void cancel() {
if (!cancelled) {
cancelled = true;
set.dispose();
if (getAndIncrement() == 0) {
queue.clear();
}
}
}
@Override
public void onSubscribe(Disposable d) {
set.add(d);
}
@Override
public void onSuccess(T value) {
queue.offer(value);
drain();
}
@Override
public void onError(Throwable e) {
if (errors.tryAddThrowableOrReport(e)) {
set.dispose();
queue.offer(NotificationLite.COMPLETE);
drain();
}
}
@Override
public void onComplete() {
queue.offer(NotificationLite.COMPLETE);
drain();
}
boolean isCancelled() {
return cancelled;
}
@SuppressWarnings("unchecked")
void drainNormal() {
int missed = 1;
Subscriber<? super T> a = downstream;
SimpleQueueWithConsumerIndex<Object> q = queue;
long e = consumed;
for (;;) {
long r = requested.get();
while (e != r) {
if (cancelled) {
q.clear();
return;
}
Throwable ex = errors.get();
if (ex != null) {
q.clear();
errors.tryTerminateConsumer(downstream);
return;
}
if (q.consumerIndex() == sourceCount) {
a.onComplete();
return;
}
Object v = q.poll();
if (v == null) {
break;
}
if (v != NotificationLite.COMPLETE) {
a.onNext((T)v);
e++;
}
}
if (e == r) {
Throwable ex = errors.get();
if (ex != null) {
q.clear();
errors.tryTerminateConsumer(downstream);
return;
}
while (q.peek() == NotificationLite.COMPLETE) {
q.drop();
}
if (q.consumerIndex() == sourceCount) {
a.onComplete();
return;
}
}
consumed = e;
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
void drainFused() {
int missed = 1;
Subscriber<? super T> a = downstream;
SimpleQueueWithConsumerIndex<Object> q = queue;
for (;;) {
if (cancelled) {
q.clear();
return;
}
Throwable ex = errors.get();
if (ex != null) {
q.clear();
a.onError(ex);
return;
}
boolean d = q.producerIndex() == sourceCount;
if (!q.isEmpty()) {
a.onNext(null);
}
if (d) {
a.onComplete();
return;
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
void drain() {
if (getAndIncrement() != 0) {
return;
}
if (outputFused) {
drainFused();
} else {
drainNormal();
}
}
}
| MergeMaybeObserver |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/reflect/ReflectDatumReader.java | {
"start": 3088,
"end": 11839
} | class
____<?> elementConversion = getData().getConversionFor(schema.getElementType().getLogicalType());
if (elementConversion != null) {
elementClass = elementConversion.getConvertedType();
}
}
if (collectionClass == null && elementClass == null)
return super.newArray(old, size, schema); // use specific/generic
if (collectionClass != null && !collectionClass.isArray()) {
if (old instanceof Collection) {
((Collection<?>) old).clear();
return old;
}
if (collectionClass.isAssignableFrom(ArrayList.class))
return new ArrayList<>();
if (collectionClass.isAssignableFrom(HashSet.class))
return new HashSet<>();
if (collectionClass.isAssignableFrom(HashMap.class))
return new HashMap<>();
return SpecificData.newInstance(collectionClass, schema);
}
if (elementClass == null) {
elementClass = collectionClass.getComponentType();
}
if (elementClass == null) {
ReflectData data = (ReflectData) getData();
elementClass = data.getClass(schema.getElementType());
}
return Array.newInstance(elementClass, size);
}
@Override
protected Object peekArray(Object array) {
return null;
}
@Override
protected void addToArray(Object array, long pos, Object e) {
throw new AvroRuntimeException("reflectDatumReader does not use addToArray");
}
@Override
/**
* Called to read an array instance. May be overridden for alternate array
* representations.
*/
protected Object readArray(Object old, Schema expected, ResolvingDecoder in) throws IOException {
Schema expectedType = expected.getElementType();
long l = in.readArrayStart();
if (l <= 0) {
return newArray(old, 0, expected);
}
Object array = newArray(old, (int) l, expected);
if (array instanceof Collection) {
@SuppressWarnings("unchecked")
Collection<Object> c = (Collection<Object>) array;
return readCollection(c, expectedType, l, in);
} else if (array instanceof Map) {
// Only for non-string keys, we can use NS_MAP_* fields
// So we check the same explicitly here
if (ReflectData.isNonStringMapSchema(expected)) {
Collection<Object> c = new ArrayList<>();
readCollection(c, expectedType, l, in);
Map m = (Map) array;
for (Object ele : c) {
IndexedRecord rec = ((IndexedRecord) ele);
Object key = rec.get(ReflectData.NS_MAP_KEY_INDEX);
Object value = rec.get(ReflectData.NS_MAP_VALUE_INDEX);
m.put(key, value);
}
return array;
} else {
String msg = "Expected a schema of map with non-string keys but got " + expected;
throw new AvroRuntimeException(msg);
}
} else {
return readJavaArray(array, expectedType, l, in);
}
}
private Object readJavaArray(Object array, Schema expectedType, long l, ResolvingDecoder in) throws IOException {
Class<?> elementType = array.getClass().getComponentType();
if (elementType.isPrimitive()) {
return readPrimitiveArray(array, elementType, l, in);
} else {
return readObjectArray((Object[]) array, expectedType, l, in);
}
}
private Object readPrimitiveArray(Object array, Class<?> c, long l, ResolvingDecoder in) throws IOException {
return ArrayAccessor.readArray(array, c, l, in);
}
private Object readObjectArray(Object[] array, Schema expectedType, long l, ResolvingDecoder in) throws IOException {
LogicalType logicalType = expectedType.getLogicalType();
Conversion<?> conversion = getData().getConversionFor(logicalType);
int index = 0;
if (logicalType != null && conversion != null) {
do {
int limit = index + (int) l;
while (index < limit) {
Object element = readWithConversion(null, expectedType, logicalType, conversion, in);
array[index] = element;
index++;
}
} while ((l = in.arrayNext()) > 0);
} else {
do {
int limit = index + (int) l;
while (index < limit) {
Object element = readWithoutConversion(null, expectedType, in);
array[index] = element;
index++;
}
} while ((l = in.arrayNext()) > 0);
}
return array;
}
private Object readCollection(Collection<Object> c, Schema expectedType, long l, ResolvingDecoder in)
throws IOException {
LogicalType logicalType = expectedType.getLogicalType();
Conversion<?> conversion = getData().getConversionFor(logicalType);
if (logicalType != null && conversion != null) {
do {
for (int i = 0; i < l; i++) {
Object element = readWithConversion(null, expectedType, logicalType, conversion, in);
c.add(element);
}
} while ((l = in.arrayNext()) > 0);
} else {
do {
for (int i = 0; i < l; i++) {
Object element = readWithoutConversion(null, expectedType, in);
c.add(element);
}
} while ((l = in.arrayNext()) > 0);
}
return c;
}
@Override
protected Object readString(Object old, Decoder in) throws IOException {
return super.readString(null, in).toString();
}
@Override
protected Object createString(String value) {
return value;
}
@Override
protected Object readBytes(Object old, Schema s, Decoder in) throws IOException {
ByteBuffer bytes = in.readBytes(null);
Class<?> c = ReflectData.getClassProp(s, SpecificData.CLASS_PROP);
if (c != null && c.isArray()) {
byte[] result = new byte[bytes.remaining()];
bytes.get(result);
return result;
} else {
return bytes;
}
}
@Override
protected Object read(Object old, Schema expected, ResolvingDecoder in) throws IOException {
CustomEncoding encoder = getReflectData().getCustomEncoding(expected);
if (encoder != null) {
return encoder.read(old, in);
} else {
return super.read(old, expected, in);
}
}
@Override
protected Object readInt(Object old, Schema expected, Decoder in) throws IOException {
Object value = in.readInt();
String intClass = expected.getProp(SpecificData.CLASS_PROP);
if (Byte.class.getName().equals(intClass))
value = ((Integer) value).byteValue();
else if (Short.class.getName().equals(intClass))
value = ((Integer) value).shortValue();
else if (Character.class.getName().equals(intClass))
value = (char) (int) (Integer) value;
return value;
}
@Override
protected void readField(Object record, Field field, Object oldDatum, ResolvingDecoder in, Object state)
throws IOException {
if (state != null) {
FieldAccessor accessor = ((FieldAccessor[]) state)[field.pos()];
if (accessor != null) {
if (accessor.supportsIO()
&& (!Schema.Type.UNION.equals(field.schema().getType()) || accessor.isCustomEncoded())) {
accessor.read(record, in);
return;
}
if (accessor.isStringable()) {
try {
String asString = (String) read(null, field.schema(), in);
accessor.set(record,
asString == null ? null : newInstanceFromString(accessor.getField().getType(), asString));
return;
} catch (Exception e) {
throw new AvroRuntimeException("Failed to read Stringable", e);
}
}
LogicalType logicalType = field.schema().getLogicalType();
if (logicalType != null) {
Conversion<?> conversion = getData().getConversionByClass(accessor.getField().getType(), logicalType);
if (conversion != null) {
try {
accessor.set(record, convert(readWithoutConversion(oldDatum, field.schema(), in), field.schema(),
logicalType, conversion));
} catch (IllegalAccessException e) {
throw new AvroRuntimeException("Failed to set " + field);
}
return;
}
}
if (Optional.class.isAssignableFrom(accessor.getField().getType())) {
try {
Object value = readWithoutConversion(oldDatum, field.schema(), in);
accessor.set(record, Optional.ofNullable(value));
return;
} catch (IllegalAccessException e) {
throw new AvroRuntimeException("Failed to set " + field);
}
}
try {
accessor.set(record, readWithoutConversion(oldDatum, field.schema(), in));
return;
} catch (IllegalAccessException e) {
throw new AvroRuntimeException("Failed to set " + field);
}
}
}
super.readField(record, field, oldDatum, in, state);
}
}
| Conversion |
java | playframework__playframework | documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/groups/PartialUserForm.java | {
"start": 477,
"end": 2111
} | class ____ implements Validatable<ValidationError> {
@Constraints.Required(groups = {Default.class, SignUpCheck.class, LoginCheck.class})
@Constraints.Email(groups = {Default.class, SignUpCheck.class})
private String email;
@Constraints.Required private String firstName;
@Constraints.Required private String lastName;
@Constraints.Required(groups = {SignUpCheck.class, LoginCheck.class})
private String password;
@Constraints.Required(groups = {SignUpCheck.class})
private String repeatPassword;
@Override
public ValidationError validate() {
if (!checkPasswords(password, repeatPassword)) {
return new ValidationError("repeatPassword", "Passwords do not match");
}
return null;
}
// getters and setters
// ###skip: 44
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepeatPassword() {
return this.repeatPassword;
}
public void setRepeatPassword(String repeatPassword) {
this.repeatPassword = repeatPassword;
}
private static boolean checkPasswords(final String pw1, final String pw2) {
return false;
}
}
// #user
| PartialUserForm |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java | {
"start": 10679,
"end": 10939
} | class ____ implements DialectFeatureCheck {
public boolean apply(Dialect dialect) {
return !( dialect instanceof DB2Dialect
|| dialect instanceof DerbyDialect
|| dialect instanceof FirebirdDialect );
}
}
public static | SupportsJdbcDriverProxying |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/web/websocket/websocketserverruntimeconfiguration/JettyWebSocketConfiguration.java | {
"start": 1356,
"end": 2066
} | class ____ implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(echoWebSocketHandler(), "/echo").setHandshakeHandler(handshakeHandler());
}
@Bean
public WebSocketHandler echoWebSocketHandler() {
return new MyEchoHandler();
}
@Bean
public DefaultHandshakeHandler handshakeHandler() {
JettyRequestUpgradeStrategy strategy = new JettyRequestUpgradeStrategy();
strategy.addWebSocketConfigurer(configurable -> {
configurable.setInputBufferSize(8192);
configurable.setIdleTimeout(Duration.ofSeconds(600));
});
return new DefaultHandshakeHandler(strategy);
}
}
// end::snippet[]
| JettyWebSocketConfiguration |
java | quarkusio__quarkus | integration-tests/maven/src/test/resources-filtered/projects/dev-mode-file-deletion/src/main/java/org/acme/HelloResource.java | {
"start": 227,
"end": 580
} | class ____ {
@ConfigProperty(name = "greeting", defaultValue = "Guten Morgen")
String greeting;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello";
}
@GET
@Path("/greetings")
@Produces(MediaType.TEXT_PLAIN)
public String greetings() {
return greeting;
}
}
| HelloResource |
java | google__guava | android/guava-testlib/src/com/google/common/collect/testing/google/BiMapInverseTester.java | {
"start": 2359,
"end": 3205
} | class ____<K, V> implements Serializable {
final BiMap<K, V> forward;
final BiMap<V, K> backward;
BiMapPair(BiMap<K, V> original) {
this.forward = original;
this.backward = original.inverse();
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
/**
* Returns {@link Method} instances for the tests that assume that the inverse will be the same
* after serialization.
*/
@J2ktIncompatible
@GwtIncompatible // reflection
public static List<Method> getInverseSameAfterSerializingMethods() {
return Collections.singletonList(getMethod("testInverseSerialization"));
}
@J2ktIncompatible
@GwtIncompatible // reflection
private static Method getMethod(String methodName) {
return Helpers.getMethod(BiMapInverseTester.class, methodName);
}
}
| BiMapPair |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/web/websocket/stomp/websocketstompconfigurationperformance/MessageSizeLimitWebSocketConfiguration.java | {
"start": 1267,
"end": 1539
} | class ____ implements WebSocketMessageBrokerConfigurer {
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
registration.setMessageSizeLimit(128 * 1024);
}
// ...
}
// end::snippet[]
| MessageSizeLimitWebSocketConfiguration |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/io/InputStreamResource.java | {
"start": 2562,
"end": 6144
} | class ____ extends AbstractResource {
private final InputStreamSource inputStreamSource;
private final String description;
private final Object equality;
private boolean read = false;
/**
* Create a new {@code InputStreamResource} with a lazy {@code InputStream}
* for single use.
* @param inputStreamSource an on-demand source for a single-use InputStream
* @since 6.1.7
*/
public InputStreamResource(InputStreamSource inputStreamSource) {
this(inputStreamSource, "resource loaded from InputStreamSource");
}
/**
* Create a new {@code InputStreamResource} with a lazy {@code InputStream}
* for single use.
* @param inputStreamSource an on-demand source for a single-use InputStream
* @param description where the InputStream comes from
* @since 6.1.7
*/
public InputStreamResource(InputStreamSource inputStreamSource, @Nullable String description) {
Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
this.inputStreamSource = inputStreamSource;
this.description = (description != null ? description : "");
this.equality = inputStreamSource;
}
/**
* Create a new {@code InputStreamResource} for an existing {@code InputStream}.
* <p>Consider retrieving the InputStream on demand if possible, reducing its
* lifetime and reliably opening it and closing it through regular
* {@link InputStreamSource#getInputStream()} usage.
* @param inputStream the InputStream to use
* @see #InputStreamResource(InputStreamSource)
*/
public InputStreamResource(InputStream inputStream) {
this(inputStream, "resource loaded through InputStream");
}
/**
* Create a new {@code InputStreamResource} for an existing {@code InputStream}.
* @param inputStream the InputStream to use
* @param description where the InputStream comes from
* @see #InputStreamResource(InputStreamSource, String)
*/
public InputStreamResource(InputStream inputStream, @Nullable String description) {
Assert.notNull(inputStream, "InputStream must not be null");
this.inputStreamSource = () -> inputStream;
this.description = (description != null ? description : "");
this.equality = inputStream;
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean exists() {
return true;
}
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean isOpen() {
return true;
}
/**
* This implementation throws IllegalStateException if attempting to
* read the underlying stream multiple times.
*/
@Override
public InputStream getInputStream() throws IOException, IllegalStateException {
if (this.read) {
throw new IllegalStateException("InputStream has already been read (possibly for early content length " +
"determination) - do not use InputStreamResource if a stream needs to be read multiple times");
}
this.read = true;
return this.inputStreamSource.getInputStream();
}
/**
* This implementation returns a description that includes the passed-in
* description, if any.
*/
@Override
public String getDescription() {
return "InputStream resource [" + this.description + "]";
}
/**
* This implementation compares the underlying InputStream.
*/
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof InputStreamResource that &&
this.equality.equals(that.equality)));
}
/**
* This implementation returns the hash code of the underlying InputStream.
*/
@Override
public int hashCode() {
return this.equality.hashCode();
}
}
| InputStreamResource |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryOptionalGetTest.java | {
"start": 895,
"end": 1325
} | class ____ {
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
BugCheckerRefactoringTestHelper.newInstance(UnnecessaryOptionalGet.class, getClass());
@Test
public void genericOptionalVars_sameVarGet_replacesWithLambdaArg() {
refactoringTestHelper
.addInputLines(
"Test.java",
"""
import java.util.Optional;
public | UnnecessaryOptionalGetTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/TaskStateManagerImpl.java | {
"start": 2739,
"end": 2837
} | class ____ both cases transparently.
*
* <p>Reported state is tagged by clients so that this | handles |
java | redisson__redisson | redisson-quarkus/redisson-quarkus-30/cache/integration-tests/src/main/java/org/redisson/quarkus/client/it/MyCredentialsResolver.java | {
"start": 922,
"end": 1218
} | class ____ implements CredentialsResolver {
private final CompletionStage<Credentials> future = CompletableFuture.completedFuture(new Credentials());
@Override
public CompletionStage<Credentials> resolve(InetSocketAddress address) {
return future;
}
}
| MyCredentialsResolver |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/shorts/Shorts_assertGreaterThanOrEqualTo_Test.java | {
"start": 1174,
"end": 3438
} | class ____ extends ShortsBaseTest {
@Test
void should_fail_if_actual_is_null() {
assertThatAssertionErrorIsThrownBy(() -> shorts.assertGreaterThanOrEqualTo(someInfo(), null,
(short) 8)).withMessage(actualIsNull());
}
@Test
void should_pass_if_actual_is_greater_than_other() {
shorts.assertGreaterThanOrEqualTo(someInfo(), (short) 8, (short) 6);
}
@Test
void should_pass_if_actual_is_equal_to_other() {
shorts.assertGreaterThanOrEqualTo(someInfo(), (short) 6, (short) 6);
}
@Test
void should_fail_if_actual_is_less_than_other() {
// GIVEN
AssertionInfo info = someInfo();
// WHEN
expectAssertionError(() -> shorts.assertGreaterThanOrEqualTo(info, (short) 6, (short) 8));
// THEN
verify(failures).failure(info, shouldBeGreaterOrEqual((short) 6, (short) 8));
}
@Test
void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
assertThatAssertionErrorIsThrownBy(() -> shortsWithAbsValueComparisonStrategy.assertGreaterThanOrEqualTo(someInfo(), null,
(short) 8))
.withMessage(actualIsNull());
}
@Test
void should_pass_if_actual_is_greater_than_other_according_to_custom_comparison_strategy() {
shortsWithAbsValueComparisonStrategy.assertGreaterThanOrEqualTo(someInfo(), (short) -8, (short) 6);
}
@Test
void should_pass_if_actual_is_equal_to_other_according_to_custom_comparison_strategy() {
shortsWithAbsValueComparisonStrategy.assertGreaterThanOrEqualTo(someInfo(), (short) 6, (short) -6);
}
@Test
void should_fail_if_actual_is_less_than_other_according_to_custom_comparison_strategy() {
// GIVEN
AssertionInfo info = someInfo();
// WHEN
expectAssertionError(() -> shortsWithAbsValueComparisonStrategy.assertGreaterThanOrEqualTo(info, (short) 6, (short) -8));
// THEN
verify(failures).failure(info, shouldBeGreaterOrEqual((short) 6, (short) -8, absValueComparisonStrategy));
}
}
| Shorts_assertGreaterThanOrEqualTo_Test |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/tree/TreeNodeTests.java | {
"start": 645,
"end": 3037
} | class ____ extends AbstractXContentSerializingTestCase<TreeNode> {
private boolean lenient;
@Before
public void chooseStrictOrLenient() {
lenient = randomBoolean();
}
@Override
protected TreeNode doParseInstance(XContentParser parser) throws IOException {
return TreeNode.fromXContent(parser, lenient).build();
}
@Override
protected boolean supportsUnknownFields() {
return lenient;
}
@Override
protected TreeNode createTestInstance() {
Integer lft = randomBoolean() ? null : randomInt(100);
Integer rgt = randomBoolean() ? randomInt(100) : null;
Double threshold = lft != null || randomBoolean() ? randomDouble() : null;
Integer featureIndex = lft != null || randomBoolean() ? randomInt(100) : null;
return createRandom(randomInt(100), lft, rgt, threshold, featureIndex, randomBoolean() ? null : randomFrom(Operator.values()))
.build();
}
@Override
protected TreeNode mutateInstance(TreeNode instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
public static TreeNode createRandomLeafNode(double internalValue) {
return TreeNode.builder(randomInt(100))
.setDefaultLeft(randomBoolean() ? null : randomBoolean())
.setNumberSamples(randomNonNegativeLong())
.setLeafValue(Collections.singletonList(internalValue))
.build();
}
public static TreeNode.Builder createRandom(
int nodeId,
Integer left,
Integer right,
Double threshold,
Integer featureIndex,
Operator operator
) {
return TreeNode.builder(nodeId)
.setLeafValue(left == null ? Collections.singletonList(randomDouble()) : null)
.setDefaultLeft(randomBoolean() ? null : randomBoolean())
.setLeftChild(left)
.setRightChild(right)
.setNumberSamples(randomNonNegativeLong())
.setThreshold(threshold)
.setOperator(operator)
.setSplitFeature(randomBoolean() ? null : randomInt())
.setSplitGain(randomBoolean() ? null : randomDouble())
.setSplitFeature(featureIndex);
}
@Override
protected Writeable.Reader<TreeNode> instanceReader() {
return TreeNode::new;
}
}
| TreeNodeTests |
java | spring-projects__spring-framework | spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java | {
"start": 64953,
"end": 66678
} | class ____ implements TransactionSynchronization {
private DataSource dataSource;
private int status;
public boolean beforeCommitCalled;
public boolean beforeCompletionCalled;
public boolean afterCommitCalled;
public boolean afterCompletionCalled;
public Throwable afterCompletionException;
public TestTransactionSynchronization(DataSource dataSource, int status) {
this.dataSource = dataSource;
this.status = status;
}
@Override
public void suspend() {
}
@Override
public void resume() {
}
@Override
public void flush() {
}
@Override
public void beforeCommit(boolean readOnly) {
if (this.status != TransactionSynchronization.STATUS_COMMITTED) {
fail("Should never be called");
}
assertThat(this.beforeCommitCalled).isFalse();
this.beforeCommitCalled = true;
}
@Override
public void beforeCompletion() {
assertThat(this.beforeCompletionCalled).isFalse();
this.beforeCompletionCalled = true;
}
@Override
public void afterCommit() {
if (this.status != TransactionSynchronization.STATUS_COMMITTED) {
fail("Should never be called");
}
assertThat(this.afterCommitCalled).isFalse();
this.afterCommitCalled = true;
}
@Override
public void afterCompletion(int status) {
try {
doAfterCompletion(status);
}
catch (Throwable ex) {
this.afterCompletionException = ex;
}
}
protected void doAfterCompletion(int status) {
assertThat(this.afterCompletionCalled).isFalse();
this.afterCompletionCalled = true;
assertThat(status).isEqualTo(this.status);
assertThat(TransactionSynchronizationManager.hasResource(this.dataSource)).isTrue();
}
}
private static | TestTransactionSynchronization |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/SingularAttributeSourceManyToOne.java | {
"start": 181,
"end": 299
} | interface ____
extends SingularAttributeSourceToOne, RelationalValueSourceContainer {
}
| SingularAttributeSourceManyToOne |
java | spring-projects__spring-boot | core/spring-boot-testcontainers/src/test/java/org/springframework/boot/testcontainers/service/connection/ServiceConnectionContextCustomizerFactoryTests.java | {
"start": 1497,
"end": 6750
} | class ____ {
private final ServiceConnectionContextCustomizerFactory factory = new ServiceConnectionContextCustomizerFactory();
@Test
void createContextCustomizerWhenNoServiceConnectionsReturnsCustomizerToApplyInitializer() {
ContextCustomizer customizer = this.factory.createContextCustomizer(NoServiceConnections.class,
Collections.emptyList());
assertThat(customizer).isNotNull();
GenericApplicationContext context = new GenericApplicationContext();
int initialNumberOfPostProcessors = context.getBeanFactoryPostProcessors().size();
MergedContextConfiguration mergedConfig = mock(MergedContextConfiguration.class);
customizer.customizeContext(context, mergedConfig);
assertThat(context.getBeanFactoryPostProcessors()).hasSize(initialNumberOfPostProcessors + 1);
}
@Test
void createContextCustomizerWhenClassHasServiceConnectionsReturnsCustomizer() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(ServiceConnections.class, Collections.emptyList());
assertThat(customizer).isNotNull();
assertThat(customizer.getSources()).hasSize(2);
}
@Test
void createContextCustomizerWhenEnclosingClassHasServiceConnectionsReturnsCustomizer() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(ServiceConnections.NestedClass.class, Collections.emptyList());
assertThat(customizer).isNotNull();
assertThat(customizer.getSources()).hasSize(3);
}
@Test
void createContextCustomizerWhenInterfaceHasServiceConnectionsReturnsCustomizer() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(ServiceConnectionsInterface.class, Collections.emptyList());
assertThat(customizer).isNotNull();
assertThat(customizer.getSources()).hasSize(2);
}
@Test
void createContextCustomizerWhenSuperclassHasServiceConnectionsReturnsCustomizer() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(ServiceConnectionsSubclass.class, Collections.emptyList());
assertThat(customizer).isNotNull();
assertThat(customizer.getSources()).hasSize(2);
}
@Test
void createContextCustomizerWhenImplementedInterfaceHasServiceConnectionsReturnsCustomizer() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(ServiceConnectionsImpl.class, Collections.emptyList());
assertThat(customizer).isNotNull();
assertThat(customizer.getSources()).hasSize(2);
}
@Test
void createContextCustomizerWhenInheritedImplementedInterfaceHasServiceConnectionsReturnsCustomizer() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(ServiceConnectionsImplSubclass.class, Collections.emptyList());
assertThat(customizer).isNotNull();
assertThat(customizer.getSources()).hasSize(2);
}
@Test
void createContextCustomizerWhenClassHasNonStaticServiceConnectionFailsWithHelpfulException() {
assertThatIllegalStateException().isThrownBy(
() -> this.factory.createContextCustomizer(NonStaticServiceConnection.class, Collections.emptyList()))
.withMessage("@ServiceConnection field 'service' must be static");
}
@Test
void createContextCustomizerWhenClassHasAnnotationOnNonConnectionFieldFailsWithHelpfulException() {
assertThatIllegalStateException()
.isThrownBy(() -> this.factory.createContextCustomizer(ServiceConnectionOnWrongFieldType.class,
Collections.emptyList()))
.withMessage("Field 'service2' in " + ServiceConnectionOnWrongFieldType.class.getName()
+ " must be a org.testcontainers.containers.Container");
}
@Test
void createContextCustomizerCreatesCustomizerSourceWithSensibleBeanNameSuffix() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(SingleServiceConnection.class, Collections.emptyList());
ContainerConnectionSource<?> source = customizer.getSources().get(0);
assertThat(source.getBeanNameSuffix()).isEqualTo("test");
}
@Test
void createContextCustomizerCreatesCustomizerSourceWithSensibleOrigin() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(SingleServiceConnection.class, Collections.emptyList());
ContainerConnectionSource<?> source = customizer.getSources().get(0);
assertThat(source.getOrigin())
.hasToString("ServiceConnectionContextCustomizerFactoryTests.SingleServiceConnection.service1");
}
@Test
void createContextCustomizerCreatesCustomizerSourceWithSensibleToString() {
ServiceConnectionContextCustomizer customizer = (ServiceConnectionContextCustomizer) this.factory
.createContextCustomizer(SingleServiceConnection.class, Collections.emptyList());
ContainerConnectionSource<?> source = customizer.getSources().get(0);
assertThat(source).hasToString(
"@ServiceConnection source for ServiceConnectionContextCustomizerFactoryTests.SingleServiceConnection.service1");
}
static | ServiceConnectionContextCustomizerFactoryTests |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestMultipleNNPortQOP.java | {
"start": 2585,
"end": 12507
} | class ____ extends SaslDataTransferTestCase {
private static final Path PATH1 = new Path("/file1");
private static final Path PATH2 = new Path("/file2");
private static final Path PATH3 = new Path("/file3");
private static final int BLOCK_SIZE = 4096;
private static final int NUM_BLOCKS = 3;
private static HdfsConfiguration clusterConf;
@BeforeEach
public void setup() throws Exception {
clusterConf = createSecureConfig(
"authentication,integrity,privacy");
clusterConf.set(DFS_NAMENODE_RPC_ADDRESS_AUXILIARY_KEY,
"12001,12101,12201");
// explicitly setting service rpc for datanode. This because
// DFSUtil.getNNServiceRpcAddressesForCluster looks up client facing port
// and service port at the same time, and if no setting for service
// rpc, it would return client port, in this case, it will be the
// auxiliary port for data node. Which is not what auxiliary is for.
// setting service rpc port to avoid this.
clusterConf.set(DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY, "localhost:9021");
clusterConf.set(
CommonConfigurationKeys.HADOOP_SECURITY_SASL_PROPS_RESOLVER_CLASS,
"org.apache.hadoop.security.IngressPortBasedResolver");
clusterConf.set("ingress.port.sasl.configured.ports", "12001,12101,12201");
clusterConf.set("ingress.port.sasl.prop.12001", "authentication");
clusterConf.set("ingress.port.sasl.prop.12101", "integrity");
clusterConf.set("ingress.port.sasl.prop.12201", "privacy");
clusterConf.setBoolean(DFS_NAMENODE_SEND_QOP_ENABLED, true);
}
/**
* Test that when NameNode returns back its established QOP,
* it only does this for auxiliary port(s), not the primary port.
*
* @throws Exception
*/
@Test
public void testAuxiliaryPortSendingQOP() throws Exception {
MiniDFSCluster cluster = null;
final String pathPrefix = "/filetestAuxiliaryPortSendingQOP";
try {
cluster = new MiniDFSCluster.Builder(clusterConf)
.numDataNodes(3).build();
cluster.waitActive();
HdfsConfiguration clientConf = new HdfsConfiguration(clusterConf);
clientConf.unset(
CommonConfigurationKeys.HADOOP_SECURITY_SASL_PROPS_RESOLVER_CLASS);
URI currentURI = cluster.getURI();
URI uriAuthPort = new URI(currentURI.getScheme() + "://" +
currentURI.getHost() + ":12001");
URI uriIntegrityPort = new URI(currentURI.getScheme() + "://" +
currentURI.getHost() + ":12101");
URI uriPrivacyPort = new URI(currentURI.getScheme() +
"://" + currentURI.getHost() + ":12201");
// If connecting to primary port, block token should not include
// handshake secret
byte[] secretOnPrimary = getHandshakeSecret(currentURI, clientConf,
new Path(pathPrefix + "Primary"));
assertTrue(secretOnPrimary == null || secretOnPrimary.length == 0);
// If connecting to auxiliary port, block token should include
// handshake secret
clientConf.set(HADOOP_RPC_PROTECTION, "privacy");
byte[] secretPrivacy = getHandshakeSecret(uriPrivacyPort, clientConf,
new Path(pathPrefix + "Privacy"));
assertTrue(secretPrivacy.length > 0);
clientConf.set(HADOOP_RPC_PROTECTION, "integrity");
byte[] secretIntegrity = getHandshakeSecret(uriIntegrityPort, clientConf,
new Path(pathPrefix + "Integrity"));
assertTrue(secretIntegrity.length > 0);
clientConf.set(HADOOP_RPC_PROTECTION, "authentication");
byte[] secretAuthentication = getHandshakeSecret(uriAuthPort,
clientConf, new Path(pathPrefix + "Authentication"));
assertTrue(secretAuthentication.length > 0);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
private byte[] getHandshakeSecret(URI uri, HdfsConfiguration conf,
Path path) throws Exception {
FileSystem fs = FileSystem.get(uri, conf);
FSDataOutputStream out = fs.create(
path, false, 4096, (short)1, BLOCK_SIZE);
try {
out.write(0);
out.hflush();
Token<BlockTokenIdentifier> token = DFSTestUtil.getBlockToken(out);
final byte[] tokenBytes = token.getIdentifier();
DataInputBuffer dib = new DataInputBuffer();
dib.reset(tokenBytes, tokenBytes.length);
BlockTokenIdentifier blockToken = new BlockTokenIdentifier();
blockToken.readFields(dib);
return blockToken.getHandshakeMsg();
} finally {
out.close();
}
}
/**
* Test accessing NameNode from three different ports.
*
* @throws Exception
*/
@Test
public void testMultipleNNPort() throws Exception {
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(clusterConf)
.numDataNodes(3).build();
cluster.waitActive();
HdfsConfiguration clientConf = new HdfsConfiguration(clusterConf);
clientConf.unset(
CommonConfigurationKeys.HADOOP_SECURITY_SASL_PROPS_RESOLVER_CLASS);
ArrayList<DataNode> dataNodes = cluster.getDataNodes();
URI currentURI = cluster.getURI();
URI uriAuthPort = new URI(currentURI.getScheme() +
"://" + currentURI.getHost() + ":12001");
URI uriIntegrityPort = new URI(currentURI.getScheme() +
"://" + currentURI.getHost() + ":12101");
URI uriPrivacyPort = new URI(currentURI.getScheme() +
"://" + currentURI.getHost() + ":12201");
clientConf.set(HADOOP_RPC_PROTECTION, "privacy");
FileSystem fsPrivacy = FileSystem.get(uriPrivacyPort, clientConf);
doTest(fsPrivacy, PATH1);
for (DataNode dn : dataNodes) {
SaslDataTransferServer saslServer = dn.getSaslServer();
assertEquals("auth-conf", saslServer.getNegotiatedQOP());
}
clientConf.set(HADOOP_RPC_PROTECTION, "integrity");
FileSystem fsIntegrity = FileSystem.get(uriIntegrityPort, clientConf);
doTest(fsIntegrity, PATH2);
for (DataNode dn : dataNodes) {
SaslDataTransferServer saslServer = dn.getSaslServer();
assertEquals("auth-int", saslServer.getNegotiatedQOP());
}
clientConf.set(HADOOP_RPC_PROTECTION, "authentication");
FileSystem fsAuth = FileSystem.get(uriAuthPort, clientConf);
doTest(fsAuth, PATH3);
for (DataNode dn : dataNodes) {
SaslDataTransferServer saslServer = dn.getSaslServer();
assertEquals("auth", saslServer.getNegotiatedQOP());
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
/**
* Test accessing NameNode from three different ports, tests
* overwriting downstream DN in the pipeline.
*
* @throws Exception
*/
@Test
public void testMultipleNNPortOverwriteDownStream() throws Exception {
clusterConf.set(DFS_ENCRYPT_DATA_OVERWRITE_DOWNSTREAM_NEW_QOP_KEY, "auth");
clusterConf.setBoolean(
DFS_ENCRYPT_DATA_OVERWRITE_DOWNSTREAM_DERIVED_QOP_KEY, true);
MiniDFSCluster cluster = null;
try {
cluster =
new MiniDFSCluster.Builder(clusterConf).numDataNodes(3).build();
cluster.waitActive();
HdfsConfiguration clientConf = new HdfsConfiguration(clusterConf);
clientConf.unset(
CommonConfigurationKeys.HADOOP_SECURITY_SASL_PROPS_RESOLVER_CLASS);
ArrayList<DataNode> dataNodes = cluster.getDataNodes();
URI currentURI = cluster.getURI();
URI uriAuthPort =
new URI(currentURI.getScheme() + "://" +
currentURI.getHost() + ":12001");
URI uriIntegrityPort =
new URI(currentURI.getScheme() + "://" +
currentURI.getHost() + ":12101");
URI uriPrivacyPort =
new URI(currentURI.getScheme() + "://" +
currentURI.getHost() + ":12201");
clientConf.set(HADOOP_RPC_PROTECTION, "privacy");
FileSystem fsPrivacy = FileSystem.get(uriPrivacyPort, clientConf);
doTest(fsPrivacy, PATH1);
long count = dataNodes.stream()
.map(dn -> dn.getSaslClient().getTargetQOP())
.filter("auth"::equals)
.count();
// For each datanode pipeline, targetQOPs of sasl clients in the first two
// datanodes become equal to auth.
// Note that it is not necessarily the case for all datanodes,
// since a datanode may be always at the last position in pipelines.
assertTrue(count >= 2, "At least two qops should be auth");
clientConf.set(HADOOP_RPC_PROTECTION, "integrity");
FileSystem fsIntegrity = FileSystem.get(uriIntegrityPort, clientConf);
doTest(fsIntegrity, PATH2);
count = dataNodes.stream()
.map(dn -> dn.getSaslClient().getTargetQOP())
.filter("auth"::equals)
.count();
assertTrue(count >= 2, "At least two qops should be auth");
clientConf.set(HADOOP_RPC_PROTECTION, "authentication");
FileSystem fsAuth = FileSystem.get(uriAuthPort, clientConf);
doTest(fsAuth, PATH3);
count = dataNodes.stream()
.map(dn -> dn.getSaslServer().getNegotiatedQOP())
.filter("auth"::equals)
.count();
assertEquals(3, count, "All qops should be auth");
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
private void doTest(FileSystem fs, Path path) throws Exception {
FileSystemTestHelper.createFile(fs, path, NUM_BLOCKS, BLOCK_SIZE);
assertArrayEquals(FileSystemTestHelper.getFileData(NUM_BLOCKS, BLOCK_SIZE),
DFSTestUtil.readFile(fs, path).getBytes(StandardCharsets.UTF_8));
BlockLocation[] blockLocations = fs.getFileBlockLocations(path, 0,
Long.MAX_VALUE);
assertNotNull(blockLocations);
assertEquals(NUM_BLOCKS, blockLocations.length);
for (BlockLocation blockLocation: blockLocations) {
assertNotNull(blockLocation.getHosts());
assertEquals(3, blockLocation.getHosts().length);
}
}
}
| TestMultipleNNPortQOP |
java | apache__camel | core/camel-core-languages/src/main/java/org/apache/camel/language/simple/SimpleNoFileLanguage.java | {
"start": 1133,
"end": 1251
} | class ____ extends SimpleLanguage {
public SimpleNoFileLanguage() {
super(true);
}
}
| SimpleNoFileLanguage |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/external/http/HttpClientTests.java | {
"start": 2701,
"end": 12802
} | class ____ extends ESTestCase {
private static final TimeValue TIMEOUT = new TimeValue(30, TimeUnit.SECONDS);
private final MockWebServer webServer = new MockWebServer();
private ThreadPool threadPool;
@Before
public void init() throws Exception {
webServer.start();
threadPool = createThreadPool(inferenceUtilityExecutors());
}
@After
public void shutdown() {
terminate(threadPool);
webServer.close();
}
public void testSend_MockServerReceivesRequest() throws Exception {
int responseCode = randomIntBetween(200, 203);
String body = randomAlphaOfLengthBetween(2, 8096);
webServer.enqueue(new MockResponse().setResponseCode(responseCode).setBody(body));
String paramKey = randomAlphaOfLength(3);
String paramValue = randomAlphaOfLength(3);
var httpPost = createHttpPost(webServer.getPort(), paramKey, paramValue);
try (var httpClient = HttpClient.create(emptyHttpSettings(), threadPool, createConnectionManager(), mockThrottlerManager())) {
httpClient.start();
PlainActionFuture<HttpResult> listener = new PlainActionFuture<>();
httpClient.send(httpPost, HttpClientContext.create(), listener);
var result = listener.actionGet(TIMEOUT);
assertThat(result.response().getStatusLine().getStatusCode(), equalTo(responseCode));
assertThat(new String(result.body(), StandardCharsets.UTF_8), is(body));
assertThat(webServer.requests(), hasSize(1));
assertThat(webServer.requests().get(0).getUri().getPath(), equalTo(httpPost.httpRequestBase().getURI().getPath()));
assertThat(webServer.requests().get(0).getUri().getQuery(), equalTo(paramKey + "=" + paramValue));
assertThat(webServer.requests().get(0).getHeader(HttpHeaders.CONTENT_TYPE), equalTo(XContentType.JSON.mediaType()));
}
}
public void testSend_ThrowsErrorIfCalledBeforeStart() throws Exception {
try (var httpClient = HttpClient.create(emptyHttpSettings(), threadPool, createConnectionManager(), mockThrottlerManager())) {
PlainActionFuture<HttpResult> listener = new PlainActionFuture<>();
var thrownException = expectThrows(
AssertionError.class,
() -> httpClient.send(HttpRequestTests.createMock("inferenceEntityId"), HttpClientContext.create(), listener)
);
assertThat(thrownException.getMessage(), is("call start() before attempting to send a request"));
}
}
public void testSend_FailedCallsOnFailure() throws Exception {
var asyncClient = mock(CloseableHttpAsyncClient.class);
doAnswer(invocation -> {
FutureCallback<?> listener = invocation.getArgument(2);
listener.failed(new ElasticsearchException("failure"));
return mock(Future.class);
}).when(asyncClient).execute(any(HttpUriRequest.class), any(), any());
var httpPost = createHttpPost(webServer.getPort(), "a", "b");
try (var client = new HttpClient(emptyHttpSettings(), asyncClient, threadPool, mockThrottlerManager())) {
client.start();
PlainActionFuture<HttpResult> listener = new PlainActionFuture<>();
client.send(httpPost, HttpClientContext.create(), listener);
var thrownException = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(thrownException.getMessage(), is("failure"));
}
}
public void testSend_CancelledCallsOnFailure() throws Exception {
var asyncClient = mock(CloseableHttpAsyncClient.class);
doAnswer(invocation -> {
FutureCallback<?> listener = invocation.getArgument(2);
listener.cancelled();
return mock(Future.class);
}).when(asyncClient).execute(any(HttpUriRequest.class), any(), any());
var httpPost = createHttpPost(webServer.getPort(), "a", "b");
try (var client = new HttpClient(emptyHttpSettings(), asyncClient, threadPool, mockThrottlerManager())) {
client.start();
PlainActionFuture<HttpResult> listener = new PlainActionFuture<>();
client.send(httpPost, HttpClientContext.create(), listener);
var thrownException = expectThrows(CancellationException.class, () -> listener.actionGet(TIMEOUT));
assertThat(
thrownException.getMessage(),
is(Strings.format("Request from inference entity id [%s] was cancelled", httpPost.inferenceEntityId()))
);
}
}
public void testStream_FailedCallsOnFailure() throws Exception {
var asyncClient = mock(CloseableHttpAsyncClient.class);
doAnswer(invocation -> {
FutureCallback<?> listener = invocation.getArgument(3);
listener.failed(new ElasticsearchException("failure"));
return mock(Future.class);
}).when(asyncClient).execute(any(HttpAsyncRequestProducer.class), any(), any(), any());
var httpPost = createHttpPost(webServer.getPort(), "a", "b");
try (var client = new HttpClient(emptyHttpSettings(), asyncClient, threadPool, mockThrottlerManager())) {
client.start();
PlainActionFuture<StreamingHttpResult> listener = new PlainActionFuture<>();
client.stream(httpPost, HttpClientContext.create(), listener);
var thrownException = expectThrows(ElasticsearchException.class, () -> listener.actionGet(TIMEOUT));
assertThat(thrownException.getMessage(), is("failure"));
}
}
public void testStream_CancelledCallsOnFailure() throws Exception {
var asyncClient = mock(CloseableHttpAsyncClient.class);
doAnswer(invocation -> {
FutureCallback<?> listener = invocation.getArgument(3);
listener.cancelled();
return mock(Future.class);
}).when(asyncClient).execute(any(HttpAsyncRequestProducer.class), any(), any(), any());
var httpPost = createHttpPost(webServer.getPort(), "a", "b");
try (var client = new HttpClient(emptyHttpSettings(), asyncClient, threadPool, mockThrottlerManager())) {
client.start();
PlainActionFuture<StreamingHttpResult> listener = new PlainActionFuture<>();
client.stream(httpPost, HttpClientContext.create(), listener);
var thrownException = expectThrows(CancellationException.class, () -> listener.actionGet(TIMEOUT));
assertThat(
thrownException.getMessage(),
is(Strings.format("Request from inference entity id [%s] was cancelled", httpPost.inferenceEntityId()))
);
}
}
@SuppressWarnings("unchecked")
public void testStart_MultipleCallsOnlyStartTheClientOnce() throws Exception {
var asyncClient = mock(CloseableHttpAsyncClient.class);
when(asyncClient.execute(any(HttpUriRequest.class), any(), any())).thenReturn(mock(Future.class));
var httpPost = createHttpPost(webServer.getPort(), "a", "b");
try (var client = new HttpClient(emptyHttpSettings(), asyncClient, threadPool, mockThrottlerManager())) {
client.start();
PlainActionFuture<HttpResult> listener = new PlainActionFuture<>();
client.send(httpPost, HttpClientContext.create(), listener);
client.send(httpPost, HttpClientContext.create(), listener);
verify(asyncClient, times(1)).start();
}
}
public void testSend_FailsWhenMaxBytesReadIsExceeded() throws Exception {
int responseCode = randomIntBetween(200, 203);
String body = randomAlphaOfLengthBetween(10, 8096);
webServer.enqueue(new MockResponse().setResponseCode(responseCode).setBody(body));
String paramKey = randomAlphaOfLength(3);
String paramValue = randomAlphaOfLength(3);
var httpPost = createHttpPost(webServer.getPort(), paramKey, paramValue);
Settings settings = Settings.builder().put(HttpSettings.MAX_HTTP_RESPONSE_SIZE.getKey(), ByteSizeValue.ONE).build();
var httpSettings = createHttpSettings(settings);
try (var httpClient = HttpClient.create(httpSettings, threadPool, createConnectionManager(), mockThrottlerManager())) {
httpClient.start();
PlainActionFuture<HttpResult> listener = new PlainActionFuture<>();
httpClient.send(httpPost, HttpClientContext.create(), listener);
var throwException = expectThrows(UncategorizedExecutionException.class, () -> listener.actionGet(TIMEOUT));
assertThat(throwException.getCause().getCause().getMessage(), is("Maximum limit of [1] bytes reached"));
}
}
public static HttpRequest createHttpPost(int port, String paramKey, String paramValue) throws URISyntaxException {
URI uri = new URIBuilder().setScheme("http")
.setHost("localhost")
.setPort(port)
.setPathSegments("/" + randomAlphaOfLength(5))
.setParameter(paramKey, paramValue)
.build();
HttpPost httpPost = new HttpPost(uri);
ByteArrayEntity byteEntity = new ByteArrayEntity(
randomAlphaOfLength(5).getBytes(StandardCharsets.UTF_8),
ContentType.APPLICATION_JSON
);
httpPost.setEntity(byteEntity);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaType());
return new HttpRequest(httpPost, "inferenceEntityId");
}
public static PoolingNHttpClientConnectionManager createConnectionManager() throws IOReactorException {
return new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor());
}
public static HttpSettings emptyHttpSettings() {
return createHttpSettings(Settings.EMPTY);
}
private static HttpSettings createHttpSettings(Settings settings) {
return new HttpSettings(settings, mockClusterService(settings));
}
}
| HttpClientTests |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/template/get/GetComposableIndexTemplateAction.java | {
"start": 4578,
"end": 8900
} | class ____ extends ActionResponse implements ToXContentObject {
public static final ParseField NAME = new ParseField("name");
public static final ParseField INDEX_TEMPLATES = new ParseField("index_templates");
public static final ParseField INDEX_TEMPLATE = new ParseField("index_template");
private final Map<String, ComposableIndexTemplate> indexTemplates;
@Nullable
private final RolloverConfiguration rolloverConfiguration;
/**
* Please use {@link GetComposableIndexTemplateAction.Response#Response(Map)}
*/
public Response(Map<String, ComposableIndexTemplate> indexTemplates, @Nullable DataStreamGlobalRetention globalRetention) {
this(indexTemplates, (RolloverConfiguration) null);
}
/**
* Please use {@link GetComposableIndexTemplateAction.Response#Response(Map, RolloverConfiguration)}
*/
@Deprecated
public Response(
Map<String, ComposableIndexTemplate> indexTemplates,
@Nullable RolloverConfiguration rolloverConfiguration,
@Nullable DataStreamGlobalRetention globalRetention
) {
this(indexTemplates, rolloverConfiguration);
}
public Response(Map<String, ComposableIndexTemplate> indexTemplates) {
this(indexTemplates, (RolloverConfiguration) null);
}
public Response(Map<String, ComposableIndexTemplate> indexTemplates, @Nullable RolloverConfiguration rolloverConfiguration) {
this.indexTemplates = indexTemplates;
this.rolloverConfiguration = rolloverConfiguration;
}
public Map<String, ComposableIndexTemplate> indexTemplates() {
return indexTemplates;
}
/**
* @return null
* @deprecated global retention is not used in composable templates anymore
*/
@Deprecated
@Nullable
public DataStreamGlobalRetention getGlobalRetention() {
return null;
}
@Nullable
public RolloverConfiguration getRolloverConfiguration() {
return rolloverConfiguration;
}
/**
* NB prior to 9.0 this was a TransportMasterNodeReadAction so for BwC we must remain able to write these responses until
* we no longer need to support calling this action remotely.
*/
@UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT)
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeMap(indexTemplates, StreamOutput::writeWriteable);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_9_X)) {
out.writeOptionalWriteable(rolloverConfiguration);
}
if (out.getTransportVersion().between(TransportVersions.V_8_14_0, TransportVersions.V_8_16_0)) {
out.writeOptionalWriteable(null);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GetComposableIndexTemplateAction.Response that = (GetComposableIndexTemplateAction.Response) o;
return Objects.equals(indexTemplates, that.indexTemplates) && Objects.equals(rolloverConfiguration, that.rolloverConfiguration);
}
@Override
public int hashCode() {
return Objects.hash(indexTemplates, rolloverConfiguration);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.startArray(INDEX_TEMPLATES.getPreferredName());
for (Map.Entry<String, ComposableIndexTemplate> indexTemplate : this.indexTemplates.entrySet()) {
builder.startObject();
builder.field(NAME.getPreferredName(), indexTemplate.getKey());
builder.field(INDEX_TEMPLATE.getPreferredName());
indexTemplate.getValue().toXContent(builder, params, rolloverConfiguration);
builder.endObject();
}
builder.endArray();
builder.endObject();
return builder;
}
}
}
| Response |
java | apache__camel | components/camel-pgevent/src/main/java/org/apache/camel/component/pgevent/PgEventComponent.java | {
"start": 1110,
"end": 1471
} | class ____ extends DefaultComponent {
public PgEventComponent() {
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
Endpoint endpoint = new PgEventEndpoint(uri, this);
setProperties(endpoint, parameters);
return endpoint;
}
}
| PgEventComponent |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/PersistenceUnitInfoDescriptor.java | {
"start": 3484,
"end": 4097
} | class ____
// in cases where we don't care about enhancement
if ( persistenceUnitInfo.getNewTempClassLoader() != null ) {
if ( JPA_LOGGER.isTraceEnabled() ) {
JPA_LOGGER.pushingClassTransformers( getName(), String.valueOf( enhancementContext.getLoadingClassLoader() ) );
}
final EnhancingClassTransformerImpl classTransformer =
new EnhancingClassTransformerImpl( enhancementContext );
this.classTransformer = classTransformer;
persistenceUnitInfo.addTransformer( classTransformer );
}
}
@Override
public ClassTransformer getClassTransformer() {
return classTransformer;
}
}
| loader |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/secondarytable/ParentChildWithSameSecondaryTableTest.java | {
"start": 6037,
"end": 6350
} | class ____ extends EntityA {
@Column(table = TABLE_NAME)
private String attrB;
public EntityB() {
}
public String getAttrB() {
return attrB;
}
public void setAttrB(String attrB) {
this.attrB = attrB;
}
}
@Entity(name = "EntityC")
@SecondaryTable(name = TABLE_NAME)
public static | EntityB |
java | bumptech__glide | annotation/compiler/test/src/test/resources/GlideExtensionOptionsTest/OverrideExtend/GlideRequest.java | {
"start": 1656,
"end": 16518
} | class ____<TranscodeType> extends RequestBuilder<TranscodeType> implements Cloneable {
GlideRequest(@NonNull Class<TranscodeType> transcodeClass, @NonNull RequestBuilder<?> other) {
super(transcodeClass, other);
}
GlideRequest(@NonNull Glide glide, @NonNull RequestManager requestManager,
@NonNull Class<TranscodeType> transcodeClass, @NonNull Context context) {
super(glide, requestManager ,transcodeClass, context);
}
@Override
@CheckResult
@NonNull
protected GlideRequest<File> getDownloadOnlyRequest() {
return new GlideRequest<>(File.class, this).apply(DOWNLOAD_ONLY_OPTIONS);
}
/**
* @see GlideOptions#sizeMultiplier(float)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> sizeMultiplier(@FloatRange(from = 0.0, to = 1.0) float value) {
return (GlideRequest<TranscodeType>) super.sizeMultiplier(value);
}
/**
* @see GlideOptions#useUnlimitedSourceGeneratorsPool(boolean)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> useUnlimitedSourceGeneratorsPool(boolean flag) {
return (GlideRequest<TranscodeType>) super.useUnlimitedSourceGeneratorsPool(flag);
}
/**
* @see GlideOptions#useAnimationPool(boolean)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> useAnimationPool(boolean flag) {
return (GlideRequest<TranscodeType>) super.useAnimationPool(flag);
}
/**
* @see GlideOptions#onlyRetrieveFromCache(boolean)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> onlyRetrieveFromCache(boolean flag) {
return (GlideRequest<TranscodeType>) super.onlyRetrieveFromCache(flag);
}
/**
* @see GlideOptions#diskCacheStrategy(DiskCacheStrategy)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> diskCacheStrategy(@NonNull DiskCacheStrategy strategy) {
return (GlideRequest<TranscodeType>) super.diskCacheStrategy(strategy);
}
/**
* @see GlideOptions#priority(Priority)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> priority(@NonNull Priority priority) {
return (GlideRequest<TranscodeType>) super.priority(priority);
}
/**
* @see GlideOptions#placeholder(Drawable)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> placeholder(@Nullable Drawable drawable) {
return (GlideRequest<TranscodeType>) super.placeholder(drawable);
}
/**
* @see GlideOptions#placeholder(int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> placeholder(@DrawableRes int id) {
return (GlideRequest<TranscodeType>) super.placeholder(id);
}
/**
* @see GlideOptions#fallback(Drawable)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> fallback(@Nullable Drawable drawable) {
return (GlideRequest<TranscodeType>) super.fallback(drawable);
}
/**
* @see GlideOptions#fallback(int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> fallback(@DrawableRes int id) {
return (GlideRequest<TranscodeType>) super.fallback(id);
}
/**
* @see GlideOptions#error(Drawable)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> error(@Nullable Drawable drawable) {
return (GlideRequest<TranscodeType>) super.error(drawable);
}
/**
* @see GlideOptions#error(int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> error(@DrawableRes int id) {
return (GlideRequest<TranscodeType>) super.error(id);
}
/**
* @see GlideOptions#theme(Resources.Theme)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> theme(@Nullable Resources.Theme theme) {
return (GlideRequest<TranscodeType>) super.theme(theme);
}
/**
* @see GlideOptions#skipMemoryCache(boolean)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> skipMemoryCache(boolean skip) {
return (GlideRequest<TranscodeType>) super.skipMemoryCache(skip);
}
/**
* @see GlideOptions#override(int, int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> override(int width, int height) {
return (GlideRequest<TranscodeType>) super.override(width, height);
}
/**
* @see GlideOptions#override(int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> override(int size) {
return (GlideRequest<TranscodeType>) super.override(size);
}
/**
* @see GlideOptions#signature(Key)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> signature(@NonNull Key key) {
return (GlideRequest<TranscodeType>) super.signature(key);
}
/**
* @see GlideOptions#set(Option<Y>, Y)
*/
@NonNull
@CheckResult
public <Y> GlideRequest<TranscodeType> set(@NonNull Option<Y> option, @NonNull Y y) {
return (GlideRequest<TranscodeType>) super.set(option, y);
}
/**
* @see GlideOptions#decode(Class<?>)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> decode(@NonNull Class<?> clazz) {
return (GlideRequest<TranscodeType>) super.decode(clazz);
}
/**
* @see GlideOptions#encodeFormat(Bitmap.CompressFormat)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> encodeFormat(@NonNull Bitmap.CompressFormat format) {
return (GlideRequest<TranscodeType>) super.encodeFormat(format);
}
/**
* @see GlideOptions#encodeQuality(int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> encodeQuality(@IntRange(from = 0, to = 100) int value) {
return (GlideRequest<TranscodeType>) super.encodeQuality(value);
}
/**
* @see GlideOptions#frame(long)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> frame(@IntRange(from = 0) long value) {
return (GlideRequest<TranscodeType>) super.frame(value);
}
/**
* @see GlideOptions#format(DecodeFormat)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> format(@NonNull DecodeFormat format) {
return (GlideRequest<TranscodeType>) super.format(format);
}
/**
* @see GlideOptions#disallowHardwareConfig()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> disallowHardwareConfig() {
return (GlideRequest<TranscodeType>) super.disallowHardwareConfig();
}
/**
* @see GlideOptions#downsample(DownsampleStrategy)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> downsample(@NonNull DownsampleStrategy strategy) {
return (GlideRequest<TranscodeType>) super.downsample(strategy);
}
/**
* @see GlideOptions#timeout(int)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> timeout(@IntRange(from = 0) int value) {
return (GlideRequest<TranscodeType>) super.timeout(value);
}
/**
* @see GlideOptions#optionalCenterCrop()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> optionalCenterCrop() {
return (GlideRequest<TranscodeType>) super.optionalCenterCrop();
}
/**
* @see GlideOptions#optionalFitCenter()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> optionalFitCenter() {
return (GlideRequest<TranscodeType>) super.optionalFitCenter();
}
/**
* @see GlideOptions#fitCenter()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> fitCenter() {
return (GlideRequest<TranscodeType>) super.fitCenter();
}
/**
* @see GlideOptions#optionalCenterInside()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> optionalCenterInside() {
return (GlideRequest<TranscodeType>) super.optionalCenterInside();
}
/**
* @see GlideOptions#centerInside()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> centerInside() {
return (GlideRequest<TranscodeType>) super.centerInside();
}
/**
* @see GlideOptions#optionalCircleCrop()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> optionalCircleCrop() {
return (GlideRequest<TranscodeType>) super.optionalCircleCrop();
}
/**
* @see GlideOptions#circleCrop()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> circleCrop() {
return (GlideRequest<TranscodeType>) super.circleCrop();
}
/**
* @see GlideOptions#transform(Transformation<Bitmap>)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> transform(@NonNull Transformation<Bitmap> transformation) {
return (GlideRequest<TranscodeType>) super.transform(transformation);
}
/**
* @see GlideOptions#transform(Transformation<Bitmap>[])
*/
@NonNull
@CheckResult
@SuppressWarnings({
"unchecked",
"varargs"
})
public GlideRequest<TranscodeType> transform(@NonNull Transformation<Bitmap>... transformations) {
return (GlideRequest<TranscodeType>) super.transform(transformations);
}
/**
* @see GlideOptions#transforms(Transformation<Bitmap>[])
*/
@Deprecated
@NonNull
@CheckResult
@SuppressWarnings({
"unchecked",
"varargs"
})
public GlideRequest<TranscodeType> transforms(
@NonNull Transformation<Bitmap>... transformations) {
return (GlideRequest<TranscodeType>) super.transforms(transformations);
}
/**
* @see GlideOptions#optionalTransform(Transformation<Bitmap>)
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> optionalTransform(
@NonNull Transformation<Bitmap> transformation) {
return (GlideRequest<TranscodeType>) super.optionalTransform(transformation);
}
/**
* @see GlideOptions#optionalTransform(Class<Y>, Transformation<Y>)
*/
@NonNull
@CheckResult
public <Y> GlideRequest<TranscodeType> optionalTransform(@NonNull Class<Y> clazz,
@NonNull Transformation<Y> transformation) {
return (GlideRequest<TranscodeType>) super.optionalTransform(clazz, transformation);
}
/**
* @see GlideOptions#transform(Class<Y>, Transformation<Y>)
*/
@NonNull
@CheckResult
public <Y> GlideRequest<TranscodeType> transform(@NonNull Class<Y> clazz,
@NonNull Transformation<Y> transformation) {
return (GlideRequest<TranscodeType>) super.transform(clazz, transformation);
}
/**
* @see GlideOptions#dontTransform()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> dontTransform() {
return (GlideRequest<TranscodeType>) super.dontTransform();
}
/**
* @see GlideOptions#dontAnimate()
*/
@NonNull
@CheckResult
public GlideRequest<TranscodeType> dontAnimate() {
return (GlideRequest<TranscodeType>) super.dontAnimate();
}
/**
* @see GlideOptions#lock()
*/
@NonNull
public GlideRequest<TranscodeType> lock() {
return (GlideRequest<TranscodeType>) super.lock();
}
/**
* @see GlideOptions#autoClone()
*/
@NonNull
public GlideRequest<TranscodeType> autoClone() {
return (GlideRequest<TranscodeType>) super.autoClone();
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> apply(@NonNull BaseRequestOptions<?> options) {
return (GlideRequest<TranscodeType>) super.apply(options);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> transition(
@NonNull TransitionOptions<?, ? super TranscodeType> options) {
return (GlideRequest<TranscodeType>) super.transition(options);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> listener(@Nullable RequestListener<TranscodeType> listener) {
return (GlideRequest<TranscodeType>) super.listener(listener);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> addListener(
@Nullable RequestListener<TranscodeType> listener) {
return (GlideRequest<TranscodeType>) super.addListener(listener);
}
@Override
@NonNull
public GlideRequest<TranscodeType> error(@Nullable RequestBuilder<TranscodeType> builder) {
return (GlideRequest<TranscodeType>) super.error(builder);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> error(Object o) {
return (GlideRequest<TranscodeType>) super.error(o);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> thumbnail(@Nullable RequestBuilder<TranscodeType> builder) {
return (GlideRequest<TranscodeType>) super.thumbnail(builder);
}
@Override
@NonNull
@CheckResult
@SafeVarargs
@SuppressWarnings("varargs")
public final GlideRequest<TranscodeType> thumbnail(
@Nullable RequestBuilder<TranscodeType>... builders) {
return (GlideRequest<TranscodeType>) super.thumbnail(builders);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> thumbnail(@Nullable List<RequestBuilder<TranscodeType>> list) {
return (GlideRequest<TranscodeType>) super.thumbnail(list);
}
@Override
@Deprecated
@NonNull
@CheckResult
public GlideRequest<TranscodeType> thumbnail(float sizeMultiplier) {
return (GlideRequest<TranscodeType>) super.thumbnail(sizeMultiplier);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable Object o) {
return (GlideRequest<TranscodeType>) super.load(o);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable Bitmap bitmap) {
return (GlideRequest<TranscodeType>) super.load(bitmap);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable Drawable drawable) {
return (GlideRequest<TranscodeType>) super.load(drawable);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable String string) {
return (GlideRequest<TranscodeType>) super.load(string);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable Uri uri) {
return (GlideRequest<TranscodeType>) super.load(uri);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable File file) {
return (GlideRequest<TranscodeType>) super.load(file);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@RawRes @DrawableRes @Nullable Integer id) {
return (GlideRequest<TranscodeType>) super.load(id);
}
@Override
@Deprecated
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable URL url) {
return (GlideRequest<TranscodeType>) super.load(url);
}
@Override
@NonNull
@CheckResult
public GlideRequest<TranscodeType> load(@Nullable byte[] bytes) {
return (GlideRequest<TranscodeType>) super.load(bytes);
}
@Override
@CheckResult
public GlideRequest<TranscodeType> clone() {
return (GlideRequest<TranscodeType>) super.clone();
}
/**
* @see Extension#centerCrop(BaseRequestOptions)
* @see GlideRequest<TranscodeType>#centerCrop()
*/
@SuppressWarnings("unchecked")
@Override
@CheckResult
@NonNull
public GlideRequest<TranscodeType> centerCrop() {
return (GlideRequest<TranscodeType>) Extension.centerCrop(super.centerCrop());
}
}
| GlideRequest |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTestBase.java | {
"start": 1333,
"end": 2462
} | class ____ extends MetricsHandlerTestBase<SubtaskMetricsHandler> {
private static final String TEST_JOB_ID = new JobID().toString();
private static final String TEST_VERTEX_ID = new JobVertexID().toString();
private static final int TEST_SUBTASK_INDEX = 0;
private static final int TEST_ATTEMPT_NUMBER = 0;
@Override
SubtaskMetricsHandler getMetricsHandler() {
return new SubtaskMetricsHandler(leaderRetriever, TIMEOUT, TEST_HEADERS, mockMetricFetcher);
}
@Override
QueryScopeInfo getQueryScopeInfo() {
return new QueryScopeInfo.TaskQueryScopeInfo(
TEST_JOB_ID, TEST_VERTEX_ID, TEST_SUBTASK_INDEX, TEST_ATTEMPT_NUMBER);
}
@Override
Map<String, String> getPathParameters() {
final Map<String, String> pathParameters = new HashMap<>();
pathParameters.put(JobIDPathParameter.KEY, TEST_JOB_ID);
pathParameters.put(JobVertexIdPathParameter.KEY, TEST_VERTEX_ID);
pathParameters.put(SubtaskIndexPathParameter.KEY, Integer.toString(TEST_SUBTASK_INDEX));
return pathParameters;
}
}
| SubtaskMetricsHandlerTestBase |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/arbiters/ScriptArbiter.java | {
"start": 2741,
"end": 4936
} | class ____ implements org.apache.logging.log4j.core.util.Builder<ScriptArbiter> {
private static final Logger LOGGER = StatusLogger.getLogger();
@PluginConfiguration
private AbstractConfiguration configuration;
@PluginNode
private Node node;
public Builder setConfiguration(final AbstractConfiguration configuration) {
this.configuration = configuration;
return asBuilder();
}
public Builder setNode(final Node node) {
this.node = node;
return asBuilder();
}
public Builder asBuilder() {
return this;
}
public ScriptArbiter build() {
AbstractScript script = null;
for (Node child : node.getChildren()) {
final PluginType<?> type = child.getType();
if (type == null) {
LOGGER.error("Node {} is missing a Plugintype", child.getName());
continue;
}
if (AbstractScript.class.isAssignableFrom(type.getPluginClass())) {
script = (AbstractScript) configuration.createPluginObject(type, child);
node.getChildren().remove(child);
break;
}
}
if (script == null) {
LOGGER.error("A Script, ScriptFile or ScriptRef element must be provided for this ScriptFilter");
return null;
}
if (configuration.getScriptManager() == null) {
LOGGER.error("Script support is not enabled");
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getId()) == null) {
LOGGER.error("No script with name {} has been declared.", script.getId());
return null;
}
} else {
if (!configuration.getScriptManager().addScript(script)) {
return null;
}
}
return new ScriptArbiter(configuration, script);
}
}
}
| Builder |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/NullOptionalTest.java | {
"start": 2485,
"end": 2918
} | class ____ {
void a(Optional<Object> o) {}
void test() {
a(Optional.empty());
}
}
""")
.doTest();
}
@Test
public void withinAssertThrows_noMatch() {
helper
.addSourceLines(
"Test.java",
"""
import static org.junit.Assert.assertThrows;
import java.util.Optional;
| Test |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanStringITests.java | {
"start": 1492,
"end": 1677
} | class ____ {
@Bean
UserDetailsManagerResourceFactoryBean userDetailsService() {
return UserDetailsManagerResourceFactoryBean.fromString("user=password,ROLE_USER");
}
}
}
| Config |
java | resilience4j__resilience4j | resilience4j-rxjava2/src/test/java/io/github/resilience4j/micrometer/transformer/ObservableTimerTest.java | {
"start": 1264,
"end": 2664
} | class ____ {
@Test
public void shouldTimeSuccessfulObservable() {
List<String> messages = List.of("Hello 1", "Hello 2", "Hello 3");
MeterRegistry registry = new SimpleMeterRegistry();
Timer timer = Timer.of("timer 1", registry);
List<String> result = Observable.fromIterable(messages)
.compose(TimerTransformer.of(timer))
.toList()
.blockingGet();
then(result).containsExactlyInAnyOrderElementsOf(messages);
thenSuccessTimed(registry, timer);
}
@Test
public void shouldTimeFailedObservable() {
IllegalStateException exception = new IllegalStateException();
MeterRegistry registry = new SimpleMeterRegistry();
TimerConfig config = TimerConfig.custom()
.onFailureTagResolver(ex -> {
then(ex).isEqualTo(exception);
return ex.toString();
})
.build();
Timer timer = Timer.of("timer 1", registry, config);
try {
Observable.error(exception)
.compose(TimerTransformer.of(timer))
.toList()
.blockingGet();
failBecauseExceptionWasNotThrown(exception.getClass());
} catch (Exception e) {
thenFailureTimed(registry, timer, e);
}
}
}
| ObservableTimerTest |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/ComparingFields_getChildrenNodeNamesOf_Test.java | {
"start": 3940,
"end": 4046
} | class ____ extends SuperClass {
private final String subClassField = "subClassField value";
}
}
| SubClass |
java | apache__camel | components/camel-openstack/src/test/java/org/apache/camel/component/openstack/keystone/KeystoneProducerTestSupport.java | {
"start": 1242,
"end": 1550
} | class ____ extends AbstractProducerTestSupport {
@Mock
protected KeystoneEndpoint endpoint;
@Mock
protected IdentityService identityService;
@BeforeEach
public void setUpComputeService() {
when(client.identity()).thenReturn(identityService);
}
}
| KeystoneProducerTestSupport |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/dataaccess/jdbc/jdbccomplextypes/TestItem.java | {
"start": 718,
"end": 1420
} | class ____ {
private Long id;
private String description;
private Date expirationDate;
public TestItem() {
}
public TestItem(Long id, String description, Date expirationDate) {
this.id = id;
this.description = description;
this.expirationDate = expirationDate;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getExpirationDate() {
return this.expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
}
| TestItem |
java | apache__dubbo | dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/zipkin/ZipkinWebClientSender.java | {
"start": 1137,
"end": 1603
} | class ____ extends HttpSender {
private final String endpoint;
private final WebClient webClient;
ZipkinWebClientSender(String endpoint, WebClient webClient) {
this.endpoint = endpoint;
this.webClient = webClient;
}
@Override
public HttpPostCall sendSpans(byte[] batchedEncodedSpans) {
return new WebClientHttpPostCall(this.endpoint, batchedEncodedSpans, this.webClient);
}
private static | ZipkinWebClientSender |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/OpenSslSession.java | {
"start": 839,
"end": 1392
} | interface ____ extends SSLSession {
/**
* Returns true if the peer has provided certificates during the handshake.
* <p>
* This method is similar to {@link SSLSession#getPeerCertificates()} but it does not throw a
* {@link SSLPeerUnverifiedException} if no certs are provided, making it more efficient to check if a mTLS
* connection is used.
*
* @return true if peer certificates are available.
*/
boolean hasPeerCertificates();
@Override
OpenSslSessionContext getSessionContext();
}
| OpenSslSession |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/TopicPartition.java | {
"start": 947,
"end": 2141
} | class ____ implements Serializable {
private static final long serialVersionUID = -613627415771699627L;
private int hash = 0;
private final int partition;
private final String topic;
public TopicPartition(String topic, int partition) {
this.partition = partition;
this.topic = topic;
}
public int partition() {
return partition;
}
public String topic() {
return topic;
}
@Override
public int hashCode() {
if (hash != 0)
return hash;
final int prime = 31;
int result = prime + partition;
result = prime * result + Objects.hashCode(topic);
this.hash = result;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TopicPartition other = (TopicPartition) obj;
return partition == other.partition && Objects.equals(topic, other.topic);
}
@Override
public String toString() {
return topic + "-" + partition;
}
}
| TopicPartition |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpSecurityDeferAddFilterTests.java | {
"start": 7662,
"end": 8046
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.addFilterAt(new MyFilter(), ChannelProcessingFilter.class)
.addFilterAt(new MyFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static | MyFilterMultipleAtConfig |
java | alibaba__fastjson | src/test/java/com/alibaba/json/test/TestFor_iteye_resolute.java | {
"start": 218,
"end": 1667
} | class ____ extends TestCase {
private static final int SIZE = 1000;
private static final int LOOP_COUNT = 1000 * 10;
public void test_perf() {
for (int i = 0; i < 10; ++i) {
json();
javaSer();
System.out.println();
}
}
public void json() {
long begin = System.currentTimeMillis();
int length = 0;
for (int i = 0; i < LOOP_COUNT; ++i) {
String json = JSON.toJSONString(mkTestDates(SIZE));
length = json.length();
}
long time = System.currentTimeMillis() - begin;
System.out.println("json time " + time + ", len " + length);
}
public void javaSer() {
long begin = System.currentTimeMillis();
int length = 0;
for (int i = 0; i < LOOP_COUNT; ++i) {
byte[] bytes = SerializationUtils.serialize(mkTestDates(SIZE));
length = bytes.length;
}
long time = System.currentTimeMillis() - begin;
System.out.println("java time " + time + ", len " + length);
}
public ArrayList<User> mkTestDates(int count) {
ArrayList<User> users = new ArrayList<User>();
for (int i = 0; i < count; i++) {
User user = new User(i);
user.setName("xxxxxxxxxxxxxxxxxxxxxx");
users.add(user);
}
return users;
}
public static | TestFor_iteye_resolute |
java | apache__camel | components/camel-nitrite/src/test/java/org/apache/camel/component/nitrite/AbstractNitriteTest.java | {
"start": 1186,
"end": 2164
} | class ____ extends CamelTestSupport {
@RegisterExtension
@Order(10)
TestNameExtension testNameExtension = new TestNameExtension();
@Override
protected void doPreSetup() throws Exception {
super.doPreSetup();
FileUtil.deleteFile(new File(tempDb()));
}
protected String tempDb() {
return "target/" + getClass().getSimpleName() + "_" + testNameExtension.getCurrentTestName() + ".db";
}
protected List<Exchange> sortByChangeTimestamp(List<Exchange> input) {
return input.stream().sorted((e1, e2) -> {
Long timestamp1 = e1.getMessage().getHeader(NitriteConstants.CHANGE_TIMESTAMP, Long.class);
Long timestamp2 = e2.getMessage().getHeader(NitriteConstants.CHANGE_TIMESTAMP, Long.class);
if (timestamp1 == null || timestamp2 == null) {
return 0;
}
return Long.compare(timestamp1, timestamp2);
}).toList();
}
}
| AbstractNitriteTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/db2/ast/DB2IntermediateResultTableSource.java | {
"start": 171,
"end": 324
} | class ____ extends SQLTableSourceImpl {
@Override
protected void accept0(SQLASTVisitor v) {
}
public static | DB2IntermediateResultTableSource |
java | spring-projects__spring-boot | buildSrc/src/main/java/org/springframework/boot/build/antora/Extensions.java | {
"start": 5612,
"end": 5807
} | class ____ extends Customizer {
RootComponent() {
super(ROOT_COMPONENT_EXTENSION);
}
void name(String name) {
customize("root_component_name", name);
}
}
}
}
| RootComponent |
java | apache__camel | core/camel-main/src/test/java/org/apache/camel/main/MainIoCNewRouteBuilderTest.java | {
"start": 3073,
"end": 3404
} | class ____ extends RouteBuilder {
@BindToRegistry("bar")
public MyBar createBar(@PropertyInject("hello") String hello) {
return new MyBar(hello);
}
@Override
public void configure() {
from("direct:start").bean("bar").to("mock:results");
}
}
}
| MyRouteBuilder |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Client.java | {
"start": 62558,
"end": 62842
} | class ____ the address and the user ticket. The client connections
* to servers are uniquely identified by {@literal <}remoteAddress, protocol,
* ticket{@literal >}
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Evolving
public static | holds |
java | quarkusio__quarkus | extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/ClassLevelCustomPermissionsAllowedTest.java | {
"start": 7195,
"end": 7572
} | class ____ {
public final String write() {
return WRITE_PERMISSION;
}
public final Uni<String> writeNonBlocking() {
return Uni.createFrom().item(WRITE_PERMISSION);
}
}
@PermissionsAllowed(value = WRITE_PERMISSION_BEAN, permission = CustomPermission.class)
@Singleton
public static | SingleAnnotationWriteBean |
java | quarkusio__quarkus | extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/TenantReauthentication.java | {
"start": 351,
"end": 714
} | class ____ {
@Inject
@IdToken
JsonWebToken idToken;
@Inject
OidcSession session;
@GET
public String getName() {
return idToken.getName();
}
@GET
@Path("tenant/{id}")
public String getTenantName(@PathParam("id") String tenantId) {
return tenantId + ":" + idToken.getName();
}
}
| TenantReauthentication |
java | apache__flink | flink-formats/flink-protobuf/src/main/java/org/apache/flink/formats/protobuf/deserialize/PbCodegenDeserializeFactory.java | {
"start": 1406,
"end": 2689
} | class ____ {
public static PbCodegenDeserializer getPbCodegenDes(
Descriptors.FieldDescriptor fd, LogicalType type, PbFormatContext formatContext)
throws PbCodegenException {
// We do not use FieldDescriptor to check because there's no way to get
// element field descriptor of array type.
if (type instanceof RowType) {
return new PbCodegenRowDeserializer(fd.getMessageType(), (RowType) type, formatContext);
} else if (PbFormatUtils.isSimpleType(type)) {
return new PbCodegenSimpleDeserializer(fd, type);
} else if (type instanceof ArrayType) {
return new PbCodegenArrayDeserializer(
fd, ((ArrayType) type).getElementType(), formatContext);
} else if (type instanceof MapType) {
return new PbCodegenMapDeserializer(fd, (MapType) type, formatContext);
} else {
throw new PbCodegenException("Do not support flink type: " + type);
}
}
public static PbCodegenDeserializer getPbCodegenTopRowDes(
Descriptors.Descriptor descriptor, RowType rowType, PbFormatContext formatContext) {
return new PbCodegenRowDeserializer(descriptor, rowType, formatContext);
}
}
| PbCodegenDeserializeFactory |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java | {
"start": 81707,
"end": 84512
} | interface ____<T extends Number> {
Builder<T> setThings(List<T> things);
ImmutableList<T> things();
ImmutableList.Builder<T> thingsBuilder();
BuilderWithCollectionBuilderAndSetter<T> build();
}
}
@Test
public void testBuilderAndSetterDefaultsEmpty() {
BuilderWithCollectionBuilderAndSetter.Builder<Integer> builder =
BuilderWithCollectionBuilderAndSetter.<Integer>builder();
assertThat(builder.things()).isEmpty();
assertThat(builder.build().things()).isEmpty();
}
@Test
public void testBuilderAndSetterUsingBuilder() {
BuilderWithCollectionBuilderAndSetter.Builder<Integer> builder =
BuilderWithCollectionBuilderAndSetter.builder();
builder.thingsBuilder().add(17, 23);
BuilderWithCollectionBuilderAndSetter<Integer> x = builder.build();
assertThat(x.things()).isEqualTo(ImmutableList.of(17, 23));
}
@Test
public void testBuilderAndSetterUsingSetter() {
ImmutableList<Integer> things = ImmutableList.of(17, 23);
BuilderWithCollectionBuilderAndSetter.Builder<Integer> builder =
BuilderWithCollectionBuilderAndSetter.<Integer>builder().setThings(things);
assertThat(builder.things()).isSameInstanceAs(things);
assertThat(builder.build().things()).isSameInstanceAs(things);
List<Integer> moreThings = Arrays.asList(5, 17, 23);
BuilderWithCollectionBuilderAndSetter.Builder<Integer> builder2 =
BuilderWithCollectionBuilderAndSetter.<Integer>builder().setThings(moreThings);
assertThat(builder2.things()).isEqualTo(moreThings);
assertThat(builder2.build().things()).isEqualTo(moreThings);
}
@Test
public void testBuilderAndSetterUsingSetterThenBuilder() {
BuilderWithCollectionBuilderAndSetter.Builder<Integer> builder =
BuilderWithCollectionBuilderAndSetter.builder();
builder.setThings(ImmutableList.of(5));
builder.thingsBuilder().add(17, 23);
List<Integer> expectedThings = ImmutableList.of(5, 17, 23);
assertThat(builder.things()).isEqualTo(expectedThings);
assertThat(builder.build().things()).isEqualTo(expectedThings);
}
@Test
public void testBuilderAndSetterCannotSetAfterBuilder() {
BuilderWithCollectionBuilderAndSetter.Builder<Integer> builder =
BuilderWithCollectionBuilderAndSetter.builder();
builder.setThings(ImmutableList.of(5));
builder.thingsBuilder().add(17, 23);
try {
builder.setThings(ImmutableList.of(1729));
fail("Setting list after retrieving builder should provoke an exception");
} catch (IllegalStateException e) {
if (omitIdentifiers) {
assertThat(e).hasMessageThat().isNull();
} else {
assertThat(e).hasMessageThat().isEqualTo("Cannot set things after calling thingsBuilder()");
}
}
}
abstract static | Builder |
java | quarkusio__quarkus | extensions/oidc-client-reactive-filter/deployment/src/test/java/io/quarkus/oidc/client/reactive/filter/OidcClientFilterRevokedAccessTokenDevModeTest.java | {
"start": 3623,
"end": 3849
} | class ____ extends AbstractOidcClientRequestReactiveFilter {
}
@RegisterRestClient
@RegisterProvider(value = NamedClientRefreshDisabled.class)
@Path(MY_SERVER_RESOURCE_PATH)
public | DefaultClientRefreshDisabled |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/throttler/AckThrottler.java | {
"start": 727,
"end": 1215
} | class ____ implements Throttler {
@Override
public Result throttle(String actionId, WatchExecutionContext ctx) {
ActionStatus actionStatus = ctx.watch().status().actionStatus(actionId);
AckStatus ackStatus = actionStatus.ackStatus();
if (ackStatus.state() == AckStatus.State.ACKED) {
return Result.throttle(ACK, "action [{}] was acked at [{}]", actionId, formatDate(ackStatus.timestamp()));
}
return Result.NO;
}
}
| AckThrottler |
java | apache__dubbo | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/support/merger/DefaultProviderURLMergeProcessor.java | {
"start": 2571,
"end": 5776
} | class ____ implements ProviderURLMergeProcessor {
@Override
public URL mergeUrl(URL remoteUrl, Map<String, String> localParametersMap) {
Map<String, String> map = new HashMap<>();
Map<String, String> remoteMap = remoteUrl.getParameters();
if (remoteMap != null && remoteMap.size() > 0) {
map.putAll(remoteMap);
// Remove configurations from provider, some items should be affected by provider.
map.remove(THREAD_NAME_KEY);
map.remove(DEFAULT_KEY_PREFIX + THREAD_NAME_KEY);
map.remove(THREADPOOL_KEY);
map.remove(DEFAULT_KEY_PREFIX + THREADPOOL_KEY);
map.remove(CORE_THREADS_KEY);
map.remove(DEFAULT_KEY_PREFIX + CORE_THREADS_KEY);
map.remove(THREADS_KEY);
map.remove(DEFAULT_KEY_PREFIX + THREADS_KEY);
map.remove(QUEUES_KEY);
map.remove(DEFAULT_KEY_PREFIX + QUEUES_KEY);
map.remove(ALIVE_KEY);
map.remove(DEFAULT_KEY_PREFIX + ALIVE_KEY);
map.remove(Constants.TRANSPORTER_KEY);
map.remove(DEFAULT_KEY_PREFIX + Constants.TRANSPORTER_KEY);
}
if (localParametersMap != null && localParametersMap.size() > 0) {
Map<String, String> copyOfLocalMap = new HashMap<>(localParametersMap);
if (map.containsKey(GROUP_KEY)) {
copyOfLocalMap.remove(GROUP_KEY);
}
if (map.containsKey(VERSION_KEY)) {
copyOfLocalMap.remove(VERSION_KEY);
}
if (map.containsKey(GENERIC_KEY)) {
copyOfLocalMap.remove(GENERIC_KEY);
}
copyOfLocalMap.remove(RELEASE_KEY);
copyOfLocalMap.remove(DUBBO_VERSION_KEY);
copyOfLocalMap.remove(METHODS_KEY);
copyOfLocalMap.remove(TIMESTAMP_KEY);
copyOfLocalMap.remove(TAG_KEY);
map.putAll(copyOfLocalMap);
if (remoteMap != null) {
map.put(REMOTE_APPLICATION_KEY, remoteMap.get(APPLICATION_KEY));
// Combine filters and listeners on Provider and Consumer
String remoteFilter = remoteMap.get(REFERENCE_FILTER_KEY);
String localFilter = copyOfLocalMap.get(REFERENCE_FILTER_KEY);
if (remoteFilter != null
&& remoteFilter.length() > 0
&& localFilter != null
&& localFilter.length() > 0) {
map.put(REFERENCE_FILTER_KEY, remoteFilter + "," + localFilter);
}
String remoteListener = remoteMap.get(INVOKER_LISTENER_KEY);
String localListener = copyOfLocalMap.get(INVOKER_LISTENER_KEY);
if (remoteListener != null
&& remoteListener.length() > 0
&& localListener != null
&& localListener.length() > 0) {
map.put(INVOKER_LISTENER_KEY, remoteListener + "," + localListener);
}
}
}
return remoteUrl.clearParameters().addParameters(map);
}
}
| DefaultProviderURLMergeProcessor |
java | apache__avro | lang/java/avro/src/test/java/org/apache/avro/io/TestBinaryDecoder.java | {
"start": 1918,
"end": 28262
} | class ____ {
// prime number buffer size so that looping tests hit the buffer edge
// at different points in the loop.
DecoderFactory factory = new DecoderFactory().configureDecoderBufferSize(521);
static EncoderFactory e_factory = EncoderFactory.get();
private Decoder newDecoderWithNoData(boolean useDirect) {
return newDecoder(new byte[0], useDirect);
}
private BinaryDecoder newDecoder(byte[] bytes, int start, int len, boolean useDirect) {
return this.newDecoder(bytes, start, len, null, useDirect);
}
private BinaryDecoder newDecoder(byte[] bytes, int start, int len, BinaryDecoder reuse, boolean useDirect) {
if (useDirect) {
final ByteArrayInputStream input = new ByteArrayInputStream(bytes, start, len);
return factory.directBinaryDecoder(input, reuse);
} else {
return factory.binaryDecoder(bytes, start, len, reuse);
}
}
private BinaryDecoder newDecoder(InputStream in, boolean useDirect) {
return this.newDecoder(in, null, useDirect);
}
private BinaryDecoder newDecoder(InputStream in, BinaryDecoder reuse, boolean useDirect) {
if (useDirect) {
return factory.directBinaryDecoder(in, reuse);
} else {
return factory.binaryDecoder(in, reuse);
}
}
private BinaryDecoder newDecoder(byte[] bytes, BinaryDecoder reuse, boolean useDirect) {
if (useDirect) {
return this.factory.directBinaryDecoder(new ByteArrayInputStream(bytes), reuse);
} else {
return factory.binaryDecoder(bytes, reuse);
}
}
private BinaryDecoder newDecoder(byte[] bytes, boolean useDirect) {
return this.newDecoder(bytes, null, useDirect);
}
/**
* Create a decoder for simulating reading corrupt, unexpected or out-of-bounds
* data.
*
* @return a {@link org.apache.avro.io.BinaryDecoder that has been initialized
* on a byte array containing the sequence of encoded longs in order.
*/
private BinaryDecoder newDecoder(boolean useDirect, long... values) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(baos, null);
for (long v : values)
encoder.writeLong(v);
encoder.flush();
return newDecoder(baos.toByteArray(), useDirect);
}
}
/** Verify EOFException throw at EOF */
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofBoolean(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readBoolean());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofInt(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readInt());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofLong(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readLong());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofFloat(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readFloat());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofDouble(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readDouble());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofBytes(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readBytes(null));
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofString(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readString(new Utf8("a")));
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofFixed(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readFixed(new byte[1]));
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eofEnum(boolean useDirect) {
Assertions.assertThrows(EOFException.class, () -> newDecoderWithNoData(useDirect).readEnum());
}
@Test
void reuse() throws IOException {
ByteBufferOutputStream bbo1 = new ByteBufferOutputStream();
ByteBufferOutputStream bbo2 = new ByteBufferOutputStream();
byte[] b1 = new byte[] { 1, 2 };
BinaryEncoder e1 = e_factory.binaryEncoder(bbo1, null);
e1.writeBytes(b1);
e1.flush();
BinaryEncoder e2 = e_factory.binaryEncoder(bbo2, null);
e2.writeBytes(b1);
e2.flush();
DirectBinaryDecoder d = new DirectBinaryDecoder(new ByteBufferInputStream(bbo1.getBufferList()));
ByteBuffer bb1 = d.readBytes(null);
Assertions.assertEquals(b1.length, bb1.limit() - bb1.position());
d.configure(new ByteBufferInputStream(bbo2.getBufferList()));
ByteBuffer bb2 = d.readBytes(null);
Assertions.assertEquals(b1.length, bb2.limit() - bb2.position());
}
private static byte[] data = null;
private static Schema schema = null;
private static final int count = 200;
private static final ArrayList<Object> records = new ArrayList<>(count);
@BeforeAll
public static void generateData() throws IOException {
int seed = (int) System.currentTimeMillis();
// note some tests (testSkipping) rely on this explicitly
String jsonSchema = "{\"type\": \"record\", \"name\": \"Test\", \"fields\": ["
+ "{\"name\":\"intField\", \"type\":\"int\"}," + "{\"name\":\"bytesField\", \"type\":\"bytes\"},"
+ "{\"name\":\"booleanField\", \"type\":\"boolean\"}," + "{\"name\":\"stringField\", \"type\":\"string\"},"
+ "{\"name\":\"floatField\", \"type\":\"float\"}," + "{\"name\":\"doubleField\", \"type\":\"double\"},"
+ "{\"name\":\"arrayField\", \"type\": " + "{\"type\":\"array\", \"items\":\"boolean\"}},"
+ "{\"name\":\"longField\", \"type\":\"long\"}]}";
schema = new Schema.Parser().parse(jsonSchema);
GenericDatumWriter<Object> writer = new GenericDatumWriter<>();
writer.setSchema(schema);
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
BinaryEncoder encoder = e_factory.binaryEncoder(baos, null);
for (Object datum : new RandomData(schema, count, seed)) {
writer.write(datum, encoder);
records.add(datum);
}
encoder.flush();
data = baos.toByteArray();
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void decodeFromSources(boolean useDirect) throws IOException {
GenericDatumReader<Object> reader = new GenericDatumReader<>();
reader.setSchema(schema);
ByteArrayInputStream is = new ByteArrayInputStream(data);
ByteArrayInputStream is2 = new ByteArrayInputStream(data);
ByteArrayInputStream is3 = new ByteArrayInputStream(data);
Decoder fromInputStream = newDecoder(is, useDirect);
Decoder fromArray = newDecoder(data, useDirect);
byte[] data2 = new byte[data.length + 30];
Arrays.fill(data2, (byte) 0xff);
System.arraycopy(data, 0, data2, 15, data.length);
Decoder fromOffsetArray = newDecoder(data2, 15, data.length, useDirect);
BinaryDecoder initOnInputStream = newDecoder(new byte[50], 0, 30, useDirect);
initOnInputStream = newDecoder(is2, initOnInputStream, useDirect);
BinaryDecoder initOnArray = this.newDecoder(is3, null, useDirect);
initOnArray = this.newDecoder(data, initOnArray, useDirect);
for (Object datum : records) {
Assertions.assertEquals(datum, reader.read(null, fromInputStream),
"InputStream based BinaryDecoder result does not match");
Assertions.assertEquals(datum, reader.read(null, fromArray), "Array based BinaryDecoder result does not match");
Assertions.assertEquals(datum, reader.read(null, fromOffsetArray),
"offset Array based BinaryDecoder result does not match");
Assertions.assertEquals(datum, reader.read(null, initOnInputStream),
"InputStream initialized BinaryDecoder result does not match");
Assertions.assertEquals(datum, reader.read(null, initOnArray),
"Array initialized BinaryDecoder result does not match");
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void inputStreamProxy(boolean useDirect) throws IOException {
BinaryDecoder d = newDecoder(data, useDirect);
if (d != null) {
BinaryDecoder bd = d;
InputStream test = bd.inputStream();
InputStream check = new ByteArrayInputStream(data);
validateInputStreamReads(test, check);
bd = this.newDecoder(data, bd, useDirect);
test = bd.inputStream();
check = new ByteArrayInputStream(data);
validateInputStreamSkips(test, check);
// with input stream sources
bd = newDecoder(new ByteArrayInputStream(data), bd, useDirect);
test = bd.inputStream();
check = new ByteArrayInputStream(data);
validateInputStreamReads(test, check);
bd = newDecoder(new ByteArrayInputStream(data), bd, useDirect);
test = bd.inputStream();
check = new ByteArrayInputStream(data);
validateInputStreamSkips(test, check);
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void inputStreamProxyDetached(boolean useDirect) throws IOException {
BinaryDecoder bd = newDecoder(data, useDirect);
InputStream test = bd.inputStream();
InputStream check = new ByteArrayInputStream(data);
// detach input stream and decoder from old source
this.newDecoder(new byte[56], useDirect);
try (InputStream bad = bd.inputStream(); InputStream check2 = new ByteArrayInputStream(data)) {
validateInputStreamReads(test, check);
Assertions.assertNotEquals(bad.read(), check2.read());
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void inputStreamPartiallyUsed(boolean useDirect) throws IOException {
BinaryDecoder bd = this.newDecoder(new ByteArrayInputStream(data), useDirect);
InputStream test = bd.inputStream();
InputStream check = new ByteArrayInputStream(data);
// triggers buffer fill if unused and tests isEnd()
try {
Assertions.assertFalse(bd.isEnd());
} catch (UnsupportedOperationException e) {
// this is ok if its a DirectBinaryDecoder.
if (bd.getClass() != DirectBinaryDecoder.class) {
throw e;
}
}
bd.readFloat(); // use data, and otherwise trigger buffer fill
check.skip(4); // skip the same # of bytes here
validateInputStreamReads(test, check);
}
private void validateInputStreamReads(InputStream test, InputStream check) throws IOException {
byte[] bt = new byte[7];
byte[] bc = new byte[7];
while (true) {
int t = test.read();
int c = check.read();
Assertions.assertEquals(c, t);
if (-1 == t) {
break;
}
t = test.read(bt);
c = check.read(bc);
Assertions.assertEquals(c, t);
Assertions.assertArrayEquals(bt, bc);
if (-1 == t) {
break;
}
t = test.read(bt, 1, 4);
c = check.read(bc, 1, 4);
Assertions.assertEquals(c, t);
Assertions.assertArrayEquals(bt, bc);
if (-1 == t) {
break;
}
}
Assertions.assertEquals(0, test.skip(5));
Assertions.assertEquals(0, test.available());
Assertions.assertFalse(test.getClass() != ByteArrayInputStream.class && test.markSupported());
test.close();
}
private void validateInputStreamSkips(InputStream test, InputStream check) throws IOException {
while (true) {
long t2 = test.skip(19);
long c2 = check.skip(19);
Assertions.assertEquals(c2, t2);
if (0 == t2) {
break;
}
}
Assertions.assertEquals(-1, test.read());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void badIntEncoding(boolean useDirect) throws IOException {
byte[] badint = new byte[5];
Arrays.fill(badint, (byte) 0xff);
Decoder bd = this.newDecoder(badint, useDirect);
String message = "";
try {
bd.readInt();
} catch (IOException ioe) {
message = ioe.getMessage();
}
Assertions.assertEquals("Invalid int encoding", message);
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void badLongEncoding(boolean useDirect) throws IOException {
byte[] badint = new byte[10];
Arrays.fill(badint, (byte) 0xff);
Decoder bd = this.newDecoder(badint, useDirect);
String message = "";
try {
bd.readLong();
} catch (IOException ioe) {
message = ioe.getMessage();
}
Assertions.assertEquals("Invalid long encoding", message);
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testStringNegativeLength(boolean useDirect) throws IOException {
Exception ex = Assertions.assertThrows(AvroRuntimeException.class, this.newDecoder(useDirect, -1L)::readString);
Assertions.assertEquals(ERROR_NEGATIVE, ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testStringVmMaxSize(boolean useDirect) throws IOException {
Exception ex = Assertions.assertThrows(UnsupportedOperationException.class,
newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1L)::readString);
Assertions.assertEquals(ERROR_VM_LIMIT_STRING, ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testStringMaxCustom(boolean useDirect) throws IOException {
try {
System.setProperty(SystemLimitException.MAX_STRING_LENGTH_PROPERTY, Long.toString(128));
resetLimits();
Exception ex = Assertions.assertThrows(SystemLimitException.class, newDecoder(useDirect, 129)::readString);
Assertions.assertEquals("String length 129 exceeds maximum allowed", ex.getMessage());
} finally {
System.clearProperty(SystemLimitException.MAX_STRING_LENGTH_PROPERTY);
resetLimits();
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testBytesNegativeLength(boolean useDirect) throws IOException {
Exception ex = Assertions.assertThrows(AvroRuntimeException.class,
() -> this.newDecoder(useDirect, -1).readBytes(null));
Assertions.assertEquals(ERROR_NEGATIVE, ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testBytesVmMaxSize(boolean useDirect) throws IOException {
Exception ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> this.newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).readBytes(null));
Assertions.assertEquals(ERROR_VM_LIMIT_BYTES, ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testBytesMaxCustom(boolean useDirect) throws IOException {
try {
System.setProperty(SystemLimitException.MAX_BYTES_LENGTH_PROPERTY, Long.toString(128));
resetLimits();
Exception ex = Assertions.assertThrows(SystemLimitException.class,
() -> newDecoder(useDirect, 129).readBytes(null));
Assertions.assertEquals("Bytes length 129 exceeds maximum allowed", ex.getMessage());
} finally {
System.clearProperty(SystemLimitException.MAX_BYTES_LENGTH_PROPERTY);
resetLimits();
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testArrayVmMaxSize(boolean useDirect) throws IOException {
// At start
Exception ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> this.newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).readArrayStart());
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Next
ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> this.newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).arrayNext());
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// An OK reads followed by an overflow
Decoder bd = newDecoder(useDirect, MAX_ARRAY_VM_LIMIT - 100, Long.MAX_VALUE);
Assertions.assertEquals(MAX_ARRAY_VM_LIMIT - 100, bd.readArrayStart());
ex = Assertions.assertThrows(UnsupportedOperationException.class, bd::arrayNext);
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Two OK reads followed by going over the VM limit.
bd = newDecoder(useDirect, MAX_ARRAY_VM_LIMIT - 100, 100, 1);
Assertions.assertEquals(MAX_ARRAY_VM_LIMIT - 100, bd.readArrayStart());
Assertions.assertEquals(100, bd.arrayNext());
ex = Assertions.assertThrows(UnsupportedOperationException.class, bd::arrayNext);
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Two OK reads followed by going over the VM limit, where negative numbers are
// followed by the byte length of the items. For testing, the 999 values are
// read but ignored.
bd = newDecoder(useDirect, 100 - MAX_ARRAY_VM_LIMIT, 999, -100, 999, 1);
Assertions.assertEquals(MAX_ARRAY_VM_LIMIT - 100, bd.readArrayStart());
Assertions.assertEquals(100, bd.arrayNext());
ex = Assertions.assertThrows(UnsupportedOperationException.class, bd::arrayNext);
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testArrayMaxCustom(boolean useDirect) throws IOException {
try {
System.setProperty(SystemLimitException.MAX_COLLECTION_LENGTH_PROPERTY, Long.toString(128));
resetLimits();
Exception ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).readArrayStart());
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Two OK reads followed by going over the custom limit.
Decoder bd = newDecoder(useDirect, 118, 10, 1);
Assertions.assertEquals(118, bd.readArrayStart());
Assertions.assertEquals(10, bd.arrayNext());
ex = Assertions.assertThrows(SystemLimitException.class, bd::arrayNext);
Assertions.assertEquals("Collection length 129 exceeds maximum allowed", ex.getMessage());
// Two OK reads followed by going over the VM limit, where negative numbers are
// followed by the byte length of the items. For testing, the 999 values are
// read but ignored.
bd = newDecoder(useDirect, -118, 999, -10, 999, 1);
Assertions.assertEquals(118, bd.readArrayStart());
Assertions.assertEquals(10, bd.arrayNext());
ex = Assertions.assertThrows(SystemLimitException.class, bd::arrayNext);
Assertions.assertEquals("Collection length 129 exceeds maximum allowed", ex.getMessage());
} finally {
System.clearProperty(SystemLimitException.MAX_COLLECTION_LENGTH_PROPERTY);
resetLimits();
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testMapVmMaxSize(boolean useDirect) throws IOException {
// At start
Exception ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> this.newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).readMapStart());
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Next
ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> this.newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).mapNext());
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Two OK reads followed by going over the VM limit.
Decoder bd = newDecoder(useDirect, MAX_ARRAY_VM_LIMIT - 100, 100, 1);
Assertions.assertEquals(MAX_ARRAY_VM_LIMIT - 100, bd.readMapStart());
Assertions.assertEquals(100, bd.mapNext());
ex = Assertions.assertThrows(UnsupportedOperationException.class, bd::mapNext);
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Two OK reads followed by going over the VM limit, where negative numbers are
// followed by the byte length of the items. For testing, the 999 values are
// read but ignored.
bd = newDecoder(useDirect, 100 - MAX_ARRAY_VM_LIMIT, 999, -100, 999, 1);
Assertions.assertEquals(MAX_ARRAY_VM_LIMIT - 100, bd.readMapStart());
Assertions.assertEquals(100, bd.mapNext());
ex = Assertions.assertThrows(UnsupportedOperationException.class, bd::mapNext);
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testMapMaxCustom(boolean useDirect) throws IOException {
try {
System.setProperty(SystemLimitException.MAX_COLLECTION_LENGTH_PROPERTY, Long.toString(128));
resetLimits();
Exception ex = Assertions.assertThrows(UnsupportedOperationException.class,
() -> newDecoder(useDirect, MAX_ARRAY_VM_LIMIT + 1).readMapStart());
Assertions.assertEquals(ERROR_VM_LIMIT_COLLECTION, ex.getMessage());
// Two OK reads followed by going over the custom limit.
Decoder bd = newDecoder(useDirect, 118, 10, 1);
Assertions.assertEquals(118, bd.readMapStart());
Assertions.assertEquals(10, bd.mapNext());
ex = Assertions.assertThrows(SystemLimitException.class, bd::mapNext);
Assertions.assertEquals("Collection length 129 exceeds maximum allowed", ex.getMessage());
// Two OK reads followed by going over the VM limit, where negative numbers are
// followed by the byte length of the items. For testing, the 999 values are
// read but ignored.
bd = newDecoder(useDirect, -118, 999, -10, 999, 1);
Assertions.assertEquals(118, bd.readMapStart());
Assertions.assertEquals(10, bd.mapNext());
ex = Assertions.assertThrows(SystemLimitException.class, bd::mapNext);
Assertions.assertEquals("Collection length 129 exceeds maximum allowed", ex.getMessage());
} finally {
System.clearProperty(SystemLimitException.MAX_COLLECTION_LENGTH_PROPERTY);
resetLimits();
}
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void longLengthEncoding(boolean useDirect) {
// Size equivalent to Integer.MAX_VALUE + 1
byte[] bad = new byte[] { (byte) -128, (byte) -128, (byte) -128, (byte) -128, (byte) 16 };
Decoder bd = this.newDecoder(bad, useDirect);
Assertions.assertThrows(UnsupportedOperationException.class, bd::readString);
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void intTooShort(boolean useDirect) {
byte[] badint = new byte[4];
Arrays.fill(badint, (byte) 0xff);
Assertions.assertThrows(EOFException.class, () -> newDecoder(badint, useDirect).readInt());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void longTooShort(boolean useDirect) {
byte[] badint = new byte[9];
Arrays.fill(badint, (byte) 0xff);
Assertions.assertThrows(EOFException.class, () -> newDecoder(badint, useDirect).readLong());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void floatTooShort(boolean useDirect) {
byte[] badint = new byte[3];
Arrays.fill(badint, (byte) 0xff);
Assertions.assertThrows(EOFException.class, () -> newDecoder(badint, useDirect).readInt());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void doubleTooShort(boolean useDirect) {
byte[] badint = new byte[7];
Arrays.fill(badint, (byte) 0xff);
Assertions.assertThrows(EOFException.class, () -> newDecoder(badint, useDirect).readLong());
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void skipping(boolean useDirect) throws IOException {
BinaryDecoder bd = newDecoder(data, useDirect);
skipGenerated(bd);
try {
Assertions.assertTrue(bd.isEnd());
} catch (UnsupportedOperationException e) {
// this is ok if its a DirectBinaryDecoder.
if (bd.getClass() != DirectBinaryDecoder.class) {
throw e;
}
}
bd = this.newDecoder(new ByteArrayInputStream(data), bd, useDirect);
skipGenerated(bd);
try {
Assertions.assertTrue(bd.isEnd());
} catch (UnsupportedOperationException e) {
// this is ok if its a DirectBinaryDecoder.
if (bd.getClass() != DirectBinaryDecoder.class) {
throw e;
}
}
}
private void skipGenerated(Decoder bd) throws IOException {
for (int i = 0; i < records.size(); i++) {
bd.readInt();
bd.skipBytes();
bd.skipFixed(1);
bd.skipString();
bd.skipFixed(4);
bd.skipFixed(8);
long leftover = bd.skipArray();
// booleans are one byte, array trailer is one byte
bd.skipFixed((int) leftover + 1);
bd.skipFixed(0);
bd.skipFixed(-8); // Should be a no-op; see AVRO-3635
bd.readLong();
}
EOFException eof = null;
try {
bd.skipFixed(4);
} catch (EOFException e) {
eof = e;
}
Assertions.assertNotNull(eof);
}
@ParameterizedTest
@ValueSource(booleans = { true, false })
void eof(boolean useDirect) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Encoder e = EncoderFactory.get().binaryEncoder(baos, null);
e.writeLong(0x10000000000000L);
e.flush();
Decoder d = newDecoder(new ByteArrayInputStream(baos.toByteArray()), useDirect);
Assertions.assertEquals(0x10000000000000L, d.readLong());
Assertions.assertThrows(EOFException.class, () -> d.readInt());
}
@Test
void testFloatPrecision() throws Exception {
String def = "{\"type\":\"record\",\"name\":\"X\",\"fields\":" + "[{\"type\":\"float\",\"name\":\"n\"}]}";
Schema schema = new Schema.Parser().parse(def);
DatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
float value = 33.33000183105469f;
GenericData.Record record = new GenericData.Record(schema);
record.put(0, value);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Encoder encoder = EncoderFactory.get().directBinaryEncoder(out, null);
DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
writer.write(record, encoder);
encoder.flush();
Decoder decoder = DecoderFactory.get().directBinaryDecoder(new ByteArrayInputStream(out.toByteArray()), null);
GenericRecord r = reader.read(null, decoder);
assertEquals(value + 0d, ((float) r.get("n")) + 0d);
}
}
| TestBinaryDecoder |
java | apache__kafka | jmh-benchmarks/src/main/java/org/apache/kafka/jmh/assignor/ClientSideAssignorBenchmark.java | {
"start": 2546,
"end": 3201
} | enum ____ {
RANGE(new RangeAssignor()),
COOPERATIVE_STICKY(new CooperativeStickyAssignor());
private final ConsumerPartitionAssignor assignor;
AssignorType(ConsumerPartitionAssignor assignor) {
this.assignor = assignor;
}
public ConsumerPartitionAssignor assignor() {
return assignor;
}
}
/**
* The subscription pattern followed by the members of the group.
*
* A subscription model is considered homogeneous if all the members of the group
* are subscribed to the same set of topics, it is heterogeneous otherwise.
*/
public | AssignorType |
java | elastic__elasticsearch | x-pack/plugin/downsample/src/main/java/org/elasticsearch/xpack/downsample/TimeseriesFieldTypeHelper.java | {
"start": 979,
"end": 3151
} | class ____ {
private final MapperService mapperService;
private final String timestampField;
private TimeseriesFieldTypeHelper(final MapperService mapperService, final String timestampField) {
this.mapperService = mapperService;
this.timestampField = timestampField;
}
public boolean isTimeSeriesLabel(final String field, final Map<String, ?> unused) {
final MappingLookup lookup = mapperService.mappingLookup();
final MappedFieldType fieldType = lookup.getFieldType(field);
return fieldType != null
&& (timestampField.equals(field) == false)
&& (fieldType.isAggregatable())
&& (fieldType.isDimension() == false)
&& (mapperService.isMetadataField(field) == false);
}
public boolean isTimeSeriesMetric(final String unused, final Map<String, ?> fieldMapping) {
final String metricType = (String) fieldMapping.get(TIME_SERIES_METRIC_PARAM);
return metricType != null
&& List.of(TimeSeriesParams.MetricType.values()).contains(TimeSeriesParams.MetricType.fromString(metricType));
}
public boolean isTimeSeriesDimension(final String unused, final Map<String, ?> fieldMapping) {
return Boolean.TRUE.equals(fieldMapping.get(TIME_SERIES_DIMENSION_PARAM)) && isPassthroughField(fieldMapping) == false;
}
public static boolean isPassthroughField(final Map<String, ?> fieldMapping) {
return PassThroughObjectMapper.CONTENT_TYPE.equals(fieldMapping.get(ContextMapping.FIELD_TYPE));
}
public List<String> extractFlattenedDimensions(final String field, final Map<String, ?> fieldMapping) {
var mapper = mapperService.mappingLookup().getMapper(field);
if (mapper instanceof FlattenedFieldMapper == false) {
return null;
}
Object dimensions = fieldMapping.get(FlattenedFieldMapper.TIME_SERIES_DIMENSIONS_ARRAY_PARAM);
if (dimensions instanceof List<?> actualList) {
return actualList.stream().map(field_in_flattened -> field + '.' + field_in_flattened).toList();
}
return null;
}
static | TimeseriesFieldTypeHelper |
java | apache__hadoop | hadoop-tools/hadoop-aliyun/src/main/java/org/apache/hadoop/fs/aliyun/oss/OSSListRequest.java | {
"start": 1030,
"end": 2616
} | class ____ {
/**
* Format for the toString() method: {@value}.
*/
private static final String DESCRIPTION
= "List %s:/%s delimiter=%s keys=%d";
private final ListObjectsRequest v1Request;
private final ListObjectsV2Request v2Request;
private OSSListRequest(ListObjectsRequest v1, ListObjectsV2Request v2) {
v1Request = v1;
v2Request = v2;
}
/**
* Restricted constructors to ensure v1 or v2, not both.
* @param request v1 request
* @return new list request container
*/
public static OSSListRequest v1(ListObjectsRequest request) {
return new OSSListRequest(request, null);
}
/**
* Restricted constructors to ensure v1 or v2, not both.
* @param request v2 request
* @return new list request container
*/
public static OSSListRequest v2(ListObjectsV2Request request) {
return new OSSListRequest(null, request);
}
/**
* Is this a v1 API request or v2?
* @return true if v1, false if v2
*/
public boolean isV1() {
return v1Request != null;
}
public ListObjectsRequest getV1() {
return v1Request;
}
public ListObjectsV2Request getV2() {
return v2Request;
}
@Override
public String toString() {
if (isV1()) {
return String.format(DESCRIPTION,
v1Request.getBucketName(), v1Request.getPrefix(),
v1Request.getDelimiter(), v1Request.getMaxKeys());
} else {
return String.format(DESCRIPTION,
v2Request.getBucketName(), v2Request.getPrefix(),
v2Request.getDelimiter(), v2Request.getMaxKeys());
}
}
} | OSSListRequest |
java | google__error-prone | core/src/test/java/com/google/errorprone/ErrorProneJavaCompilerTest.java | {
"start": 18222,
"end": 18739
} | class ____ {
String s = "old-value";
}
""");
CompilationResult result =
doCompile(
Collections.singleton(fileObject),
Arrays.asList(
"-XepPatchChecks:", "-XepPatchLocation:IN_PLACE", "-Xep:AssignmentUpdater:OFF"),
ImmutableList.of(AssignmentUpdater.class));
assertSucceeded(result);
assertThat(Files.readString(Path.of(fileObject.toUri())))
.isEqualTo(
"""
| StringConstantWrapper |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/legacy/Eye.java | {
"start": 220,
"end": 1041
} | class ____ {
private long id;
private String name;
private Jay jay;
private Set jays = new HashSet();
/**
* @return Returns the id.
*/
public long getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(long id) {
this.id = id;
}
/**
* @return Returns the jay.
*/
public Jay getJay() {
return jay;
}
/**
* @param jay The jay to set.
*/
public void setJay(Jay jay) {
this.jay = jay;
}
/**
* @return Returns the jays.
*/
public Set getJays() {
return jays;
}
/**
* @param jays The jays to set.
*/
public void setJays(Set jays) {
this.jays = jays;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
}
| Eye |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AsteriskEndpointBuilderFactory.java | {
"start": 16210,
"end": 16517
} | interface ____
extends
AdvancedAsteriskEndpointConsumerBuilder,
AdvancedAsteriskEndpointProducerBuilder {
default AsteriskEndpointBuilder basic() {
return (AsteriskEndpointBuilder) this;
}
}
public | AdvancedAsteriskEndpointBuilder |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/cluster/routing/allocation/FilterRoutingTests.java | {
"start": 2668,
"end": 22281
} | class ____ extends ESAllocationTestCase {
public void testClusterIncludeFiltersSingleAttribute() {
testClusterFilters(
Settings.builder().put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1,value2"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag1", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag1", "value4")))
);
}
public void testClusterIncludeFiltersMultipleAttributes() {
testClusterFilters(
Settings.builder()
.put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1")
.put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag2", "value2"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag2", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag2", "value4")))
);
}
public void testClusterIncludeFiltersOptionalAttribute() {
testClusterFilters(
Settings.builder().put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1,value2"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag1", "value2")))
.add(newNode("node3", attrMap()))
.add(newNode("node4", attrMap()))
);
}
public void testClusterIncludeFiltersWildcards() {
testClusterFilters(
Settings.builder()
.put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "*incl*")
.put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag2", "*incl*"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "do_include_this")))
.add(newNode("node2", attrMap("tag2", "also_include_this")))
.add(newNode("node3", attrMap("tag1", "exclude_this")))
.add(newNode("node4", attrMap("tag2", "also_exclude_this")))
);
}
public void testClusterExcludeFiltersSingleAttribute() {
testClusterFilters(
Settings.builder().put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value3,value4"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag1", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag1", "value4")))
);
}
public void testClusterExcludeFiltersMultipleAttributes() {
testClusterFilters(
Settings.builder()
.put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value3")
.put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag2", "value4"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag2", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag2", "value4")))
);
}
public void testClusterExcludeFiltersOptionalAttribute() {
testClusterFilters(
Settings.builder().put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value3,value4"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap()))
.add(newNode("node2", attrMap()))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag1", "value4")))
);
}
public void testClusterExcludeFiltersWildcards() {
testClusterFilters(
Settings.builder()
.put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "*excl*")
.put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag2", "*excl*"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "do_include_this")))
.add(newNode("node2", attrMap("tag2", "also_include_this")))
.add(newNode("node3", attrMap("tag1", "exclude_this")))
.add(newNode("node4", attrMap("tag2", "also_exclude_this")))
);
}
public void testClusterIncludeAndExcludeFilters() {
testClusterFilters(
Settings.builder()
.put(CLUSTER_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "*incl*")
.put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag2", "*excl*"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "do_include_this")))
.add(newNode("node2", attrMap("tag1", "also_include_this", "tag2", "ok_by_tag2")))
.add(newNode("node3", attrMap("tag1", "included_by_tag1", "tag2", "excluded_by_tag2")))
.add(newNode("node4", attrMap("tag1", "excluded_by_tag1", "tag2", "included_by_tag2")))
);
}
public void testClusterRequireFilters() {
testClusterFilters(
Settings.builder()
.put(CLUSTER_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "tag1", "req1")
.put(CLUSTER_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "tag2", "req2"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "req1", "tag2", "req2")))
.add(newNode("node2", attrMap("tag1", "req1", "tag2", "req2")))
.add(newNode("node3", attrMap("tag1", "req1")))
.add(newNode("node4", attrMap("tag1", "other", "tag2", "req2")))
);
}
private static Map<String, String> attrMap(String... keysValues) {
if (keysValues.length == 0) {
return emptyMap();
}
if (keysValues.length == 2) {
return singletonMap(keysValues[0], keysValues[1]);
}
Map<String, String> result = new HashMap<>();
for (int i = 0; i < keysValues.length; i += 2) {
result.put(keysValues[i], keysValues[i + 1]);
}
return result;
}
/**
* A test that creates a 2p1r index and which expects the given allocation service's settings only to allocate the shards of this index
* to `node1` and `node2`.
*/
private void testClusterFilters(Settings.Builder allocationServiceSettings, DiscoveryNodes.Builder nodes) {
final AllocationService strategy = createAllocationService(allocationServiceSettings.build());
logger.info("Building initial routing table");
final Metadata metadata = Metadata.builder()
.put(IndexMetadata.builder("test").settings(settings(IndexVersion.current())).numberOfShards(2).numberOfReplicas(1))
.build();
final RoutingTable initialRoutingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)
.addAsNew(metadata.getProject().index("test"))
.build();
ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT)
.metadata(metadata)
.routingTable(initialRoutingTable)
.nodes(nodes)
.build();
logger.info("--> rerouting");
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
assertThat(shardsWithState(clusterState.getRoutingNodes(), INITIALIZING).size(), equalTo(2));
logger.info("--> start the shards (primaries)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
logger.info("--> start the shards (replicas)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
logger.info("--> make sure shards are only allocated on tag1 with value1 and value2");
final List<ShardRouting> startedShards = shardsWithState(clusterState.getRoutingNodes(), ShardRoutingState.STARTED);
assertThat(startedShards.size(), equalTo(4));
for (ShardRouting startedShard : startedShards) {
assertThat(startedShard.currentNodeId(), Matchers.anyOf(equalTo("node1"), equalTo("node2")));
}
}
public void testIndexIncludeFilters() {
testIndexFilters(
Settings.builder().put(INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1,value2"),
Settings.builder().put(INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1,value4"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag1", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag1", "value4")))
.add(newNode("node5", attrMap()))
);
}
public void testIndexExcludeFilters() {
testIndexFilters(
Settings.builder().put(INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value3,value4"),
Settings.builder().put(INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value2,value3"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap()))
.add(newNode("node2", attrMap("tag1", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag1", "value4")))
);
}
public void testIndexIncludeThenExcludeFilters() {
testIndexFilters(
Settings.builder().put(INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1,value2"),
Settings.builder()
.put(INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value2,value3")
.putNull(INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap("tag1", "value2")))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap()))
);
}
public void testIndexExcludeThenIncludeFilters() {
testIndexFilters(
Settings.builder().put(INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value3,value4"),
Settings.builder()
.put(INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "tag1", "value1,value4")
.putNull(INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1")))
.add(newNode("node2", attrMap()))
.add(newNode("node3", attrMap("tag1", "value3")))
.add(newNode("node4", attrMap("tag1", "value4")))
);
}
public void testIndexRequireFilters() {
testIndexFilters(
Settings.builder()
.put(INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "tag1", "value1")
.put(INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "tag2", "value2"),
Settings.builder()
.putNull(INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "tag2")
.put(INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "tag3", "value3"),
DiscoveryNodes.builder()
.add(newNode("node1", attrMap("tag1", "value1", "tag2", "value2", "tag3", "value3")))
.add(newNode("node2", attrMap("tag1", "value1", "tag2", "value2", "tag3", "other")))
.add(newNode("node3", attrMap("tag1", "other", "tag2", "value2", "tag3", "other")))
.add(newNode("node4", attrMap("tag1", "value1", "tag2", "other", "tag3", "value3")))
.add(newNode("node5", attrMap("tag2", "value2", "tag3", "value3")))
.add(newNode("node6", attrMap()))
);
}
/**
* A test that creates a 2p1r index and expects the given index allocation settings only to allocate the shards to `node1` and `node2`;
* on updating the index allocation settings the shards should be relocated to nodes `node1` and `node4`.
*/
private void testIndexFilters(Settings.Builder initialIndexSettings, Settings.Builder updatedIndexSettings, Builder nodesBuilder) {
AllocationService strategy = createAllocationService(Settings.builder().build());
logger.info("Building initial routing table");
final Metadata initialMetadata = Metadata.builder()
.put(IndexMetadata.builder("test").settings(indexSettings(IndexVersion.current(), 2, 1).put(initialIndexSettings.build())))
.build();
final RoutingTable initialRoutingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)
.addAsNew(initialMetadata.getProject().index("test"))
.build();
ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT)
.metadata(initialMetadata)
.routingTable(initialRoutingTable)
.nodes(nodesBuilder)
.build();
logger.info("--> rerouting");
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
assertThat(shardsWithState(clusterState.getRoutingNodes(), INITIALIZING).size(), equalTo(2));
logger.info("--> start the shards (primaries)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
logger.info("--> start the shards (replicas)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
logger.info("--> make sure shards are only allocated on tag1 with value1 and value2");
List<ShardRouting> startedShards = shardsWithState(clusterState.getRoutingNodes(), ShardRoutingState.STARTED);
assertThat(startedShards.size(), equalTo(4));
for (ShardRouting startedShard : startedShards) {
assertThat(startedShard.currentNodeId(), Matchers.anyOf(equalTo("node1"), equalTo("node2")));
}
logger.info("--> switch between value2 and value4, shards should be relocating");
final IndexMetadata existingMetadata = clusterState.metadata().getProject().index("test");
final Metadata updatedMetadata = Metadata.builder()
.put(
IndexMetadata.builder(existingMetadata)
.settings(Settings.builder().put(existingMetadata.getSettings()).put(updatedIndexSettings.build()).build())
)
.build();
clusterState = ClusterState.builder(clusterState).metadata(updatedMetadata).build();
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
assertThat(shardsWithState(clusterState.getRoutingNodes(), ShardRoutingState.STARTED).size(), equalTo(2));
assertThat(shardsWithState(clusterState.getRoutingNodes(), ShardRoutingState.RELOCATING).size(), equalTo(2));
assertThat(shardsWithState(clusterState.getRoutingNodes(), ShardRoutingState.INITIALIZING).size(), equalTo(2));
logger.info("--> finish relocation");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
startedShards = shardsWithState(clusterState.getRoutingNodes(), ShardRoutingState.STARTED);
assertThat(startedShards.size(), equalTo(4));
for (ShardRouting startedShard : startedShards) {
assertThat(startedShard.currentNodeId(), Matchers.anyOf(equalTo("node1"), equalTo("node4")));
}
}
public void testConcurrentRecoveriesAfterShardsCannotRemainOnNode() {
AllocationService strategy = createAllocationService(Settings.builder().build());
logger.info("Building initial routing table");
Metadata metadata = Metadata.builder()
.put(IndexMetadata.builder("test1").settings(settings(IndexVersion.current())).numberOfShards(2).numberOfReplicas(0))
.put(IndexMetadata.builder("test2").settings(settings(IndexVersion.current())).numberOfShards(2).numberOfReplicas(0))
.build();
RoutingTable initialRoutingTable = RoutingTable.builder(TestShardRoutingRoleStrategies.DEFAULT_ROLE_ONLY)
.addAsNew(metadata.getProject().index("test1"))
.addAsNew(metadata.getProject().index("test2"))
.build();
ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(metadata).routingTable(initialRoutingTable).build();
logger.info("--> adding two nodes and performing rerouting");
DiscoveryNode node1 = newNode("node1", singletonMap("tag1", "value1"));
DiscoveryNode node2 = newNode("node2", singletonMap("tag1", "value2"));
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().add(node1).add(node2)).build();
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
assertThat(clusterState.getRoutingNodes().node(node1.getId()).numberOfShardsWithState(INITIALIZING), equalTo(2));
assertThat(clusterState.getRoutingNodes().node(node2.getId()).numberOfShardsWithState(INITIALIZING), equalTo(2));
logger.info("--> start the shards (only primaries)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
logger.info("--> make sure all shards are started");
assertThat(shardsWithState(clusterState.getRoutingNodes(), STARTED).size(), equalTo(4));
logger.info("--> disable allocation for node1 and reroute");
strategy = createAllocationService(
Settings.builder()
.put(CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING.getKey(), "1")
.put(CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "tag1", "value1")
.build()
);
logger.info("--> move shards from node1 to node2");
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
logger.info("--> check that concurrent recoveries only allows 1 shard to move");
assertThat(clusterState.getRoutingNodes().node(node1.getId()).numberOfShardsWithState(STARTED), equalTo(1));
assertThat(clusterState.getRoutingNodes().node(node2.getId()).numberOfShardsWithState(INITIALIZING), equalTo(1));
assertThat(clusterState.getRoutingNodes().node(node2.getId()).numberOfShardsWithState(STARTED), equalTo(2));
logger.info("--> start the shards (only primaries)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
logger.info("--> move second shard from node1 to node2");
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
assertThat(clusterState.getRoutingNodes().node(node2.getId()).numberOfShardsWithState(INITIALIZING), equalTo(1));
assertThat(clusterState.getRoutingNodes().node(node2.getId()).numberOfShardsWithState(STARTED), equalTo(3));
logger.info("--> start the shards (only primaries)");
clusterState = startInitializingShardsAndReroute(strategy, clusterState);
clusterState = strategy.reroute(clusterState, "reroute", ActionListener.noop());
assertThat(clusterState.getRoutingNodes().node(node2.getId()).numberOfShardsWithState(STARTED), equalTo(4));
}
}
| FilterRoutingTests |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/runtime/src/main/java/io/quarkus/rest/client/reactive/ClientFormParam.java | {
"start": 2274,
"end": 2983
} | interface ____ the annotation contains a <code>@ClientFormParam</code>
* annotation with a
* <code>value</code> attribute that references a method that does not exist, or contains an invalid signature.
* <p>
* The <code>required</code> attribute will determine what action the implementation should take if the method specified in the
* <code>value</code>
* attribute throws an exception. If the attribute is true (default), then the implementation will abort the request and will
* throw the exception
* back to the caller. If the <code>required</code> attribute is set to false, then the implementation will not send this
* form parameter if the method throws an exception.
* <p>
* Note that if an | if |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/io/ResourceTests.java | {
"start": 20530,
"end": 21576
} | class ____ extends Dispatcher {
boolean withHeadSupport;
public ResourceDispatcher(boolean withHeadSupport) {
this.withHeadSupport = withHeadSupport;
}
@Override
public MockResponse dispatch(RecordedRequest request) {
if (request.getTarget().equals("/resource")) {
return switch (request.getMethod()) {
case "HEAD" -> (this.withHeadSupport ?
new MockResponse.Builder()
.addHeader("Content-Type", "text/plain")
.addHeader("Content-Length", "6")
.addHeader("Last-Modified", LAST_MODIFIED)
.build() :
new MockResponse.Builder().code(405).build());
case "GET" -> new MockResponse.Builder()
.addHeader("Content-Type", "text/plain")
.addHeader("Content-Length", "6")
.addHeader("Last-Modified", LAST_MODIFIED)
.body("Spring")
.build();
default -> new MockResponse.Builder().code(404).build();
};
}
return new MockResponse.Builder().code(404).build();
}
}
}
@Nested
| ResourceDispatcher |
java | micronaut-projects__micronaut-core | router/src/main/java/io/micronaut/web/router/uri/PercentEncoder.java | {
"start": 753,
"end": 863
} | class ____ different URL percent encoding sets.
*
* @since 4.9.0
* @author Jonas Konrad
*/
@Internal
final | for |
java | elastic__elasticsearch | distribution/tools/plugin-cli/src/main/java/org/elasticsearch/plugins/cli/RemovePluginAction.java | {
"start": 1325,
"end": 10166
} | class ____ {
// exit codes for remove
/** A plugin cannot be removed because it is extended by another plugin. */
static final int PLUGIN_STILL_USED = 11;
private final Terminal terminal;
private final Environment env;
private boolean purge;
/**
* Creates a new action.
*
* @param terminal the terminal to use for input/output
* @param env the environment for the local node
* @param purge if true, plugin configuration files will be removed but otherwise preserved
*/
public RemovePluginAction(Terminal terminal, Environment env, boolean purge) {
this.terminal = terminal;
this.env = env;
this.purge = purge;
}
public void setPurge(boolean purge) {
this.purge = purge;
}
/**
* Remove the plugin specified by {@code pluginName}.
*
* @param plugins the IDs of the plugins to remove
* @throws IOException if any I/O exception occurs while performing a file operation
* @throws UserException if plugins is null or empty
* @throws UserException if plugin directory does not exist
* @throws UserException if the plugin bin directory is not a directory
*/
public void execute(List<InstallablePlugin> plugins) throws IOException, UserException {
if (plugins == null || plugins.isEmpty()) {
throw new UserException(ExitCodes.USAGE, "At least one plugin ID is required");
}
ensurePluginsNotUsedByOtherPlugins(plugins);
for (InstallablePlugin plugin : plugins) {
checkCanRemove(plugin);
}
for (InstallablePlugin plugin : plugins) {
removePlugin(plugin);
}
}
private void ensurePluginsNotUsedByOtherPlugins(List<InstallablePlugin> plugins) throws IOException, UserException {
// First make sure nothing extends this plugin
final Map<String, List<String>> usedBy = new HashMap<>();
// We build a new map where the keys are plugins that extend plugins
// we want to remove and the values are the plugins we can't remove
// because of this dependency
Map<String, List<String>> pluginDependencyMap = PluginsUtils.getDependencyMapView(env.pluginsDir());
for (Map.Entry<String, List<String>> entry : pluginDependencyMap.entrySet()) {
for (String extendedPlugin : entry.getValue()) {
for (InstallablePlugin plugin : plugins) {
String pluginId = plugin.getId();
if (extendedPlugin.equals(pluginId)) {
usedBy.computeIfAbsent(entry.getKey(), (_key -> new ArrayList<>())).add(pluginId);
}
}
}
}
if (usedBy.isEmpty()) {
return;
}
final StringJoiner message = new StringJoiner("\n");
message.add("Cannot remove plugins because the following are extended by other plugins:");
usedBy.forEach((key, value) -> {
String s = "\t" + key + " used by " + value;
message.add(s);
});
throw new UserException(PLUGIN_STILL_USED, message.toString());
}
private void checkCanRemove(InstallablePlugin plugin) throws UserException {
String pluginId = plugin.getId();
final Path pluginDir = env.pluginsDir().resolve(pluginId);
final Path pluginConfigDir = env.configDir().resolve(pluginId);
final Path removing = env.pluginsDir().resolve(".removing-" + pluginId);
/*
* If the plugin does not exist and the plugin config does not exist, fail to the user that the plugin is not found, unless there's
* a marker file left from a previously failed attempt in which case we proceed to clean up the marker file. Or, if the plugin does
* not exist, the plugin config does, and we are not purging, again fail to the user that the plugin is not found.
*/
if ((Files.exists(pluginDir) == false && Files.exists(pluginConfigDir) == false && Files.exists(removing) == false)
|| (Files.exists(pluginDir) == false && Files.exists(pluginConfigDir) && this.purge == false)) {
if (PLUGINS_CONVERTED_TO_MODULES.contains(pluginId)) {
terminal.errorPrintln(
"plugin [" + pluginId + "] is no longer a plugin but instead a module packaged with this distribution of Elasticsearch"
);
} else {
final String message = String.format(
Locale.ROOT,
"plugin [%s] not found; run 'elasticsearch-plugin list' to get list of installed plugins",
pluginId
);
throw new UserException(ExitCodes.CONFIG, message);
}
}
final Path pluginBinDir = env.binDir().resolve(pluginId);
if (Files.exists(pluginBinDir)) {
if (Files.isDirectory(pluginBinDir) == false) {
throw new UserException(ExitCodes.IO_ERROR, "bin dir for " + pluginId + " is not a directory");
}
}
}
private void removePlugin(InstallablePlugin plugin) throws IOException {
final String pluginId = plugin.getId();
final Path pluginDir = env.pluginsDir().resolve(pluginId);
final Path pluginConfigDir = env.configDir().resolve(pluginId);
final Path removing = env.pluginsDir().resolve(".removing-" + pluginId);
terminal.println("-> removing [" + pluginId + "]...");
final List<Path> pluginPaths = new ArrayList<>();
/*
* Add the contents of the plugin directory before creating the marker file and adding it to the list of paths to be deleted so
* that the marker file is the last file to be deleted.
*/
if (Files.exists(pluginDir)) {
try (Stream<Path> paths = Files.list(pluginDir)) {
pluginPaths.addAll(paths.toList());
}
terminal.println(VERBOSE, "removing [" + pluginDir + "]");
}
final Path pluginBinDir = env.binDir().resolve(pluginId);
if (Files.exists(pluginBinDir)) {
try (Stream<Path> paths = Files.list(pluginBinDir)) {
pluginPaths.addAll(paths.toList());
}
pluginPaths.add(pluginBinDir);
terminal.println(VERBOSE, "removing [" + pluginBinDir + "]");
}
if (Files.exists(pluginConfigDir)) {
if (this.purge) {
try (Stream<Path> paths = Files.list(pluginConfigDir)) {
pluginPaths.addAll(paths.toList());
}
pluginPaths.add(pluginConfigDir);
terminal.println(VERBOSE, "removing [" + pluginConfigDir + "]");
} else {
/*
* By default we preserve the config files in case the user is upgrading the plugin, but we print a message so the user
* knows in case they want to remove manually.
*/
final String message = String.format(
Locale.ROOT,
"-> preserving plugin config files [%s] in case of upgrade; use --purge if not needed",
pluginConfigDir
);
terminal.println(message);
}
}
/*
* We are going to create a marker file in the plugin directory that indicates that this plugin is a state of removal. If the
* removal fails, the existence of this marker file indicates that the plugin is in a garbage state. We check for existence of this
* marker file during startup so that we do not startup with plugins in such a garbage state. Up to this point, we have not done
* anything destructive, so we create the marker file as the last action before executing destructive operations. We place this
* marker file in the root plugin directory (not the specific plugin directory) so that we do not have to create the specific plugin
* directory if it does not exist (we are purging configuration files).
*/
try {
Files.createFile(removing);
} catch (final FileAlreadyExistsException e) {
/*
* We need to suppress the marker file already existing as we could be in this state if a previous removal attempt failed and
* the user is attempting to remove the plugin again.
*/
terminal.println(VERBOSE, "marker file [" + removing + "] already exists");
}
// add the plugin directory
pluginPaths.add(pluginDir);
// finally, add the marker file
pluginPaths.add(removing);
IOUtils.rm(pluginPaths.toArray(new Path[0]));
}
}
| RemovePluginAction |
java | elastic__elasticsearch | x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/history/ILMHistoryStoreTests.java | {
"start": 14132,
"end": 15161
} | class ____ extends NoOpClient {
private TriFunction<ActionType<?>, ActionRequest, ActionListener<?>, ActionResponse> verifier = (a, r, l) -> {
fail("verifier not set");
return null;
};
VerifyingClient(ThreadPool threadPool) {
super(threadPool);
}
@Override
@SuppressWarnings("unchecked")
protected <Request extends ActionRequest, Response extends ActionResponse> void doExecute(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
try {
listener.onResponse((Response) verifier.apply(action, request, listener));
} catch (Exception e) {
listener.onFailure(e);
}
}
VerifyingClient setVerifier(TriFunction<ActionType<?>, ActionRequest, ActionListener<?>, ActionResponse> verifier) {
this.verifier = verifier;
return this;
}
}
}
| VerifyingClient |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/join/JoinAndFetchWithCriteriaSelectionQueryTest.java | {
"start": 8535,
"end": 9504
} | class ____ {
@Id
private Long id;
private String title;
@OneToMany
private List<Author> authors = new ArrayList<>();
public Book() {
}
public Book(Long id, String title) {
this.id = id;
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
@Override
public boolean equals(Object object) {
if ( object == null || getClass() != object.getClass() ) {
return false;
}
Book book = (Book) object;
return Objects.equals( title, book.title );
}
@Override
public int hashCode() {
return Objects.hashCode( title );
}
@Override
public String toString() {
return id + ":" + title;
}
}
}
| Book |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/MembershipStats.java | {
"start": 1204,
"end": 5238
} | class ____ extends BaseRecord {
public static MembershipStats newInstance() throws IOException {
MembershipStats record =
StateStoreSerializer.newRecord(MembershipStats.class);
record.init();
return record;
}
public abstract void setTotalSpace(long space);
public abstract long getTotalSpace();
public abstract void setAvailableSpace(long space);
public abstract long getAvailableSpace();
public abstract void setProvidedSpace(long capacity);
public abstract long getProvidedSpace();
public abstract void setNumOfFiles(long files);
public abstract long getNumOfFiles();
public abstract void setNumOfBlocks(long blocks);
public abstract long getNumOfBlocks();
public abstract void setNumOfBlocksMissing(long blocks);
public abstract long getNumOfBlocksMissing();
public abstract void setNumOfBlocksPendingReplication(long blocks);
public abstract long getNumOfBlocksPendingReplication();
public abstract void setNumOfBlocksUnderReplicated(long blocks);
public abstract long getNumOfBlocksUnderReplicated();
public abstract void setNumOfBlocksPendingDeletion(long blocks);
public abstract long getNumOfBlocksPendingDeletion();
public abstract void setNumOfActiveDatanodes(int nodes);
public abstract int getNumOfActiveDatanodes();
public abstract void setNumOfDeadDatanodes(int nodes);
public abstract int getNumOfDeadDatanodes();
public abstract void setNumOfStaleDatanodes(int nodes);
public abstract int getNumOfStaleDatanodes();
public abstract void setNumOfDecommissioningDatanodes(int nodes);
public abstract int getNumOfDecommissioningDatanodes();
public abstract void setNumOfDecomActiveDatanodes(int nodes);
public abstract int getNumOfDecomActiveDatanodes();
public abstract void setNumOfDecomDeadDatanodes(int nodes);
public abstract int getNumOfDecomDeadDatanodes();
public abstract void setNumOfInMaintenanceLiveDataNodes(int nodes);
public abstract int getNumOfInMaintenanceLiveDataNodes();
public abstract void setNumOfInMaintenanceDeadDataNodes(int nodes);
public abstract int getNumOfInMaintenanceDeadDataNodes();
public abstract void setNumOfEnteringMaintenanceDataNodes(int nodes);
public abstract int getNumOfEnteringMaintenanceDataNodes();
public abstract void setCorruptFilesCount(int num);
public abstract int getCorruptFilesCount();
public abstract void setScheduledReplicationBlocks(long blocks);
public abstract long getScheduledReplicationBlocks();
public abstract void setNumberOfMissingBlocksWithReplicationFactorOne(
long blocks);
public abstract long getNumberOfMissingBlocksWithReplicationFactorOne();
public abstract void setNumberOfBadlyDistributedBlocks(
long blocks);
public abstract long getNumberOfBadlyDistributedBlocks();
public abstract void setHighestPriorityLowRedundancyReplicatedBlocks(
long blocks);
public abstract long getHighestPriorityLowRedundancyReplicatedBlocks();
public abstract void setHighestPriorityLowRedundancyECBlocks(
long blocks);
public abstract long getHighestPriorityLowRedundancyECBlocks();
public abstract void setPendingSPSPaths(int pendingSPSPaths);
public abstract int getPendingSPSPaths();
@Override
public SortedMap<String, String> getPrimaryKeys() {
// This record is not stored directly, no key needed
SortedMap<String, String> map = new TreeMap<String, String>();
return map;
}
@Override
public long getExpirationMs() {
// This record is not stored directly, no expiration needed
return -1;
}
@Override
public void setDateModified(long time) {
// We don't store this record directly
}
@Override
public long getDateModified() {
// We don't store this record directly
return 0;
}
@Override
public void setDateCreated(long time) {
// We don't store this record directly
}
@Override
public long getDateCreated() {
// We don't store this record directly
return 0;
}
}
| MembershipStats |
java | google__error-prone | core/src/test/java/com/google/errorprone/matchers/MatchersTest.java | {
"start": 19614,
"end": 20129
} | class ____ extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (Matchers.methodInvocation(
MethodMatchers.anyMethod(),
ChildMultiMatcher.MatchType.AT_LEAST_ONE,
Matchers.booleanConstant(true))
.matches(tree, state)) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}
}
| BooleanConstantTrueChecker |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesPodsEndpointBuilderFactory.java | {
"start": 1612,
"end": 16013
} | interface ____
extends
EndpointConsumerBuilder {
default AdvancedKubernetesPodsEndpointConsumerBuilder advanced() {
return (AdvancedKubernetesPodsEndpointConsumerBuilder) this;
}
/**
* The Kubernetes API Version to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param apiVersion the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder apiVersion(String apiVersion) {
doSetProperty("apiVersion", apiVersion);
return this;
}
/**
* The dns domain, used for ServiceCall EIP.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param dnsDomain the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder dnsDomain(String dnsDomain) {
doSetProperty("dnsDomain", dnsDomain);
return this;
}
/**
* Default KubernetesClient to use if provided.
*
* The option is a:
* <code>io.fabric8.kubernetes.client.KubernetesClient</code> type.
*
* Group: common
*
* @param kubernetesClient the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder kubernetesClient(io.fabric8.kubernetes.client.KubernetesClient kubernetesClient) {
doSetProperty("kubernetesClient", kubernetesClient);
return this;
}
/**
* Default KubernetesClient to use if provided.
*
* The option will be converted to a
* <code>io.fabric8.kubernetes.client.KubernetesClient</code> type.
*
* Group: common
*
* @param kubernetesClient the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder kubernetesClient(String kubernetesClient) {
doSetProperty("kubernetesClient", kubernetesClient);
return this;
}
/**
* The namespace.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param namespace the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder namespace(String namespace) {
doSetProperty("namespace", namespace);
return this;
}
/**
* The port name, used for ServiceCall EIP.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param portName the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder portName(String portName) {
doSetProperty("portName", portName);
return this;
}
/**
* The port protocol, used for ServiceCall EIP.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: tcp
* Group: common
*
* @param portProtocol the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder portProtocol(String portProtocol) {
doSetProperty("portProtocol", portProtocol);
return this;
}
/**
* The Consumer CRD Resource Group we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdGroup the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder crdGroup(String crdGroup) {
doSetProperty("crdGroup", crdGroup);
return this;
}
/**
* The Consumer CRD Resource name we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdName the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder crdName(String crdName) {
doSetProperty("crdName", crdName);
return this;
}
/**
* The Consumer CRD Resource Plural we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdPlural the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder crdPlural(String crdPlural) {
doSetProperty("crdPlural", crdPlural);
return this;
}
/**
* The Consumer CRD Resource Scope we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdScope the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder crdScope(String crdScope) {
doSetProperty("crdScope", crdScope);
return this;
}
/**
* The Consumer CRD Resource Version we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param crdVersion the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder crdVersion(String crdVersion) {
doSetProperty("crdVersion", crdVersion);
return this;
}
/**
* The Consumer Label key when watching at some resources.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param labelKey the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder labelKey(String labelKey) {
doSetProperty("labelKey", labelKey);
return this;
}
/**
* The Consumer Label value when watching at some resources.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param labelValue the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder labelValue(String labelValue) {
doSetProperty("labelValue", labelValue);
return this;
}
/**
* The Consumer pool size.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param poolSize the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder poolSize(int poolSize) {
doSetProperty("poolSize", poolSize);
return this;
}
/**
* The Consumer pool size.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param poolSize the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder poolSize(String poolSize) {
doSetProperty("poolSize", poolSize);
return this;
}
/**
* The Consumer Resource Name we would like to watch.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param resourceName the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder resourceName(String resourceName) {
doSetProperty("resourceName", resourceName);
return this;
}
/**
* The CA Cert Data.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param caCertData the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder caCertData(String caCertData) {
doSetProperty("caCertData", caCertData);
return this;
}
/**
* The CA Cert File.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param caCertFile the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder caCertFile(String caCertFile) {
doSetProperty("caCertFile", caCertFile);
return this;
}
/**
* The Client Cert Data.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientCertData the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder clientCertData(String clientCertData) {
doSetProperty("clientCertData", clientCertData);
return this;
}
/**
* The Client Cert File.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientCertFile the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder clientCertFile(String clientCertFile) {
doSetProperty("clientCertFile", clientCertFile);
return this;
}
/**
* The Key Algorithm used by the client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyAlgo the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder clientKeyAlgo(String clientKeyAlgo) {
doSetProperty("clientKeyAlgo", clientKeyAlgo);
return this;
}
/**
* The Client Key data.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyData the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder clientKeyData(String clientKeyData) {
doSetProperty("clientKeyData", clientKeyData);
return this;
}
/**
* The Client Key file.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyFile the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder clientKeyFile(String clientKeyFile) {
doSetProperty("clientKeyFile", clientKeyFile);
return this;
}
/**
* The Client Key Passphrase.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientKeyPassphrase the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder clientKeyPassphrase(String clientKeyPassphrase) {
doSetProperty("clientKeyPassphrase", clientKeyPassphrase);
return this;
}
/**
* The Auth Token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauthToken the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder oauthToken(String oauthToken) {
doSetProperty("oauthToken", oauthToken);
return this;
}
/**
* Password to connect to Kubernetes.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* Define if the certs we used are trusted anyway or not.
*
* The option is a: <code>java.lang.Boolean</code> type.
*
* Default: false
* Group: security
*
* @param trustCerts the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder trustCerts(Boolean trustCerts) {
doSetProperty("trustCerts", trustCerts);
return this;
}
/**
* Define if the certs we used are trusted anyway or not.
*
* The option will be converted to a <code>java.lang.Boolean</code>
* type.
*
* Default: false
* Group: security
*
* @param trustCerts the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder trustCerts(String trustCerts) {
doSetProperty("trustCerts", trustCerts);
return this;
}
/**
* Username to connect to Kubernetes.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default KubernetesPodsEndpointConsumerBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the Kubernetes Pods component.
*/
public | KubernetesPodsEndpointConsumerBuilder |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/plain/SortedNumericIndexFieldData.java | {
"start": 6648,
"end": 6886
} | class ____ can be configured to load nanosecond field data either in nanosecond resolution retaining the original
* values or in millisecond resolution converting the nanosecond values to milliseconds
*/
public static final | that |
java | quarkusio__quarkus | extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/config/ReactiveMessagingConfigGroup.java | {
"start": 219,
"end": 483
} | interface ____ extends MicrometerConfig.CapabilityEnabled {
/**
* Kafka metrics support.
* <p>
* Support for Reactive Messaging metrics will be enabled if Micrometer support is enabled,
* MessageObservationCollector | ReactiveMessagingConfigGroup |
java | junit-team__junit5 | junit-vintage-engine/src/test/java/org/junit/vintage/engine/support/UniqueIdStringifierTests.java | {
"start": 2258,
"end": 2599
} | class ____ implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Serial
Object writeReplace() throws ObjectStreamException {
throw new InvalidObjectException("failed on purpose");
}
@Override
public String toString() {
return "value from toString()";
}
}
}
| ClassWithErroneousSerialization |
java | google__dagger | javatests/dagger/internal/codegen/DependencyCycleValidationTest.java | {
"start": 1748,
"end": 1851
} | class ____ {",
" @Inject A(C cParam) {}",
" }",
"",
" static | A |
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/TestRLESparseResourceAllocation.java | {
"start": 2204,
"end": 23633
} | class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(TestRLESparseResourceAllocation.class);
@Test
public void testMergeAdd() throws PlanningException {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResourceAllocation rleB =
new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.add, 18, 45);
System.out.println(out);
long[] time = { 18, 20, 22, 30, 33, 40, 43, 45 };
int[] alloc = { 10, 15, 20, 25, 30, 40, 30 };
validate(out, time, alloc);
}
@Test
public void testMergeMin() throws PlanningException {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResourceAllocation rleB =
new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.min, 0, 60);
System.out.println(out);
long[] time = { 10, 22, 33, 40, 43, 50, 60 };
int[] alloc = { 5, 10, 15, 20, 10, 0 };
validate(out, time, alloc);
}
@Test
public void testMergeMax() throws PlanningException {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResourceAllocation rleB =
new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.max, 0, 60);
System.out.println(out);
long[] time = { 10, 20, 30, 40, 50, 60 };
int[] alloc = { 5, 10, 15, 20, 10 };
validate(out, time, alloc);
}
@Test
public void testMergeSubtract() throws PlanningException {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResourceAllocation rleB =
new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.subtract, 0, 60);
System.out.println(out);
long[] time = { 10, 11, 20, 22, 30, 33, 43, 50, 60 };
int[] alloc = { 5, 0, 5, 0, 5, 0, 10, -10 };
validate(out, time, alloc);
}
@Test
public void testMergesubtractTestNonNegative() throws PlanningException {
// starting with default array example
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
setupArrays(a, b);
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResourceAllocation rleB =
new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
try {
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.subtractTestNonNegative, 0, 60);
fail();
} catch (PlanningException pe) {
// Expected!
}
// NOTE a is empty!! so the subtraction is implicitly considered negative
// and the test should fail
a = new TreeMap<>();
b = new TreeMap<>();
b.put(11L, Resource.newInstance(5, 6));
rleA = new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
rleB = new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
try {
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.subtractTestNonNegative, 0, 60);
fail();
} catch (PlanningException pe) {
// Expected!
}
// Testing that the subtractTestNonNegative detects problems even if only
// one
// of the resource dimensions is "<0"
a.put(10L, Resource.newInstance(10, 5));
b.put(11L, Resource.newInstance(5, 6));
rleA = new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
rleB = new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
try {
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.subtractTestNonNegative, 0, 60);
fail();
} catch (PlanningException pe) {
// Expected!
}
// try with reverse setting
a.put(10L, Resource.newInstance(5, 10));
b.put(11L, Resource.newInstance(6, 5));
rleA = new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
rleB = new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
try {
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.subtractTestNonNegative, 0, 60);
fail();
} catch (PlanningException pe) {
// Expected!
}
// trying a case that should work
a.put(10L, Resource.newInstance(10, 6));
b.put(11L, Resource.newInstance(5, 6));
rleA = new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
rleB = new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.subtractTestNonNegative, 0, 60);
}
@Test
@Disabled
public void testMergeSpeed() throws PlanningException {
for (int j = 0; j < 100; j++) {
TreeMap<Long, Resource> a = new TreeMap<>();
TreeMap<Long, Resource> b = new TreeMap<>();
Random rand = new Random();
long startA = 0;
long startB = 0;
for (int i = 0; i < 1000 + rand.nextInt(9000); i++) {
startA += rand.nextInt(100);
startB += rand.nextInt(100);
a.put(startA,
Resource.newInstance(rand.nextInt(10240), rand.nextInt(10)));
b.put(startB,
Resource.newInstance(rand.nextInt(10240), rand.nextInt(10)));
}
RLESparseResourceAllocation rleA =
new RLESparseResourceAllocation(a, new DefaultResourceCalculator());
RLESparseResourceAllocation rleB =
new RLESparseResourceAllocation(b, new DefaultResourceCalculator());
long start = System.currentTimeMillis();
RLESparseResourceAllocation out =
RLESparseResourceAllocation.merge(new DefaultResourceCalculator(),
Resource.newInstance(100 * 128 * 1024, 100 * 32), rleA, rleB,
RLEOperator.add, Long.MIN_VALUE, Long.MAX_VALUE);
long end = System.currentTimeMillis();
System.out.println(" Took: " + (end - start) + "ms ");
}
}
@Test
public void testRangeOverlapping() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation r = new RLESparseResourceAllocation(resCalc);
int[] alloc = { 10, 10, 10, 10, 10, 10 };
int start = 100;
Set<Entry<ReservationInterval, Resource>> inputs =
generateAllocation(start, alloc, false).entrySet();
for (Entry<ReservationInterval, Resource> ip : inputs) {
r.addInterval(ip.getKey(), ip.getValue());
}
long s = r.getEarliestStartTime();
long d = r.getLatestNonNullTime();
// tries to trigger "out-of-range" bug
r = r.getRangeOverlapping(s, d);
r = r.getRangeOverlapping(s - 1, d - 1);
r = r.getRangeOverlapping(s + 1, d + 1);
}
@Test
public void testBlocks() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
int[] alloc = { 10, 10, 10, 10, 10, 10 };
int start = 100;
Set<Entry<ReservationInterval, Resource>> inputs =
generateAllocation(start, alloc, false).entrySet();
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.addInterval(ip.getKey(), ip.getValue());
}
LOG.info(rleSparseVector.toString());
assertFalse(rleSparseVector.isEmpty());
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(99));
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + alloc.length + 1));
for (int i = 0; i < alloc.length; i++) {
assertEquals(Resource.newInstance(1024 * (alloc[i]), (alloc[i])),
rleSparseVector.getCapacityAtTime(start + i));
}
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + alloc.length + 2));
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.removeInterval(ip.getKey(), ip.getValue());
}
LOG.info(rleSparseVector.toString());
for (int i = 0; i < alloc.length; i++) {
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + i));
}
assertTrue(rleSparseVector.isEmpty());
}
@Test
public void testPartialRemoval() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
ReservationInterval riAdd = new ReservationInterval(10, 20);
Resource rr = Resource.newInstance(1024 * 100, 100);
ReservationInterval riAdd2 = new ReservationInterval(20, 30);
Resource rr2 = Resource.newInstance(1024 * 200, 200);
ReservationInterval riRemove = new ReservationInterval(12, 25);
// same if we use this
// ReservationRequest rrRemove =
// ReservationRequest.newInstance(Resource.newInstance(1024, 1), 100, 1,6);
LOG.info(rleSparseVector.toString());
rleSparseVector.addInterval(riAdd, rr);
rleSparseVector.addInterval(riAdd2, rr2);
LOG.info(rleSparseVector.toString());
rleSparseVector.removeInterval(riRemove, rr);
LOG.info(rleSparseVector.toString());
// Current bug prevents this to pass. The RLESparseResourceAllocation
// does not handle removal of "partial"
// allocations correctly.
assertEquals(102400,
rleSparseVector.getCapacityAtTime(10).getMemorySize());
assertEquals(0,
rleSparseVector.getCapacityAtTime(13).getMemorySize());
assertEquals(0,
rleSparseVector.getCapacityAtTime(19).getMemorySize());
assertEquals(102400,
rleSparseVector.getCapacityAtTime(21).getMemorySize());
assertEquals(2 * 102400,
rleSparseVector.getCapacityAtTime(26).getMemorySize());
ReservationInterval riRemove2 = new ReservationInterval(9, 13);
rleSparseVector.removeInterval(riRemove2, rr);
LOG.info(rleSparseVector.toString());
assertEquals(0,
rleSparseVector.getCapacityAtTime(11).getMemorySize());
assertEquals(-102400,
rleSparseVector.getCapacityAtTime(9).getMemorySize());
assertEquals(0,
rleSparseVector.getCapacityAtTime(13).getMemorySize());
assertEquals(102400,
rleSparseVector.getCapacityAtTime(20).getMemorySize());
}
@Test
public void testSteps() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
int[] alloc = { 10, 10, 10, 10, 10, 10 };
int start = 100;
Set<Entry<ReservationInterval, Resource>> inputs =
generateAllocation(start, alloc, true).entrySet();
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.addInterval(ip.getKey(), ip.getValue());
}
LOG.info(rleSparseVector.toString());
assertFalse(rleSparseVector.isEmpty());
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(99));
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + alloc.length + 1));
for (int i = 0; i < alloc.length; i++) {
assertEquals(
Resource.newInstance(1024 * (alloc[i] + i), (alloc[i] + i)),
rleSparseVector.getCapacityAtTime(start + i));
}
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + alloc.length + 2));
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.removeInterval(ip.getKey(), ip.getValue());
}
LOG.info(rleSparseVector.toString());
for (int i = 0; i < alloc.length; i++) {
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + i));
}
assertTrue(rleSparseVector.isEmpty());
}
@Test
public void testSkyline() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
int[] alloc = { 0, 5, 10, 10, 5, 0 };
int start = 100;
Set<Entry<ReservationInterval, Resource>> inputs =
generateAllocation(start, alloc, true).entrySet();
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.addInterval(ip.getKey(), ip.getValue());
}
LOG.info(rleSparseVector.toString());
assertFalse(rleSparseVector.isEmpty());
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(99));
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + alloc.length + 1));
for (int i = 0; i < alloc.length; i++) {
assertEquals(
Resource.newInstance(1024 * (alloc[i] + i), (alloc[i] + i)),
rleSparseVector.getCapacityAtTime(start + i));
}
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + alloc.length + 2));
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.removeInterval(ip.getKey(), ip.getValue());
}
LOG.info(rleSparseVector.toString());
for (int i = 0; i < alloc.length; i++) {
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(start + i));
}
assertTrue(rleSparseVector.isEmpty());
}
@Test
public void testZeroAllocation() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
rleSparseVector.addInterval(new ReservationInterval(0, Long.MAX_VALUE),
Resource.newInstance(0, 0));
LOG.info(rleSparseVector.toString());
assertEquals(Resource.newInstance(0, 0),
rleSparseVector.getCapacityAtTime(new Random().nextLong()));
assertTrue(rleSparseVector.isEmpty());
}
@Test
public void testToIntervalMap() {
ResourceCalculator resCalc = new DefaultResourceCalculator();
RLESparseResourceAllocation rleSparseVector =
new RLESparseResourceAllocation(resCalc);
Map<ReservationInterval, Resource> mapAllocations;
// Check empty
mapAllocations = rleSparseVector.toIntervalMap();
assertTrue(mapAllocations.isEmpty());
// Check full
int[] alloc = { 0, 5, 10, 10, 5, 0, 5, 0 };
int start = 100;
Set<Entry<ReservationInterval, Resource>> inputs =
generateAllocation(start, alloc, false).entrySet();
for (Entry<ReservationInterval, Resource> ip : inputs) {
rleSparseVector.addInterval(ip.getKey(), ip.getValue());
}
mapAllocations = rleSparseVector.toIntervalMap();
assertTrue(mapAllocations.size() == 5);
for (Entry<ReservationInterval, Resource> entry : mapAllocations
.entrySet()) {
ReservationInterval interval = entry.getKey();
Resource resource = entry.getValue();
if (interval.getStartTime() == 101L) {
assertTrue(interval.getEndTime() == 102L);
assertEquals(resource, Resource.newInstance(5 * 1024, 5));
} else if (interval.getStartTime() == 102L) {
assertTrue(interval.getEndTime() == 104L);
assertEquals(resource, Resource.newInstance(10 * 1024, 10));
} else if (interval.getStartTime() == 104L) {
assertTrue(interval.getEndTime() == 105L);
assertEquals(resource, Resource.newInstance(5 * 1024, 5));
} else if (interval.getStartTime() == 105L) {
assertTrue(interval.getEndTime() == 106L);
assertEquals(resource, Resource.newInstance(0 * 1024, 0));
} else if (interval.getStartTime() == 106L) {
assertTrue(interval.getEndTime() == 107L);
assertEquals(resource, Resource.newInstance(5 * 1024, 5));
} else {
fail();
}
}
}
@Test
public void testMaxPeriodicCapacity() {
long[] timeSteps = { 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L };
int[] alloc = { 2, 5, 7, 10, 3, 4, 6, 8 };
RLESparseResourceAllocation rleSparseVector = ReservationSystemTestUtil
.generateRLESparseResourceAllocation(alloc, timeSteps);
LOG.info(rleSparseVector.toString());
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(0, 1),
Resource.newInstance(10, 10));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(0, 2),
Resource.newInstance(7, 7));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(0, 3),
Resource.newInstance(10, 10));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(0, 4),
Resource.newInstance(3, 3));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(0, 5),
Resource.newInstance(4, 4));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(0, 5),
Resource.newInstance(4, 4));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(7, 5),
Resource.newInstance(8, 8));
assertEquals(rleSparseVector.getMaximumPeriodicCapacity(10, 3),
Resource.newInstance(0, 0));
}
@Test
public void testGetMinimumCapacityInInterval() {
long[] timeSteps = { 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L };
int[] alloc = { 2, 5, 7, 10, 3, 4, 0, 8 };
RLESparseResourceAllocation rleSparseVector = ReservationSystemTestUtil
.generateRLESparseResourceAllocation(alloc, timeSteps);
LOG.info(rleSparseVector.toString());
assertEquals(rleSparseVector.getMinimumCapacityInInterval(
new ReservationInterval(1L, 3L)), Resource.newInstance(5, 5));
assertEquals(rleSparseVector.getMinimumCapacityInInterval(
new ReservationInterval(2L, 5L)), Resource.newInstance(3, 3));
assertEquals(rleSparseVector.getMinimumCapacityInInterval(
new ReservationInterval(1L, 7L)), Resource.newInstance(0, 0));
}
private void setupArrays(TreeMap<Long, Resource> a,
TreeMap<Long, Resource> b) {
a.put(10L, Resource.newInstance(5, 5));
a.put(20L, Resource.newInstance(10, 10));
a.put(30L, Resource.newInstance(15, 15));
a.put(40L, Resource.newInstance(20, 20));
a.put(50L, Resource.newInstance(0, 0));
b.put(11L, Resource.newInstance(5, 5));
b.put(22L, Resource.newInstance(10, 10));
b.put(33L, Resource.newInstance(15, 15));
b.put(40L, Resource.newInstance(20, 20));
b.put(42L, Resource.newInstance(20, 20));
b.put(43L, Resource.newInstance(10, 10));
}
private void validate(RLESparseResourceAllocation out, long[] time,
int[] alloc) {
int i = 0;
for (Entry<Long, Resource> res : out.getCumulative().entrySet()) {
assertEquals(time[i], ((long) res.getKey()));
if (i > alloc.length - 1) {
assertNull(res.getValue());
} else {
assertEquals(alloc[i], res.getValue().getVirtualCores());
}
i++;
}
assertEquals(time.length, i);
}
private Map<ReservationInterval, Resource> generateAllocation(int startTime,
int[] alloc, boolean isStep) {
Map<ReservationInterval, Resource> req =
new HashMap<ReservationInterval, Resource>();
int numContainers = 0;
for (int i = 0; i < alloc.length; i++) {
if (isStep) {
numContainers = alloc[i] + i;
} else {
numContainers = alloc[i];
}
req.put(new ReservationInterval(startTime + i, startTime + i + 1),
ReservationSystemUtil.toResource(ReservationRequest
.newInstance(Resource.newInstance(1024, 1), (numContainers))));
}
return req;
}
}
| TestRLESparseResourceAllocation |
java | apache__camel | components/camel-as2/camel-as2-api/src/main/java/org/apache/camel/component/as2/api/entity/MultipartSignedEntity.java | {
"start": 1110,
"end": 2533
} | class ____ extends MultipartMimeEntity {
public MultipartSignedEntity(MimeEntity data, AS2SignedDataGenerator signer, String signatureCharSet,
String signatureTransferEncoding, boolean isMainBody, String boundary) throws HttpException {
super(signer, isMainBody, (boundary == null) ? EntityUtils.createBoundaryValue() : boundary);
addPart(data);
ApplicationPkcs7SignatureEntity signature
= new ApplicationPkcs7SignatureEntity(data, signer, signatureCharSet, signatureTransferEncoding, false);
addPart(signature);
}
protected MultipartSignedEntity(ContentType contentType, String contentTransferEncoding, String boundary,
boolean isMainBody) {
super(contentType, contentTransferEncoding);
this.boundary = boundary;
this.isMainBody = isMainBody;
}
public MimeEntity getSignedDataEntity() {
if (getPartCount() > 0) {
return getPart(0);
}
return null;
}
public ApplicationPkcs7SignatureEntity getSignatureEntity() {
if (getPartCount() > 1 && getPart(1) instanceof ApplicationPkcs7SignatureEntity) {
return (ApplicationPkcs7SignatureEntity) getPart(1);
}
return null;
}
@Override
public void close() throws IOException {
// do nothing
}
}
| MultipartSignedEntity |
java | quarkusio__quarkus | extensions/elasticsearch-rest-client/deployment/src/test/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/DevServicesElasticsearchDevModeTestCase.java | {
"start": 289,
"end": 1119
} | class ____ {
@RegisterExtension
static QuarkusDevModeTest test = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar
.addClass(TestResource.class));
@Test
public void testDatasource() throws Exception {
var fruit = new TestResource.Fruit();
fruit.id = "1";
fruit.name = "banana";
fruit.color = "yellow";
RestAssured
.given().body(fruit).contentType("application/json")
.when().post("/fruits")
.then().statusCode(204);
RestAssured.when().get("/fruits/search?term=color&match=yellow")
.then()
.statusCode(200)
.body(equalTo("[{\"id\":\"1\",\"name\":\"banana\",\"color\":\"yellow\"}]"));
}
}
| DevServicesElasticsearchDevModeTestCase |
java | google__guava | android/guava/src/com/google/common/util/concurrent/ExecutionSequencer.java | {
"start": 13917,
"end": 14837
} | class ____ certainly be simpler and easier to reason about if it were built with
* ThreadLocal; however, ThreadLocal is not well optimized for the case where the ThreadLocal is
* non-static, and is initialized/removed frequently - this causes churn in the Thread specific
* hashmaps. Using a static ThreadLocal to avoid that overhead would mean that different
* ExecutionSequencer objects interfere with each other, which would be undesirable, in addition
* to increasing the memory footprint of every thread that interacted with it. In order to release
* entries in thread-specific maps when the ThreadLocal object itself is no longer referenced,
* ThreadLocal is usually implemented with a WeakReference, which can have negative performance
* properties; for example, calling WeakReference.get() on Android will block during an
* otherwise-concurrent GC cycle.
*/
private static final | would |
java | spring-projects__spring-boot | module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/server/RestartServer.java | {
"start": 1684,
"end": 2940
} | class ____ {
private static final Log logger = LogFactory.getLog(RestartServer.class);
private final SourceDirectoryUrlFilter sourceDirectoryUrlFilter;
private final ClassLoader classLoader;
/**
* Create a new {@link RestartServer} instance.
* @param sourceDirectoryUrlFilter the source filter used to link remote directory to
* the local classpath
*/
public RestartServer(SourceDirectoryUrlFilter sourceDirectoryUrlFilter) {
this(sourceDirectoryUrlFilter, Thread.currentThread().getContextClassLoader());
}
/**
* Create a new {@link RestartServer} instance.
* @param sourceDirectoryUrlFilter the source filter used to link remote directory to
* the local classpath
* @param classLoader the application classloader
*/
public RestartServer(SourceDirectoryUrlFilter sourceDirectoryUrlFilter, ClassLoader classLoader) {
Assert.notNull(sourceDirectoryUrlFilter, "'sourceDirectoryUrlFilter' must not be null");
Assert.notNull(classLoader, "'classLoader' must not be null");
this.sourceDirectoryUrlFilter = sourceDirectoryUrlFilter;
this.classLoader = classLoader;
}
/**
* Update the current running application with the specified {@link ClassLoaderFiles}
* and trigger a reload.
* @param files updated | RestartServer |
java | alibaba__nacos | api/src/test/java/com/alibaba/nacos/api/naming/remote/response/BatchInstanceResponseTest.java | {
"start": 1161,
"end": 2209
} | class ____ {
protected static ObjectMapper mapper;
@BeforeAll
static void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Test
void testSerialize() throws JsonProcessingException {
BatchInstanceResponse response = new BatchInstanceResponse(NamingRemoteConstants.REGISTER_INSTANCE);
String json = mapper.writeValueAsString(response);
assertTrue(json.contains("\"type\":\"" + NamingRemoteConstants.REGISTER_INSTANCE + "\""));
}
@Test
void testDeserialize() throws JsonProcessingException {
String json = "{\"resultCode\":200,\"errorCode\":0,\"type\":\"registerInstance\",\"success\":true}";
BatchInstanceResponse response = mapper.readValue(json, BatchInstanceResponse.class);
assertEquals(NamingRemoteConstants.REGISTER_INSTANCE, response.getType());
}
} | BatchInstanceResponseTest |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java | {
"start": 7119,
"end": 7270
} | class ____ extends Purchaser implements Person {
@Override
public String getGreeting() {
return "may I help you?";
}
}
private static | Shopper |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java | {
"start": 1895,
"end": 8940
} | class ____ implements ApplicationContextAware {
public static final String BEAN_NAME = "dubboReferenceBeanManager";
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
// reference key -> reference bean names
private ConcurrentMap<String, CopyOnWriteArrayList<String>> referenceKeyMap = new ConcurrentHashMap<>();
// reference alias -> reference bean name
private ConcurrentMap<String, String> referenceAliasMap = new ConcurrentHashMap<>();
// reference bean name -> ReferenceBean
private ConcurrentMap<String, ReferenceBean> referenceBeanMap = new ConcurrentHashMap<>();
// reference key -> ReferenceConfig instance
private ConcurrentMap<String, ReferenceConfig> referenceConfigMap = new ConcurrentHashMap<>();
private ApplicationContext applicationContext;
private volatile boolean initialized = false;
private ModuleModel moduleModel;
public void addReference(ReferenceBean referenceBean) throws Exception {
String referenceBeanName = referenceBean.getId();
Assert.notEmptyString(referenceBeanName, "The id of ReferenceBean cannot be empty");
if (!initialized) {
// TODO add issue url to describe early initialization
logger.warn(
CONFIG_DUBBO_BEAN_INITIALIZER,
"",
"",
"Early initialize reference bean before DubboConfigBeanInitializer,"
+ " the BeanPostProcessor has not been loaded at this time, which may cause abnormalities in some components (such as seata): "
+ referenceBeanName
+ " = " + ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext));
}
String referenceKey = getReferenceKeyByBeanName(referenceBeanName);
if (StringUtils.isEmpty(referenceKey)) {
referenceKey = ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext);
}
ReferenceBean oldReferenceBean = referenceBeanMap.get(referenceBeanName);
if (oldReferenceBean != null) {
if (referenceBean != oldReferenceBean) {
String oldReferenceKey =
ReferenceBeanSupport.generateReferenceKey(oldReferenceBean, applicationContext);
throw new IllegalStateException("Found duplicated ReferenceBean with id: " + referenceBeanName
+ ", old: " + oldReferenceKey + ", new: " + referenceKey);
}
return;
}
referenceBeanMap.put(referenceBeanName, referenceBean);
// save cache, map reference key to referenceBeanName
this.registerReferenceKeyAndBeanName(referenceKey, referenceBeanName);
// if add reference after prepareReferenceBeans(), should init it immediately.
if (initialized) {
initReferenceBean(referenceBean);
}
}
private String getReferenceKeyByBeanName(String referenceBeanName) {
Set<Map.Entry<String, CopyOnWriteArrayList<String>>> entries = referenceKeyMap.entrySet();
for (Map.Entry<String, CopyOnWriteArrayList<String>> entry : entries) {
if (entry.getValue().contains(referenceBeanName)) {
return entry.getKey();
}
}
return null;
}
public void registerReferenceKeyAndBeanName(String referenceKey, String referenceBeanNameOrAlias) {
CopyOnWriteArrayList<String> list = ConcurrentHashMapUtils.computeIfAbsent(
referenceKeyMap, referenceKey, (key) -> new CopyOnWriteArrayList<>());
if (list.addIfAbsent(referenceBeanNameOrAlias)) {
// register bean name as alias
referenceAliasMap.put(referenceBeanNameOrAlias, list.get(0));
}
}
public ReferenceBean getById(String referenceBeanNameOrAlias) {
String referenceBeanName = transformName(referenceBeanNameOrAlias);
return referenceBeanMap.get(referenceBeanName);
}
// convert reference name/alias to referenceBeanName
private String transformName(String referenceBeanNameOrAlias) {
return referenceAliasMap.getOrDefault(referenceBeanNameOrAlias, referenceBeanNameOrAlias);
}
public List<String> getBeanNamesByKey(String key) {
return Collections.unmodifiableList(referenceKeyMap.getOrDefault(key, new CopyOnWriteArrayList<>()));
}
public Collection<ReferenceBean> getReferences() {
return new HashSet<>(referenceBeanMap.values());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
}
/**
* Initialize all reference beans, call at Dubbo starting
*
* @throws Exception
*/
public void prepareReferenceBeans() throws Exception {
initialized = true;
for (ReferenceBean referenceBean : getReferences()) {
initReferenceBean(referenceBean);
}
}
/**
* NOTE: This method should only call after all dubbo config beans and all property resolvers is loaded.
*
* @param referenceBean
* @throws Exception
*/
public synchronized void initReferenceBean(ReferenceBean referenceBean) throws Exception {
if (referenceBean.getReferenceConfig() != null) {
return;
}
// TOTO check same unique service name but difference reference key (means difference attributes).
// reference key
String referenceKey = getReferenceKeyByBeanName(referenceBean.getId());
if (StringUtils.isEmpty(referenceKey)) {
referenceKey = ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext);
}
ReferenceConfig referenceConfig = referenceConfigMap.get(referenceKey);
if (referenceConfig == null) {
// create real ReferenceConfig
Map<String, Object> referenceAttributes = ReferenceBeanSupport.getReferenceAttributes(referenceBean);
referenceConfig = ReferenceCreator.create(referenceAttributes, applicationContext)
.defaultInterfaceClass(referenceBean.getObjectType())
.build();
// set id if it is not a generated name
if (referenceBean.getId() != null && !referenceBean.getId().contains("#")) {
referenceConfig.setId(referenceBean.getId());
}
// cache referenceConfig
referenceConfigMap.put(referenceKey, referenceConfig);
// register ReferenceConfig
moduleModel.getConfigManager().addReference(referenceConfig);
moduleModel.getDeployer().setPending();
}
// associate referenceConfig to referenceBean
referenceBean.setKeyAndReferenceConfig(referenceKey, referenceConfig);
}
}
| ReferenceBeanManager |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/cli/ConnectDistributed.java | {
"start": 2662,
"end": 5630
} | class ____ extends AbstractConnectCli<DistributedHerder, DistributedConfig> {
public ConnectDistributed(String... args) {
super(args);
}
@Override
protected String usage() {
return "ConnectDistributed worker.properties";
}
@Override
protected DistributedHerder createHerder(DistributedConfig config, String workerId, Plugins plugins,
ConnectorClientConfigOverridePolicy connectorClientConfigOverridePolicy,
RestServer restServer, RestClient restClient) {
String kafkaClusterId = config.kafkaClusterId();
String clientIdBase = ConnectUtils.clientIdBase(config);
// Create the admin client to be shared by all backing stores.
Map<String, Object> adminProps = new HashMap<>(config.originals());
ConnectUtils.addMetricsContextProperties(adminProps, config, kafkaClusterId);
adminProps.put(CLIENT_ID_CONFIG, clientIdBase + "shared-admin");
SharedTopicAdmin sharedAdmin = new SharedTopicAdmin(adminProps);
KafkaOffsetBackingStore offsetBackingStore = new KafkaOffsetBackingStore(sharedAdmin, () -> clientIdBase,
plugins.newInternalConverter(true, JsonConverter.class.getName(),
Map.of(JsonConverterConfig.SCHEMAS_ENABLE_CONFIG, "false")));
offsetBackingStore.configure(config);
Worker worker = new Worker(workerId, Time.SYSTEM, plugins, config, offsetBackingStore, connectorClientConfigOverridePolicy);
WorkerConfigTransformer configTransformer = worker.configTransformer();
Converter internalValueConverter = worker.getInternalValueConverter();
StatusBackingStore statusBackingStore = new KafkaStatusBackingStore(Time.SYSTEM, internalValueConverter, sharedAdmin, clientIdBase);
statusBackingStore.configure(config);
ConfigBackingStore configBackingStore = new KafkaConfigBackingStore(
internalValueConverter,
config,
configTransformer,
sharedAdmin,
clientIdBase);
// Pass the shared admin to the distributed herder as an additional AutoCloseable object that should be closed when the
// herder is stopped. This is easier than having to track and own the lifecycle ourselves.
return new DistributedHerder(config, Time.SYSTEM, worker,
kafkaClusterId, statusBackingStore, configBackingStore,
restServer.advertisedUrl().toString(), restClient, connectorClientConfigOverridePolicy,
List.of(), sharedAdmin);
}
@Override
protected DistributedConfig createConfig(Map<String, String> workerProps) {
return new DistributedConfig(workerProps);
}
public static void main(String[] args) {
ConnectDistributed connectDistributed = new ConnectDistributed(args);
connectDistributed.run();
}
}
| ConnectDistributed |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/HistogramAggregationBuilder.java | {
"start": 2065,
"end": 16071
} | class ____ extends ValuesSourceAggregationBuilder<HistogramAggregationBuilder> {
public static final String NAME = "histogram";
public static final ValuesSourceRegistry.RegistryKey<HistogramAggregatorSupplier> REGISTRY_KEY = new ValuesSourceRegistry.RegistryKey<>(
NAME,
HistogramAggregatorSupplier.class
);
public static final ObjectParser<HistogramAggregationBuilder, String> PARSER = ObjectParser.fromBuilder(
NAME,
HistogramAggregationBuilder::new
);
static {
ValuesSourceAggregationBuilder.declareFields(PARSER, true, true, false);
PARSER.declareDouble(HistogramAggregationBuilder::interval, Histogram.INTERVAL_FIELD);
PARSER.declareDouble(HistogramAggregationBuilder::offset, Histogram.OFFSET_FIELD);
PARSER.declareBoolean(HistogramAggregationBuilder::keyed, Histogram.KEYED_FIELD);
PARSER.declareLong(HistogramAggregationBuilder::minDocCount, Histogram.MIN_DOC_COUNT_FIELD);
PARSER.declareField(
HistogramAggregationBuilder::extendedBounds,
parser -> DoubleBounds.PARSER.apply(parser, null),
Histogram.EXTENDED_BOUNDS_FIELD,
ObjectParser.ValueType.OBJECT
);
PARSER.declareField(
HistogramAggregationBuilder::hardBounds,
parser -> DoubleBounds.PARSER.apply(parser, null),
Histogram.HARD_BOUNDS_FIELD,
ObjectParser.ValueType.OBJECT
);
PARSER.declareObjectArray(
HistogramAggregationBuilder::order,
(p, c) -> InternalOrder.Parser.parseOrderParam(p),
Histogram.ORDER_FIELD
);
}
public static void registerAggregators(ValuesSourceRegistry.Builder builder) {
HistogramAggregatorFactory.registerAggregators(builder);
}
private double interval;
private double offset = 0;
private DoubleBounds extendedBounds;
private DoubleBounds hardBounds;
private BucketOrder order = BucketOrder.key(true);
private boolean keyed = false;
private long minDocCount = 0;
@Override
protected ValuesSourceType defaultValueSourceType() {
return CoreValuesSourceType.NUMERIC;
}
/** Create a new builder with the given name. */
public HistogramAggregationBuilder(String name) {
super(name);
}
protected HistogramAggregationBuilder(
HistogramAggregationBuilder clone,
AggregatorFactories.Builder factoriesBuilder,
Map<String, Object> metadata
) {
super(clone, factoriesBuilder, metadata);
this.interval = clone.interval;
this.offset = clone.offset;
this.extendedBounds = clone.extendedBounds;
this.hardBounds = clone.hardBounds;
this.order = clone.order;
this.keyed = clone.keyed;
this.minDocCount = clone.minDocCount;
}
@Override
public boolean supportsSampling() {
return true;
}
@Override
protected AggregationBuilder shallowCopy(AggregatorFactories.Builder factoriesBuilder, Map<String, Object> metadata) {
return new HistogramAggregationBuilder(this, factoriesBuilder, metadata);
}
/** Read from a stream, for internal use only. */
public HistogramAggregationBuilder(StreamInput in) throws IOException {
super(in);
order = InternalOrder.Streams.readHistogramOrder(in);
keyed = in.readBoolean();
minDocCount = in.readVLong();
interval = in.readDouble();
offset = in.readDouble();
extendedBounds = in.readOptionalWriteable(DoubleBounds::new);
hardBounds = in.readOptionalWriteable(DoubleBounds::new);
}
@Override
protected void innerWriteTo(StreamOutput out) throws IOException {
InternalOrder.Streams.writeHistogramOrder(order, out);
out.writeBoolean(keyed);
out.writeVLong(minDocCount);
out.writeDouble(interval);
out.writeDouble(offset);
out.writeOptionalWriteable(extendedBounds);
out.writeOptionalWriteable(hardBounds);
}
/** Get the current interval that is set on this builder. */
public double interval() {
return interval;
}
/** Set the interval on this builder, and return the builder so that calls can be chained. */
public HistogramAggregationBuilder interval(double interval) {
if (interval <= 0) {
throw new IllegalArgumentException("[interval] must be >0 for histogram aggregation [" + name + "]");
}
this.interval = interval;
return this;
}
/** Get the current offset that is set on this builder. */
public double offset() {
return offset;
}
/** Set the offset on this builder, and return the builder so that calls can be chained. */
public HistogramAggregationBuilder offset(double offset) {
this.offset = offset;
return this;
}
/** Get the current minimum bound that is set on this builder. */
public double minBound() {
return DoubleBounds.getEffectiveMin(extendedBounds);
}
/** Get the current maximum bound that is set on this builder. */
public double maxBound() {
return DoubleBounds.getEffectiveMax(extendedBounds);
}
/**
* Set extended bounds on this builder: buckets between {@code minBound} and
* {@code maxBound} will be created even if no documents fell into these
* buckets.
*
* @throws IllegalArgumentException
* if maxBound is less that minBound, or if either of the bounds
* are not finite.
*/
public HistogramAggregationBuilder extendedBounds(double minBound, double maxBound) {
return extendedBounds(new DoubleBounds(minBound, maxBound));
}
/**
* Set extended bounds on this builder: buckets between {@code minBound} and
* {@code maxBound} will be created even if no documents fell into these
* buckets.
*
* @throws IllegalArgumentException
* if maxBound is less that minBound, or if either of the bounds
* are not finite.
*/
public HistogramAggregationBuilder extendedBounds(DoubleBounds extendedBounds) {
if (extendedBounds == null) {
throw new IllegalArgumentException("[extended_bounds] must not be null: [" + name + "]");
}
this.extendedBounds = extendedBounds;
return this;
}
/**
* Set hard bounds on this histogram, specifying boundaries outside which buckets cannot be created.
*/
public HistogramAggregationBuilder hardBounds(DoubleBounds hardBounds) {
if (hardBounds == null) {
throw new IllegalArgumentException("[hardBounds] must not be null: [" + name + "]");
}
this.hardBounds = hardBounds;
return this;
}
/** Return the order to use to sort buckets of this histogram. */
public BucketOrder order() {
return order;
}
/** Set a new order on this builder and return the builder so that calls
* can be chained. A tie-breaker may be added to avoid non-deterministic ordering. */
public HistogramAggregationBuilder order(BucketOrder order) {
if (order == null) {
throw new IllegalArgumentException("[order] must not be null: [" + name + "]");
}
if (order instanceof CompoundOrder || InternalOrder.isKeyOrder(order)) {
this.order = order; // if order already contains a tie-breaker we are good to go
} else { // otherwise add a tie-breaker by using a compound order
this.order = BucketOrder.compound(order);
}
return this;
}
/**
* Sets the order in which the buckets will be returned. A tie-breaker may be added to avoid non-deterministic
* ordering.
*/
public HistogramAggregationBuilder order(List<BucketOrder> orders) {
if (orders == null) {
throw new IllegalArgumentException("[orders] must not be null: [" + name + "]");
}
// if the list only contains one order use that to avoid inconsistent xcontent
order(orders.size() > 1 ? BucketOrder.compound(orders) : orders.get(0));
return this;
}
/** Return whether buckets should be returned as a hash. In case
* {@code keyed} is false, buckets will be returned as an array. */
public boolean keyed() {
return keyed;
}
/** Set whether to return buckets as a hash or as an array, and return the
* builder so that calls can be chained. */
public HistogramAggregationBuilder keyed(boolean keyed) {
this.keyed = keyed;
return this;
}
/** Return the minimum count of documents that buckets need to have in order
* to be included in the response. */
public long minDocCount() {
return minDocCount;
}
/** Set the minimum count of matching documents that buckets need to have
* and return this builder so that calls can be chained. */
public HistogramAggregationBuilder minDocCount(long minDocCount) {
if (minDocCount < 0) {
throw new IllegalArgumentException(
"[minDocCount] must be greater than or equal to 0. Found [" + minDocCount + "] in [" + name + "]"
);
}
this.minDocCount = minDocCount;
return this;
}
@Override
public BucketCardinality bucketCardinality() {
return BucketCardinality.MANY;
}
@Override
protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
builder.field(Histogram.INTERVAL_FIELD.getPreferredName(), interval);
builder.field(Histogram.OFFSET_FIELD.getPreferredName(), offset);
if (order != null) {
builder.field(Histogram.ORDER_FIELD.getPreferredName());
order.toXContent(builder, params);
}
builder.field(Histogram.KEYED_FIELD.getPreferredName(), keyed);
builder.field(Histogram.MIN_DOC_COUNT_FIELD.getPreferredName(), minDocCount);
if (extendedBounds != null) {
builder.startObject(Histogram.EXTENDED_BOUNDS_FIELD.getPreferredName());
extendedBounds.toXContent(builder, params);
builder.endObject();
}
if (hardBounds != null) {
builder.startObject(Histogram.HARD_BOUNDS_FIELD.getPreferredName());
hardBounds.toXContent(builder, params);
builder.endObject();
}
return builder;
}
@Override
public String getType() {
return NAME;
}
@Override
protected ValuesSourceAggregatorFactory innerBuild(
AggregationContext context,
ValuesSourceConfig config,
AggregatorFactory parent,
AggregatorFactories.Builder subFactoriesBuilder
) throws IOException {
HistogramAggregatorSupplier aggregatorSupplier = context.getValuesSourceRegistry().getAggregator(REGISTRY_KEY, config);
if (hardBounds != null && extendedBounds != null) {
if (hardBounds.getMax() != null && extendedBounds.getMax() != null && hardBounds.getMax() < extendedBounds.getMax()) {
throw new IllegalArgumentException(
"Extended bounds have to be inside hard bounds, hard bounds: ["
+ hardBounds
+ "], extended bounds: ["
+ extendedBounds.getMin()
+ "--"
+ extendedBounds.getMax()
+ "]"
);
}
if (hardBounds.getMin() != null && extendedBounds.getMin() != null && hardBounds.getMin() > extendedBounds.getMin()) {
throw new IllegalArgumentException(
"Extended bounds have to be inside hard bounds, hard bounds: ["
+ hardBounds
+ "], extended bounds: ["
+ extendedBounds.getMin()
+ "--"
+ extendedBounds.getMax()
+ "]"
);
}
}
return new HistogramAggregatorFactory(
name,
config,
interval,
offset,
order,
keyed,
minDocCount,
extendedBounds,
hardBounds,
context,
parent,
subFactoriesBuilder,
metadata,
aggregatorSupplier
);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), order, keyed, minDocCount, interval, offset, extendedBounds, hardBounds);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
if (super.equals(obj) == false) return false;
HistogramAggregationBuilder other = (HistogramAggregationBuilder) obj;
return Objects.equals(order, other.order)
&& Objects.equals(keyed, other.keyed)
&& Objects.equals(minDocCount, other.minDocCount)
&& Objects.equals(interval, other.interval)
&& Objects.equals(offset, other.offset)
&& Objects.equals(extendedBounds, other.extendedBounds)
&& Objects.equals(hardBounds, other.hardBounds);
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
@Override
protected void validateSequentiallyOrdered(String type, String name, Consumer<String> addValidationError) {}
@Override
protected void validateSequentiallyOrderedWithoutGaps(String type, String name, Consumer<String> addValidationError) {
if (minDocCount != 0) {
addValidationError.accept("parent histogram of " + type + " aggregation [" + name + "] must have min_doc_count of 0");
}
}
}
| HistogramAggregationBuilder |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/AuthenticationFailureResponseBodyDevModeTest.java | {
"start": 1282,
"end": 3650
} | enum ____ {
AUTH_FAILED_WITH_BODY(() -> new AuthenticationFailedException(RESPONSE_BODY), true),
AUTH_COMPLETION_WITH_BODY(() -> new AuthenticationCompletionException(RESPONSE_BODY), true),
AUTH_FAILED_WITHOUT_BODY(AuthenticationFailedException::new, false),
AUTH_COMPLETION_WITHOUT_BODY(AuthenticationCompletionException::new, false);
public final Supplier<Throwable> failureSupplier;
private final boolean expectBody;
AuthFailure(Supplier<Throwable> failureSupplier, boolean expectBody) {
this.failureSupplier = failureSupplier;
this.expectBody = expectBody;
}
}
@RegisterExtension
static QuarkusDevModeTest runner = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar
.addClasses(SecuredResource.class, FailingAuthenticator.class, AuthFailure.class)
.addAsResource(new StringAsset("""
quarkus.http.auth.proactive=false
"""), "application.properties"));
@Test
public void testAuthenticationFailedExceptionBody() {
assertExceptionBody(AuthFailure.AUTH_FAILED_WITHOUT_BODY, false);
assertExceptionBody(AuthFailure.AUTH_FAILED_WITHOUT_BODY, true);
assertExceptionBody(AuthFailure.AUTH_FAILED_WITH_BODY, false);
assertExceptionBody(AuthFailure.AUTH_FAILED_WITH_BODY, true);
}
@Test
public void testAuthenticationCompletionExceptionBody() {
assertExceptionBody(AuthFailure.AUTH_COMPLETION_WITHOUT_BODY, false);
assertExceptionBody(AuthFailure.AUTH_COMPLETION_WITH_BODY, false);
}
private static void assertExceptionBody(AuthFailure failure, boolean challenge) {
int statusCode = challenge ? 302 : 401;
boolean expectBody = failure.expectBody && statusCode == 401;
RestAssured
.given()
.redirects().follow(false)
.header("auth-failure", failure.toString())
.header("challenge-data", challenge)
.get("/secured")
.then()
.statusCode(statusCode)
.body(expectBody ? Matchers.equalTo(RESPONSE_BODY) : Matchers.not(Matchers.containsString(RESPONSE_BODY)));
}
@Authenticated
@Path("secured")
public static | AuthFailure |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/converter/stream/CipherPair.java | {
"start": 1114,
"end": 1184
} | class ____ hold a pair of encryption and decryption ciphers.
*/
public | to |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/rest/RestActionTestCase.java | {
"start": 3598,
"end": 7827
} | class ____ extends NoOpNodeClient {
AtomicReference<BiFunction<ActionType<?>, ActionRequest, ActionResponse>> executeVerifier = new AtomicReference<>();
AtomicReference<BiFunction<ActionType<?>, ActionRequest, ActionResponse>> executeLocallyVerifier = new AtomicReference<>();
public VerifyingClient(ThreadPool threadPool) {
super(threadPool);
reset();
}
@Override
public String getLocalNodeId() {
return "test_node_id";
}
/**
* Clears any previously set verifier functions set by {@link #setExecuteVerifier} and/or
* {@link #setExecuteLocallyVerifier}. These functions are replaced with functions which will throw an
* {@link AssertionError} if called.
*/
public void reset() {
executeVerifier.set((arg1, arg2) -> { throw new AssertionError(); });
executeLocallyVerifier.set((arg1, arg2) -> { throw new AssertionError(); });
}
/**
* Sets the function that will be called when {@link #doExecute(ActionType, ActionRequest, ActionListener)} is called. The given
* function should return a subclass of {@link ActionResponse} that is appropriate for the action.
* @param verifier A function which is called in place of {@link #doExecute(ActionType, ActionRequest, ActionListener)}
*/
public <R extends ActionResponse> void setExecuteVerifier(BiFunction<ActionType<R>, ActionRequest, R> verifier) {
/*
* Perform a little generics dance to force the callers to mock
* a return type appropriate for the action even though we can't
* declare such types. We have force the caller to be specific
* and then throw away their specificity. Then we case back
* to the specific erased type in the method below.
*/
BiFunction<?, ?, ?> dropTypeInfo = (BiFunction<?, ?, ?>) verifier;
@SuppressWarnings("unchecked")
BiFunction<ActionType<?>, ActionRequest, ActionResponse> pasteGenerics = (BiFunction<
ActionType<?>,
ActionRequest,
ActionResponse>) dropTypeInfo;
executeVerifier.set(pasteGenerics);
}
@Override
public <Request extends ActionRequest, Response extends ActionResponse> void doExecute(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
@SuppressWarnings("unchecked") // The method signature of setExecuteVerifier forces this case to work
Response response = (Response) executeVerifier.get().apply(action, request);
listener.onResponse(response);
}
/**
* Sets the function that will be called when {@link #executeLocally(ActionType, ActionRequest, ActionListener)} is called. The
* given function should return either a subclass of {@link ActionResponse} or {@code null}.
* @param verifier A function which is called in place of {@link #executeLocally(ActionType, ActionRequest, ActionListener)}
*/
public void setExecuteLocallyVerifier(BiFunction<ActionType<?>, ActionRequest, ActionResponse> verifier) {
executeLocallyVerifier.set(verifier);
}
private static final AtomicLong taskIdGenerator = new AtomicLong(0L);
@Override
public <Request extends ActionRequest, Response extends ActionResponse> Task executeLocally(
ActionType<Response> action,
Request request,
ActionListener<Response> listener
) {
@SuppressWarnings("unchecked") // Callers are responsible for lining this up
Response response = (Response) executeLocallyVerifier.get().apply(action, request);
ActionListener.respondAndRelease(listener, response);
return request.createTask(
taskIdGenerator.incrementAndGet(),
"transport",
action.name(),
request.getParentTask(),
Collections.emptyMap()
);
}
}
}
| VerifyingClient |
java | alibaba__nacos | naming/src/test/java/com/alibaba/nacos/naming/remote/rpc/handler/BatchInstanceRequestHandlerTest.java | {
"start": 1552,
"end": 2839
} | class ____ {
@InjectMocks
private BatchInstanceRequestHandler batchInstanceRequestHandler;
@Mock
private EphemeralClientOperationServiceImpl clientOperationService;
@Test
void testHandle() throws NacosException {
BatchInstanceRequest batchInstanceRequest = new BatchInstanceRequest();
batchInstanceRequest.setType(NamingRemoteConstants.BATCH_REGISTER_INSTANCE);
batchInstanceRequest.setServiceName("service1");
batchInstanceRequest.setGroupName("group1");
List<Instance> instanceList = new ArrayList<>();
Instance instance = new Instance();
instanceList.add(instance);
batchInstanceRequest.setInstances(instanceList);
RequestMeta requestMeta = new RequestMeta();
batchInstanceRequestHandler.handle(batchInstanceRequest, requestMeta);
Mockito.verify(clientOperationService).batchRegisterInstance(Mockito.any(), Mockito.any(), Mockito.anyString());
batchInstanceRequest.setType("google");
try {
batchInstanceRequestHandler.handle(batchInstanceRequest, requestMeta);
} catch (Exception e) {
assertEquals(NacosException.INVALID_PARAM, ((NacosException) e).getErrCode());
}
}
}
| BatchInstanceRequestHandlerTest |
java | apache__camel | components/camel-resilience4j/src/test/java/org/apache/camel/component/resilience4j/ResilienceInheritErrorHandlerTest.java | {
"start": 1049,
"end": 2907
} | class ____ extends CamelTestSupport {
@Test
public void testResilience() throws Exception {
test("direct:start");
}
@Test
public void testResilienceWithTimeOut() throws Exception {
test("direct:start.with.timeout.enabled");
}
private void test(String endPointUri) throws InterruptedException {
getMockEndpoint("mock:a").expectedMessageCount(3 + 1);
getMockEndpoint("mock:dead").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBody(endPointUri, "Hello World");
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(3).redeliveryDelay(0));
from("direct:start").to("log:start")
// turn on Camel's error handler so it can do
// redeliveries
.circuitBreaker().inheritErrorHandler(true).to("mock:a")
.throwException(new IllegalArgumentException("Forced")).end().to("log:result").to("mock:result");
from("direct:start.with.timeout.enabled").to("log:direct:start.with.timeout.enabled")
// turn on Camel's error handler on so it can do
// redeliveries
.circuitBreaker().inheritErrorHandler(true).resilience4jConfiguration().timeoutEnabled(true).timeoutDuration(2000).end()
.to("mock:a")
.throwException(new IllegalArgumentException("Forced")).end().to("log:result").to("mock:result");
}
};
}
}
| ResilienceInheritErrorHandlerTest |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/hint/FlinkHintStrategies.java | {
"start": 3045,
"end": 14193
} | class ____ {
/**
* Customize the {@link HintStrategyTable} which contains hint strategies supported by Flink.
*/
public static HintStrategyTable createHintStrategyTable() {
return HintStrategyTable.builder()
// Configure to always throw when we encounter any hint errors
// (either the non-registered hint or the hint format).
.errorHandler(Litmus.THROW)
.hintStrategy(
FlinkHints.HINT_NAME_OPTIONS,
HintStrategy.builder(HintPredicates.TABLE_SCAN)
.optionChecker(OPTIONS_KV_OPTION_CHECKER)
.build())
.hintStrategy(
FlinkHints.HINT_NAME_JSON_AGGREGATE_WRAPPED,
HintStrategy.builder(HintPredicates.AGGREGATE)
.excludedRules(WrapJsonAggFunctionArgumentsRule.INSTANCE)
.build())
// internal query hint used for alias
.hintStrategy(
FlinkHints.HINT_ALIAS,
// currently, only correlate&join nodes care about query block alias
HintStrategy.builder(
HintPredicates.or(
HintPredicates.CORRELATE, HintPredicates.JOIN))
.optionChecker(fixedSizeListOptionChecker(1))
.build())
// TODO semi/anti join with CORRELATE is not supported
.hintStrategy(
JoinStrategy.BROADCAST.getJoinHintName(),
HintStrategy.builder(HintPredicates.JOIN)
.optionChecker(NON_EMPTY_LIST_OPTION_CHECKER)
.build())
.hintStrategy(
JoinStrategy.SHUFFLE_HASH.getJoinHintName(),
HintStrategy.builder(HintPredicates.JOIN)
.optionChecker(NON_EMPTY_LIST_OPTION_CHECKER)
.build())
.hintStrategy(
JoinStrategy.SHUFFLE_MERGE.getJoinHintName(),
HintStrategy.builder(HintPredicates.JOIN)
.optionChecker(NON_EMPTY_LIST_OPTION_CHECKER)
.build())
.hintStrategy(
JoinStrategy.NEST_LOOP.getJoinHintName(),
HintStrategy.builder(HintPredicates.JOIN)
.optionChecker(NON_EMPTY_LIST_OPTION_CHECKER)
.build())
.hintStrategy(
JoinStrategy.LOOKUP.getJoinHintName(),
HintStrategy.builder(
HintPredicates.or(
HintPredicates.CORRELATE, HintPredicates.JOIN))
.optionChecker(LOOKUP_NON_EMPTY_KV_OPTION_CHECKER)
.build())
.hintStrategy(
JoinStrategy.MULTI_JOIN.getJoinHintName(),
HintStrategy.builder(HintPredicates.JOIN)
.optionChecker(NON_EMPTY_LIST_OPTION_CHECKER)
.build())
.hintStrategy(
StateTtlHint.STATE_TTL.getHintName(),
HintStrategy.builder(
HintPredicates.or(
HintPredicates.JOIN, HintPredicates.AGGREGATE))
.optionChecker(STATE_TTL_NON_EMPTY_KV_OPTION_CHECKER)
.build())
.build();
}
private static HintOptionChecker fixedSizeListOptionChecker(int size) {
return (hint, errorHandler) ->
errorHandler.check(
hint.listOptions.size() == size,
"Invalid hint: {}, expecting {} table or view {} "
+ "specified in hint {}.",
FlinkHints.stringifyHints(Collections.singletonList(hint)),
size,
size > 1 ? "names" : "name",
hint.hintName);
}
// ~ hint option checker ------------------------------------------------------------
private static final HintOptionChecker NON_EMPTY_LIST_OPTION_CHECKER =
(hint, errorHandler) ->
errorHandler.check(
hint.listOptions.size() > 0,
"Invalid hint: {}, expecting at least "
+ "one table or view specified in hint {}.",
FlinkHints.stringifyHints(Collections.singletonList(hint)),
hint.hintName);
private static final HintOptionChecker OPTIONS_KV_OPTION_CHECKER =
(hint, errorHandler) -> {
errorHandler.check(
hint.kvOptions.size() > 0,
"Hint [{}] only support non empty key value options",
hint.hintName);
Configuration conf = Configuration.fromMap(hint.kvOptions);
Optional<String> errMsgOptional = FactoryUtil.checkWatermarkOptions(conf);
errorHandler.check(
!errMsgOptional.isPresent(), errMsgOptional.orElse("No errors."));
return true;
};
private static final HintOptionChecker LOOKUP_NON_EMPTY_KV_OPTION_CHECKER =
(lookupHint, litmus) -> {
litmus.check(
lookupHint.listOptions.size() == 0,
"Invalid list options in LOOKUP hint, only support key-value options.");
Configuration conf = Configuration.fromMap(lookupHint.kvOptions);
ImmutableSet<ConfigOption> requiredKeys =
LookupJoinHintOptions.getRequiredOptions();
litmus.check(
requiredKeys.stream().allMatch(conf::contains),
"Invalid LOOKUP hint: incomplete required option(s): {}",
requiredKeys);
ImmutableSet<ConfigOption> supportedKeys =
LookupJoinHintOptions.getSupportedOptions();
litmus.check(
lookupHint.kvOptions.size() <= supportedKeys.size(),
"Too many LOOKUP hint options {} beyond max number of supported options {}",
lookupHint.kvOptions.size(),
supportedKeys.size());
try {
// try to validate all hint options by parsing them
supportedKeys.forEach(conf::get);
} catch (IllegalArgumentException e) {
litmus.fail("Invalid LOOKUP hint options: {}", e.getMessage());
}
// option value check
// async options are all optional
Boolean async = conf.get(LookupJoinHintOptions.ASYNC_LOOKUP);
if (Boolean.TRUE.equals(async)) {
Integer capacity = conf.get(LookupJoinHintOptions.ASYNC_CAPACITY);
litmus.check(
null == capacity || capacity > 0,
"Invalid LOOKUP hint option: {} value should be positive integer but was {}",
LookupJoinHintOptions.ASYNC_CAPACITY.key(),
capacity);
}
// retry options can be both null or all not null
String retryPredicate = conf.get(LookupJoinHintOptions.RETRY_PREDICATE);
LookupJoinHintOptions.RetryStrategy retryStrategy =
conf.get(LookupJoinHintOptions.RETRY_STRATEGY);
Duration fixedDelay = conf.get(LookupJoinHintOptions.FIXED_DELAY);
Integer maxAttempts = conf.get(LookupJoinHintOptions.MAX_ATTEMPTS);
litmus.check(
(null == retryPredicate
&& null == retryStrategy
&& null == fixedDelay
&& null == fixedDelay
&& null == maxAttempts)
|| (null != retryPredicate
&& null != retryStrategy
&& null != fixedDelay
&& null != fixedDelay
&& null != maxAttempts),
"Invalid LOOKUP hint: retry options can be both null or all not null");
// if with retry options, all values should be valid
if (null != retryPredicate) {
litmus.check(
LookupJoinHintOptions.LOOKUP_MISS_PREDICATE.equalsIgnoreCase(
retryPredicate),
"Invalid LOOKUP hint option: unsupported {} '{}', only '{}' is supported currently",
LookupJoinHintOptions.RETRY_PREDICATE.key(),
retryPredicate,
LookupJoinHintOptions.LOOKUP_MISS_PREDICATE);
litmus.check(
maxAttempts > 0,
"Invalid LOOKUP hint option: {} value should be positive integer but was {}",
LookupJoinHintOptions.MAX_ATTEMPTS.key(),
maxAttempts);
}
return true;
};
private static final HintOptionChecker STATE_TTL_NON_EMPTY_KV_OPTION_CHECKER =
(ttlHint, litmus) -> {
litmus.check(
ttlHint.listOptions.size() == 0,
"Invalid list options in STATE_TTL hint, only support key-value options.");
litmus.check(
ttlHint.kvOptions.size() > 0,
"Invalid STATE_TTL hint, expecting at least one key-value options specified.");
// validate the hint value
ttlHint.kvOptions
.values()
.forEach(
value -> {
try {
TimeUtils.parseDuration(value);
} catch (IllegalArgumentException e) {
litmus.fail(
"Invalid STATE_TTL hint value: {}", e.getMessage());
}
});
return true;
};
}
| FlinkHintStrategies |
java | elastic__elasticsearch | test/yaml-rest-runner/src/main/java/org/elasticsearch/test/rest/yaml/section/Assertion.java | {
"start": 707,
"end": 778
} | class ____ executable sections that hold assertions
*/
public abstract | for |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java | {
"start": 14228,
"end": 14640
} | class ____ extends DiscriminatorEntitySubclass {
public DiscriminatorEntitySubSubclass() {
}
public DiscriminatorEntitySubSubclass(Integer id, String name) {
super( id, name );
}
public DiscriminatorEntitySubSubclass(
Integer id,
String name,
DiscriminatorEntity other) {
super( id, name, other );
}
}
@Entity(name = "Animal")
public static abstract | DiscriminatorEntitySubSubclass |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java | {
"start": 4217,
"end": 29967
} | class ____ {
static PropertyBinder createCompositeBinder(
PropertyHolder propertyHolder,
PropertyData inferredData,
EntityBinder entityBinder,
boolean isIdentifierMapper,
boolean isComponentEmbedded,
MetadataBuildingContext context,
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
MemberDetails property,
AnnotatedColumns columns,
ClassDetails returnedClass,
boolean isId,
boolean isOverridden,
PropertyData mapsIdProperty,
Class<? extends CompositeUserType<?>> compositeUserType) {
return createEmbeddedProperty(
inferredData,
propertyHolder,
entityBinder,
context,
isComponentEmbedded,
isId,
inheritanceStatePerClass,
createEmbeddable(
propertyHolder,
inferredData,
entityBinder,
isIdentifierMapper,
isComponentEmbedded,
context,
inheritanceStatePerClass,
property,
columns,
returnedClass,
isId,
isOverridden,
mapsIdProperty,
compositeUserType
)
);
}
private static Component createEmbeddable(
PropertyHolder propertyHolder,
PropertyData inferredData,
EntityBinder entityBinder,
boolean isIdentifierMapper,
boolean isComponentEmbedded,
MetadataBuildingContext context,
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
MemberDetails property,
AnnotatedColumns columns,
ClassDetails returnedClass,
boolean isId,
boolean isOverridden,
PropertyData mapsIdProperty,
Class<? extends CompositeUserType<?>> compositeUserType) {
if ( isOverridden ) {
if ( compositeUserType != null ) {
// I suppose this assertion is correct, but it might not be
// Perhaps it was OK that we were just ignoring the CUT
throw new AssertionFailure( "CompositeUserType not allowed with @MapsId" );
}
return bindOverriddenEmbeddable(
propertyHolder,
inferredData,
isIdentifierMapper,
isComponentEmbedded,
context,
inheritanceStatePerClass,
property,
columns,
returnedClass,
isId,
mapsIdProperty
);
}
else {
return bindEmbeddable(
inferredData,
propertyHolder,
entityBinder.getPropertyAccessor( property ),
entityBinder,
isIdentifierMapper,
context,
isComponentEmbedded,
isId,
inheritanceStatePerClass,
determineCustomInstantiator( property, returnedClass, context ),
compositeUserType,
columns
);
}
}
private static Component bindOverriddenEmbeddable(
PropertyHolder propertyHolder,
PropertyData inferredData,
boolean isIdentifierMapper,
boolean isComponentEmbedded,
MetadataBuildingContext context,
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
MemberDetails property,
AnnotatedColumns columns,
ClassDetails returnedClass,
boolean isId,
PropertyData mapsIdProperty) {
// careful: not always a @MapsId property, sometimes it's from an @IdClass
final String propertyName = mapsIdProperty.getPropertyName();
final var actualColumns = new AnnotatedJoinColumns();
actualColumns.setBuildingContext( context );
actualColumns.setPropertyHolder( propertyHolder );
actualColumns.setPropertyName( getRelativePath( propertyHolder, propertyName ) );
//TODO: resetting the parent here looks like a dangerous thing to do
// should we be cloning them first (the legacy code did not)
for ( AnnotatedColumn column : columns.getColumns() ) {
column.setParent( actualColumns );
}
return bindOverriddenEmbeddable(
inferredData,
propertyHolder,
isIdentifierMapper,
context,
isComponentEmbedded,
isId,
inheritanceStatePerClass,
mapsIdProperty.getClassOrElementName(),
propertyName,
determineCustomInstantiator( property, returnedClass, context ),
actualColumns
);
}
static boolean isEmbedded(MemberDetails memberDetails, ClassDetails returnedClass) {
return memberDetails.hasDirectAnnotationUsage( Embedded.class )
|| memberDetails.hasDirectAnnotationUsage( EmbeddedId.class )
|| returnedClass.hasDirectAnnotationUsage( Embeddable.class )
&& !memberDetails.hasDirectAnnotationUsage( Convert.class );
}
static boolean isEmbedded(MemberDetails memberDetails, TypeDetails returnedClass) {
if ( memberDetails.hasDirectAnnotationUsage( Embedded.class )
|| memberDetails.hasDirectAnnotationUsage( EmbeddedId.class ) ) {
return true;
}
else {
final var returnClassDetails = returnedClass.determineRawClass();
return returnClassDetails.hasDirectAnnotationUsage( Embeddable.class )
&& !memberDetails.hasDirectAnnotationUsage( Convert.class );
}
}
private static Component bindOverriddenEmbeddable(
PropertyData inferredData,
PropertyHolder propertyHolder,
boolean isIdentifierMapper,
MetadataBuildingContext context,
boolean isComponentEmbedded,
boolean isId, // is an identifier
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
String referencedEntityName, // is a embeddable which is overridden by a @MapsId
String propertyName,
Class<? extends EmbeddableInstantiator> customInstantiatorImpl,
AnnotatedJoinColumns annotatedJoinColumns) {
final var embeddable = createEmbeddable(
propertyHolder,
inferredData,
isComponentEmbedded,
isIdentifierMapper,
customInstantiatorImpl,
context
);
context.getMetadataCollector()
.addSecondPass( new CopyIdentifierComponentSecondPass(
embeddable,
referencedEntityName,
propertyName,
annotatedJoinColumns,
context
) );
if ( isId ) {
embeddable.setKey( true );
checkEmbeddedId( inferredData, propertyHolder, referencedEntityName, embeddable );
}
callTypeBinders( embeddable, context, inferredData.getPropertyType() );
return embeddable;
}
static Component bindEmbeddable(
PropertyData inferredData,
PropertyHolder propertyHolder,
AccessType propertyAccessor,
EntityBinder entityBinder,
boolean isIdentifierMapper,
MetadataBuildingContext context,
boolean isComponentEmbedded,
boolean isId, //is an identifier
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
Class<? extends EmbeddableInstantiator> customInstantiatorImpl,
Class<? extends CompositeUserType<?>> compositeUserTypeClass,
AnnotatedColumns annotatedColumns) {
final var embeddable = fillEmbeddable(
propertyHolder,
inferredData,
propertyAccessor,
!isId,
entityBinder,
isComponentEmbedded,
isIdentifierMapper,
context.getMetadataCollector().isInSecondPass(),
customInstantiatorImpl,
compositeUserTypeClass,
annotatedColumns,
context,
inheritanceStatePerClass
);
if ( isId ) {
embeddable.setKey( true );
checkEmbeddedId( inferredData, propertyHolder, null, embeddable );
}
callTypeBinders( embeddable, context, inferredData.getPropertyType() );
return embeddable;
}
private static void callTypeBinders(Component embeddable, MetadataBuildingContext context, TypeDetails annotatedClass ) {
final var metaAnnotatedAnnotations =
annotatedClass.determineRawClass()
.getMetaAnnotated( TypeBinderType.class,
context.getBootstrapContext().getModelsContext() );
for ( var metaAnnotated : metaAnnotatedAnnotations ) {
final var binderType = metaAnnotated.annotationType().getAnnotation( TypeBinderType.class );
try {
//noinspection rawtypes
final TypeBinder binder = binderType.binder().getDeclaredConstructor().newInstance();
//noinspection unchecked
binder.bind( metaAnnotated, context, embeddable );
}
catch (Exception e) {
throw new AnnotationException(
"error processing @TypeBinderType annotation '" + metaAnnotated + "'", e );
}
}
}
private static PropertyBinder createEmbeddedProperty(
PropertyData inferredData,
PropertyHolder propertyHolder,
EntityBinder entityBinder,
MetadataBuildingContext context,
boolean isComponentEmbedded,
boolean isId,
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
Component embeddable) {
final var binder = new PropertyBinder();
binder.setDeclaringClass( inferredData.getDeclaringClass() );
binder.setName( inferredData.getPropertyName() );
binder.setValue( embeddable );
binder.setMemberDetails( inferredData.getAttributeMember() );
binder.setAccessType( inferredData.getDefaultAccess() );
binder.setEmbedded( isComponentEmbedded );
binder.setHolder( propertyHolder );
binder.setId( isId );
binder.setEntityBinder( entityBinder );
binder.setInheritanceStatePerClass( inheritanceStatePerClass );
binder.setBuildingContext( context );
binder.makePropertyAndBind();
return binder;
}
private static void checkEmbeddedId(
PropertyData inferredData,
PropertyHolder propertyHolder,
String referencedEntityName,
Component embeddable) {
if ( propertyHolder.getPersistentClass().getIdentifier() != null ) {
throw new AnnotationException(
"Embeddable class '" + embeddable.getComponentClassName()
+ "' may not have a property annotated '@Id' since it is used by '"
+ getPath(propertyHolder, inferredData)
+ "' as an '@EmbeddedId'"
);
}
if ( referencedEntityName == null && embeddable.getPropertySpan() == 0 ) {
throw new AnnotationException(
"Embeddable class '" + embeddable.getComponentClassName()
+ "' may not be used as an '@EmbeddedId' by '"
+ getPath(propertyHolder, inferredData)
+ "' because it has no properties"
);
}
}
static Component fillEmbeddable(
PropertyHolder propertyHolder,
PropertyData inferredData,
AccessType propertyAccessor,
boolean isNullable,
EntityBinder entityBinder,
boolean isComponentEmbedded,
boolean isIdentifierMapper,
boolean inSecondPass,
Class<? extends EmbeddableInstantiator> customInstantiatorImpl,
Class<? extends CompositeUserType<?>> compositeUserTypeClass,
AnnotatedColumns columns,
MetadataBuildingContext context,
Map<ClassDetails, InheritanceState> inheritanceStatePerClass) {
return fillEmbeddable(
propertyHolder,
inferredData,
null,
propertyAccessor,
null,
isNullable,
entityBinder,
isComponentEmbedded,
isIdentifierMapper,
inSecondPass,
customInstantiatorImpl,
compositeUserTypeClass,
columns,
context,
inheritanceStatePerClass,
false
);
}
static Component fillEmbeddable(
PropertyHolder propertyHolder,
PropertyData inferredData,
PropertyData baseInferredData, //base inferred data correspond to the entity reproducing inferredData's properties (ie IdClass)
AccessType propertyAccessor,
ClassDetails entityAtStake,
boolean isNullable,
EntityBinder entityBinder,
boolean isComponentEmbedded,
boolean isIdentifierMapper,
boolean inSecondPass,
Class<? extends EmbeddableInstantiator> customInstantiatorImpl,
Class<? extends CompositeUserType<?>> compositeUserTypeClass,
AnnotatedColumns columns,
MetadataBuildingContext context,
Map<ClassDetails, InheritanceState> inheritanceStatePerClass,
boolean isIdClass) {
// inSecondPass can only be used to apply right away the second pass of a composite-element
// Because it's a value type, there is no bidirectional association, hence second pass
// ordering does not matter
final var embeddable = createEmbeddable(
propertyHolder,
inferredData,
isComponentEmbedded,
isIdentifierMapper,
customInstantiatorImpl,
context
);
final String subpath = getPath( propertyHolder, inferredData );
BOOT_LOGGER.bindingEmbeddable( subpath );
final var subholder = buildPropertyHolder(
embeddable,
subpath,
inferredData,
propertyHolder,
context,
inheritanceStatePerClass
);
// propertyHolder here is the owner of the embeddable property.
// Tell it we are about to start the embeddable...
propertyHolder.startingProperty( inferredData.getAttributeMember() );
final CompositeUserType<?> compositeUserType;
final ClassDetails returnedClassOrElement;
if ( compositeUserTypeClass == null ) {
compositeUserType = null;
returnedClassOrElement = inferredData.getClassOrElementType().determineRawClass();
}
else {
compositeUserType = compositeUserType( compositeUserTypeClass, context );
embeddable.setTypeName( compositeUserTypeClass.getName() );
returnedClassOrElement = context.getBootstrapContext().getModelsContext().getClassDetailsRegistry().resolveClassDetails( compositeUserType.embeddable().getName() );
}
processAggregate(
embeddable,
propertyHolder,
inferredData,
returnedClassOrElement,
columns,
context
);
final var inheritanceState = inheritanceStatePerClass.get( returnedClassOrElement );
if ( inheritanceState != null ) {
inheritanceState.postProcess( embeddable );
// Main entry point for binding embeddable inheritance
bindDiscriminator(
embeddable,
returnedClassOrElement,
propertyHolder,
subholder,
inferredData,
inheritanceState,
context
);
}
final var annotatedTypeDetails = inferredData.getPropertyType();
final Map<String, String> subclassToSuperclass =
embeddable.isPolymorphic() ? new HashMap<>() : null;
final var classElements = collectClassElements(
propertyAccessor,
context,
returnedClassOrElement,
annotatedTypeDetails,
isIdClass,
subclassToSuperclass
);
if ( embeddable.isPolymorphic() ) {
validateInheritanceIsSupported( subholder, compositeUserType );
final var discriminatorType = (BasicType<?>) embeddable.getDiscriminator().getType();
// Discriminator values are used to construct the embeddable domain
// type hierarchy so order of processing is important
final Map<Object, String> discriminatorValues = new LinkedHashMap<>();
collectDiscriminatorValue( returnedClassOrElement, discriminatorType, discriminatorValues );
collectSubclassElements(
propertyAccessor,
context,
returnedClassOrElement,
classElements,
discriminatorType,
discriminatorValues,
subclassToSuperclass
);
embeddable.setDiscriminatorValues( discriminatorValues );
embeddable.setSubclassToSuperclass( subclassToSuperclass );
}
final var baseClassElements =
collectBaseClassElements( baseInferredData, propertyAccessor, context, entityAtStake );
if ( baseClassElements != null
//useful to avoid breaking pre JPA 2 mappings
&& !hasAnnotationsOnIdClass( annotatedTypeDetails ) ) {
processIdClassElements( propertyHolder, baseInferredData, classElements, baseClassElements );
}
for ( var propertyAnnotatedElement : classElements ) {
processElementAnnotations(
subholder,
entityBinder.getPersistentClass() instanceof SingleTableSubclass
// subclasses in single table inheritance can't have not null constraints
? Nullability.FORCED_NULL
: ( isNullable ? Nullability.NO_CONSTRAINT : Nullability.FORCED_NOT_NULL ),
propertyAnnotatedElement,
entityBinder,
isIdentifierMapper,
isComponentEmbedded,
inSecondPass,
context,
inheritanceStatePerClass
);
processGeneratorAnnotations(
propertyHolder,
inferredData,
isIdClass,
propertyAnnotatedElement,
subholder,
embeddable,
context
);
}
if ( compositeUserType != null ) {
processCompositeUserType( embeddable, compositeUserType );
}
return embeddable;
}
private static void processGeneratorAnnotations(
PropertyHolder propertyHolder, PropertyData inferredData,
boolean isIdClass,
PropertyData propertyAnnotatedElement, PropertyHolder subholder,
Component embeddable,
MetadataBuildingContext context) {
final var memberDetails = propertyAnnotatedElement.getAttributeMember();
if ( isIdClass || subholder.isOrWithinEmbeddedId() ) {
final var property = findProperty( embeddable, memberDetails.getName() );
if ( property != null ) {
// Identifier properties are always simple values
final var value = (SimpleValue) property.getValue();
createIdGeneratorsFromGeneratorAnnotations(
subholder,
propertyAnnotatedElement,
value,
context
);
}
}
else if ( memberDetails.hasDirectAnnotationUsage( GeneratedValue.class ) ) {
throw new AnnotationException(
"Property '" + memberDetails.getName() + "' of '"
+ getPath( propertyHolder, inferredData )
+ "' is annotated '@GeneratedValue' but is not part of an identifier" );
}
}
private static Property findProperty(Component embeddable, String name) {
for ( var property : embeddable.getProperties() ) {
if ( property.getName().equals( name ) ) {
return property;
}
}
return null;
}
private static CompositeUserType<?> compositeUserType(
Class<? extends CompositeUserType<?>> compositeUserTypeClass,
MetadataBuildingContext context) {
if ( !context.getBuildingOptions().isAllowExtensionsInCdi() ) {
FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( compositeUserTypeClass );
}
return context.getBootstrapContext().getManagedBeanRegistry()
.getBean( compositeUserTypeClass )
.getBeanInstance();
}
private static void bindDiscriminator(
Component embeddable,
ClassDetails componentClass,
PropertyHolder parentHolder,
PropertyHolder holder,
PropertyData propertyData,
InheritanceState inheritanceState,
MetadataBuildingContext context) {
if ( inheritanceState != null ) {
final var discriminatorColumn = processEmbeddableDiscriminatorProperties(
componentClass,
propertyData,
parentHolder,
holder,
inheritanceState,
context
);
if ( discriminatorColumn != null ) {
bindDiscriminatorColumnToComponent( embeddable, discriminatorColumn, holder, context );
}
}
}
private static AnnotatedDiscriminatorColumn processEmbeddableDiscriminatorProperties(
ClassDetails classDetails,
PropertyData propertyData,
PropertyHolder parentHolder,
PropertyHolder holder,
InheritanceState inheritanceState,
MetadataBuildingContext context) {
final var discriminatorColumn = classDetails.getDirectAnnotationUsage( DiscriminatorColumn.class );
final var discriminatorFormula = getOverridableAnnotation( classDetails, DiscriminatorFormula.class, context );
if ( !inheritanceState.hasParents() ) {
if ( inheritanceState.hasSiblings() ) {
final String path = qualify( holder.getPath(), EntityDiscriminatorMapping.DISCRIMINATOR_ROLE_NAME );
final String columnPrefix;
final Column[] overrides;
if ( holder.isWithinElementCollection() ) {
columnPrefix = unqualify( parentHolder.getPath() );
overrides = parentHolder.getOverriddenColumn( path );
}
else {
columnPrefix = propertyData.getPropertyName();
overrides = holder.getOverriddenColumn( path );
}
return buildDiscriminatorColumn(
discriminatorColumn,
discriminatorFormula,
overrides == null ? null : overrides[0],
columnPrefix + "_" + DEFAULT_DISCRIMINATOR_COLUMN_NAME,
context
);
}
}
else {
// not a root entity
if ( discriminatorColumn != null ) {
throw new AnnotationException( String.format(
"Embeddable class '%s' is annotated '@DiscriminatorColumn' but it is not the root of the inheritance hierarchy",
classDetails.getName()
) );
}
if ( discriminatorFormula != null ) {
throw new AnnotationException( String.format(
"Embeddable class '%s' is annotated '@DiscriminatorFormula' but it is not the root of the inheritance hierarchy",
classDetails.getName()
) );
}
}
return null;
}
private static void bindDiscriminatorColumnToComponent(
Component embeddable,
AnnotatedDiscriminatorColumn discriminatorColumn,
PropertyHolder holder,
MetadataBuildingContext context) {
assert embeddable.getDiscriminator() == null;
final var columns = new AnnotatedColumns();
columns.setPropertyHolder( holder );
columns.setBuildingContext( context );
discriminatorColumn.setParent( columns );
final var discriminatorColumnBinding = new BasicValue( context, embeddable.getTable() );
discriminatorColumnBinding.setAggregateColumn( embeddable.getAggregateColumn() );
embeddable.setDiscriminator( discriminatorColumnBinding );
discriminatorColumn.linkWithValue( discriminatorColumnBinding );
discriminatorColumnBinding.setTypeName( discriminatorColumn.getDiscriminatorTypeName() );
}
private static void validateInheritanceIsSupported(
PropertyHolder holder,
CompositeUserType<?> compositeUserType) {
if ( holder.isOrWithinEmbeddedId() ) {
throw new AnnotationException( String.format(
"Embeddable class '%s' defines an inheritance hierarchy and cannot be used in an '@EmbeddedId'",
holder.getClassName()
) );
}
else if ( holder.isInIdClass() ) {
throw new AnnotationException( String.format(
"Embeddable class '%s' defines an inheritance hierarchy and cannot be used in an '@IdClass'",
holder.getClassName()
) );
}
else if ( compositeUserType != null ) {
throw new AnnotationException( String.format(
"Embeddable class '%s' defines an inheritance hierarchy and cannot be used with a custom '@CompositeType'",
holder.getClassName()
) );
}
}
private static List<PropertyData> collectClassElements(
AccessType propertyAccessor,
MetadataBuildingContext context,
ClassDetails returnedClassOrElement,
TypeDetails annotatedClass,
boolean isIdClass,
Map<String, String> subclassToSuperclass) {
final List<PropertyData> classElements = new ArrayList<>();
//embeddable elements can have type defs
final var container = new PropertyContainer( returnedClassOrElement, annotatedClass, propertyAccessor );
addElementsOfClass( classElements, container, context, 0 );
//add elements of the embeddable's mapped superclasses
ClassDetails subclass = returnedClassOrElement;
ClassDetails superClass;
while ( isValidSuperclass( superClass = subclass.getSuperClass(), isIdClass ) ) {
//FIXME: proper support of type variables incl var resolved at upper levels
final var superContainer = new PropertyContainer( superClass, annotatedClass, propertyAccessor );
addElementsOfClass( classElements, superContainer, context, 0 );
if ( subclassToSuperclass != null ) {
subclassToSuperclass.put( subclass.getName(), superClass.getName() );
}
subclass = superClass;
}
return classElements;
}
private static void collectSubclassElements(
AccessType propertyAccessor,
MetadataBuildingContext context,
ClassDetails superclass,
List<PropertyData> classElements,
BasicType<?> discriminatorType,
Map<Object, String> discriminatorValues,
Map<String, String> subclassToSuperclass) {
for ( var subclass : context.getMetadataCollector().getEmbeddableSubclasses( superclass ) ) {
// collect the discriminator value details
final String old = collectDiscriminatorValue( subclass, discriminatorType, discriminatorValues );
if ( old != null ) {
throw new AnnotationException( String.format(
"Embeddable subclass '%s' defines the same discriminator value as '%s",
subclass.getName(),
old
) );
}
final String put = subclassToSuperclass.put( subclass.getName().intern(), superclass.getName().intern() );
assert put == null;
// collect property of subclass
final var superContainer = new PropertyContainer( subclass, superclass, propertyAccessor );
addElementsOfClass( classElements, superContainer, context, 0 );
// recursively do that same for all subclasses
collectSubclassElements(
propertyAccessor,
context,
subclass,
classElements,
discriminatorType,
discriminatorValues,
subclassToSuperclass
);
}
}
private static String collectDiscriminatorValue(
ClassDetails annotatedClass,
BasicType<?> discriminatorType,
Map<Object, String> discriminatorValues) {
return discriminatorValues.put(
discriminatorType.getJavaTypeDescriptor()
.fromString( discriminatorValue( annotatedClass, discriminatorType ) ),
annotatedClass.getName().intern()
);
}
private static String discriminatorValue(ClassDetails annotatedClass, BasicType<?> discriminatorType) {
final String explicitValue =
annotatedClass.hasDirectAnnotationUsage( DiscriminatorValue.class )
? annotatedClass.getDirectAnnotationUsage( DiscriminatorValue.class ).value()
: null;
if ( isBlank( explicitValue ) ) {
final String name = unqualify( annotatedClass.getName() );
return switch ( discriminatorType.getName() ) {
case "character" ->
throw new AnnotationException( "Embeddable '" + name
+ "' has a discriminator of character type and must specify its '@DiscriminatorValue'" );
case "integer" -> String.valueOf( name.hashCode() );
default -> name;
};
}
else {
return explicitValue;
}
}
private static boolean isValidSuperclass(ClassDetails superClass, boolean isIdClass) {
if ( superClass == null ) {
return false;
}
else if ( superClass.hasDirectAnnotationUsage( MappedSuperclass.class ) ) {
return true;
}
else if ( isIdClass ) {
final String superClassName = superClass.getName();
return !superClassName.equals( OBJECT_CLASS_NAME )
&& !superClassName.equals( RECORD_CLASS_NAME );
}
else {
return false;
}
}
private static List<PropertyData> collectBaseClassElements(
PropertyData baseInferredData,
AccessType propertyAccessor,
MetadataBuildingContext context,
ClassDetails entityAtStake) {
if ( baseInferredData != null ) {
final List<PropertyData> baseClassElements = new ArrayList<>();
// iterate from base returned | EmbeddableBinder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/ondeletecascade/OnDeleteManyToManyTest.java | {
"start": 1059,
"end": 2436
} | class ____ {
@Test void test(EntityManagerFactoryScope scope) {
var inspector = scope.getCollectingStatementInspector();
scope.inTransaction( em -> {
B b = new B();
b.id = 1;
em.persist( b );
A a = new A();
a.id = 2;
a.bs.add( b );
em.persist( a );
} );
inspector.assertExecutedCount( 3 );
inspector.clear();
scope.inTransaction( em -> {
A a = em.find( A.class, 2L );
inspector.assertExecutedCount( 1 );
assertEquals( 1, a.bs.size() );
inspector.assertExecutedCount( 2 );
assertTrue( Hibernate.isInitialized( a.bs ) );
} );
inspector.clear();
scope.inTransaction( em -> {
A a = em.find( A.class, 2L );
inspector.assertExecutedCount( 1 );
em.remove( a );
assertFalse( Hibernate.isInitialized( a.bs ) );
} );
inspector.assertExecutedCount( scope.getDialect().supportsCascadeDelete() ? 2 : 3 );
scope.inTransaction( em -> {
assertEquals( 1,
em.createNativeQuery( "select count(*) from B", Integer.class )
.getSingleResultOrNull() );
assertEquals( 0,
em.createNativeQuery( "select count(*) from A_B", Integer.class )
.getSingleResultOrNull() );
assertEquals( 0,
em.createNativeQuery( "select count(*) from A", Integer.class )
.getSingleResultOrNull() );
});
}
@Entity(name = "A")
@Inheritance(strategy = InheritanceType.JOINED)
static | OnDeleteManyToManyTest |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/launcher/MethodFilterTests.java | {
"start": 7179,
"end": 7321
} | class ____ {
@Test
void test1() {
}
@Test
void test2() {
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
private static | Class1 |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/table/FunctionITCase.java | {
"start": 1844,
"end": 5377
} | class ____ extends StreamingTestBase {
@Test
void testScalarFunction() throws Exception {
final List<Row> sourceData =
Arrays.asList(Row.of(1, 1L, 1L), Row.of(2, 2L, 1L), Row.of(3, 3L, 1L));
final List<Row> sinkData =
Arrays.asList(Row.of(1, 2L, 1L), Row.of(2, 4L, 1L), Row.of(3, 6L, 1L));
TestCollectionTableFactory.reset();
TestCollectionTableFactory.initData(sourceData);
tEnv().executeSql(
"CREATE TABLE TestTable(a INT, b BIGINT, c BIGINT) WITH ('connector' = 'COLLECTION')");
final Table table =
tEnv().from("TestTable")
.select(
$("a"),
call(new SimpleScalarFunction(), $("a"), $("b")),
call(new SimpleScalarFunction(), $("a"), $("b"))
.plus(1)
.minus(call(new SimpleScalarFunction(), $("a"), $("b"))));
table.executeInsert("TestTable").await();
assertThat(TestCollectionTableFactory.getResult()).isEqualTo(sinkData);
}
@Test
void testJoinWithTableFunction() throws Exception {
final List<Row> sourceData =
Arrays.asList(
Row.of("1,2,3"), Row.of("2,3,4"), Row.of("3,4,5"), Row.of((String) null));
final List<Row> sinkData =
Arrays.asList(
Row.of("1,2,3", new String[] {"1", "2", "3"}),
Row.of("2,3,4", new String[] {"2", "3", "4"}),
Row.of("3,4,5", new String[] {"3", "4", "5"}));
TestCollectionTableFactory.reset();
TestCollectionTableFactory.initData(sourceData);
tEnv().executeSql("CREATE TABLE SourceTable(s STRING) WITH ('connector' = 'COLLECTION')");
tEnv().executeSql(
"CREATE TABLE SinkTable(s STRING, sa ARRAY<STRING>) WITH ('connector' = 'COLLECTION')");
tEnv().from("SourceTable")
.joinLateral(call(new SimpleTableFunction(), $("s")).as("a", "b"))
.select($("a"), $("b"))
.executeInsert("SinkTable")
.await();
assertThat(TestCollectionTableFactory.getResult()).isEqualTo(sinkData);
}
@Test
void testLateralJoinWithScalarFunction() throws Exception {
TestCollectionTableFactory.reset();
tEnv().executeSql("CREATE TABLE SourceTable(s STRING) WITH ('connector' = 'COLLECTION')");
tEnv().executeSql(
"CREATE TABLE SinkTable(s STRING, sa ARRAY<STRING>) WITH ('connector' = 'COLLECTION')");
assertThatThrownBy(
() -> {
tEnv().from("SourceTable")
.joinLateral(
call(new RowScalarFunction(), $("s")).as("a", "b"));
})
.satisfies(
anyCauseMatches(
ValidationException.class,
"A lateral join only accepts an expression which defines a table function"));
}
// --------------------------------------------------------------------------------------------
// Test functions
// --------------------------------------------------------------------------------------------
/** Simple scalar function. */
public static | FunctionITCase |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.