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-docs/src/main/java/org/apache/flink/docs/configuration/ConfigOptionsDocGenerator.java | {
"start": 21594,
"end": 26135
} | enum ____ {@link DescribedEnum}, this includes the given description for each
* constant. Otherwise, only the constant itself is printed.
*/
private static List<InlineElement> formatEnumOption(Object e) {
final List<InlineElement> elements = new LinkedList<>();
elements.add(text("\"%s\"", text(escapeCharacters(e.toString()))));
if (DescribedEnum.class.isAssignableFrom(e.getClass())) {
elements.add(text(": "));
elements.add(((DescribedEnum) e).getDescription());
}
return elements;
}
private static Class<?> getClazz(ConfigOption<?> option) {
try {
Method getClazzMethod = ConfigOption.class.getDeclaredMethod("getClazz");
getClazzMethod.setAccessible(true);
Class clazz = (Class) getClazzMethod.invoke(option);
getClazzMethod.setAccessible(false);
return clazz;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static boolean isList(ConfigOption<?> option) {
try {
Method getClazzMethod = ConfigOption.class.getDeclaredMethod("isList");
getClazzMethod.setAccessible(true);
boolean isList = (boolean) getClazzMethod.invoke(option);
getClazzMethod.setAccessible(false);
return isList;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@VisibleForTesting
static String typeToHtml(OptionWithMetaInfo optionWithMetaInfo) {
ConfigOption<?> option = optionWithMetaInfo.option;
Class<?> clazz = getClazz(option);
boolean isList = isList(option);
if (clazz.isEnum()) {
return enumTypeToHtml(isList);
}
return atomicTypeToHtml(clazz, isList);
}
private static String atomicTypeToHtml(Class<?> clazz, boolean isList) {
String typeName = clazz.getSimpleName();
final String type;
if (isList) {
type = String.format("List<%s>", typeName);
} else {
type = typeName;
}
return escapeCharacters(type);
}
private static String enumTypeToHtml(boolean isList) {
final String type;
if (isList) {
type = "List<Enum>";
} else {
type = "Enum";
}
return String.format("<p>%s</p>", escapeCharacters(type));
}
@VisibleForTesting
static String stringifyDefault(OptionWithMetaInfo optionWithMetaInfo) {
ConfigOption<?> option = optionWithMetaInfo.option;
Documentation.OverrideDefault overrideDocumentedDefault =
optionWithMetaInfo.field.getAnnotation(Documentation.OverrideDefault.class);
if (overrideDocumentedDefault != null) {
return overrideDocumentedDefault.value();
} else {
Object value = option.defaultValue();
return stringifyObject(value);
}
}
@SuppressWarnings("unchecked")
private static String stringifyObject(Object value) {
if (value instanceof String) {
if (((String) value).isEmpty()) {
return "(none)";
}
return "\"" + value + "\"";
} else if (value instanceof Duration) {
return TimeUtils.formatWithHighestUnit((Duration) value);
} else if (value instanceof List) {
return ((List<Object>) value)
.stream()
.map(ConfigOptionsDocGenerator::stringifyObject)
.collect(Collectors.joining(";"));
} else if (value instanceof Map) {
return ((Map<String, String>) value)
.entrySet().stream()
.map(e -> String.format("%s:%s", e.getKey(), e.getValue()))
.collect(Collectors.joining(","));
}
return value == null ? "(none)" : value.toString();
}
private static String addWordBreakOpportunities(String value) {
return value
// allow breaking of semicolon separated lists
.replace(";", ";<wbr>");
}
private static void sortOptions(List<OptionWithMetaInfo> configOptions) {
configOptions.sort(Comparator.comparing(option -> getDocumentedKey(option)));
}
/**
* Data structure used to assign {@link ConfigOption ConfigOptions} to the {@link ConfigGroup}
* with the longest matching prefix.
*/
private static | implements |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/score/DecayCartesianPointEvaluator.java | {
"start": 4949,
"end": 6178
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory value;
private final BytesRef origin;
private final double scale;
private final double offset;
private final double decay;
private final Decay.DecayFunction decayFunction;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory value, BytesRef origin,
double scale, double offset, double decay, Decay.DecayFunction decayFunction) {
this.source = source;
this.value = value;
this.origin = origin;
this.scale = scale;
this.offset = offset;
this.decay = decay;
this.decayFunction = decayFunction;
}
@Override
public DecayCartesianPointEvaluator get(DriverContext context) {
return new DecayCartesianPointEvaluator(source, value.get(context), origin, scale, offset, decay, decayFunction, context);
}
@Override
public String toString() {
return "DecayCartesianPointEvaluator[" + "value=" + value + ", origin=" + origin + ", scale=" + scale + ", offset=" + offset + ", decay=" + decay + ", decayFunction=" + decayFunction + "]";
}
}
}
| Factory |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/core/Flowable.java | {
"start": 7594,
"end": 12176
} | class ____<@NonNull T> implements Publisher<T> {
/** The default buffer size. */
static final int BUFFER_SIZE;
static {
BUFFER_SIZE = Math.max(1, Integer.getInteger("rx3.buffer-size", 128));
}
/**
* Mirrors the one {@link Publisher} in an {@link Iterable} of several {@code Publisher}s that first either emits an item or sends
* a termination notification.
* <p>
* <img width="640" height="417" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.amb.png" alt="">
* <p>
* When one of the {@code Publisher}s signal an item or terminates first, all subscriptions to the other
* {@code Publisher}s are canceled.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator itself doesn't interfere with backpressure which is determined by the winning
* {@code Publisher}'s backpressure behavior.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>
* If any of the losing {@code Publisher}s signals an error, the error is routed to the global
* error handler via {@link RxJavaPlugins#onError(Throwable)}.
* </dd>
* </dl>
*
* @param <T> the common element type
* @param sources
* an {@code Iterable} of {@code Publisher}s sources competing to react first. A subscription to each {@code Publisher} will
* occur in the same order as in this {@code Iterable}.
* @return the new {@code Flowable} instance
* @throws NullPointerException if {@code sources} is {@code null}
* @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a>
*/
@CheckReturnValue
@NonNull
@BackpressureSupport(BackpressureKind.PASS_THROUGH)
@SchedulerSupport(SchedulerSupport.NONE)
public static <@NonNull T> Flowable<T> amb(@NonNull Iterable<@NonNull ? extends Publisher<? extends T>> sources) {
Objects.requireNonNull(sources, "sources is null");
return RxJavaPlugins.onAssembly(new FlowableAmb<>(null, sources));
}
/**
* Mirrors the one {@link Publisher} in an array of several {@code Publisher}s that first either emits an item or sends
* a termination notification.
* <p>
* <img width="640" height="417" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.ambArray.png" alt="">
* <p>
* When one of the {@code Publisher}s signal an item or terminates first, all subscriptions to the other
* {@code Publisher}s are canceled.
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The operator itself doesn't interfere with backpressure which is determined by the winning
* {@code Publisher}'s backpressure behavior.</dd>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd>
* <dt><b>Error handling:</b></dt>
* <dd>
* If any of the losing {@code Publisher}s signals an error, the error is routed to the global
* error handler via {@link RxJavaPlugins#onError(Throwable)}.
* </dd>
* </dl>
*
* @param <T> the common element type
* @param sources
* an array of {@code Publisher} sources competing to react first. A subscription to each {@code Publisher} will
* occur in the same order as in this array.
* @return the new {@code Flowable} instance
* @throws NullPointerException if {@code sources} is {@code null}
* @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a>
*/
@CheckReturnValue
@NonNull
@BackpressureSupport(BackpressureKind.PASS_THROUGH)
@SchedulerSupport(SchedulerSupport.NONE)
@SafeVarargs
public static <@NonNull T> Flowable<T> ambArray(@NonNull Publisher<? extends T>... sources) {
Objects.requireNonNull(sources, "sources is null");
int len = sources.length;
if (len == 0) {
return empty();
} else
if (len == 1) {
return fromPublisher(sources[0]);
}
return RxJavaPlugins.onAssembly(new FlowableAmb<>(sources, null));
}
/**
* Returns the default internal buffer size used by most async operators.
* <p>The value can be overridden via system parameter {@code rx3.buffer-size}
* <em>before</em> the {@code Flowable} | Flowable |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/pc/CascadeOnDeleteCollectionTest.java | {
"start": 2662,
"end": 3406
} | class ____ {
@Id
private Long id;
@Column(name = "`number`")
private String number;
@ManyToOne(fetch = FetchType.LAZY)
private Person owner;
//Getters and setters are omitted for brevity
//end::pc-cascade-on-delete-collection-mapping-Phone-example[]
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = owner;
}
//tag::pc-cascade-on-delete-collection-mapping-Phone-example[]
}
//end::pc-cascade-on-delete-collection-mapping-Phone-example[]
}
| Phone |
java | spring-projects__spring-framework | spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/aot/scan/reflective/ReflectiveOnConstructor.java | {
"start": 799,
"end": 1068
} | class ____ {
private final String name;
public ReflectiveOnConstructor(String name) {
this.name = name;
}
@Reflective
public ReflectiveOnConstructor(String firstName, String lastName) {
this("%s %s".formatted(firstName, lastName));
}
}
| ReflectiveOnConstructor |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/EndpointToIdRefTest.java | {
"start": 1029,
"end": 1513
} | class ____ extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/EndpointToIdRefTest.xml");
}
@Test
public void testEndpoint() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
}
| EndpointToIdRefTest |
java | netty__netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketSslClientRenegotiateTest.java | {
"start": 9358,
"end": 10926
} | class ____ extends SimpleChannelInboundHandler<ByteBuf> {
protected final AtomicReference<Throwable> exception;
private int handshakeCounter;
TestHandler(AtomicReference<Throwable> exception) {
this.exception = exception;
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
exception.compareAndSet(null, cause);
ctx.close();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent) {
SslHandshakeCompletionEvent handshakeEvt = (SslHandshakeCompletionEvent) evt;
if (handshakeCounter == 0) {
handshakeCounter++;
if (handshakeEvt.cause() != null) {
logger.warn("Handshake failed:", handshakeEvt.cause());
}
assertSame(SslHandshakeCompletionEvent.SUCCESS, evt);
} else {
if (ctx.channel().parent() == null) {
assertTrue(handshakeEvt.cause() instanceof ClosedChannelException);
}
}
}
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception { }
}
}
| TestHandler |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java | {
"start": 11223,
"end": 11379
} | class ____ {
@Bean
ImportedBean importedBean() {
return new ImportedBean("from class");
}
}
@Import(ImportedConfig.class)
| OverridingImportedConfig |
java | elastic__elasticsearch | libs/h3/src/main/java/org/elasticsearch/h3/HexRing.java | {
"start": 1074,
"end": 17931
} | class ____ {
private static final int INVALID_BASE_CELL = 127;
/** Neighboring base cell ID in each IJK direction.
*
* For each base cell, for each direction, the neighboring base
* cell ID is given. 127 indicates there is no neighbor in that direction.
*/
private static final int[][] baseCellNeighbors = new int[][] {
{ 0, 1, 5, 2, 4, 3, 8 }, // base cell 0
{ 1, 7, 6, 9, 0, 3, 2 }, // base cell 1
{ 2, 6, 10, 11, 0, 1, 5 }, // base cell 2
{ 3, 13, 1, 7, 4, 12, 0 }, // base cell 3
{ 4, INVALID_BASE_CELL, 15, 8, 3, 0, 12 }, // base cell 4 (pentagon)
{ 5, 2, 18, 10, 8, 0, 16 }, // base cell 5
{ 6, 14, 11, 17, 1, 9, 2 }, // base cell 6
{ 7, 21, 9, 19, 3, 13, 1 }, // base cell 7
{ 8, 5, 22, 16, 4, 0, 15 }, // base cell 8
{ 9, 19, 14, 20, 1, 7, 6 }, // base cell 9
{ 10, 11, 24, 23, 5, 2, 18 }, // base cell 10
{ 11, 17, 23, 25, 2, 6, 10 }, // base cell 11
{ 12, 28, 13, 26, 4, 15, 3 }, // base cell 12
{ 13, 26, 21, 29, 3, 12, 7 }, // base cell 13
{ 14, INVALID_BASE_CELL, 17, 27, 9, 20, 6 }, // base cell 14 (pentagon)
{ 15, 22, 28, 31, 4, 8, 12 }, // base cell 15
{ 16, 18, 33, 30, 8, 5, 22 }, // base cell 16
{ 17, 11, 14, 6, 35, 25, 27 }, // base cell 17
{ 18, 24, 30, 32, 5, 10, 16 }, // base cell 18
{ 19, 34, 20, 36, 7, 21, 9 }, // base cell 19
{ 20, 14, 19, 9, 40, 27, 36 }, // base cell 20
{ 21, 38, 19, 34, 13, 29, 7 }, // base cell 21
{ 22, 16, 41, 33, 15, 8, 31 }, // base cell 22
{ 23, 24, 11, 10, 39, 37, 25 }, // base cell 23
{ 24, INVALID_BASE_CELL, 32, 37, 10, 23, 18 }, // base cell 24 (pentagon)
{ 25, 23, 17, 11, 45, 39, 35 }, // base cell 25
{ 26, 42, 29, 43, 12, 28, 13 }, // base cell 26
{ 27, 40, 35, 46, 14, 20, 17 }, // base cell 27
{ 28, 31, 42, 44, 12, 15, 26 }, // base cell 28
{ 29, 43, 38, 47, 13, 26, 21 }, // base cell 29
{ 30, 32, 48, 50, 16, 18, 33 }, // base cell 30
{ 31, 41, 44, 53, 15, 22, 28 }, // base cell 31
{ 32, 30, 24, 18, 52, 50, 37 }, // base cell 32
{ 33, 30, 49, 48, 22, 16, 41 }, // base cell 33
{ 34, 19, 38, 21, 54, 36, 51 }, // base cell 34
{ 35, 46, 45, 56, 17, 27, 25 }, // base cell 35
{ 36, 20, 34, 19, 55, 40, 54 }, // base cell 36
{ 37, 39, 52, 57, 24, 23, 32 }, // base cell 37
{ 38, INVALID_BASE_CELL, 34, 51, 29, 47, 21 }, // base cell 38 (pentagon)
{ 39, 37, 25, 23, 59, 57, 45 }, // base cell 39
{ 40, 27, 36, 20, 60, 46, 55 }, // base cell 40
{ 41, 49, 53, 61, 22, 33, 31 }, // base cell 41
{ 42, 58, 43, 62, 28, 44, 26 }, // base cell 42
{ 43, 62, 47, 64, 26, 42, 29 }, // base cell 43
{ 44, 53, 58, 65, 28, 31, 42 }, // base cell 44
{ 45, 39, 35, 25, 63, 59, 56 }, // base cell 45
{ 46, 60, 56, 68, 27, 40, 35 }, // base cell 46
{ 47, 38, 43, 29, 69, 51, 64 }, // base cell 47
{ 48, 49, 30, 33, 67, 66, 50 }, // base cell 48
{ 49, INVALID_BASE_CELL, 61, 66, 33, 48, 41 }, // base cell 49 (pentagon)
{ 50, 48, 32, 30, 70, 67, 52 }, // base cell 50
{ 51, 69, 54, 71, 38, 47, 34 }, // base cell 51
{ 52, 57, 70, 74, 32, 37, 50 }, // base cell 52
{ 53, 61, 65, 75, 31, 41, 44 }, // base cell 53
{ 54, 71, 55, 73, 34, 51, 36 }, // base cell 54
{ 55, 40, 54, 36, 72, 60, 73 }, // base cell 55
{ 56, 68, 63, 77, 35, 46, 45 }, // base cell 56
{ 57, 59, 74, 78, 37, 39, 52 }, // base cell 57
{ 58, INVALID_BASE_CELL, 62, 76, 44, 65, 42 }, // base cell 58 (pentagon)
{ 59, 63, 78, 79, 39, 45, 57 }, // base cell 59
{ 60, 72, 68, 80, 40, 55, 46 }, // base cell 60
{ 61, 53, 49, 41, 81, 75, 66 }, // base cell 61
{ 62, 43, 58, 42, 82, 64, 76 }, // base cell 62
{ 63, INVALID_BASE_CELL, 56, 45, 79, 59, 77 }, // base cell 63 (pentagon)
{ 64, 47, 62, 43, 84, 69, 82 }, // base cell 64
{ 65, 58, 53, 44, 86, 76, 75 }, // base cell 65
{ 66, 67, 81, 85, 49, 48, 61 }, // base cell 66
{ 67, 66, 50, 48, 87, 85, 70 }, // base cell 67
{ 68, 56, 60, 46, 90, 77, 80 }, // base cell 68
{ 69, 51, 64, 47, 89, 71, 84 }, // base cell 69
{ 70, 67, 52, 50, 83, 87, 74 }, // base cell 70
{ 71, 89, 73, 91, 51, 69, 54 }, // base cell 71
{ 72, INVALID_BASE_CELL, 73, 55, 80, 60, 88 }, // base cell 72 (pentagon)
{ 73, 91, 72, 88, 54, 71, 55 }, // base cell 73
{ 74, 78, 83, 92, 52, 57, 70 }, // base cell 74
{ 75, 65, 61, 53, 94, 86, 81 }, // base cell 75
{ 76, 86, 82, 96, 58, 65, 62 }, // base cell 76
{ 77, 63, 68, 56, 93, 79, 90 }, // base cell 77
{ 78, 74, 59, 57, 95, 92, 79 }, // base cell 78
{ 79, 78, 63, 59, 93, 95, 77 }, // base cell 79
{ 80, 68, 72, 60, 99, 90, 88 }, // base cell 80
{ 81, 85, 94, 101, 61, 66, 75 }, // base cell 81
{ 82, 96, 84, 98, 62, 76, 64 }, // base cell 82
{ 83, INVALID_BASE_CELL, 74, 70, 100, 87, 92 }, // base cell 83 (pentagon)
{ 84, 69, 82, 64, 97, 89, 98 }, // base cell 84
{ 85, 87, 101, 102, 66, 67, 81 }, // base cell 85
{ 86, 76, 75, 65, 104, 96, 94 }, // base cell 86
{ 87, 83, 102, 100, 67, 70, 85 }, // base cell 87
{ 88, 72, 91, 73, 99, 80, 105 }, // base cell 88
{ 89, 97, 91, 103, 69, 84, 71 }, // base cell 89
{ 90, 77, 80, 68, 106, 93, 99 }, // base cell 90
{ 91, 73, 89, 71, 105, 88, 103 }, // base cell 91
{ 92, 83, 78, 74, 108, 100, 95 }, // base cell 92
{ 93, 79, 90, 77, 109, 95, 106 }, // base cell 93
{ 94, 86, 81, 75, 107, 104, 101 }, // base cell 94
{ 95, 92, 79, 78, 109, 108, 93 }, // base cell 95
{ 96, 104, 98, 110, 76, 86, 82 }, // base cell 96
{ 97, INVALID_BASE_CELL, 98, 84, 103, 89, 111 }, // base cell 97 (pentagon)
{ 98, 110, 97, 111, 82, 96, 84 }, // base cell 98
{ 99, 80, 105, 88, 106, 90, 113 }, // base cell 99
{ 100, 102, 83, 87, 108, 114, 92 }, // base cell 100
{ 101, 102, 107, 112, 81, 85, 94 }, // base cell 101
{ 102, 101, 87, 85, 114, 112, 100 }, // base cell 102
{ 103, 91, 97, 89, 116, 105, 111 }, // base cell 103
{ 104, 107, 110, 115, 86, 94, 96 }, // base cell 104
{ 105, 88, 103, 91, 113, 99, 116 }, // base cell 105
{ 106, 93, 99, 90, 117, 109, 113 }, // base cell 106
{ 107, INVALID_BASE_CELL, 101, 94, 115, 104, 112 }, // base cell 107 (pentagon)
{ 108, 100, 95, 92, 118, 114, 109 }, // base cell 108
{ 109, 108, 93, 95, 117, 118, 106 }, // base cell 109
{ 110, 98, 104, 96, 119, 111, 115 }, // base cell 110
{ 111, 97, 110, 98, 116, 103, 119 }, // base cell 111
{ 112, 107, 102, 101, 120, 115, 114 }, // base cell 112
{ 113, 99, 116, 105, 117, 106, 121 }, // base cell 113
{ 114, 112, 100, 102, 118, 120, 108 }, // base cell 114
{ 115, 110, 107, 104, 120, 119, 112 }, // base cell 115
{ 116, 103, 119, 111, 113, 105, 121 }, // base cell 116
{ 117, INVALID_BASE_CELL, 109, 118, 113, 121, 106 }, // base cell 117 (pentagon)
{ 118, 120, 108, 114, 117, 121, 109 }, // base cell 118
{ 119, 111, 115, 110, 121, 116, 120 }, // base cell 119
{ 120, 115, 114, 112, 121, 119, 118 }, // base cell 120
{ 121, 116, 120, 119, 117, 113, 118 }, // base cell 121
};
/** @brief Neighboring base cell rotations in each IJK direction.
*
* For each base cell, for each direction, the number of 60 degree
* CCW rotations to the coordinate system of the neighbor is given.
* -1 indicates there is no neighbor in that direction.
*/
private static final int[][] baseCellNeighbor60CCWRots = new int[][] {
{ 0, 5, 0, 0, 1, 5, 1 }, // base cell 0
{ 0, 0, 1, 0, 1, 0, 1 }, // base cell 1
{ 0, 0, 0, 0, 0, 5, 0 }, // base cell 2
{ 0, 5, 0, 0, 2, 5, 1 }, // base cell 3
{ 0, -1, 1, 0, 3, 4, 2 }, // base cell 4 (pentagon)
{ 0, 0, 1, 0, 1, 0, 1 }, // base cell 5
{ 0, 0, 0, 3, 5, 5, 0 }, // base cell 6
{ 0, 0, 0, 0, 0, 5, 0 }, // base cell 7
{ 0, 5, 0, 0, 0, 5, 1 }, // base cell 8
{ 0, 0, 1, 3, 0, 0, 1 }, // base cell 9
{ 0, 0, 1, 3, 0, 0, 1 }, // base cell 10
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 11
{ 0, 5, 0, 0, 3, 5, 1 }, // base cell 12
{ 0, 0, 1, 0, 1, 0, 1 }, // base cell 13
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 14 (pentagon)
{ 0, 5, 0, 0, 4, 5, 1 }, // base cell 15
{ 0, 0, 0, 0, 0, 5, 0 }, // base cell 16
{ 0, 3, 3, 3, 3, 0, 3 }, // base cell 17
{ 0, 0, 0, 3, 5, 5, 0 }, // base cell 18
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 19
{ 0, 3, 3, 3, 0, 3, 0 }, // base cell 20
{ 0, 0, 0, 3, 5, 5, 0 }, // base cell 21
{ 0, 0, 1, 0, 1, 0, 1 }, // base cell 22
{ 0, 3, 3, 3, 0, 3, 0 }, // base cell 23
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 24 (pentagon)
{ 0, 0, 0, 3, 0, 0, 3 }, // base cell 25
{ 0, 0, 0, 0, 0, 5, 0 }, // base cell 26
{ 0, 3, 0, 0, 0, 3, 3 }, // base cell 27
{ 0, 0, 1, 0, 1, 0, 1 }, // base cell 28
{ 0, 0, 1, 3, 0, 0, 1 }, // base cell 29
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 30
{ 0, 0, 0, 0, 0, 5, 0 }, // base cell 31
{ 0, 3, 3, 3, 3, 0, 3 }, // base cell 32
{ 0, 0, 1, 3, 0, 0, 1 }, // base cell 33
{ 0, 3, 3, 3, 3, 0, 3 }, // base cell 34
{ 0, 0, 3, 0, 3, 0, 3 }, // base cell 35
{ 0, 0, 0, 3, 0, 0, 3 }, // base cell 36
{ 0, 3, 0, 0, 0, 3, 3 }, // base cell 37
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 38 (pentagon)
{ 0, 3, 0, 0, 3, 3, 0 }, // base cell 39
{ 0, 3, 0, 0, 3, 3, 0 }, // base cell 40
{ 0, 0, 0, 3, 5, 5, 0 }, // base cell 41
{ 0, 0, 0, 3, 5, 5, 0 }, // base cell 42
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 43
{ 0, 0, 1, 3, 0, 0, 1 }, // base cell 44
{ 0, 0, 3, 0, 0, 3, 3 }, // base cell 45
{ 0, 0, 0, 3, 0, 3, 0 }, // base cell 46
{ 0, 3, 3, 3, 0, 3, 0 }, // base cell 47
{ 0, 3, 3, 3, 0, 3, 0 }, // base cell 48
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 49 (pentagon)
{ 0, 0, 0, 3, 0, 0, 3 }, // base cell 50
{ 0, 3, 0, 0, 0, 3, 3 }, // base cell 51
{ 0, 0, 3, 0, 3, 0, 3 }, // base cell 52
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 53
{ 0, 0, 3, 0, 3, 0, 3 }, // base cell 54
{ 0, 0, 3, 0, 0, 3, 3 }, // base cell 55
{ 0, 3, 3, 3, 0, 0, 3 }, // base cell 56
{ 0, 0, 0, 3, 0, 3, 0 }, // base cell 57
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 58 (pentagon)
{ 0, 3, 3, 3, 3, 3, 0 }, // base cell 59
{ 0, 3, 3, 3, 3, 3, 0 }, // base cell 60
{ 0, 3, 3, 3, 3, 0, 3 }, // base cell 61
{ 0, 3, 3, 3, 3, 0, 3 }, // base cell 62
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 63 (pentagon)
{ 0, 0, 0, 3, 0, 0, 3 }, // base cell 64
{ 0, 3, 3, 3, 0, 3, 0 }, // base cell 65
{ 0, 3, 0, 0, 0, 3, 3 }, // base cell 66
{ 0, 3, 0, 0, 3, 3, 0 }, // base cell 67
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 68
{ 0, 3, 0, 0, 3, 3, 0 }, // base cell 69
{ 0, 0, 3, 0, 0, 3, 3 }, // base cell 70
{ 0, 0, 0, 3, 0, 3, 0 }, // base cell 71
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 72 (pentagon)
{ 0, 3, 3, 3, 0, 0, 3 }, // base cell 73
{ 0, 3, 3, 3, 0, 0, 3 }, // base cell 74
{ 0, 0, 0, 3, 0, 0, 3 }, // base cell 75
{ 0, 3, 0, 0, 0, 3, 3 }, // base cell 76
{ 0, 0, 0, 3, 0, 5, 0 }, // base cell 77
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 78
{ 0, 0, 1, 3, 1, 0, 1 }, // base cell 79
{ 0, 0, 1, 3, 1, 0, 1 }, // base cell 80
{ 0, 0, 3, 0, 3, 0, 3 }, // base cell 81
{ 0, 0, 3, 0, 3, 0, 3 }, // base cell 82
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 83 (pentagon)
{ 0, 0, 3, 0, 0, 3, 3 }, // base cell 84
{ 0, 0, 0, 3, 0, 3, 0 }, // base cell 85
{ 0, 3, 0, 0, 3, 3, 0 }, // base cell 86
{ 0, 3, 3, 3, 3, 3, 0 }, // base cell 87
{ 0, 0, 0, 3, 0, 5, 0 }, // base cell 88
{ 0, 3, 3, 3, 3, 3, 0 }, // base cell 89
{ 0, 0, 0, 0, 0, 0, 1 }, // base cell 90
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 91
{ 0, 0, 0, 3, 0, 5, 0 }, // base cell 92
{ 0, 5, 0, 0, 5, 5, 0 }, // base cell 93
{ 0, 0, 3, 0, 0, 3, 3 }, // base cell 94
{ 0, 0, 0, 0, 0, 0, 1 }, // base cell 95
{ 0, 0, 0, 3, 0, 3, 0 }, // base cell 96
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 97 (pentagon)
{ 0, 3, 3, 3, 0, 0, 3 }, // base cell 98
{ 0, 5, 0, 0, 5, 5, 0 }, // base cell 99
{ 0, 0, 1, 3, 1, 0, 1 }, // base cell 100
{ 0, 3, 3, 3, 0, 0, 3 }, // base cell 101
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 102
{ 0, 0, 1, 3, 1, 0, 1 }, // base cell 103
{ 0, 3, 3, 3, 3, 3, 0 }, // base cell 104
{ 0, 0, 0, 0, 0, 0, 1 }, // base cell 105
{ 0, 0, 1, 0, 3, 5, 1 }, // base cell 106
{ 0, -1, 3, 0, 5, 2, 0 }, // base cell 107 (pentagon)
{ 0, 5, 0, 0, 5, 5, 0 }, // base cell 108
{ 0, 0, 1, 0, 4, 5, 1 }, // base cell 109
{ 0, 3, 3, 3, 0, 0, 0 }, // base cell 110
{ 0, 0, 0, 3, 0, 5, 0 }, // base cell 111
{ 0, 0, 0, 3, 0, 5, 0 }, // base cell 112
{ 0, 0, 1, 0, 2, 5, 1 }, // base cell 113
{ 0, 0, 0, 0, 0, 0, 1 }, // base cell 114
{ 0, 0, 1, 3, 1, 0, 1 }, // base cell 115
{ 0, 5, 0, 0, 5, 5, 0 }, // base cell 116
{ 0, -1, 1, 0, 3, 4, 2 }, // base cell 117 (pentagon)
{ 0, 0, 1, 0, 0, 5, 1 }, // base cell 118
{ 0, 0, 0, 0, 0, 0, 1 }, // base cell 119
{ 0, 5, 0, 0, 5, 5, 0 }, // base cell 120
{ 0, 0, 1, 0, 1, 5, 1 }, // base cell 121
};
/**
* Directions used for traversing a hexagonal ring counterclockwise around
* {1, 0, 0}
*
* <pre>
* _
* _/ \\_
* / \\5/ \\
* \\0/ \\4/
* / \\_/ \\
* \\1/ \\3/
* \\2/
* </pre>
*/
static final CoordIJK.Direction[] DIRECTIONS = new CoordIJK.Direction[] {
CoordIJK.Direction.J_AXES_DIGIT,
CoordIJK.Direction.JK_AXES_DIGIT,
CoordIJK.Direction.K_AXES_DIGIT,
CoordIJK.Direction.IK_AXES_DIGIT,
CoordIJK.Direction.I_AXES_DIGIT,
CoordIJK.Direction.IJ_AXES_DIGIT };
/**
* New digit when traversing along | HexRing |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ZendeskComponentBuilderFactory.java | {
"start": 1850,
"end": 8575
} | interface ____ extends ComponentBuilder<ZendeskComponent> {
/**
* The server URL to connect.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param serverUrl the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder serverUrl(java.lang.String serverUrl) {
doSetProperty("serverUrl", serverUrl);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* Component configuration.
*
* The option is a:
* <code>org.apache.camel.component.zendesk.ZendeskConfiguration</code> type.
*
* Group: advanced
*
* @param configuration the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder configuration(org.apache.camel.component.zendesk.ZendeskConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* To use a shared Zendesk instance.
*
* The option is a:
* <code>org.zendesk.client.v2.Zendesk</code> type.
*
* Group: advanced
*
* @param zendesk the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder zendesk(org.zendesk.client.v2.Zendesk zendesk) {
doSetProperty("zendesk", zendesk);
return this;
}
/**
* The OAuth token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauthToken the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder oauthToken(java.lang.String oauthToken) {
doSetProperty("oauthToken", oauthToken);
return this;
}
/**
* The password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder password(java.lang.String password) {
doSetProperty("password", password);
return this;
}
/**
* The security token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param token the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder token(java.lang.String token) {
doSetProperty("token", token);
return this;
}
/**
* The user name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default ZendeskComponentBuilder username(java.lang.String username) {
doSetProperty("username", username);
return this;
}
}
| ZendeskComponentBuilder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/LocalRMInterface.java | {
"start": 1789,
"end": 3061
} | class ____ implements ResourceTracker {
private static final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null);
@Override
public RegisterNodeManagerResponse registerNodeManager(
RegisterNodeManagerRequest request) throws YarnException,
IOException {
RegisterNodeManagerResponse response = recordFactory.newRecordInstance(RegisterNodeManagerResponse.class);
MasterKey masterKey = new MasterKeyPBImpl();
masterKey.setKeyId(123);
masterKey.setBytes(ByteBuffer.wrap(new byte[] { new Integer(123)
.byteValue() }));
response.setContainerTokenMasterKey(masterKey);
response.setNMTokenMasterKey(masterKey);
return response;
}
@Override
public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request)
throws YarnException, IOException {
NodeHeartbeatResponse response = recordFactory.newRecordInstance(NodeHeartbeatResponse.class);
return response;
}
@Override
public UnRegisterNodeManagerResponse unRegisterNodeManager(
UnRegisterNodeManagerRequest request) throws YarnException, IOException {
UnRegisterNodeManagerResponse response = recordFactory
.newRecordInstance(UnRegisterNodeManagerResponse.class);
return response;
}
} | LocalRMInterface |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/runtime/src/main/java/io/quarkus/smallrye/reactivemessaging/runtime/SmallRyeReactiveMessagingLifecycle.java | {
"start": 846,
"end": 2716
} | class ____ {
@Inject
MediatorManager mediatorManager;
void onStaticInit(@Observes @Initialized(ApplicationScoped.class) Object event,
SmallRyeReactiveMessagingRecorder.SmallRyeReactiveMessagingContext context,
QuarkusWorkerPoolRegistry workerPoolRegistry) {
mediatorManager.addAnalyzed(context.getMediatorConfigurations());
for (WorkerConfiguration worker : context.getWorkerConfigurations()) {
workerPoolRegistry.defineWorker(worker.getClassName(), worker.getMethodName(), worker.getPoolName(),
worker.isVirtualThread());
}
for (EmitterConfiguration emitter : context.getEmitterConfigurations()) {
mediatorManager.addEmitter(emitter);
}
for (ChannelConfiguration channel : context.getChannelConfigurations()) {
mediatorManager.addChannel(channel);
}
}
void onApplicationStart(@Observes @Priority(Interceptor.Priority.LIBRARY_BEFORE) StartupEvent event) {
// We do not want a request scope during the wiring, or it will be propagated and never terminated.
ManagedContext requestContext = Arc.container().requestContext();
boolean isRequestScopeActive = requestContext.isActive();
InjectableContext.ContextState state = null;
if (isRequestScopeActive) {
state = requestContext.getState();
requestContext.deactivate();
}
try {
mediatorManager.start();
} catch (Exception e) {
if (e instanceof DeploymentException || e instanceof DefinitionException) {
throw e;
}
throw new DeploymentException(e);
} finally {
if (state != null) {
requestContext.activate(state);
}
}
}
}
| SmallRyeReactiveMessagingLifecycle |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/querydsl/query/SingleValueQuery.java | {
"start": 2631,
"end": 5498
} | class ____ extends Query {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(
QueryBuilder.class,
"esql_single_value",
Builder::new
);
private final Query next;
private final String field;
private final UseSyntheticSourceDelegate useSyntheticSourceDelegate;
/**
* Build.
* @param next the query whose documents we should use for single-valued fields
* @param field the name of the field whose values to check
* @param useSyntheticSourceDelegate Should we check the field's synthetic source delegate (true)
* or it's values itself? If the field is a {@code text} field
* we often want to use its delegate.
*/
public SingleValueQuery(Query next, String field, boolean useSyntheticSourceDelegate) {
this(next, field, useSyntheticSourceDelegate ? UseSyntheticSourceDelegate.YES : UseSyntheticSourceDelegate.NO);
}
public SingleValueQuery(Query next, String field, UseSyntheticSourceDelegate useSyntheticSourceDelegate) {
super(next.source());
this.next = next;
this.field = field;
this.useSyntheticSourceDelegate = useSyntheticSourceDelegate;
}
@Override
protected AbstractBuilder asBuilder() {
return switch (useSyntheticSourceDelegate) {
case NO -> new Builder(next.toQueryBuilder(), field, next.source());
case YES -> new SyntheticSourceDelegateBuilder(next.toQueryBuilder(), field, next.source());
case YES_NEGATED -> new NegatedSyntheticSourceDelegateBuilder(next.toQueryBuilder(), field, next.source());
};
}
@Override
protected String innerToString() {
return next.toString();
}
@Override
public SingleValueQuery negate(Source source) {
return new SingleValueQuery(next.negate(source), field, switch (useSyntheticSourceDelegate) {
case NO -> UseSyntheticSourceDelegate.NO;
case YES -> UseSyntheticSourceDelegate.YES_NEGATED;
case YES_NEGATED -> UseSyntheticSourceDelegate.YES;
});
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass() || false == super.equals(o)) {
return false;
}
SingleValueQuery other = (SingleValueQuery) o;
return Objects.equals(next, other.next)
&& Objects.equals(field, other.field)
&& useSyntheticSourceDelegate == other.useSyntheticSourceDelegate;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), next, field, useSyntheticSourceDelegate);
}
@Override
public boolean containsPlan() {
return next.containsPlan();
}
public abstract static | SingleValueQuery |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java | {
"start": 14512,
"end": 14858
} | class ____ {
final Holder<String> h = null;
}
""")
.doTest();
}
@Test
public void mutableTypeArgumentInstantiation() {
compilationHelper
.addSourceLines(
"Holder.java",
"""
import com.google.errorprone.annotations.Immutable;
public | Test |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/similarity/ScriptedSimilarity.java | {
"start": 7558,
"end": 8255
} | class ____ {
private final long docFreq;
private final long totalTermFreq;
private Term(long docFreq, long totalTermFreq) {
this.docFreq = docFreq;
this.totalTermFreq = totalTermFreq;
}
/** Return the number of documents that contain this term in the index. */
public long getDocFreq() {
return docFreq;
}
/** Return the total number of occurrences of this term in the index, or {@code -1} if this statistic is not available. */
public long getTotalTermFreq() {
return totalTermFreq;
}
}
/** Statistics that are specific to a document. */
public static | Term |
java | apache__avro | lang/java/integration-test/codegen-test/src/test/java/org/apache/avro/codegentest/AbstractSpecificRecordTest.java | {
"start": 1264,
"end": 3549
} | class ____ {
@SuppressWarnings("unchecked")
<T extends SpecificRecordBase> void verifySerDeAndStandardMethods(T original) {
final SpecificDatumWriter<T> datumWriterFromSchema = new SpecificDatumWriter<>(original.getSchema());
final SpecificDatumReader<T> datumReaderFromSchema = new SpecificDatumReader<>(original.getSchema(),
original.getSchema());
verifySerDeAndStandardMethods(original, datumWriterFromSchema, datumReaderFromSchema);
final SpecificDatumWriter<T> datumWriterFromClass = new SpecificDatumWriter(original.getClass());
final SpecificDatumReader<T> datumReaderFromClass = new SpecificDatumReader(original.getClass());
verifySerDeAndStandardMethods(original, datumWriterFromClass, datumReaderFromClass);
}
private <T extends SpecificRecordBase> void verifySerDeAndStandardMethods(T original,
SpecificDatumWriter<T> datumWriter, SpecificDatumReader<T> datumReader) {
final byte[] serialized = serialize(original, datumWriter);
final T copy = deserialize(serialized, datumReader);
assertEquals(original, copy);
// In addition to equals() tested above, make sure the other methods that use
// SpecificData work as intended
// compareTo() throws an exception for maps, otherwise we would have tested it
// here
// Assert.assertEquals(0, original.compareTo(copy));
assertEquals(original.hashCode(), copy.hashCode());
assertEquals(original.toString(), copy.toString());
}
private <T extends SpecificRecordBase> byte[] serialize(T object, SpecificDatumWriter<T> datumWriter) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
datumWriter.write(object, EncoderFactory.get().directBinaryEncoder(outputStream, null));
return outputStream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private <T extends SpecificRecordBase> T deserialize(byte[] bytes, SpecificDatumReader<T> datumReader) {
try {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
return datumReader.read(null, DecoderFactory.get().directBinaryDecoder(byteArrayInputStream, null));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| AbstractSpecificRecordTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SelfAssignmentTest.java | {
"start": 6662,
"end": 6743
} | class ____ {
int a;
}
private static | Foo |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/support/spring/mock/controller/FastJsonControllerTest.java | {
"start": 1163,
"end": 2915
} | class ____ {
@RequestMapping("test1")
public
@ResponseBody
JSONObject test1(@RequestBody FastJsonTestVO vo) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", vo.getId());
jsonObj.put("name", vo.getName());
return jsonObj;
}
@RequestMapping("test2")
public
@ResponseBody
JSONObject test1(@RequestBody List<FastJsonParentTestVO> vos) {
JSONObject jsonObj = new JSONObject();
for (FastJsonParentTestVO fastJsonParentTestVO : vos) {
jsonObj.put(fastJsonParentTestVO.getName(), fastJsonParentTestVO.getSonList().size());
}
return jsonObj;
}
@ResponseBody
@RequestMapping(value = "test3", method = RequestMethod.POST)
public Company test3(HttpServletRequest request, HttpServletResponse response) {
Company company = new Company();
return company;
}
@RequestMapping("test4")
public
@ResponseBody
String test4(@RequestBody FastJsonGenericityTestVO<FastJsonTestVO> queryCondition) {
return JSON.toJSONString(queryCondition);
}
@RequestMapping("test5")
public
@ResponseBody
String test5(@RequestBody FastJsonEnumTestVO vo) {
return JSON.toJSONString(vo);
}
@RequestMapping(value = "/test6", method = {RequestMethod.POST, RequestMethod.GET}, produces = {"text/plain", "application/*"})
public
@ResponseBody
Object test6(@RequestParam long userId, @RequestParam boolean flag) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId",userId);
jsonObject.put("flag",flag);
System.out.println(jsonObject.toJSONString());
return jsonObject;
}
}
| FastJsonControllerTest |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContext.java | {
"start": 3827,
"end": 6347
} | class ____
extends AbstractBuilder<OAuth2AuthorizationConsentAuthenticationContext, Builder> {
private Builder(OAuth2AuthorizationConsentAuthenticationToken authentication) {
super(authentication);
}
/**
* Sets the {@link OAuth2AuthorizationConsent.Builder authorization consent
* builder}.
* @param authorizationConsent the {@link OAuth2AuthorizationConsent.Builder}
* @return the {@link Builder} for further configuration
*/
public Builder authorizationConsent(OAuth2AuthorizationConsent.Builder authorizationConsent) {
return put(OAuth2AuthorizationConsent.Builder.class, authorizationConsent);
}
/**
* Sets the {@link RegisteredClient registered client}.
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder} for further configuration
*/
public Builder registeredClient(RegisteredClient registeredClient) {
return put(RegisteredClient.class, registeredClient);
}
/**
* Sets the {@link OAuth2Authorization authorization}.
* @param authorization the {@link OAuth2Authorization}
* @return the {@link Builder} for further configuration
*/
public Builder authorization(OAuth2Authorization authorization) {
return put(OAuth2Authorization.class, authorization);
}
/**
* Sets the {@link OAuth2AuthorizationRequest authorization request}.
* @param authorizationRequest the {@link OAuth2AuthorizationRequest}
* @return the {@link Builder} for further configuration
*/
public Builder authorizationRequest(OAuth2AuthorizationRequest authorizationRequest) {
return put(OAuth2AuthorizationRequest.class, authorizationRequest);
}
/**
* Builds a new {@link OAuth2AuthorizationConsentAuthenticationContext}.
* @return the {@link OAuth2AuthorizationConsentAuthenticationContext}
*/
@Override
public OAuth2AuthorizationConsentAuthenticationContext build() {
Assert.notNull(get(OAuth2AuthorizationConsent.Builder.class), "authorizationConsentBuilder cannot be null");
Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null");
OAuth2Authorization authorization = get(OAuth2Authorization.class);
Assert.notNull(authorization, "authorization cannot be null");
if (authorization.getAuthorizationGrantType().equals(AuthorizationGrantType.AUTHORIZATION_CODE)) {
Assert.notNull(get(OAuth2AuthorizationRequest.class), "authorizationRequest cannot be null");
}
return new OAuth2AuthorizationConsentAuthenticationContext(getContext());
}
}
}
| Builder |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/conditional/propertyname/sourcepropertyname/ConditionalMethodInMapperWithAllOptions.java | {
"start": 884,
"end": 1073
} | interface ____ {
ConditionalMethodInMapperWithAllOptions INSTANCE
= Mappers.getMapper( ConditionalMethodInMapperWithAllOptions.class );
| ConditionalMethodInMapperWithAllOptions |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/internal/ExitableDirectoryReader.java | {
"start": 2015,
"end": 2234
} | class ____ extends FilterDirectoryReader {
/**
* Used to check if query cancellation is actually enabled
* and if so use it to check if the query is cancelled or timed-out.
*/
| ExitableDirectoryReader |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/ThreadPoolRejectedPolicyTest.java | {
"start": 7436,
"end": 7625
} | class ____ extends MockRunnable implements Rejectable {
@Override
public void reject() {
countRejection();
}
}
private static | MockRejectableRunnable |
java | spring-projects__spring-boot | module/spring-boot-data-couchbase-test/src/dockerTest/java/org/springframework/boot/data/couchbase/test/autoconfigure/DataCouchbaseTestWithIncludeFilterIntegrationTests.java | {
"start": 1870,
"end": 2559
} | class ____ {
@Container
@ServiceConnection
static final CouchbaseContainer couchbase = TestImage.container(CouchbaseContainer.class)
.withEnabledServices(CouchbaseService.KV, CouchbaseService.INDEX, CouchbaseService.QUERY)
.withBucket(new BucketDefinition("cbbucket"));
@Autowired
private ExampleRepository exampleRepository;
@Autowired
private ExampleService service;
@Test
void testService() {
ExampleDocument document = new ExampleDocument();
document.setText("Look, new @DataCouchbaseTest!");
document = this.exampleRepository.save(document);
assertThat(this.service.findById(document.getId())).isNotNull();
}
}
| DataCouchbaseTestWithIncludeFilterIntegrationTests |
java | spring-projects__spring-framework | spring-tx/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java | {
"start": 1825,
"end": 2015
} | interface ____ the invoked method
* has been called through (in case of a JDK proxy) will be checked.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 1.1
*/
public abstract | that |
java | quarkusio__quarkus | extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CertChainPublicKeyResolver.java | {
"start": 616,
"end": 5366
} | class ____ implements RefreshableVerificationKeyResolver {
private static final Logger LOG = Logger.getLogger(OidcProvider.class);
final OidcTenantConfig oidcConfig;
final Set<String> thumbprints;
final Optional<String> expectedLeafCertificateName;
final List<TokenCertificateValidator> certificateValidators;
public CertChainPublicKeyResolver(OidcTenantConfig oidcConfig) {
this.oidcConfig = oidcConfig;
if (oidcConfig.certificateChain().trustStorePassword().isEmpty()) {
throw new ConfigurationException(
"Truststore with configured password which keeps thumbprints of the trusted certificates must be present");
}
this.thumbprints = TrustStoreUtils.getTrustedCertificateThumbprints(
oidcConfig.certificateChain().trustStoreFile().get(),
oidcConfig.certificateChain().trustStorePassword().get(),
oidcConfig.certificateChain().trustStoreCertAlias(),
oidcConfig.certificateChain().trustStoreFileType());
this.expectedLeafCertificateName = oidcConfig.certificateChain().leafCertificateName();
this.certificateValidators = TenantFeatureFinder.find(oidcConfig, TokenCertificateValidator.class);
}
@Override
public Key resolveKey(JsonWebSignature jws, List<JsonWebStructure> nestingContext)
throws UnresolvableKeyException {
try {
List<X509Certificate> chain = jws.getCertificateChainHeaderValue();
if (chain == null) {
LOG.debug("Token does not have an 'x5c' certificate chain header");
return null;
}
if (chain.isEmpty()) {
LOG.debug("Token 'x5c' certificate chain is empty");
return null;
}
// General certificate chain validation
//TODO: support revocation lists
CertificateHelper.checkValidity(chain, null);
if (chain.size() == 1) {
// CertificateHelper.checkValidity does not currently
// verify the certificate signature if it is a single certificate chain
final X509Certificate root = chain.get(0);
root.verify(root.getPublicKey());
}
// Always do the root certificate thumbprint check
LOG.debug("Checking a thumbprint of the root chain certificate");
String rootThumbprint = TrustStoreUtils.calculateThumprint(chain.get(chain.size() - 1));
if (!thumbprints.contains(rootThumbprint)) {
LOG.error("Thumprint of the root chain certificate is invalid");
throw new UnresolvableKeyException("Thumprint of the root chain certificate is invalid");
}
// Run custom validators if any
if (!certificateValidators.isEmpty()) {
LOG.debug("Running custom TokenCertificateValidators");
for (TokenCertificateValidator validator : certificateValidators) {
validator.validate(oidcConfig, chain, jws.getUnverifiedPayload());
}
}
// Finally, check the leaf certificate if required
if (expectedLeafCertificateName.isPresent()) {
// Compare the leaf certificate common name against the configured value
String leafCertificateName = HttpSecurityUtils.getCommonName(chain.get(0).getSubjectX500Principal());
if (!expectedLeafCertificateName.get().equals(leafCertificateName)) {
LOG.errorf("Wrong leaf certificate common name: %s", leafCertificateName);
throw new UnresolvableKeyException("Wrong leaf certificate common name");
}
} else if (certificateValidators.isEmpty()) {
// No custom validators are registered and no leaf certificate CN is configured
// Check that the truststore contains a leaf certificate thumbprint
LOG.debug("Checking a thumbprint of the leaf chain certificate");
String thumbprint = TrustStoreUtils.calculateThumprint(chain.get(0));
if (!thumbprints.contains(thumbprint)) {
LOG.error("Thumprint of the leaf chain certificate is invalid");
throw new UnresolvableKeyException("Thumprint of the leaf chain certificate is invalid");
}
}
return chain.get(0).getPublicKey();
} catch (UnresolvableKeyException ex) {
throw ex;
} catch (Exception ex) {
throw new UnresolvableKeyException("Invalid certificate chain", ex);
}
}
}
| CertChainPublicKeyResolver |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/EqualsGetClassTest.java | {
"start": 5544,
"end": 5961
} | class ____ {
private int a;
@Override
public boolean equals(Object o) {
if (o == null || !o.getClass().equals(((Object) this).getClass())) {
return false;
}
return ((Test) o).a == a;
}
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java | {
"start": 7647,
"end": 7827
} | class ____ extends BazTestCase {
@Test
@DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL)
void test() {
}
}
}
| MethodLevelDirtiesContextWithCurrentLevelModeTestCase |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/analytics/reports/SyncReportResults.java | {
"start": 920,
"end": 1205
} | class ____ extends AbstractReportResultsBase {
private SyncAttributes attributes;
public SyncAttributes getAttributes() {
return attributes;
}
public void setAttributes(SyncAttributes attributes) {
this.attributes = attributes;
}
}
| SyncReportResults |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/validation/AbstractBindingResult.java | {
"start": 1231,
"end": 1519
} | interface ____
* its super-interface {@link Errors}. Encapsulates common management of
* {@link ObjectError ObjectErrors} and {@link FieldError FieldErrors}.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @since 2.0
* @see Errors
*/
@SuppressWarnings("serial")
public abstract | and |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/test/src/main/java/org/elasticsearch/compute/test/NoOpReleasable.java | {
"start": 345,
"end": 444
} | class ____ implements Releasable {
@Override
public void close() {/* no-op */}
}
| NoOpReleasable |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/strategy/BaseAdaptiveJoinOperatorOptimizationStrategy.java | {
"start": 2368,
"end": 7288
} | class ____
implements StreamGraphOptimizationStrategy {
protected static final int LEFT_INPUT_TYPE_NUMBER = 1;
protected static final int RIGHT_INPUT_TYPE_NUMBER = 2;
/** Set of partitioners that can automatically correct key group. */
private static final Set<Class<?>> PARTITIONERS_CAN_CORRECT_KEY_GROUP_AUTOMATIC =
Set.of(
BinaryHashPartitioner.class,
BroadcastPartitioner.class,
CustomPartitionerWrapper.class,
GlobalPartitioner.class,
KeyGroupStreamPartitioner.class,
RebalancePartitioner.class,
RowDataCustomStreamPartitioner.class,
ShufflePartitioner.class);
/**
* Set of partitioners that can force key group correction but may introduce additional shuffle
* overhead.
*/
private static final Set<Class<?>> PARTITIONERS_CAN_CORRECT_KEY_GROUP_FORCED =
Set.of(ForwardForConsecutiveHashPartitioner.class);
protected void visitDownstreamAdaptiveJoinNode(
OperatorsFinished operatorsFinished, StreamGraphContext context) {
ImmutableStreamGraph streamGraph = context.getStreamGraph();
List<Integer> finishedStreamNodeIds = operatorsFinished.getFinishedStreamNodeIds();
Map<ImmutableStreamNode, List<ImmutableStreamEdge>> joinNodesWithInEdges = new HashMap<>();
for (Integer finishedStreamNodeId : finishedStreamNodeIds) {
for (ImmutableStreamEdge streamEdge :
streamGraph.getStreamNode(finishedStreamNodeId).getOutEdges()) {
ImmutableStreamNode downstreamNode =
streamGraph.getStreamNode(streamEdge.getTargetId());
if (downstreamNode.getOperatorFactory() instanceof AdaptiveJoin) {
joinNodesWithInEdges
.computeIfAbsent(downstreamNode, k -> new ArrayList<>())
.add(streamEdge);
}
}
}
for (ImmutableStreamNode joinNode : joinNodesWithInEdges.keySet()) {
tryOptimizeAdaptiveJoin(
operatorsFinished,
context,
joinNode,
joinNodesWithInEdges.get(joinNode),
(AdaptiveJoin) joinNode.getOperatorFactory());
}
}
abstract void tryOptimizeAdaptiveJoin(
OperatorsFinished operatorsFinished,
StreamGraphContext context,
ImmutableStreamNode adaptiveJoinNode,
List<ImmutableStreamEdge> upstreamStreamEdges,
AdaptiveJoin adaptiveJoin);
static boolean canPerformOptimizationAutomatic(
StreamGraphContext context, ImmutableStreamNode adaptiveJoinNode) {
return adaptiveJoinNode.getOutEdges().stream()
.allMatch(
edge -> {
Class<?> classOfOutputPartitioner =
checkNotNull(
context.getOutputPartitioner(
edge.getEdgeId(),
edge.getSourceId(),
edge.getTargetId()))
.getClass();
return !edge.isIntraInputKeyCorrelated()
|| PARTITIONERS_CAN_CORRECT_KEY_GROUP_AUTOMATIC.contains(
classOfOutputPartitioner);
});
}
static boolean canPerformOptimizationForced(
StreamGraphContext context, ImmutableStreamNode adaptiveJoinNode) {
return adaptiveJoinNode.getOutEdges().stream()
.allMatch(
edge -> {
Class<?> classOfOutputPartitioner =
checkNotNull(
context.getOutputPartitioner(
edge.getEdgeId(),
edge.getSourceId(),
edge.getTargetId()))
.getClass();
return !edge.isIntraInputKeyCorrelated()
|| PARTITIONERS_CAN_CORRECT_KEY_GROUP_AUTOMATIC.contains(
classOfOutputPartitioner)
|| PARTITIONERS_CAN_CORRECT_KEY_GROUP_FORCED.contains(
classOfOutputPartitioner);
});
}
}
| BaseAdaptiveJoinOperatorOptimizationStrategy |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AAnalyticsAcceleratorStreamReading.java | {
"start": 3870,
"end": 4145
} | class ____ on reading local parquet files stored in resources.
* These files are copied from local to S3 and then read via the analytics stream.
* This is done to ensure AAL can read the parquet format, and handles exceptions from malformed
* parquet files.
*
*/
public | rely |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/config/env/DataSourceFactory.java | {
"start": 1099,
"end": 1380
} | class ____ {
private final URI uri;
public DataSource(URI uri) {
this.uri = uri;
}
Connection connect() {
throw new UnsupportedOperationException("Can't really connect. I'm not a real data source");
}
}
}
| DataSource |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/filter/FilterParameterTests.java | {
"start": 2393,
"end": 11085
} | class ____ extends AbstractStatefulStatelessFilterTest {
@ParameterizedTest
@MethodSource("transactionKind")
public void testYesNo(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
scope.inTransaction( (session) -> {
session.disableFilter( "subDepartmentFilter" );
final EntityOne loaded = session.find( EntityOne.class, 1 );
assertThat( loaded ).isNotNull();
} );
inTransaction.accept( scope, session -> {
session.disableFilter( "subDepartmentFilter" );
session.enableFilter( "filterYesNoConverter" ).setParameter( "yesNo", Boolean.FALSE );
final EntityOne loaded = session.createQuery( "from EntityOne e where e.id = :id", EntityOne.class )
.setParameter( "id", 1 )
.getSingleResultOrNull();
assertThat( loaded ).isNull();
} );
}
@ParameterizedTest
@MethodSource("transactionKind")
// most dialects silently convert boolean to string types
@RequiresDialect(SQLServerDialect.class)
@RequiresDialect(value = PostgreSQLDialect.class, matchSubTypes = false)
public void testYesNoMismatch(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
scope.inTransaction( (session) -> {
session.disableFilter( "subDepartmentFilter" );
final EntityOne loaded = session.find( EntityOne.class, 1 );
assertThat( loaded ).isNotNull();
} );
inTransaction.accept( scope, session -> {
session.disableFilter( "subDepartmentFilter" );
session.enableFilter( "filterYesNoBoolean" ).setParameter( "yesNo", Boolean.FALSE );
assertThatThrownBy( () -> session.createQuery( "from EntityOne e where e.id = :id", EntityOne.class )
.setParameter( "id", 1 )
.getSingleResultOrNull() )
.isInstanceOf( Exception.class );
} );
}
@ParameterizedTest
@MethodSource("transactionKind")
public void testNumeric(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
scope.inTransaction( (session) -> {
session.disableFilter( "subDepartmentFilter" );
final EntityTwo loaded = session.find( EntityTwo.class, 1 );
assertThat( loaded ).isNotNull();
} );
inTransaction.accept( scope, session -> {
session.disableFilter( "subDepartmentFilter" );
session.enableFilter( "filterNumberConverter" ).setParameter( "zeroOne", Boolean.FALSE );
final EntityTwo loaded = session.createQuery( "from EntityTwo e where e.id = :id", EntityTwo.class )
.setParameter( "id", 1 )
.getSingleResultOrNull();
assertThat( loaded ).isNull();
} );
}
@ParameterizedTest
@MethodSource("transactionKind")
// most dialects silently convert boolean to integral types
@RequiresDialect(PostgreSQLDialect.class)
@RequiresDialect(CockroachDialect.class)
public void testNumericMismatch(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
scope.inTransaction( (session) -> {
session.disableFilter( "subDepartmentFilter" );
final EntityTwo loaded = session.find( EntityTwo.class, 1 );
assertThat( loaded ).isNotNull();
} );
inTransaction.accept( scope, session -> {
session.disableFilter( "subDepartmentFilter" );
session.enableFilter( "filterNumberBoolean" ).setParameter( "zeroOne", Boolean.FALSE );
assertThatThrownBy( () -> session.createQuery( "from EntityTwo e where e.id = :id", EntityTwo.class )
.setParameter( "id", 1 )
.getSingleResultOrNull() )
.isInstanceOf( Exception.class );
} );
}
@ParameterizedTest
@MethodSource("transactionKind")
@SkipForDialect(dialectClass = MySQLDialect.class, reason = "MySQL silently converts strings to integral types")
@SkipForDialect(dialectClass = MariaDBDialect.class, reason = "MariaDB silently converts strings to integral types")
@SkipForDialect(dialectClass = TiDBDialect.class, reason = "TiDB silently converts strings to integral types")
@SkipForDialect(dialectClass = PostgresPlusDialect.class, reason = "PostgresPlus silently converts strings to integral types")
public void testMismatch(BiConsumer<SessionFactoryScope, Consumer<? extends SharedSessionContract>> inTransaction) {
scope.inTransaction( (session) -> {
session.disableFilter( "subDepartmentFilter" );
final EntityThree loaded = session.find( EntityThree.class, 1 );
assertThat( loaded ).isNotNull();
} );
inTransaction.accept( scope, session -> {
session.disableFilter( "subDepartmentFilter" );
session.enableFilter( "filterMismatchConverter" ).setParameter( "mismatch", Boolean.FALSE );
assertThatThrownBy( () -> session.createQuery( "from EntityThree e where e.id = :id", EntityThree.class )
.setParameter( "id", 1 )
.getSingleResultOrNull() )
.isInstanceOf( Exception.class );
} );
}
@ParameterizedTest
@MethodSource("transactionKind")
public void testAutoEnableWithResolver() {
final SeContainerInitializer cdiInitializer = SeContainerInitializer.newInstance()
.disableDiscovery()
.addBeanClasses( EntityFourDepartmentResolver.class );
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( JAKARTA_CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();
try {
scope.inTransaction( (session) -> {
session.getEnabledFilter("subDepartmentFilter").setParameter("subdepartment", "FIRST_A" );
//noinspection removal
final EntityFour first_a = session.createQuery( "from EntityFour e where e.id = :id", EntityFour.class )
.setParameter( "id", 1 )
.getSingleResultOrNull();
assertThat( first_a ).isNotNull();
assertThat( first_a.getDepartment() ).isEqualTo( "FIRST" );
session.getEnabledFilter("subDepartmentFilter").setParameter("subdepartment", "SECOND_A" );
//noinspection removal
final EntityFour second = session.createQuery( "from EntityFour e where e.id = :id", EntityFour.class )
.setParameter( "id", 3 )
.getSingleResultOrNull();
assertThat( second ).isNull();
} );
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
}
}
}
@ParameterizedTest
@MethodSource("transactionKind")
public void testAutoEnableWithoutResolver() {
final SeContainerInitializer cdiInitializer = SeContainerInitializer.newInstance()
.disableDiscovery()
.addBeanClasses( EntityFourDepartmentResolver.class );
try ( final SeContainer cdiContainer = cdiInitializer.initialize() ) {
BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
final StandardServiceRegistry ssr = ServiceRegistryUtil.serviceRegistryBuilder( bsr )
.applySetting( JAKARTA_CDI_BEAN_MANAGER, cdiContainer.getBeanManager() )
.build();
try {
scope.inTransaction( (session) -> {
session.getEnabledFilter("subDepartmentFilter").setParameter("subdepartment", "FIRST_A" );
//noinspection removal
final EntityFour first_a = session.createQuery( "from EntityFour e where e.id = :id", EntityFour.class )
.setParameter( "id", 1 )
.getSingleResultOrNull();
assertThat( first_a ).isNotNull();
assertThat( first_a.getDepartment() ).isEqualTo( "FIRST" );
//noinspection removal
final EntityFour first_b = session.createQuery( "from EntityFour e where e.id = :id", EntityFour.class )
.setParameter( "id", 2 )
.getSingleResultOrNull();
assertThat( first_b ).isNull();
} );
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
}
}
}
@BeforeEach
public void prepareTestData() {
scope.inTransaction( (session) -> {
session.persist( new EntityOne( 1, "one" ) );
session.persist( new EntityTwo( 1, "two" ) );
session.persist( new EntityThree( 1, "three" ) );
session.persist( new EntityFour( 1, "four", "FIRST", "FIRST_A" ) );
session.persist( new EntityFour( 2, "four", "FIRST", "FIRST_B" ) );
session.persist( new EntityFour( 3, "four", "SECOND", "SECOND_A" ) );
} );
}
@AfterEach
public void dropTestData() {
scope.getSessionFactory().getSchemaManager().truncate();
}
@SuppressWarnings("unused")
@FilterDef(
name = "filterYesNoConverter",
defaultCondition = "yes_no = :yesNo",
parameters = @ParamDef( name = "yesNo", type = YesNoConverter.class )
)
@FilterDef(
name = "filterYesNoBoolean",
defaultCondition = "yes_no = :yesNo",
parameters = @ParamDef( name = "yesNo", type = Boolean.class )
)
@Filter( name = "filterYesNoConverter" )
@Filter( name = "filterYesNoBoolean" )
@Entity( name = "EntityOne" )
@Table( name = "EntityOne" )
public static | FilterParameterTests |
java | apache__kafka | connect/runtime/src/test/resources/test-plugins/bad-packaging/test/plugins/StaticInitializerThrowsRestExtension.java | {
"start": 1386,
"end": 1918
} | class ____ implements ConnectRestExtension {
static {
setup();
}
public static void setup() {
throw new RuntimeException("I always throw an exception");
}
@Override
public void close() throws IOException {
}
@Override
public void configure(Map<String, ?> configs) {
}
@Override
public String version() {
return null;
}
@Override
public void register(ConnectRestExtensionContext restPluginContext) {
}
}
| StaticInitializerThrowsRestExtension |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLColumnUniqueKey.java | {
"start": 771,
"end": 1261
} | class ____ extends SQLConstraintImpl implements SQLColumnConstraint, SQLReplaceable {
public SQLColumnUniqueKey() {
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, this.getName());
}
visitor.endVisit(this);
}
public SQLColumnUniqueKey clone() {
SQLColumnUniqueKey x = new SQLColumnUniqueKey();
super.cloneTo(x);
return x;
}
}
| SQLColumnUniqueKey |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/forms/FormsSubmissionsWithListsTest.java | {
"start": 3367,
"end": 3735
} | class ____ {
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Post("/save")
QuestionSave save(@Body QuestionSave questionSave) {
return questionSave;
}
}
@Introspected
@ReflectiveAccess
public record QuestionSave(String question,
List<Long> usersId) {
}
}
| QuestionController |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/TestInstancePostProcessor.java | {
"start": 1987,
"end": 2217
} | interface ____ extends TestInstantiationAwareExtension {
/**
* Callback for post-processing the supplied test instance.
*
* <p>By default, the supplied {@link ExtensionContext} represents the test
* | TestInstancePostProcessor |
java | resilience4j__resilience4j | resilience4j-rxjava2/src/main/java/io/github/resilience4j/AbstractSingleObserver.java | {
"start": 135,
"end": 1032
} | class ____<T> extends AbstractDisposable implements
SingleObserver<T> {
private final SingleObserver<? super T> downstreamObserver;
public AbstractSingleObserver(SingleObserver<? super T> downstreamObserver) {
this.downstreamObserver = requireNonNull(downstreamObserver);
}
@Override
protected void hookOnSubscribe() {
downstreamObserver.onSubscribe(this);
}
@Override
public void onError(Throwable e) {
whenNotCompleted(() -> {
hookOnError(e);
downstreamObserver.onError(e);
});
}
protected abstract void hookOnError(Throwable e);
@Override
public void onSuccess(T value) {
whenNotCompleted(() -> {
hookOnSuccess(value);
downstreamObserver.onSuccess(value);
});
}
protected abstract void hookOnSuccess(T value);
}
| AbstractSingleObserver |
java | google__guava | android/guava/src/com/google/common/collect/TreeRangeSet.java | {
"start": 15437,
"end": 23819
} | class ____<C extends Comparable<?>>
extends AbstractNavigableMap<Cut<C>, Range<C>> {
private final NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound;
private final NavigableMap<Cut<C>, Range<C>> positiveRangesByUpperBound;
/**
* complementLowerBoundWindow represents the headMap/subMap/tailMap view of the entire
* "complement ranges by lower bound" map; it's a constraint on the *keys*, and does not affect
* the values.
*/
private final Range<Cut<C>> complementLowerBoundWindow;
ComplementRangesByLowerBound(NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound) {
this(positiveRangesByLowerBound, Range.all());
}
private ComplementRangesByLowerBound(
NavigableMap<Cut<C>, Range<C>> positiveRangesByLowerBound, Range<Cut<C>> window) {
this.positiveRangesByLowerBound = positiveRangesByLowerBound;
this.positiveRangesByUpperBound = new RangesByUpperBound<>(positiveRangesByLowerBound);
this.complementLowerBoundWindow = window;
}
private NavigableMap<Cut<C>, Range<C>> subMap(Range<Cut<C>> subWindow) {
if (!complementLowerBoundWindow.isConnected(subWindow)) {
return ImmutableSortedMap.of();
} else {
subWindow = subWindow.intersection(complementLowerBoundWindow);
return new ComplementRangesByLowerBound<>(positiveRangesByLowerBound, subWindow);
}
}
@Override
public NavigableMap<Cut<C>, Range<C>> subMap(
Cut<C> fromKey, boolean fromInclusive, Cut<C> toKey, boolean toInclusive) {
return subMap(
Range.range(
fromKey, BoundType.forBoolean(fromInclusive),
toKey, BoundType.forBoolean(toInclusive)));
}
@Override
public NavigableMap<Cut<C>, Range<C>> headMap(Cut<C> toKey, boolean inclusive) {
return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive)));
}
@Override
public NavigableMap<Cut<C>, Range<C>> tailMap(Cut<C> fromKey, boolean inclusive) {
return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive)));
}
@Override
public Comparator<? super Cut<C>> comparator() {
return Ordering.natural();
}
@Override
Iterator<Entry<Cut<C>, Range<C>>> entryIterator() {
/*
* firstComplementRangeLowerBound is the first complement range lower bound inside
* complementLowerBoundWindow. Complement range lower bounds are either positive range upper
* bounds, or Cut.belowAll().
*
* positiveItr starts at the first positive range with lower bound greater than
* firstComplementRangeLowerBound. (Positive range lower bounds correspond to complement range
* upper bounds.)
*/
Collection<Range<C>> positiveRanges;
if (complementLowerBoundWindow.hasLowerBound()) {
positiveRanges =
positiveRangesByUpperBound
.tailMap(
complementLowerBoundWindow.lowerEndpoint(),
complementLowerBoundWindow.lowerBoundType() == BoundType.CLOSED)
.values();
} else {
positiveRanges = positiveRangesByUpperBound.values();
}
PeekingIterator<Range<C>> positiveItr = peekingIterator(positiveRanges.iterator());
Cut<C> firstComplementRangeLowerBound;
if (complementLowerBoundWindow.contains(Cut.belowAll())
&& (!positiveItr.hasNext() || positiveItr.peek().lowerBound != Cut.<C>belowAll())) {
firstComplementRangeLowerBound = Cut.belowAll();
} else if (positiveItr.hasNext()) {
firstComplementRangeLowerBound = positiveItr.next().upperBound;
} else {
return emptyIterator();
}
return new AbstractIterator<Entry<Cut<C>, Range<C>>>() {
Cut<C> nextComplementRangeLowerBound = firstComplementRangeLowerBound;
@Override
protected @Nullable Entry<Cut<C>, Range<C>> computeNext() {
if (complementLowerBoundWindow.upperBound.isLessThan(nextComplementRangeLowerBound)
|| nextComplementRangeLowerBound == Cut.<C>aboveAll()) {
return endOfData();
}
Range<C> negativeRange;
if (positiveItr.hasNext()) {
Range<C> positiveRange = positiveItr.next();
negativeRange = Range.create(nextComplementRangeLowerBound, positiveRange.lowerBound);
nextComplementRangeLowerBound = positiveRange.upperBound;
} else {
negativeRange = Range.create(nextComplementRangeLowerBound, Cut.aboveAll());
nextComplementRangeLowerBound = Cut.aboveAll();
}
return immutableEntry(negativeRange.lowerBound, negativeRange);
}
};
}
@Override
Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() {
/*
* firstComplementRangeUpperBound is the upper bound of the last complement range with lower
* bound inside complementLowerBoundWindow.
*
* positiveItr starts at the first positive range with upper bound less than
* firstComplementRangeUpperBound. (Positive range upper bounds correspond to complement range
* lower bounds.)
*/
Cut<C> startingPoint =
complementLowerBoundWindow.hasUpperBound()
? complementLowerBoundWindow.upperEndpoint()
: Cut.aboveAll();
boolean inclusive =
complementLowerBoundWindow.hasUpperBound()
&& complementLowerBoundWindow.upperBoundType() == BoundType.CLOSED;
PeekingIterator<Range<C>> positiveItr =
peekingIterator(
positiveRangesByUpperBound
.headMap(startingPoint, inclusive)
.descendingMap()
.values()
.iterator());
Cut<C> cut;
if (positiveItr.hasNext()) {
cut =
(positiveItr.peek().upperBound == Cut.<C>aboveAll())
? positiveItr.next().lowerBound
: positiveRangesByLowerBound.higherKey(positiveItr.peek().upperBound);
} else if (!complementLowerBoundWindow.contains(Cut.belowAll())
|| positiveRangesByLowerBound.containsKey(Cut.belowAll())) {
return emptyIterator();
} else {
cut = positiveRangesByLowerBound.higherKey(Cut.belowAll());
}
Cut<C> firstComplementRangeUpperBound = firstNonNull(cut, Cut.aboveAll());
return new AbstractIterator<Entry<Cut<C>, Range<C>>>() {
Cut<C> nextComplementRangeUpperBound = firstComplementRangeUpperBound;
@Override
protected @Nullable Entry<Cut<C>, Range<C>> computeNext() {
if (nextComplementRangeUpperBound == Cut.<C>belowAll()) {
return endOfData();
} else if (positiveItr.hasNext()) {
Range<C> positiveRange = positiveItr.next();
Range<C> negativeRange =
Range.create(positiveRange.upperBound, nextComplementRangeUpperBound);
nextComplementRangeUpperBound = positiveRange.lowerBound;
if (complementLowerBoundWindow.lowerBound.isLessThan(negativeRange.lowerBound)) {
return immutableEntry(negativeRange.lowerBound, negativeRange);
}
} else if (complementLowerBoundWindow.lowerBound.isLessThan(Cut.belowAll())) {
Range<C> negativeRange = Range.create(Cut.belowAll(), nextComplementRangeUpperBound);
nextComplementRangeUpperBound = Cut.belowAll();
return immutableEntry(Cut.belowAll(), negativeRange);
}
return endOfData();
}
};
}
@Override
public int size() {
return Iterators.size(entryIterator());
}
@Override
public @Nullable Range<C> get(@Nullable Object key) {
if (key instanceof Cut) {
try {
@SuppressWarnings("unchecked")
Cut<C> cut = (Cut<C>) key;
// tailMap respects the current window
Entry<Cut<C>, Range<C>> firstEntry = tailMap(cut, true).firstEntry();
if (firstEntry != null && firstEntry.getKey().equals(cut)) {
return firstEntry.getValue();
}
} catch (ClassCastException e) {
return null;
}
}
return null;
}
@Override
public boolean containsKey(@Nullable Object key) {
return get(key) != null;
}
}
private final | ComplementRangesByLowerBound |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/properties/PropertiesRouteIdTest.java | {
"start": 1157,
"end": 2138
} | class ____ extends ContextTestSupport {
@Test
public void testPropertiesRouteId() {
assertEquals(1, context.getRoutes().size());
assertNotNull(context.getRoute("Camel"), "Route with name Camel should exist");
String id = context.getRouteDefinition("Camel").getOutputs().get(0).getId();
assertEquals("Cheese", id);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").routeId("{{cool.name}}").to("mock:result").id("{{cool.other.name}}");
}
};
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getPropertiesComponent().setLocation("classpath:org/apache/camel/component/properties/myproperties.properties");
return context;
}
}
| PropertiesRouteIdTest |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/AnnotationBasedAuthMechanismSelectionTest.java | {
"start": 14521,
"end": 15462
} | class ____ {
@Inject
SecurityIdentity securityIdentity;
@Path("permit")
@GET
public String permit() {
return "permit";
}
@Path("deny")
@GET
public String deny() {
return "deny";
}
@Path("roles-allowed")
@GET
public String rolesAllowed() {
return "roles-allowed";
}
@Path("roles-allowed-jax-rs-policy")
@GET
public String rolesAllowedJaxRsPolicy() {
return "roles-allowed-jax-rs-policy";
}
@Path("authenticated")
@GET
public String authenticated() {
return "authenticated";
}
@Authenticated
@Path("authenticated-form")
@GET
public String authenticatedNoPolicyFormAuthMech() {
// verifies class-level annotation declared on this | AbstractHttpPermissionsResource |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ParameterizedConstructorInjectionTestClassScopedExtensionContextNestedTests.java | {
"start": 3418,
"end": 3952
} | class ____ {
final String bar;
final ApplicationContext localContext;
AutowiredConstructorParameterTests(@Autowired String bar, ApplicationContext context) {
this.bar = bar;
this.localContext = context;
}
@Test
void nestedTest() {
assertThat(foo).isEqualTo("foo");
assertThat(bar).isEqualTo("bar");
if (beanName.equals("bar")) {
assertThat(localContext.getBean(beanName, String.class)).isEqualTo(beanName);
}
}
}
@Nested
@SpringJUnitConfig(NestedConfig.class)
| AutowiredConstructorParameterTests |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/event/ApplicationEvents.java | {
"start": 2748,
"end": 3682
} | interface ____ {
/**
* Stream all application events that were fired during test execution.
* @return a stream of all application events
* @see #stream(Class)
* @see #clear()
*/
Stream<ApplicationEvent> stream();
/**
* Stream all application events or event payloads of the given type that
* were fired during test execution.
* @param <T> the event type
* @param type the type of events or payloads to stream; never {@code null}
* @return a stream of all application events or event payloads of the
* specified type
* @see #stream()
* @see #clear()
*/
<T> Stream<T> stream(Class<T> type);
/**
* Clear all application events recorded by this {@code ApplicationEvents} instance.
* <p>Subsequent calls to {@link #stream()} or {@link #stream(Class)} will
* only include events recorded since this method was invoked.
* @see #stream()
* @see #stream(Class)
*/
void clear();
}
| ApplicationEvents |
java | apache__avro | lang/java/protobuf/src/test/java/org/apache/avro/protobuf/multiplefiles/Foo.java | {
"start": 9986,
"end": 33476
} | enum ____ is set.
*/
@java.lang.Override
public boolean hasEnum() {
return ((bitField0_ & 0x00008000) != 0);
}
/**
* <code>optional .org.apache.avro.protobuf.multiplefiles.A enum = 16 [default = Z];</code>
*
* @return The enum.
*/
@java.lang.Override
public org.apache.avro.protobuf.multiplefiles.A getEnum() {
org.apache.avro.protobuf.multiplefiles.A result = org.apache.avro.protobuf.multiplefiles.A.forNumber(enum_);
return result == null ? org.apache.avro.protobuf.multiplefiles.A.Z : result;
}
public static final int INTARRAY_FIELD_NUMBER = 17;
@SuppressWarnings("serial")
private com.google.protobuf.Internal.IntList intArray_ = emptyIntList();
/**
* <pre>
* some repeated types
* </pre>
*
* <code>repeated int32 intArray = 17;</code>
*
* @return A list containing the intArray.
*/
@java.lang.Override
public java.util.List<java.lang.Integer> getIntArrayList() {
return intArray_;
}
/**
* <pre>
* some repeated types
* </pre>
*
* <code>repeated int32 intArray = 17;</code>
*
* @return The count of intArray.
*/
public int getIntArrayCount() {
return intArray_.size();
}
/**
* <pre>
* some repeated types
* </pre>
*
* <code>repeated int32 intArray = 17;</code>
*
* @param index The index of the element to return.
* @return The intArray at the given index.
*/
public int getIntArray(int index) {
return intArray_.getInt(index);
}
public static final int FOOARRAY_FIELD_NUMBER = 20;
@SuppressWarnings("serial")
private java.util.List<org.apache.avro.protobuf.multiplefiles.Foo> fooArray_;
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.Foo fooArray = 20;</code>
*/
@java.lang.Override
public java.util.List<org.apache.avro.protobuf.multiplefiles.Foo> getFooArrayList() {
return fooArray_;
}
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.Foo fooArray = 20;</code>
*/
@java.lang.Override
public java.util.List<? extends org.apache.avro.protobuf.multiplefiles.FooOrBuilder> getFooArrayOrBuilderList() {
return fooArray_;
}
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.Foo fooArray = 20;</code>
*/
@java.lang.Override
public int getFooArrayCount() {
return fooArray_.size();
}
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.Foo fooArray = 20;</code>
*/
@java.lang.Override
public org.apache.avro.protobuf.multiplefiles.Foo getFooArray(int index) {
return fooArray_.get(index);
}
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.Foo fooArray = 20;</code>
*/
@java.lang.Override
public org.apache.avro.protobuf.multiplefiles.FooOrBuilder getFooArrayOrBuilder(int index) {
return fooArray_.get(index);
}
public static final int SYMS_FIELD_NUMBER = 19;
@SuppressWarnings("serial")
private java.util.List<java.lang.Integer> syms_;
private static final com.google.protobuf.Internal.ListAdapter.Converter<java.lang.Integer, org.apache.avro.protobuf.multiplefiles.A> syms_converter_ = new com.google.protobuf.Internal.ListAdapter.Converter<java.lang.Integer, org.apache.avro.protobuf.multiplefiles.A>() {
public org.apache.avro.protobuf.multiplefiles.A convert(java.lang.Integer from) {
org.apache.avro.protobuf.multiplefiles.A result = org.apache.avro.protobuf.multiplefiles.A.forNumber(from);
return result == null ? org.apache.avro.protobuf.multiplefiles.A.X : result;
}
};
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.A syms = 19;</code>
*
* @return A list containing the syms.
*/
@java.lang.Override
public java.util.List<org.apache.avro.protobuf.multiplefiles.A> getSymsList() {
return new com.google.protobuf.Internal.ListAdapter<java.lang.Integer, org.apache.avro.protobuf.multiplefiles.A>(
syms_, syms_converter_);
}
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.A syms = 19;</code>
*
* @return The count of syms.
*/
@java.lang.Override
public int getSymsCount() {
return syms_.size();
}
/**
* <code>repeated .org.apache.avro.protobuf.multiplefiles.A syms = 19;</code>
*
* @param index The index of the element to return.
* @return The syms at the given index.
*/
@java.lang.Override
public org.apache.avro.protobuf.multiplefiles.A getSyms(int index) {
return syms_converter_.convert(syms_.get(index));
}
public static final int FOO_FIELD_NUMBER = 18;
private org.apache.avro.protobuf.multiplefiles.Foo foo_;
/**
* <pre>
* a recursive type
* </pre>
*
* <code>optional .org.apache.avro.protobuf.multiplefiles.Foo foo = 18;</code>
*
* @return Whether the foo field is set.
*/
@java.lang.Override
public boolean hasFoo() {
return ((bitField0_ & 0x00010000) != 0);
}
/**
* <pre>
* a recursive type
* </pre>
*
* <code>optional .org.apache.avro.protobuf.multiplefiles.Foo foo = 18;</code>
*
* @return The foo.
*/
@java.lang.Override
public org.apache.avro.protobuf.multiplefiles.Foo getFoo() {
return foo_ == null ? org.apache.avro.protobuf.multiplefiles.Foo.getDefaultInstance() : foo_;
}
/**
* <pre>
* a recursive type
* </pre>
*
* <code>optional .org.apache.avro.protobuf.multiplefiles.Foo foo = 18;</code>
*/
@java.lang.Override
public org.apache.avro.protobuf.multiplefiles.FooOrBuilder getFooOrBuilder() {
return foo_ == null ? org.apache.avro.protobuf.multiplefiles.Foo.getDefaultInstance() : foo_;
}
public static final int TIMESTAMP_FIELD_NUMBER = 21;
private com.google.protobuf.Timestamp timestamp_;
/**
* <pre>
* a predefined message type
* </pre>
*
* <code>optional .google.protobuf.Timestamp timestamp = 21;</code>
*
* @return Whether the timestamp field is set.
*/
@java.lang.Override
public boolean hasTimestamp() {
return ((bitField0_ & 0x00020000) != 0);
}
/**
* <pre>
* a predefined message type
* </pre>
*
* <code>optional .google.protobuf.Timestamp timestamp = 21;</code>
*
* @return The timestamp.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getTimestamp() {
return timestamp_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : timestamp_;
}
/**
* <pre>
* a predefined message type
* </pre>
*
* <code>optional .google.protobuf.Timestamp timestamp = 21;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getTimestampOrBuilder() {
return timestamp_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : timestamp_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1)
return true;
if (isInitialized == 0)
return false;
if (!hasInt32()) {
memoizedIsInitialized = 0;
return false;
}
for (int i = 0; i < getFooArrayCount(); i++) {
if (!getFooArray(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
if (hasFoo()) {
if (!getFoo().isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(1, int32_);
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeInt64(2, int64_);
}
if (((bitField0_ & 0x00000004) != 0)) {
output.writeUInt32(3, uint32_);
}
if (((bitField0_ & 0x00000008) != 0)) {
output.writeUInt64(4, uint64_);
}
if (((bitField0_ & 0x00000010) != 0)) {
output.writeSInt32(5, sint32_);
}
if (((bitField0_ & 0x00000020) != 0)) {
output.writeSInt64(6, sint64_);
}
if (((bitField0_ & 0x00000040) != 0)) {
output.writeFixed32(7, fixed32_);
}
if (((bitField0_ & 0x00000080) != 0)) {
output.writeFixed64(8, fixed64_);
}
if (((bitField0_ & 0x00000100) != 0)) {
output.writeSFixed32(9, sfixed32_);
}
if (((bitField0_ & 0x00000200) != 0)) {
output.writeSFixed64(10, sfixed64_);
}
if (((bitField0_ & 0x00000400) != 0)) {
output.writeFloat(11, float_);
}
if (((bitField0_ & 0x00000800) != 0)) {
output.writeDouble(12, double_);
}
if (((bitField0_ & 0x00001000) != 0)) {
output.writeBool(13, bool_);
}
if (((bitField0_ & 0x00002000) != 0)) {
com.google.protobuf.GeneratedMessage.writeString(output, 14, string_);
}
if (((bitField0_ & 0x00004000) != 0)) {
output.writeBytes(15, bytes_);
}
if (((bitField0_ & 0x00008000) != 0)) {
output.writeEnum(16, enum_);
}
for (int i = 0; i < intArray_.size(); i++) {
output.writeInt32(17, intArray_.getInt(i));
}
if (((bitField0_ & 0x00010000) != 0)) {
output.writeMessage(18, getFoo());
}
for (int i = 0; i < syms_.size(); i++) {
output.writeEnum(19, syms_.get(i));
}
for (int i = 0; i < fooArray_.size(); i++) {
output.writeMessage(20, fooArray_.get(i));
}
if (((bitField0_ & 0x00020000) != 0)) {
output.writeMessage(21, getTimestamp());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1)
return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, int32_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(2, int64_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeUInt32Size(3, uint32_);
}
if (((bitField0_ & 0x00000008) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeUInt64Size(4, uint64_);
}
if (((bitField0_ & 0x00000010) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeSInt32Size(5, sint32_);
}
if (((bitField0_ & 0x00000020) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeSInt64Size(6, sint64_);
}
if (((bitField0_ & 0x00000040) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeFixed32Size(7, fixed32_);
}
if (((bitField0_ & 0x00000080) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeFixed64Size(8, fixed64_);
}
if (((bitField0_ & 0x00000100) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeSFixed32Size(9, sfixed32_);
}
if (((bitField0_ & 0x00000200) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeSFixed64Size(10, sfixed64_);
}
if (((bitField0_ & 0x00000400) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(11, float_);
}
if (((bitField0_ & 0x00000800) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeDoubleSize(12, double_);
}
if (((bitField0_ & 0x00001000) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(13, bool_);
}
if (((bitField0_ & 0x00002000) != 0)) {
size += com.google.protobuf.GeneratedMessage.computeStringSize(14, string_);
}
if (((bitField0_ & 0x00004000) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(15, bytes_);
}
if (((bitField0_ & 0x00008000) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(16, enum_);
}
{
int dataSize = 0;
for (int i = 0; i < intArray_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream.computeInt32SizeNoTag(intArray_.getInt(i));
}
size += dataSize;
size += 2 * getIntArrayList().size();
}
if (((bitField0_ & 0x00010000) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(18, getFoo());
}
{
int dataSize = 0;
for (int i = 0; i < syms_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream.computeEnumSizeNoTag(syms_.get(i));
}
size += dataSize;
size += 2 * syms_.size();
}
for (int i = 0; i < fooArray_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(20, fooArray_.get(i));
}
if (((bitField0_ & 0x00020000) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(21, getTimestamp());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.avro.protobuf.multiplefiles.Foo)) {
return super.equals(obj);
}
org.apache.avro.protobuf.multiplefiles.Foo other = (org.apache.avro.protobuf.multiplefiles.Foo) obj;
if (hasInt32() != other.hasInt32())
return false;
if (hasInt32()) {
if (getInt32() != other.getInt32())
return false;
}
if (hasInt64() != other.hasInt64())
return false;
if (hasInt64()) {
if (getInt64() != other.getInt64())
return false;
}
if (hasUint32() != other.hasUint32())
return false;
if (hasUint32()) {
if (getUint32() != other.getUint32())
return false;
}
if (hasUint64() != other.hasUint64())
return false;
if (hasUint64()) {
if (getUint64() != other.getUint64())
return false;
}
if (hasSint32() != other.hasSint32())
return false;
if (hasSint32()) {
if (getSint32() != other.getSint32())
return false;
}
if (hasSint64() != other.hasSint64())
return false;
if (hasSint64()) {
if (getSint64() != other.getSint64())
return false;
}
if (hasFixed32() != other.hasFixed32())
return false;
if (hasFixed32()) {
if (getFixed32() != other.getFixed32())
return false;
}
if (hasFixed64() != other.hasFixed64())
return false;
if (hasFixed64()) {
if (getFixed64() != other.getFixed64())
return false;
}
if (hasSfixed32() != other.hasSfixed32())
return false;
if (hasSfixed32()) {
if (getSfixed32() != other.getSfixed32())
return false;
}
if (hasSfixed64() != other.hasSfixed64())
return false;
if (hasSfixed64()) {
if (getSfixed64() != other.getSfixed64())
return false;
}
if (hasFloat() != other.hasFloat())
return false;
if (hasFloat()) {
if (java.lang.Float.floatToIntBits(getFloat()) != java.lang.Float.floatToIntBits(other.getFloat()))
return false;
}
if (hasDouble() != other.hasDouble())
return false;
if (hasDouble()) {
if (java.lang.Double.doubleToLongBits(getDouble()) != java.lang.Double.doubleToLongBits(other.getDouble()))
return false;
}
if (hasBool() != other.hasBool())
return false;
if (hasBool()) {
if (getBool() != other.getBool())
return false;
}
if (hasString() != other.hasString())
return false;
if (hasString()) {
if (!getString().equals(other.getString()))
return false;
}
if (hasBytes() != other.hasBytes())
return false;
if (hasBytes()) {
if (!getBytes().equals(other.getBytes()))
return false;
}
if (hasEnum() != other.hasEnum())
return false;
if (hasEnum()) {
if (enum_ != other.enum_)
return false;
}
if (!getIntArrayList().equals(other.getIntArrayList()))
return false;
if (!getFooArrayList().equals(other.getFooArrayList()))
return false;
if (!syms_.equals(other.syms_))
return false;
if (hasFoo() != other.hasFoo())
return false;
if (hasFoo()) {
if (!getFoo().equals(other.getFoo()))
return false;
}
if (hasTimestamp() != other.hasTimestamp())
return false;
if (hasTimestamp()) {
if (!getTimestamp().equals(other.getTimestamp()))
return false;
}
if (!getUnknownFields().equals(other.getUnknownFields()))
return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasInt32()) {
hash = (37 * hash) + INT32_FIELD_NUMBER;
hash = (53 * hash) + getInt32();
}
if (hasInt64()) {
hash = (37 * hash) + INT64_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getInt64());
}
if (hasUint32()) {
hash = (37 * hash) + UINT32_FIELD_NUMBER;
hash = (53 * hash) + getUint32();
}
if (hasUint64()) {
hash = (37 * hash) + UINT64_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getUint64());
}
if (hasSint32()) {
hash = (37 * hash) + SINT32_FIELD_NUMBER;
hash = (53 * hash) + getSint32();
}
if (hasSint64()) {
hash = (37 * hash) + SINT64_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSint64());
}
if (hasFixed32()) {
hash = (37 * hash) + FIXED32_FIELD_NUMBER;
hash = (53 * hash) + getFixed32();
}
if (hasFixed64()) {
hash = (37 * hash) + FIXED64_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getFixed64());
}
if (hasSfixed32()) {
hash = (37 * hash) + SFIXED32_FIELD_NUMBER;
hash = (53 * hash) + getSfixed32();
}
if (hasSfixed64()) {
hash = (37 * hash) + SFIXED64_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSfixed64());
}
if (hasFloat()) {
hash = (37 * hash) + FLOAT_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getFloat());
}
if (hasDouble()) {
hash = (37 * hash) + DOUBLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(java.lang.Double.doubleToLongBits(getDouble()));
}
if (hasBool()) {
hash = (37 * hash) + BOOL_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getBool());
}
if (hasString()) {
hash = (37 * hash) + STRING_FIELD_NUMBER;
hash = (53 * hash) + getString().hashCode();
}
if (hasBytes()) {
hash = (37 * hash) + BYTES_FIELD_NUMBER;
hash = (53 * hash) + getBytes().hashCode();
}
if (hasEnum()) {
hash = (37 * hash) + ENUM_FIELD_NUMBER;
hash = (53 * hash) + enum_;
}
if (getIntArrayCount() > 0) {
hash = (37 * hash) + INTARRAY_FIELD_NUMBER;
hash = (53 * hash) + getIntArrayList().hashCode();
}
if (getFooArrayCount() > 0) {
hash = (37 * hash) + FOOARRAY_FIELD_NUMBER;
hash = (53 * hash) + getFooArrayList().hashCode();
}
if (getSymsCount() > 0) {
hash = (37 * hash) + SYMS_FIELD_NUMBER;
hash = (53 * hash) + syms_.hashCode();
}
if (hasFoo()) {
hash = (37 * hash) + FOO_FIELD_NUMBER;
hash = (53 * hash) + getFoo().hashCode();
}
if (hasTimestamp()) {
hash = (37 * hash) + TIMESTAMP_FIELD_NUMBER;
hash = (53 * hash) + getTimestamp().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseDelimitedFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input);
}
public static org.apache.avro.protobuf.multiplefiles.Foo parseFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(org.apache.avro.protobuf.multiplefiles.Foo prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.apache.avro.protobuf.multiplefiles.Foo}
*/
public static final | field |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/ibmwatsonx/completion/IbmWatsonxChatCompletionServiceSettings.java | {
"start": 1881,
"end": 7131
} | class ____ extends FilteredXContentObject
implements
ServiceSettings,
IbmWatsonxRateLimitServiceSettings {
public static final String NAME = "ibm_watsonx_completion_service_settings";
private static final TransportVersion ML_INFERENCE_IBM_WATSONX_COMPLETION_ADDED = TransportVersion.fromName(
"ml_inference_ibm_watsonx_completion_added"
);
/**
* Rate limits are defined at
* <a href="https://www.ibm.com/docs/en/watsonx/saas?topic=learning-watson-machine-plans">Watson Machine Learning plans</a>.
* For the Lite plan, the limit is 120 requests per minute.
*/
private static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(120);
public static IbmWatsonxChatCompletionServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) {
ValidationException validationException = new ValidationException();
String url = extractRequiredString(map, URL, ModelConfigurations.SERVICE_SETTINGS, validationException);
URI uri = convertToUri(url, URL, ModelConfigurations.SERVICE_SETTINGS, validationException);
String apiVersion = extractRequiredString(map, API_VERSION, ModelConfigurations.SERVICE_SETTINGS, validationException);
String modelId = extractRequiredString(map, MODEL_ID, ModelConfigurations.SERVICE_SETTINGS, validationException);
String projectId = extractRequiredString(map, PROJECT_ID, ModelConfigurations.SERVICE_SETTINGS, validationException);
RateLimitSettings rateLimitSettings = RateLimitSettings.of(
map,
DEFAULT_RATE_LIMIT_SETTINGS,
validationException,
IbmWatsonxService.NAME,
context
);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
return new IbmWatsonxChatCompletionServiceSettings(uri, apiVersion, modelId, projectId, rateLimitSettings);
}
private final URI uri;
private final String apiVersion;
private final String modelId;
private final String projectId;
private final RateLimitSettings rateLimitSettings;
public IbmWatsonxChatCompletionServiceSettings(
URI uri,
String apiVersion,
String modelId,
String projectId,
@Nullable RateLimitSettings rateLimitSettings
) {
this.uri = uri;
this.apiVersion = apiVersion;
this.projectId = projectId;
this.modelId = modelId;
this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS);
}
public IbmWatsonxChatCompletionServiceSettings(StreamInput in) throws IOException {
this.uri = createUri(in.readString());
this.apiVersion = in.readString();
this.modelId = in.readString();
this.projectId = in.readString();
this.rateLimitSettings = new RateLimitSettings(in);
}
public URI uri() {
return uri;
}
public String apiVersion() {
return apiVersion;
}
@Override
public String modelId() {
return modelId;
}
public String projectId() {
return projectId;
}
@Override
public RateLimitSettings rateLimitSettings() {
return rateLimitSettings;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
toXContentFragmentOfExposedFields(builder, params);
builder.endObject();
return builder;
}
@Override
protected XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException {
builder.field(URL, uri.toString());
builder.field(API_VERSION, apiVersion);
builder.field(MODEL_ID, modelId);
builder.field(PROJECT_ID, projectId);
rateLimitSettings.toXContent(builder, params);
return builder;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return ML_INFERENCE_IBM_WATSONX_COMPLETION_ADDED;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(uri.toString());
out.writeString(apiVersion);
out.writeString(modelId);
out.writeString(projectId);
rateLimitSettings.writeTo(out);
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
IbmWatsonxChatCompletionServiceSettings that = (IbmWatsonxChatCompletionServiceSettings) object;
return Objects.equals(uri, that.uri)
&& Objects.equals(apiVersion, that.apiVersion)
&& Objects.equals(modelId, that.modelId)
&& Objects.equals(projectId, that.projectId)
&& Objects.equals(rateLimitSettings, that.rateLimitSettings);
}
@Override
public int hashCode() {
return Objects.hash(uri, apiVersion, modelId, projectId, rateLimitSettings);
}
}
| IbmWatsonxChatCompletionServiceSettings |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/module/SimpleModuleArgCheckTest.java | {
"start": 277,
"end": 3039
} | class ____ extends DatabindTestUtil
{
/*
/**********************************************************
/* Unit tests for invalid deserializers
/**********************************************************
*/
@Test
public void testInvalidForDeserializers() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
try {
mod.addDeserializer(String.class, null);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as deserializer");
}
try {
mod.addKeyDeserializer(String.class, null);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as key deserializer");
}
}
/*
/**********************************************************
/* Unit tests for invalid misc other
/**********************************************************
*/
@Test
public void testInvalidAbstractTypeMapping() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
try {
mod.addAbstractTypeMapping(null, String.class);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as abstract type to map");
}
try {
mod.addAbstractTypeMapping(String.class, null);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as concrete type to map to");
}
}
@Test
public void testInvalidSubtypeMappings() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
try {
mod.registerSubtypes(String.class, null);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as subtype to register");
}
try {
mod.registerSubtypes(new NamedType(Integer.class), (NamedType) null);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as subtype to register");
}
}
@Test
public void testInvalidValueInstantiator() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
try {
mod.addValueInstantiator(null, null);
fail("Should not pass");
} catch (IllegalArgumentException e) {
verifyException(e, "Cannot pass `null` as | SimpleModuleArgCheckTest |
java | apache__dubbo | dubbo-remoting/dubbo-remoting-netty4/src/main/java/org/apache/dubbo/remoting/transport/netty4/logging/MessageFormatter.java | {
"start": 3587,
"end": 14481
} | class ____ {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MessageFormatter.class);
static final char DELIM_START = '{';
static final char DELIM_STOP = '}';
static final String DELIM_STR = "{}";
private static final char ESCAPE_CHAR = '\\';
/**
* Performs single argument substitution for the 'messagePattern' passed as
* parameter.
* <p/>
* For example,
* <p/>
* <pre>
* MessageFormatter.format("Hi {}.", "there");
* </pre>
* <p/>
* will return the string "Hi there.".
* <p/>
*
* @param messagePattern The message pattern which will be parsed and formatted
* @param arg The argument to be substituted in place of the formatting anchor
* @return The formatted message
*/
static FormattingTuple format(String messagePattern, Object arg) {
return arrayFormat(messagePattern, new Object[] {arg});
}
/**
* Performs a two argument substitution for the 'messagePattern' passed as
* parameter.
* <p/>
* For example,
* <p/>
* <pre>
* MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
* </pre>
* <p/>
* will return the string "Hi Alice. My name is Bob.".
*
* @param messagePattern The message pattern which will be parsed and formatted
* @param argA The argument to be substituted in place of the first formatting
* anchor
* @param argB The argument to be substituted in place of the second formatting
* anchor
* @return The formatted message
*/
static FormattingTuple format(final String messagePattern, Object argA, Object argB) {
return arrayFormat(messagePattern, new Object[] {argA, argB});
}
static Throwable getThrowableCandidate(Object[] argArray) {
if (ArrayUtils.isEmpty(argArray)) {
return null;
}
final Object lastEntry = argArray[argArray.length - 1];
if (lastEntry instanceof Throwable) {
return (Throwable) lastEntry;
}
return null;
}
/**
* Same principle as the {@link #format(String, Object)} and
* {@link #format(String, Object, Object)} methods except that any number of
* arguments can be passed in an array.
*
* @param messagePattern The message pattern which will be parsed and formatted
* @param argArray An array of arguments to be substituted in place of formatting
* anchors
* @return The formatted message
*/
static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) {
Throwable throwableCandidate = getThrowableCandidate(argArray);
if (messagePattern == null) {
return new FormattingTuple(null, argArray, throwableCandidate);
}
if (argArray == null) {
return new FormattingTuple(messagePattern);
}
int i = 0;
int j;
StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50);
int l;
for (l = 0; l < argArray.length; l++) {
j = messagePattern.indexOf(DELIM_STR, i);
if (j == -1) {
// no more variables
if (i == 0) { // this is a simple string
return new FormattingTuple(messagePattern, argArray, throwableCandidate);
} else { // add the tail string which contains no variables and return
// the result.
sbuf.append(messagePattern.substring(i));
return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
}
} else {
if (isEscapedDelimeter(messagePattern, j)) {
if (!isDoubleEscaped(messagePattern, j)) {
l--; // DELIM_START was escaped, thus should not be incremented
sbuf.append(messagePattern, i, j - 1);
sbuf.append(DELIM_START);
i = j + 1;
} else {
// The escape character preceding the delimiter start is
// itself escaped: "abc x:\\{}"
// we have to consume one backward slash
sbuf.append(messagePattern, i, j - 1);
deeplyAppendParameter(sbuf, argArray[l], new HashMap<Object[], Void>());
i = j + 2;
}
} else {
// normal case
sbuf.append(messagePattern, i, j);
deeplyAppendParameter(sbuf, argArray[l], new HashMap<Object[], Void>());
i = j + 2;
}
}
}
// append the characters following the last {} pair.
sbuf.append(messagePattern.substring(i));
if (l < argArray.length - 1) {
return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
} else {
return new FormattingTuple(sbuf.toString(), argArray, null);
}
}
static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
if (delimeterStartIndex == 0) {
return false;
}
return messagePattern.charAt(delimeterStartIndex - 1) == ESCAPE_CHAR;
}
static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR;
}
// special treatment of array values was suggested by 'lizongbo'
private static void deeplyAppendParameter(StringBuffer sbuf, Object o, Map<Object[], Void> seenMap) {
if (o == null) {
sbuf.append("null");
return;
}
if (!o.getClass().isArray()) {
safeObjectAppend(sbuf, o);
} else {
// check for primitive array types because they
// unfortunately cannot be cast to Object[]
if (o instanceof boolean[]) {
booleanArrayAppend(sbuf, (boolean[]) o);
} else if (o instanceof byte[]) {
byteArrayAppend(sbuf, (byte[]) o);
} else if (o instanceof char[]) {
charArrayAppend(sbuf, (char[]) o);
} else if (o instanceof short[]) {
shortArrayAppend(sbuf, (short[]) o);
} else if (o instanceof int[]) {
intArrayAppend(sbuf, (int[]) o);
} else if (o instanceof long[]) {
longArrayAppend(sbuf, (long[]) o);
} else if (o instanceof float[]) {
floatArrayAppend(sbuf, (float[]) o);
} else if (o instanceof double[]) {
doubleArrayAppend(sbuf, (double[]) o);
} else {
objectArrayAppend(sbuf, (Object[]) o, seenMap);
}
}
}
private static void safeObjectAppend(StringBuffer sbuf, Object o) {
try {
String oAsString = o.toString();
sbuf.append(oAsString);
} catch (Throwable t) {
System.err.println("SLF4J: Failed toString() invocation on an object of type ["
+ o.getClass().getName() + ']');
logger.error(TRANSPORT_UNSUPPORTED_MESSAGE, "", "", t.getMessage(), t);
sbuf.append("[FAILED toString()]");
}
}
private static void objectArrayAppend(StringBuffer sbuf, Object[] a, Map<Object[], Void> seenMap) {
sbuf.append('[');
if (!seenMap.containsKey(a)) {
seenMap.put(a, null);
final int len = a.length;
for (int i = 0; i < len; i++) {
deeplyAppendParameter(sbuf, a[i], seenMap);
if (i != len - 1) {
sbuf.append(", ");
}
}
// allow repeats in siblings
seenMap.remove(a);
} else {
sbuf.append("...");
}
sbuf.append(']');
}
private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void byteArrayAppend(StringBuffer sbuf, byte[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void charArrayAppend(StringBuffer sbuf, char[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void shortArrayAppend(StringBuffer sbuf, short[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void intArrayAppend(StringBuffer sbuf, int[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void longArrayAppend(StringBuffer sbuf, long[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void floatArrayAppend(StringBuffer sbuf, float[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void doubleArrayAppend(StringBuffer sbuf, double[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private MessageFormatter() {}
}
| MessageFormatter |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ParentPk.java | {
"start": 307,
"end": 965
} | class ____ implements Serializable {
@Column(length = 50)
String firstName;
String lastName;
/**
* is a male or a female
*/
//show hetereogenous PK types
boolean isMale;
public int hashCode() {
//this implem sucks
return firstName.hashCode() + lastName.hashCode() + ( isMale ? 0 : 1 );
}
public boolean equals(Object obj) {
//firstName and lastName are expected to be set in this implem
if ( obj != null && obj instanceof ParentPk ) {
ParentPk other = (ParentPk) obj;
return firstName.equals( other.firstName )
&& lastName.equals( other.lastName )
&& isMale == other.isMale;
}
else {
return false;
}
}
}
| ParentPk |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/search/aggregate/ReducerParams.java | {
"start": 757,
"end": 1332
} | class ____ implements Reducer {
private String as;
private String functionName;
private List<String> args;
ReducerParams(String functionName, String... args) {
this.functionName = functionName;
this.args = Arrays.asList(args);
}
@Override
public Reducer as(String alias) {
this.as = alias;
return this;
}
public String getAs() {
return as;
}
public String getFunctionName() {
return functionName;
}
public List<String> getArgs() {
return args;
}
}
| ReducerParams |
java | apache__maven | api/maven-api-core/src/main/java/org/apache/maven/api/services/ArtifactCoordinatesFactoryRequest.java | {
"start": 5843,
"end": 9339
} | class ____ extends BaseRequest<Session>
implements ArtifactCoordinatesFactoryRequest {
private final String groupId;
private final String artifactId;
private final String version;
private final String classifier;
private final String extension;
private final String type;
private final String coordinatesString;
@SuppressWarnings("checkstyle:ParameterNumber")
DefaultArtifactFactoryRequestArtifact(
@Nonnull Session session,
RequestTrace trace,
String groupId,
String artifactId,
String version,
String classifier,
String extension,
String type,
String coordinatesString) {
super(session, trace);
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.classifier = classifier;
this.extension = extension;
this.type = type;
this.coordinatesString = coordinatesString;
}
@Override
public String getGroupId() {
return groupId;
}
@Override
public String getArtifactId() {
return artifactId;
}
@Override
public String getVersion() {
return version;
}
@Override
public String getClassifier() {
return classifier;
}
@Override
public String getExtension() {
return extension;
}
@Override
public String getType() {
return type;
}
@Override
public String getCoordinatesString() {
return coordinatesString;
}
@Override
public boolean equals(Object o) {
return o instanceof DefaultArtifactFactoryRequestArtifact that
&& Objects.equals(groupId, that.groupId)
&& Objects.equals(artifactId, that.artifactId)
&& Objects.equals(version, that.version)
&& Objects.equals(classifier, that.classifier)
&& Objects.equals(extension, that.extension)
&& Objects.equals(type, that.type)
&& Objects.equals(coordinatesString, that.coordinatesString);
}
@Override
public int hashCode() {
return Objects.hash(groupId, artifactId, version, classifier, extension, type, coordinatesString);
}
@Override
public String toString() {
return "ArtifactFactoryRequestArtifact[" + "groupId='"
+ groupId + '\'' + ", artifactId='"
+ artifactId + '\'' + ", version='"
+ version + '\'' + ", classifier='"
+ classifier + '\'' + ", extension='"
+ extension + '\'' + ", type='"
+ type + '\'' + ", coordinatesString='"
+ coordinatesString + '\'' + ']';
}
}
}
}
| DefaultArtifactFactoryRequestArtifact |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/internal/ProxyFactoryFactoryInitiator.java | {
"start": 659,
"end": 1235
} | class ____ implements StandardServiceInitiator<ProxyFactoryFactory> {
/**
* Singleton access
*/
public static final StandardServiceInitiator<ProxyFactoryFactory> INSTANCE = new ProxyFactoryFactoryInitiator();
@Override
public ProxyFactoryFactory initiateService(Map<String, Object> configurationValues, ServiceRegistryImplementor registry) {
return registry.requireService( BytecodeProvider.class ).getProxyFactoryFactory();
}
@Override
public Class<ProxyFactoryFactory> getServiceInitiated() {
return ProxyFactoryFactory.class;
}
}
| ProxyFactoryFactoryInitiator |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/FunctionsTest.java | {
"start": 38175,
"end": 38613
} | interface ____ properly defined to throw any exception. using the top level generic types
* Object and Throwable.
*/
@Test
void testThrows_FailableRunnable_Object_Throwable() {
new Functions.FailableRunnable<Throwable>() {
@Override
public void run() throws Throwable {
throw new IOException("test");
}
};
}
/**
* Tests that our failable | is |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/unmappedsource/SourceTargetMapperWithoutMapperConfig.java | {
"start": 422,
"end": 680
} | interface ____ {
SourceTargetMapperWithoutMapperConfig INSTANCE = Mappers.getMapper( SourceTargetMapperWithoutMapperConfig.class );
Target sourceToTarget(Source source);
Source targetToSource(Target target);
}
| SourceTargetMapperWithoutMapperConfig |
java | quarkusio__quarkus | extensions/devui/deployment/src/main/java/io/quarkus/vertx/http/deployment/console/ConsoleProcessor.java | {
"start": 10013,
"end": 10560
} | class ____ implements CommandValidator<SetConfigCommand, CommandInvocation> {
@Override
public void validate(SetConfigCommand command) throws CommandValidatorException {
//-1 because the last char can't be equals
for (int i = 0; i < command.command.length() - 1; ++i) {
if (command.command.charAt(i) == '=') {
return;
}
}
throw new CommandValidatorException("Set command must be in the form key=value");
}
}
}
| SetValidator |
java | apache__hadoop | hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KeyAuthorizationKeyProvider.java | {
"start": 2216,
"end": 2412
} | class ____ extends KeyProviderCryptoExtension {
public static final String KEY_ACL = "key.acl.";
private static final String KEY_ACL_NAME = KEY_ACL + "name";
public | KeyAuthorizationKeyProvider |
java | grpc__grpc-java | core/src/test/java/io/grpc/internal/TransportFrameUtilTest.java | {
"start": 1452,
"end": 5978
} | class ____ {
private static final String NONCOMPLIANT_ASCII_STRING = new String(new char[]{1, 2, 3});
private static final String COMPLIANT_ASCII_STRING = "Kyle";
private static final BinaryMarshaller<String> UTF8_STRING_MARSHALLER =
new BinaryMarshaller<String>() {
@Override
public byte[] toBytes(String value) {
return value.getBytes(UTF_8);
}
@Override
public String parseBytes(byte[] serialized) {
return new String(serialized, UTF_8);
}
};
private static final Metadata.Key<String> PLAIN_STRING =
Metadata.Key.of("plainstring", ASCII_STRING_MARSHALLER);
private static final Metadata.Key<String> BINARY_STRING =
Metadata.Key.of("string-bin", UTF8_STRING_MARSHALLER);
private static final Metadata.Key<String> BINARY_STRING_WITHOUT_SUFFIX =
Metadata.Key.of("string", ASCII_STRING_MARSHALLER);
private static final Metadata.Key<byte[]> BINARY_BYTES =
Metadata.Key.of("bytes-bin", BINARY_BYTE_MARSHALLER);
@Test
public void testToHttp2Headers() {
Metadata headers = new Metadata();
headers.put(PLAIN_STRING, COMPLIANT_ASCII_STRING);
headers.put(BINARY_STRING, NONCOMPLIANT_ASCII_STRING);
headers.put(BINARY_STRING_WITHOUT_SUFFIX, NONCOMPLIANT_ASCII_STRING);
byte[][] http2Headers = TransportFrameUtil.toHttp2Headers(headers);
// BINARY_STRING_WITHOUT_SUFFIX should not get in because it contains non-compliant ASCII
// characters but doesn't have "-bin" in the name.
byte[][] answer = new byte[][] {
"plainstring".getBytes(US_ASCII), COMPLIANT_ASCII_STRING.getBytes(US_ASCII),
"string-bin".getBytes(US_ASCII),
base64Encode(NONCOMPLIANT_ASCII_STRING.getBytes(US_ASCII))};
assertEquals(answer.length, http2Headers.length);
// http2Headers may re-sort the keys, so we cannot compare it with the answer side-by-side.
for (int i = 0; i < answer.length; i += 2) {
assertContains(http2Headers, answer[i], answer[i + 1]);
}
}
@Test(expected = IllegalArgumentException.class)
public void binaryHeaderWithoutSuffix() {
Metadata.Key.of("plainstring", UTF8_STRING_MARSHALLER);
}
@Test
public void testToAndFromHttp2Headers() {
Metadata headers = new Metadata();
headers.put(PLAIN_STRING, COMPLIANT_ASCII_STRING);
headers.put(BINARY_STRING, NONCOMPLIANT_ASCII_STRING);
headers.put(BINARY_STRING_WITHOUT_SUFFIX, NONCOMPLIANT_ASCII_STRING);
byte[][] http2Headers = TransportFrameUtil.toHttp2Headers(headers);
byte[][] rawSerialized = TransportFrameUtil.toRawSerializedHeaders(http2Headers);
Metadata recoveredHeaders = InternalMetadata.newMetadata(rawSerialized);
assertEquals(COMPLIANT_ASCII_STRING, recoveredHeaders.get(PLAIN_STRING));
assertEquals(NONCOMPLIANT_ASCII_STRING, recoveredHeaders.get(BINARY_STRING));
assertNull(recoveredHeaders.get(BINARY_STRING_WITHOUT_SUFFIX));
}
@Test
public void dupBinHeadersWithComma() {
byte[][] http2Headers = new byte[][] {
BINARY_BYTES.name().getBytes(US_ASCII),
"BaS,e6,,4+,padding==".getBytes(US_ASCII),
BINARY_BYTES.name().getBytes(US_ASCII),
"more".getBytes(US_ASCII),
BINARY_BYTES.name().getBytes(US_ASCII),
"".getBytes(US_ASCII)};
byte[][] rawSerialized = TransportFrameUtil.toRawSerializedHeaders(http2Headers);
Metadata recoveredHeaders = InternalMetadata.newMetadata(rawSerialized);
byte[][] values = Iterables.toArray(recoveredHeaders.getAll(BINARY_BYTES), byte[].class);
assertTrue(Arrays.deepEquals(
new byte[][] {
BaseEncoding.base64().decode("BaS"),
BaseEncoding.base64().decode("e6"),
BaseEncoding.base64().decode(""),
BaseEncoding.base64().decode("4+"),
BaseEncoding.base64().decode("padding"),
BaseEncoding.base64().decode("more"),
BaseEncoding.base64().decode("")},
values));
}
private static void assertContains(byte[][] headers, byte[] key, byte[] value) {
String keyString = new String(key, US_ASCII);
for (int i = 0; i < headers.length; i += 2) {
if (Arrays.equals(headers[i], key)) {
assertArrayEquals("value for key=" + keyString, value, headers[i + 1]);
return;
}
}
fail("key=" + keyString + " not found");
}
private static byte[] base64Encode(byte[] input) {
return InternalMetadata.BASE64_ENCODING_OMIT_PADDING.encode(input).getBytes(US_ASCII);
}
}
| TransportFrameUtilTest |
java | square__javapoet | src/test/java/com/squareup/javapoet/TypeSpecTest.java | {
"start": 54751,
"end": 55460
} | class ____ {\n"
+ " }\n"
+ "}\n");
}
@Test public void defaultModifiersForMemberInterfacesAndEnums() throws Exception {
TypeSpec taco = TypeSpec.classBuilder("Taco")
.addType(TypeSpec.classBuilder("Meat")
.addModifiers(Modifier.STATIC)
.build())
.addType(TypeSpec.interfaceBuilder("Tortilla")
.addModifiers(Modifier.STATIC)
.build())
.addType(TypeSpec.enumBuilder("Topping")
.addModifiers(Modifier.STATIC)
.addEnumConstant("SALSA")
.build())
.build();
assertThat(toString(taco)).isEqualTo(""
+ "package com.squareup.tacos;\n"
+ "\n"
+ " | Topping |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-catalog/hadoop-yarn-applications-catalog-webapp/src/main/java/org/apache/hadoop/yarn/appcatalog/controller/AppStoreController.java | {
"start": 1505,
"end": 6163
} | class ____ {
public AppStoreController() {
}
/**
* Display the most frequently used applications on YARN AppCatalog home page.
*
* @apiGroup AppStoreController
* @apiName get
* @api {get} /app_store/recommended Display recommended applications.
* @apiSuccess {Object} AppEntry Application configuration.
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id":"96b7833a-e3",
* "org":"Hortonworks",
* "name":"LAMP",
* "desc":"Linux Apache MySQL PHP web application",
* "icon":"/css/img/feather.png",
* "like":0,
* "download":0,
* "app":null
* },
* {
* ...
* }
* ]
* @return - List of YARN applications
*/
@GET
@Path("recommended")
@Produces(MediaType.APPLICATION_JSON)
public List<AppStoreEntry> get() {
AppCatalogSolrClient sc = new AppCatalogSolrClient();
return sc.getRecommendedApps();
}
/**
* Search for yarn applications from solr.
*
* @apiGroup AppStoreController
* @apiName search
* @api {get} /app_store/search Find application from appstore.
* @apiParam {String} q Keyword to search.
* @apiSuccess {Object} AppStoreEntry List of matched applications.
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id":"96b7833a-e3",
* "org":"Hortonworks",
* "name":"LAMP",
* "desc":"Linux Apache MySQL PHP web application",
* "icon":"/css/img/feather.png",
* "like":0,
* "download":0,
* "app":null
* },
* {
* ...
* }
* ]
* @param keyword - search for keyword
* @return - List of YARN applications matching keyword search.
*/
@GET
@Path("search")
@Produces(MediaType.APPLICATION_JSON)
public List<AppStoreEntry> search(@QueryParam("q") String keyword) {
AppCatalogSolrClient sc = new AppCatalogSolrClient();
return sc.search(keyword);
}
/**
* Find yarn application from solr.
*
* @param id Application ID
* @return AppEntry
*/
@GET
@Path("get/{id}")
@Produces(MediaType.APPLICATION_JSON)
public AppStoreEntry get(@PathParam("id") String id) {
AppCatalogSolrClient sc = new AppCatalogSolrClient();
return sc.findAppStoreEntry(id);
}
/**
* Register an application.
*
* @apiGroup AppStoreController
* @apiName register
* @api {post} /app_store/register Register an application in appstore.
* @apiParam {Object} app Application definition.
* @apiParamExample {json} Request-Example:
* {
* "name": "Jenkins",
* "organization": "Jenkins-ci.org",
* "description": "The leading open source automation server",
* "icon": "/css/img/jenkins.png",
* "lifetime": "3600",
* "components": [
* {
* "name": "jenkins",
* "number_of_containers": 1,
* "artifact": {
* "id": "eyang-1.openstacklocal:5000/jenkins:latest",
* "type": "DOCKER"
* },
* "launch_command": "",
* "resource": {
* "cpus": 1,
* "memory": "2048"
* },
* "configuration": {
* "env": {
* },
* "files": [
* ]
* }
* }
* ],
* "quicklinks": {
* "Jenkins UI": "http://jenkins.${SERVICE_NAME}.${USER}.${DOMAIN}:8080/"
* }
* }
* @apiSuccess {String} Response Application register result.
* @apiError BadRequest Error in process application registration.
* @param app - Yarnfile in JSON form
* @return Web response
*/
@POST
@Path("register")
@Produces(MediaType.APPLICATION_JSON)
public Response register(Application app) {
try {
if (app.getName()==null) {
throw new IOException("Application name can not be empty.");
}
if (app.getOrganization()==null) {
throw new IOException("Application organization can not be empty.");
}
if (app.getDescription()==null) {
throw new IOException("Application description can not be empty.");
}
AppCatalogSolrClient sc = new AppCatalogSolrClient();
sc.register(app);
} catch (IOException e) {
return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
}
return Response.status(Status.ACCEPTED).build();
}
}
| AppStoreController |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/models/xml/internal/XmlProcessingHelper.java | {
"start": 821,
"end": 1003
} | class ____ in XML, accounting for {@code <package/>}
*
* @param jaxbRoot The {@code <entity-mappings/>} node for access to the package (if one)
* @param jaxbManagedType The | defined |
java | apache__camel | components/camel-stream/src/test/java/org/apache/camel/component/stream/StreamRouteBuilderTest.java | {
"start": 990,
"end": 1616
} | class ____ extends CamelTestSupport {
@Test
public void testStringContent() {
template.sendBody("direct:start", "this is text\n");
}
@Test
public void testBinaryContent() {
template.sendBody("direct:start", "This is bytes\n".getBytes());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").setHeader("stream", constant(System.out))
.to("stream:err", "stream:out", "stream:header");
}
};
}
}
| StreamRouteBuilderTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TypeNameShadowingTest.java | {
"start": 7950,
"end": 8510
} | class ____ {}
<T2, U2> void f(T2 t, U2 u) {}
}
""")
.doTest();
}
/**
* Tests that we only suggest a fix when the type variable name is style-guide-adherent;
* otherwise, it is likely the developer did not mean to use a generic and the fix is misleading
* Input program here is alpha-equivalent to the refactorMultiple test case; output only fixes T
*/
@Test
public void fixOnlyWellNamedVariables() {
refactoring
.addInputLines(
"in/Foo.java",
"""
| U |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/TableFunction.java | {
"start": 4576,
"end": 5612
} | class ____ extends TableFunction<String> {
*
* // implement an "eval" method with as many parameters as you want
* public void eval(String str) {
* for (String s : str.split(" ")) {
* collect(s); // use collect(...) to emit an output row
* }
* }
*
* // you can overload the eval method here ...
* }
*
* TableEnvironment tEnv = ...
* Table table = ... // schema: ROW< a VARCHAR >
*
* // for Scala users
* table.joinLateral(call(classOf[Split], $"a") as ("s")).select($"a", $"s")
*
* // for Java users
* table.joinLateral(call(Split.class, $("a")).as("s")).select($("a"), $("s"));
*
* // for SQL users
* tEnv.createTemporarySystemFunction("split", Split.class); // register table function first
* tEnv.sqlQuery("SELECT a, s FROM MyTable, LATERAL TABLE(split(a)) as T(s)");
* }</pre>
*
* @param <T> The type of the output row. Either an explicit composite type or an atomic type that
* is implicitly wrapped into a row consisting of one field.
*/
@PublicEvolving
public abstract | Split |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateSequenceTest_5_noorder.java | {
"start": 1021,
"end": 2656
} | class ____ extends OracleTest {
public void test_0() throws Exception {
String sql = //
"CREATE SEQUENCE \"GJS_ZIXUN\".\"FINANCE_EXPLAIN_ID_GENERATOR\" NOORDER";
OracleStatementParser parser = new OracleStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
assertEquals("CREATE SEQUENCE \"GJS_ZIXUN\".\"FINANCE_EXPLAIN_ID_GENERATOR\" NOORDER",
SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE));
OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("relationships : " + visitor.getRelationships());
System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(0, visitor.getTables().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("cdc.en_complaint_ipr_stat_fdt0")));
assertEquals(0, visitor.getColumns().size());
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*")));
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR")));
// assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode")));
}
}
| OracleCreateSequenceTest_5_noorder |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/factories/TestProcedureCatalogFactory.java | {
"start": 5493,
"end": 6609
} | class ____ implements Procedure {
public long[] call(ProcedureContext procedureContext, int n) throws Exception {
return generate(procedureContext.getExecutionEnvironment(), n);
}
public long[] call(ProcedureContext procedureContext, int n, String runTimeMode)
throws Exception {
StreamExecutionEnvironment env = procedureContext.getExecutionEnvironment();
env.setRuntimeMode(RuntimeExecutionMode.valueOf(runTimeMode));
return generate(env, n);
}
private long[] generate(StreamExecutionEnvironment env, int n) throws Exception {
env.setParallelism(1);
long[] sequenceN = new long[n];
int i = 0;
try (CloseableIterator<Long> result = env.fromSequence(0, n - 1).executeAndCollect()) {
while (result.hasNext()) {
sequenceN[i++] = result.next();
}
}
return sequenceN;
}
}
/** A procedure to sum decimal values for testing purpose. */
public static | GenerateSequenceProcedure |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryBuilder.java | {
"start": 1061,
"end": 1416
} | class ____ custom implementors of SessionFactoryBuilder, using delegation
*
* @author Steve Ebersole
* @author Gunnar Morling
* @author Guillaume Smet
*
* @param <T> The specific subclass; Allows subclasses to narrow the return type of the contract methods
* to a specialization of {@link MetadataBuilderImplementor}.
*/
public abstract | for |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/examples/CoreExamples.java | {
"start": 9299,
"end": 9447
} | class ____ extends VerticleBase {
}
public void example9(Vertx vertx) {
// Deploy a Java verticle - the name is the fully qualified | MyVerticle |
java | apache__flink | flink-python/src/main/java/org/apache/flink/streaming/api/operators/python/process/ExternalPythonKeyedProcessOperator.java | {
"start": 3264,
"end": 11356
} | class ____<OUT>
extends AbstractExternalOneInputPythonFunctionOperator<Row, OUT>
implements Triggerable<Row, Object> {
private static final long serialVersionUID = 2L;
/** The TypeSerializer of the namespace. */
private final TypeSerializer namespaceSerializer;
/** TimerService for current operator to register or fire timer. */
private transient InternalTimerService internalTimerService;
/** The TypeInformation of the key. */
private transient TypeInformation<Row> keyTypeInfo;
/** The TypeSerializer of the key. */
private transient TypeSerializer<Row> keyTypeSerializer;
/** The TypeInformation of timer data. */
private transient TypeInformation<Row> timerDataTypeInfo;
/** The TypeSerializer of timer data. */
private transient TypeSerializer<Row> timerDataSerializer;
private transient TimerHandler timerHandler;
private transient Object keyForTimerService;
public ExternalPythonKeyedProcessOperator(
Configuration config,
DataStreamPythonFunctionInfo pythonFunctionInfo,
RowTypeInfo inputTypeInfo,
TypeInformation<OUT> outputTypeInfo) {
this(
config,
pythonFunctionInfo,
inputTypeInfo,
outputTypeInfo,
VoidNamespaceSerializer.INSTANCE);
}
public ExternalPythonKeyedProcessOperator(
Configuration config,
DataStreamPythonFunctionInfo pythonFunctionInfo,
RowTypeInfo inputTypeInfo,
TypeInformation<OUT> outputTypeInfo,
TypeSerializer namespaceSerializer) {
super(config, pythonFunctionInfo, inputTypeInfo, outputTypeInfo);
this.namespaceSerializer = namespaceSerializer;
}
@Override
public void open() throws Exception {
internalTimerService = getInternalTimerService("user-timers", namespaceSerializer, this);
keyTypeInfo = new RowTypeInfo(((RowTypeInfo) this.getInputTypeInfo()).getTypeAt(0));
keyTypeSerializer =
PythonTypeUtils.TypeInfoToSerializerConverter.typeInfoSerializerConverter(
keyTypeInfo);
timerDataTypeInfo = createTimerDataTypeInfo(keyTypeInfo);
timerDataSerializer =
PythonTypeUtils.TypeInfoToSerializerConverter.typeInfoSerializerConverter(
timerDataTypeInfo);
timerHandler = new TimerHandler();
super.open();
}
@Override
public void onEventTime(InternalTimer<Row, Object> timer) throws Exception {
processTimer(TimeDomain.EVENT_TIME, timer);
}
@Override
public void onProcessingTime(InternalTimer<Row, Object> timer) throws Exception {
processTimer(TimeDomain.PROCESSING_TIME, timer);
}
@Override
public PythonFunctionRunner createPythonFunctionRunner() throws Exception {
return new BeamDataStreamPythonFunctionRunner(
getContainingTask().getEnvironment(),
getRuntimeContext().getTaskInfo().getTaskName(),
createPythonEnvironmentManager(),
STATEFUL_FUNCTION_URN,
ProtoUtils.createUserDefinedDataStreamStatefulFunctionProtos(
getPythonFunctionInfo(),
getRuntimeContext(),
getInternalParameters(),
keyTypeInfo,
inBatchExecutionMode(getKeyedStateBackend()),
config.get(PYTHON_METRIC_ENABLED),
config.get(PYTHON_PROFILE_ENABLED),
getSideOutputTags().size() > 0,
config.get(STATE_CACHE_SIZE),
config.get(MAP_STATE_READ_CACHE_SIZE),
config.get(MAP_STATE_WRITE_CACHE_SIZE)),
getFlinkMetricContainer(),
getKeyedStateBackend(),
getOperatorStateBackend(),
keyTypeSerializer,
namespaceSerializer,
new TimerRegistration(
getKeyedStateBackend(),
internalTimerService,
this,
namespaceSerializer,
timerDataSerializer),
getContainingTask().getEnvironment().getMemoryManager(),
getOperatorConfig()
.getManagedMemoryFractionOperatorUseCaseOfSlot(
ManagedMemoryUseCase.PYTHON,
getContainingTask().getJobConfiguration(),
getContainingTask()
.getEnvironment()
.getTaskManagerInfo()
.getConfiguration(),
getContainingTask()
.getEnvironment()
.getUserCodeClassLoader()
.asClassLoader()),
createInputCoderInfoDescriptor(),
createOutputCoderInfoDescriptor(),
createTimerDataCoderInfoDescriptorProto(timerDataTypeInfo),
createSideOutputCoderDescriptors());
}
@Override
public void processElement(StreamRecord<Row> element) throws Exception {
processElement(
element.getTimestamp(),
internalTimerService.currentWatermark(),
element.getValue());
}
/**
* It is responsible to send timer data to python worker when a registered timer is fired. The
* input data is a Row containing 4 fields: TimerFlag 0 for proc time, 1 for event time;
* Timestamp of the fired timer; Current watermark and the key of the timer.
*
* @param timeDomain The type of the timer.
* @param timer The internal timer.
* @throws Exception The runnerInputSerializer might throw exception.
*/
private void processTimer(TimeDomain timeDomain, InternalTimer<Row, Object> timer)
throws Exception {
Object namespace = timer.getNamespace();
byte[] encodedNamespace;
if (VoidNamespace.INSTANCE.equals(namespace)) {
encodedNamespace = null;
} else {
namespaceSerializer.serialize(namespace, baosWrapper);
encodedNamespace = baos.toByteArray();
baos.reset();
}
Row timerData =
timerHandler.buildTimerData(
timeDomain,
internalTimerService.currentWatermark(),
timer.getTimestamp(),
timer.getKey(),
encodedNamespace);
timerDataSerializer.serialize(timerData, baosWrapper);
pythonFunctionRunner.processTimer(baos.toByteArray());
baos.reset();
elementCount++;
checkInvokeFinishBundleByCount();
emitResults();
}
/**
* As the beam state gRPC service will access the KeyedStateBackend in parallel with this
* operator, we must override this method to prevent changing the current key of the
* KeyedStateBackend while the beam service is handling requests.
*/
@Override
public void setCurrentKey(Object key) {
if (inBatchExecutionMode(getKeyedStateBackend())) {
super.setCurrentKey(key);
}
keyForTimerService = key;
}
@Override
public Object getCurrentKey() {
return keyForTimerService;
}
@Override
public <T> AbstractExternalDataStreamPythonFunctionOperator<T> copy(
DataStreamPythonFunctionInfo pythonFunctionInfo, TypeInformation<T> outputTypeInfo) {
return new ExternalPythonKeyedProcessOperator<>(
config,
pythonFunctionInfo,
(RowTypeInfo) getInputTypeInfo(),
outputTypeInfo,
namespaceSerializer);
}
}
| ExternalPythonKeyedProcessOperator |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/AbstractInitializableBeanDefinition.java | {
"start": 7454,
"end": 37026
} | class ____
beanAnnotationMetadata = new BeanAnnotationMetadata(annotationMetadata);
}
this.annotationMetadata = EvaluatedAnnotationMetadata.wrapIfNecessary(beanAnnotationMetadata);
}
this.constructor = constructor;
this.methodInjection = methodInjection;
this.fieldInjection = fieldInjection;
this.annotationInjection = annotationInjection;
this.executableMethodsDefinition = executableMethodsDefinition;
this.typeArgumentsMap = typeArgumentsMap;
this.precalculatedInfo = precalculatedInfo;
}
@Override
public Qualifier<T> getDeclaredQualifier() {
if (declaredQualifier == null) {
declaredQualifier = InstantiatableBeanDefinition.super.getDeclaredQualifier();
}
return declaredQualifier;
}
@Override
public final boolean isContainerType() {
return precalculatedInfo.isContainerType;
}
@Override
@SuppressWarnings("java:S2789") // performance optimization
public final Optional<Argument<?>> getContainerElement() {
if (precalculatedInfo.isContainerType) {
if (containerElement != null) {
return containerElement;
}
if (getBeanType().isArray()) {
containerElement = Optional.of(Argument.of(getBeanType().getComponentType()));
} else {
final List<Argument<?>> iterableArguments = getTypeArguments(Iterable.class);
if (!iterableArguments.isEmpty()) {
containerElement = Optional.of(iterableArguments.iterator().next());
}
}
return containerElement;
}
return Optional.empty();
}
@Override
public final boolean hasPropertyExpressions() {
return getAnnotationMetadata().hasPropertyExpressions();
}
@Override
public boolean hasEvaluatedExpressions() {
return precalculatedInfo.hasEvaluatedExpressions();
}
@Override
public final @NonNull
List<Argument<?>> getTypeArguments(String type) {
if (type == null || typeArgumentsMap == null) {
return Collections.emptyList();
}
Argument<?>[] arguments = typeArgumentsMap.get(type);
if (arguments != null) {
return Arrays.asList(arguments);
}
return Collections.emptyList();
}
@Override
@NonNull
public AnnotationMetadata getAnnotationMetadata() {
return annotationMetadata;
}
@Override
public boolean isAbstract() {
return precalculatedInfo.isAbstract;
}
@Override
public boolean isIterable() {
return precalculatedInfo.isIterable;
}
@Override
public final boolean isConfigurationProperties() {
return precalculatedInfo.isConfigurationProperties;
}
@Override
public boolean isPrimary() {
return precalculatedInfo.isPrimary;
}
@Override
public boolean requiresMethodProcessing() {
return precalculatedInfo.requiresMethodProcessing;
}
@Override
public final <R> Optional<ExecutableMethod<T, R>> findMethod(String name, Class<?>... argumentTypes) {
if (executableMethodsDefinition == null) {
return Optional.empty();
}
return executableMethodsDefinition.findMethod(name, argumentTypes);
}
@Override
public final <R> Stream<ExecutableMethod<T, R>> findPossibleMethods(String name) {
if (executableMethodsDefinition == null) {
return Stream.empty();
}
return executableMethodsDefinition.findPossibleMethods(name);
}
@Override
public final Iterable<ExecutableMethod<T, ?>> getExecutableMethodsForProcessing() {
int[] indexes = getIndexesOfExecutableMethodsForProcessing();
if (indexes == null) {
// Fallback to runtime filtering
return InstantiatableBeanDefinition.super.getExecutableMethodsForProcessing();
}
return new Iterable<>() {
private final int length = indexes.length;
@Override
@NonNull
public Iterator<ExecutableMethod<T, ?>> iterator() {
return new Iterator<>() {
private int index = 0;
@Override
public boolean hasNext() {
return index < length;
}
@Override
public ExecutableMethod<T, ?> next() {
if (hasNext()) {
return executableMethodsDefinition.getExecutableMethodByIndex(indexes[index++]);
}
throw new NoSuchElementException();
}
};
}
};
}
@Nullable
protected int[] getIndexesOfExecutableMethodsForProcessing() {
return null; // Fallback to
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String toString() {
if (constructor == null) {
return "Definition: " + type.getName();
}
if (constructor.declaringType.equals(type)) {
return "Definition: " + type.getName();
}
if (constructor instanceof MethodReference methodConstructor) {
return "Definition: " + type.getName() + " Factory: " + constructor.declaringType.getName() + "#" + methodConstructor.methodName;
}
if (constructor instanceof FieldReference fieldReference) {
return "Definition: " + type.getName() + " Factory: " + constructor.declaringType.getName() + "." + fieldReference.argument.getName();
}
return "Definition: " + type.getName() + " Factory: " + constructor.declaringType.getName();
}
@Override
public boolean isSingleton() {
return precalculatedInfo.isSingleton;
}
@SuppressWarnings({"OptionalAssignedToNull", "unchecked"})
@Override
public final Optional<Class<? extends Annotation>> getScope() {
Optional<Class<? extends Annotation>> scope = this.scope;
if (scope == null) {
scope = precalculatedInfo.scope.flatMap(scopeClassName -> {
if (Singleton.class.getName().equals(scopeClassName)) {
return SINGLETON_SCOPE;
}
return (Optional) ClassUtils.forName(scopeClassName, getClass().getClassLoader());
});
this.scope = scope;
}
return scope;
}
@Override
public final Optional<String> getScopeName() {
return precalculatedInfo.scope;
}
@Override
public final Class<T> getBeanType() {
return type;
}
@Override
@NonNull
public Set<Class<?>> getExposedTypes() {
return Collections.EMPTY_SET;
}
@Override
public final Optional<Class<?>> getDeclaringType() {
if (constructor == null) {
return Optional.of(type);
}
return Optional.of(constructor.declaringType);
}
@Override
public final ConstructorInjectionPoint<T> getConstructor() {
if (constructorInjectionPoint != null) {
return constructorInjectionPoint;
}
if (constructor == null) {
DefaultConstructorInjectionPoint<T> point = new DefaultConstructorInjectionPoint<>(
this,
getBeanType(),
AnnotationMetadata.EMPTY_METADATA,
Argument.ZERO_ARGUMENTS
);
if (environment != null) {
point.configure(environment);
}
constructorInjectionPoint = point;
} else if (constructor instanceof MethodReference methodConstructor) {
if ("<init>".equals(methodConstructor.methodName)) {
DefaultConstructorInjectionPoint<T> point = new DefaultConstructorInjectionPoint<>(
this,
methodConstructor.declaringType,
methodConstructor.annotationMetadata,
methodConstructor.arguments
);
if (environment != null) {
point.configure(environment);
}
constructorInjectionPoint = point;
} else {
DefaultMethodConstructorInjectionPoint<T> point = new DefaultMethodConstructorInjectionPoint<>(
this,
methodConstructor.declaringType,
methodConstructor.methodName,
methodConstructor.arguments,
methodConstructor.annotationMetadata
);
if (environment != null) {
point.configure(environment);
}
constructorInjectionPoint = point;
}
} else if (constructor instanceof FieldReference fieldConstructor) {
DefaultFieldConstructorInjectionPoint<T> point = new DefaultFieldConstructorInjectionPoint<>(
this,
fieldConstructor.declaringType,
type,
fieldConstructor.argument.getName(),
fieldConstructor.argument.getAnnotationMetadata()
);
if (environment != null) {
point.configure(environment);
}
constructorInjectionPoint = point;
}
return constructorInjectionPoint;
}
@Override
public final Collection<Class<?>> getRequiredComponents() {
if (requiredComponents != null) {
return requiredComponents;
}
Set<Class<?>> requiredComponents = new HashSet<>();
Consumer<Argument> argumentConsumer = argument -> {
if (argument.isContainerType() || argument.isProvider()) {
argument.getFirstTypeVariable()
.map(Argument::getType)
.ifPresent(requiredComponents::add);
} else {
requiredComponents.add(argument.getType());
}
};
if (constructor != null) {
if (constructor instanceof MethodReference methodConstructor) {
if (methodConstructor.arguments != null && methodConstructor.arguments.length > 0) {
for (Argument<?> argument : methodConstructor.arguments) {
argumentConsumer.accept(argument);
}
}
}
}
if (methodInjection != null) {
for (MethodReference methodReference : methodInjection) {
if (methodReference.annotationMetadata.hasDeclaredAnnotation(AnnotationUtil.INJECT)) {
if (methodReference.arguments != null && methodReference.arguments.length > 0) {
for (Argument<?> argument : methodReference.arguments) {
argumentConsumer.accept(argument);
}
}
}
}
}
if (fieldInjection != null) {
for (FieldReference fieldReference : fieldInjection) {
if (annotationMetadata != null && annotationMetadata.hasDeclaredAnnotation(AnnotationUtil.INJECT)) {
argumentConsumer.accept(fieldReference.argument);
}
}
}
if (annotationInjection != null) {
for (AnnotationReference annotationReference : annotationInjection) {
if (annotationReference.argument != null) {
argumentConsumer.accept(annotationReference.argument);
}
}
}
this.requiredComponents = Collections.unmodifiableSet(requiredComponents);
return this.requiredComponents;
}
@Override
public final List<MethodInjectionPoint<T, ?>> getInjectedMethods() {
if (methodInjection == null) {
return Collections.emptyList();
}
if (methodInjectionPoints != null) {
return methodInjectionPoints;
}
List<MethodInjectionPoint<T, ?>> methodInjectionPoints = new ArrayList<>(methodInjection.length);
for (MethodReference methodReference : methodInjection) {
MethodInjectionPoint<T, ?> methodInjectionPoint = new DefaultMethodInjectionPoint<>(
this,
methodReference.declaringType,
methodReference.methodName,
methodReference.arguments,
methodReference.annotationMetadata
);
methodInjectionPoints.add(methodInjectionPoint);
if (environment != null) {
((EnvironmentConfigurable) methodInjectionPoint).configure(environment);
}
}
this.methodInjectionPoints = Collections.unmodifiableList(methodInjectionPoints);
return this.methodInjectionPoints;
}
@Override
public final List<FieldInjectionPoint<T, ?>> getInjectedFields() {
if (fieldInjection == null) {
return Collections.emptyList();
}
if (fieldInjectionPoints != null) {
return fieldInjectionPoints;
}
List<FieldInjectionPoint<T, ?>> fieldInjectionPoints = new ArrayList<>(fieldInjection.length);
for (FieldReference fieldReference : fieldInjection) {
FieldInjectionPoint<T, ?> fieldInjectionPoint = new DefaultFieldInjectionPoint<>(
this,
fieldReference.declaringType,
fieldReference.argument.getType(),
fieldReference.argument.getName(),
fieldReference.argument.getAnnotationMetadata(),
fieldReference.argument.getTypeParameters()
);
if (environment != null) {
((EnvironmentConfigurable) fieldInjectionPoint).configure(environment);
}
fieldInjectionPoints.add(fieldInjectionPoint);
}
this.fieldInjectionPoints = Collections.unmodifiableList(fieldInjectionPoints);
return this.fieldInjectionPoints;
}
@Override
public final List<MethodInjectionPoint<T, ?>> getPostConstructMethods() {
if (methodInjection == null) {
return Collections.emptyList();
}
if (postConstructMethods != null) {
return postConstructMethods;
}
List<MethodInjectionPoint<T, ?>> postConstructMethods = new ArrayList<>(1);
for (MethodInjectionPoint<T, ?> methodInjectionPoint : getInjectedMethods()) {
if (methodInjectionPoint.isPostConstructMethod()) {
postConstructMethods.add(methodInjectionPoint);
}
}
this.postConstructMethods = Collections.unmodifiableList(postConstructMethods);
return this.postConstructMethods;
}
@Override
public final List<MethodInjectionPoint<T, ?>> getPreDestroyMethods() {
if (methodInjection == null) {
return Collections.emptyList();
}
if (preDestroyMethods != null) {
return preDestroyMethods;
}
List<MethodInjectionPoint<T, ?>> preDestroyMethods = new ArrayList<>(1);
for (MethodInjectionPoint<T, ?> methodInjectionPoint : getInjectedMethods()) {
if (methodInjectionPoint.isPreDestroyMethod()) {
preDestroyMethods.add(methodInjectionPoint);
}
}
this.preDestroyMethods = Collections.unmodifiableList(preDestroyMethods);
return this.preDestroyMethods;
}
@Override
@NonNull
public final String getName() {
return getBeanType().getName();
}
@Override
public T inject(BeanResolutionContext resolutionContext, BeanContext context, T bean) {
return bean;
}
@Override
public final List<ExecutableMethod<T, ?>> getExecutableMethods() {
if (executableMethodsDefinition == null) {
return Collections.emptyList();
}
return executableMethodsDefinition.getExecutableMethods();
}
/**
* Configures the bean for the given {@link BeanContext}. If the context features an
* {@link Environment} this method configures the annotation metadata such that
* environment aware values are returned.
*
* @param environment The environment
*/
@Internal
@Override
public final void configure(Environment environment) {
if (environment != null) {
this.environment = environment;
if (constructorInjectionPoint instanceof EnvironmentConfigurable environmentConfigurable) {
environmentConfigurable.configure(environment);
}
if (methodInjectionPoints != null) {
for (MethodInjectionPoint<T, ?> methodInjectionPoint : methodInjectionPoints) {
if (methodInjectionPoint instanceof EnvironmentConfigurable environmentConfigurable) {
environmentConfigurable.configure(environment);
}
}
}
if (fieldInjectionPoints != null) {
for (FieldInjectionPoint<T, ?> fieldInjectionPoint : fieldInjectionPoints) {
if (fieldInjectionPoint instanceof EnvironmentConfigurable environmentConfigurable) {
environmentConfigurable.configure(environment);
}
}
}
if (executableMethodsDefinition instanceof EnvironmentConfigurable environmentConfigurable) {
environmentConfigurable.configure(environment);
}
}
}
@Override
public void configure(BeanContext beanContext) {
if (beanContext == null || !hasEvaluatedExpressions()) {
return;
}
if (annotationMetadata instanceof EvaluatedAnnotationMetadata eam) {
eam.configure(beanContext);
eam.setBeanDefinition(this);
}
if (constructor != null) {
if (constructor instanceof MethodReference mr) {
if (mr.annotationMetadata instanceof EvaluatedAnnotationMetadata eam) {
eam.configure(beanContext);
eam.setBeanDefinition(this);
}
if (mr.arguments != null) {
for (Argument<?> argument: mr.arguments) {
if (argument instanceof ExpressionsAwareArgument<?> exprArg) {
exprArg.configure(beanContext);
exprArg.setBeanDefinition(this);
}
}
}
}
if (constructor instanceof FieldReference fr
&& fr.argument instanceof ExpressionsAwareArgument<?> exprArg) {
exprArg.configure(beanContext);
exprArg.setBeanDefinition(this);
}
}
if (constructorInjectionPoint != null) {
if (constructorInjectionPoint.getAnnotationMetadata() instanceof EvaluatedAnnotationMetadata eam) {
eam.configure(beanContext);
eam.setBeanDefinition(this);
}
}
if (methodInjection != null) {
for (MethodReference methodReference: methodInjection) {
if (methodReference.annotationMetadata instanceof EvaluatedAnnotationMetadata eam) {
eam.configure(beanContext);
eam.setBeanDefinition(this);
}
if (methodReference.arguments != null) {
for (Argument<?> argument: methodReference.arguments) {
if (argument instanceof ExpressionsAwareArgument<?> exprArg) {
exprArg.configure(beanContext);
exprArg.setBeanDefinition(this);
}
}
}
}
}
if (methodInjectionPoints != null) {
for (MethodInjectionPoint<T, ?> methodInjectionPoint : methodInjectionPoints) {
if (methodInjectionPoint.getAnnotationMetadata() instanceof EvaluatedAnnotationMetadata eam) {
eam.configure(beanContext);
eam.setBeanDefinition(this);
}
}
}
if (fieldInjection != null) {
for (FieldReference fieldReference: fieldInjection) {
if (fieldReference.argument instanceof ExpressionsAwareArgument<?> exprArg) {
exprArg.configure(beanContext);
exprArg.setBeanDefinition(this);
}
}
}
if (fieldInjectionPoints != null) {
for (FieldInjectionPoint<T, ?> fieldInjectionPoint : fieldInjectionPoints) {
if (fieldInjectionPoint.getAnnotationMetadata() instanceof EvaluatedAnnotationMetadata eam) {
eam.configure(beanContext);
eam.setBeanDefinition(this);
}
}
}
if (executableMethodsDefinition instanceof BeanContextConfigurable ctxConfigurable) {
ctxConfigurable.configure(beanContext);
}
}
/**
* Allows printing warning messages produced by the compiler.
*
* @param message The message
* @deprecated No longer used
*/
@Internal
@Deprecated(forRemoval = true, since = "4.4.0")
protected final void warn(String message) {
}
/**
* Allows printing warning messages produced by the compiler.
*
* @param type The type
* @param method The method
* @param property The property
* @deprecated No longer used
*/
@SuppressWarnings("unused")
@Internal
@Deprecated(forRemoval = true, since = "4.4.0")
protected final void warnMissingProperty(Class type, String method, String property) {
}
/**
* Implementing possible {@link io.micronaut.inject.ParametrizedInstantiatableBeanDefinition#getRequiredArguments()}.
*
* @return The arguments required to construct parametrized bean
*/
public final Argument<?>[] getRequiredArguments() {
if (requiredParametrizedArguments != null) {
return requiredParametrizedArguments;
}
ConstructorInjectionPoint<T> ctor = getConstructor();
if (ctor != null) {
requiredParametrizedArguments = Arrays.stream(ctor.getArguments())
.filter(arg -> {
Optional<String> qualifierType = AnnotationUtil.findQualifierAnnotation(arg.getAnnotationMetadata());
return qualifierType.isPresent() && qualifierType.get().equals(Parameter.class.getName());
})
.toArray(Argument[]::new);
} else {
requiredParametrizedArguments = Argument.ZERO_ARGUMENTS;
}
return requiredParametrizedArguments;
}
/**
* Implementing possible {@link io.micronaut.inject.ParametrizedInstantiatableBeanDefinition#instantiate(BeanResolutionContext, BeanContext)}.
*
* @param resolutionContext The {@link BeanResolutionContext}
* @param context The {@link BeanContext}
* @param requiredArgumentValues The required arguments values. The keys should match the names of the arguments
* returned by {@link #getRequiredArguments()}
* @return The instantiated bean
* @throws BeanInstantiationException If the bean cannot be instantiated for the arguments supplied
*/
@SuppressWarnings({"java:S2789", "OptionalAssignedToNull"}) // performance optimization
public final T instantiate(BeanResolutionContext resolutionContext,
BeanContext context,
Map<String, Object> requiredArgumentValues) throws BeanInstantiationException {
requiredArgumentValues = requiredArgumentValues != null ? new LinkedHashMap<>(requiredArgumentValues) : Collections.emptyMap();
Optional<Class> eachBeanType = null;
for (Argument<?> requiredArgument : getRequiredArguments()) {
try (BeanResolutionContext.Path ignored = resolutionContext.getPath().pushConstructorResolve(this, requiredArgument)) {
String argumentName = requiredArgument.getName();
Object value = requiredArgumentValues.get(argumentName);
if (value == null && !requiredArgument.isNullable()) {
if (eachBeanType == null) {
eachBeanType = classValue(EachBean.class);
}
if (eachBeanType.filter(type -> type == requiredArgument.getType()).isPresent()) {
throw new DisabledBeanException("@EachBean parameter disabled for argument: " + requiredArgument.getName());
}
throw new BeanInstantiationException(resolutionContext, "Missing bean argument value: " + argumentName);
}
boolean requiresConversion = value != null && !requiredArgument.getType().isInstance(value);
if (requiresConversion) {
Optional<?> converted = context.getConversionService().convert(value, requiredArgument.getType(), ConversionContext.of(requiredArgument));
Object finalValue = value;
value = converted.orElseThrow(() -> new BeanInstantiationException(resolutionContext, "Invalid value [" + finalValue + "] for argument: " + argumentName));
requiredArgumentValues.put(argumentName, value);
}
}
}
return doInstantiate(resolutionContext, context, requiredArgumentValues);
}
/**
* Method to be implemented by the generated code if the bean definition is implementing {@link io.micronaut.inject.ParametrizedInstantiatableBeanDefinition}.
*
* @param resolutionContext The resolution context
* @param context The bean context
* @param requiredArgumentValues The required arguments
* @return The built instance
*/
@Internal
@UsedByGeneratedCode
protected T doInstantiate(BeanResolutionContext resolutionContext, BeanContext context, Map<String, Object> requiredArgumentValues) {
throw new IllegalStateException("Method must be implemented for 'ParametrizedInstantiatableBeanDefinition' instance!");
}
/**
* Default postConstruct hook that only invokes methods that require reflection. Generated subclasses should
* override to call methods that don't require reflection.
*
* @param resolutionContext The resolution hook
* @param context The context
* @param bean The bean
* @return The bean
*/
@SuppressWarnings({"unused", "unchecked"})
@Internal
@UsedByGeneratedCode
protected Object postConstruct(BeanResolutionContext resolutionContext, BeanContext context, Object bean) {
final List<Map.Entry<Class<?>, ListenersSupplier<BeanInitializedEventListener>>> beanInitializedEventListeners
= ((DefaultBeanContext) context).beanInitializedEventListeners;
if (CollectionUtils.isNotEmpty(beanInitializedEventListeners)) {
BeanInitializingEvent event = new BeanInitializingEvent(context, this, bean);
List<ListenersSupplier.ListenerAndOrder<BeanInitializedEventListener>> listeners = new ArrayList<>();
for (Map.Entry<Class<?>, ListenersSupplier<BeanInitializedEventListener>> entry : beanInitializedEventListeners) {
if (entry.getKey().isAssignableFrom(getBeanType())) {
for (ListenersSupplier.ListenerAndOrder<BeanInitializedEventListener> listener : entry.getValue().get(resolutionContext)) {
listeners.add(listener);
}
}
}
OrderUtil.sort(listeners);
for (ListenersSupplier.ListenerAndOrder<BeanInitializedEventListener> listener : listeners) {
bean = listener.bean().onInitialized(event);
if (bean == null) {
throw new BeanInstantiationException(resolutionContext, "Listener [" + listener + "] returned null from onInitialized event");
}
}
}
if (bean instanceof LifeCycle<?> lifeCycle) {
bean = lifeCycle.start();
}
return bean;
}
/**
* Default preDestroy hook that only invokes methods that require reflection. Generated subclasses should override
* to call methods that don't require reflection.
*
* @param resolutionContext The resolution hook
* @param context The context
* @param bean The bean
* @return The bean
*/
@Internal
@UsedByGeneratedCode
protected Object preDestroy(BeanResolutionContext resolutionContext, BeanContext context, Object bean) {
if (bean instanceof LifeCycle<?> lifeCycle) {
bean = lifeCycle.stop();
}
return bean;
}
/**
* Check if the | metadata |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/runtime/isolation/PluginUtilsTest.java | {
"start": 29681,
"end": 30225
} | class ____ implements Converter, Versioned {
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
}
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
return new byte[0];
}
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
return null;
}
@Override
public String version() {
return "1.0";
}
}
public static | CollidingConverter |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/MultiJoinRestoreTest.java | {
"start": 1124,
"end": 2228
} | class ____ extends RestoreTestBase {
public MultiJoinRestoreTest() {
super(StreamExecMultiJoin.class);
}
@Override
public List<TableTestProgram> programs() {
return Arrays.asList(
MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_INNER_JOIN_WITH_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_LEFT_OUTER_JOIN_WITH_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_FOUR_WAY_COMPLEX_WITH_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_FOUR_WAY_NO_COMMON_JOIN_KEY_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_WITH_TIME_ATTRIBUTES_MATERIALIZATION_WITH_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_INNER_JOIN_WITH_TTL_HINTS_WITH_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_FOUR_WAY_COMPLEX_PRESERVES_UPSERT_KEY_WITH_RESTORE,
MultiJoinTestPrograms
.MULTI_JOIN_TWO_WAY_LEFT_JOIN_PRESERVES_UPSERT_KEY_WITH_RESTORE,
MultiJoinTestPrograms.MULTI_JOIN_THREE_WAY_JOIN_PRESERVES_UPSERT_KEY_WITH_RESTORE);
}
}
| MultiJoinRestoreTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/client/response/DefaultResponseCreatorTests.java | {
"start": 2034,
"end": 8679
} | class ____ {
@ParameterizedTest(name = "expect status to be set [{0}]")
@ValueSource(ints = {200, 401, 429})
void expectStatus(int statusValue) throws IOException {
HttpStatus status = HttpStatus.valueOf(statusValue);
DefaultResponseCreator creator = new DefaultResponseCreator(status);
assertThat(createResponse(creator).getStatusCode()).isEqualTo(status);
}
@Test
void setBodyFromString() throws IOException {
// Use unicode codepoint for "thinking" emoji to help verify correct encoding is used internally.
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK).body("hello, world! \uD83E\uDD14");
assertThat(IOUtils.toByteArray(createResponse(creator).getBody()))
.isEqualTo("hello, world! \uD83E\uDD14".getBytes(StandardCharsets.UTF_8));
}
@ParameterizedTest(name = "setBodyFromStringWithCharset [{0}]")
@ValueSource(strings = {"Cp1047", "UTF-8", "UTF-16", "US-ASCII", "ISO-8859-1"})
void setBodyFromStringWithCharset(String charset) throws IOException {
assumeThat(Charset.isSupported(charset))
.overridingErrorMessage("charset %s is not supported by this JVM", charset)
.isTrue();
Charset charsetObj = Charset.forName(charset);
String content = "hello! €½$~@><·─";
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK).body(content, charsetObj);
ByteBuffer expectBuff = charsetObj.encode(content);
byte[] expect = new byte[expectBuff.remaining()];
expectBuff.get(expect);
assertThat(IOUtils.toByteArray(createResponse(creator).getBody())).isEqualTo(expect);
}
@Test
void setBodyFromByteArray() throws IOException {
byte[] body = { 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 };
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK).body(body);
assertThat(IOUtils.toByteArray(createResponse(creator).getBody())).isEqualTo(body);
}
@Test
void setBodyFromResource() throws IOException {
byte[] resourceContent = {7, 14, 21, 28, 35};
Resource resource = mock();
given(resource.getInputStream()).willReturn(new ByteArrayInputStream(resourceContent));
ClientHttpResponse response = createResponse(new DefaultResponseCreator(HttpStatus.OK).body(resource));
then(resource).should().getInputStream();
assertThat(IOUtils.toByteArray(response.getBody())).isEqualTo(resourceContent);
}
@Test
void setContentType() throws IOException {
MediaType mediaType = MediaType.APPLICATION_JSON;
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK).contentType(mediaType);
assertThat(createResponse(creator).getHeaders().getContentType()).isEqualTo(mediaType);
}
@Test
void setLocation() throws IOException {
URI uri = URI.create("https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html");
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK).location(uri);
assertThat(createResponse(creator).getHeaders().getLocation()).isEqualTo(uri);
}
@Test
void setHeader() throws IOException {
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK)
.header("foo", "bar")
.header("baz", "bork")
.header("lorem", "ipsum", "dolor", "sit", "amet");
HttpHeaders headers = createResponse(creator).getHeaders();
assertThat(headers.get("foo")).isNotNull().isEqualTo(Collections.singletonList("bar"));
assertThat(headers.get("baz")).isNotNull().isEqualTo(Collections.singletonList("bork"));
assertThat(headers.get("lorem")).isNotNull().isEqualTo(Arrays.asList("ipsum", "dolor", "sit", "amet"));
}
@Test
void setHeaders() throws IOException {
HttpHeaders firstHeaders = new HttpHeaders();
firstHeaders.setContentType(MediaType.APPLICATION_JSON);
firstHeaders.setOrigin("https://github.com");
HttpHeaders secondHeaders = new HttpHeaders();
secondHeaders.setAllow(Collections.singleton(HttpMethod.PUT));
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK)
.headers(firstHeaders)
.headers(secondHeaders);
HttpHeaders responseHeaders = createResponse(creator).getHeaders();
assertThat(responseHeaders.getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(responseHeaders.getOrigin()).isEqualTo("https://github.com");
assertThat(responseHeaders.getAllow()).isEqualTo(Collections.singleton(HttpMethod.PUT));
}
@Test
void setCookie() throws IOException {
ResponseCookie firstCookie = ResponseCookie.from("user-id", "1234").build();
ResponseCookie secondCookie = ResponseCookie.from("group-id", "5432").build();
ResponseCookie thirdCookie = ResponseCookie.from("cookie-cookie", "cookies").build();
ResponseCookie fourthCookie = ResponseCookie.from("foobar", "bazbork").build();
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK)
.cookies(firstCookie)
.cookies(secondCookie)
.cookies(thirdCookie, fourthCookie);
HttpHeaders responseHeaders = createResponse(creator).getHeaders();
assertThat(responseHeaders.get(HttpHeaders.SET_COOKIE))
.containsExactly(
firstCookie.toString(),
secondCookie.toString(),
thirdCookie.toString(),
fourthCookie.toString()
);
}
@Test
void setCookies() throws IOException {
ResponseCookie firstCookie = ResponseCookie.from("user-id", "1234").build();
ResponseCookie secondCookie = ResponseCookie.from("group-id", "5432").build();
MultiValueMap<String, ResponseCookie> firstCookies = new LinkedMultiValueMap<>();
firstCookies.add(firstCookie.getName(), firstCookie);
firstCookies.add(secondCookie.getName(), secondCookie);
ResponseCookie thirdCookie = ResponseCookie.from("cookie-cookie", "cookies").build();
ResponseCookie fourthCookie = ResponseCookie.from("foobar", "bazbork").build();
MultiValueMap<String, ResponseCookie> secondCookies = new LinkedMultiValueMap<>();
firstCookies.add(thirdCookie.getName(), thirdCookie);
firstCookies.add(fourthCookie.getName(), fourthCookie);
DefaultResponseCreator creator = new DefaultResponseCreator(HttpStatus.OK)
.cookies(firstCookies)
.cookies(secondCookies);
HttpHeaders responseHeaders = createResponse(creator).getHeaders();
assertThat(responseHeaders.get(HttpHeaders.SET_COOKIE))
.containsExactly(
firstCookie.toString(),
secondCookie.toString(),
thirdCookie.toString(),
fourthCookie.toString()
);
}
private static ClientHttpResponse createResponse(DefaultResponseCreator creator) throws IOException {
URI uri = UriComponentsBuilder.fromUriString("/foo/bar").build().toUri();
return creator.createResponse(new MockClientHttpRequest(HttpMethod.POST, uri));
}
}
| DefaultResponseCreatorTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/metrics/dump/QueryScopeInfo.java | {
"start": 2504,
"end": 3121
} | class ____ extends QueryScopeInfo {
public JobManagerQueryScopeInfo() {
super("");
}
public JobManagerQueryScopeInfo(String scope) {
super(scope);
}
@Override
public JobManagerQueryScopeInfo copy(String additionalScope) {
return new JobManagerQueryScopeInfo(concatScopes(additionalScope));
}
@Override
public byte getCategory() {
return INFO_CATEGORY_JM;
}
}
/** Container for the task manager scope. Stores the ID of the task manager. */
public static | JobManagerQueryScopeInfo |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MissingSuperCallTest.java | {
"start": 16585,
"end": 16966
} | class ____ extends Super {
@Override
// BUG: Diagnostic contains:
// This method overrides Super#doIt, which is annotated with @CallSuper,
// but does not call the super method
public void doIt() {
Runnable r = super::doIt;
}
}
""")
.doTest();
}
}
| Sub |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/QuerydslRepositorySupport.java | {
"start": 1889,
"end": 4510
} | class ____ not be null");
this.builder = new PathBuilderFactory().create(domainClass);
}
/**
* Setter to inject {@link EntityManager}.
*
* @param entityManager must not be {@literal null}.
*/
@Autowired
public void setEntityManager(EntityManager entityManager) {
Assert.notNull(entityManager, "EntityManager must not be null");
this.querydsl = new Querydsl(entityManager, builder);
this.entityManager = entityManager;
}
/**
* Callback to verify configuration. Used by containers.
*/
@PostConstruct
public void validate() {
Assert.notNull(entityManager, "EntityManager must not be null");
Assert.notNull(querydsl, "Querydsl must not be null");
}
/**
* Returns the {@link EntityManager}.
*
* @return the entityManager
*/
protected @Nullable EntityManager getEntityManager() {
return entityManager;
}
/**
* Returns a fresh {@link JPQLQuery}.
*
* @param paths must not be {@literal null}.
* @return the Querydsl {@link JPQLQuery}.
*/
protected JPQLQuery<Object> from(EntityPath<?>... paths) {
return getRequiredQuerydsl().createQuery(paths);
}
/**
* Returns a {@link JPQLQuery} for the given {@link EntityPath}.
*
* @param path must not be {@literal null}.
* @return
*/
protected <T> JPQLQuery<T> from(EntityPath<T> path) {
return getRequiredQuerydsl().createQuery(path).select(path);
}
/**
* Returns a fresh {@link DeleteClause}.
*
* @param path
* @return the Querydsl {@link DeleteClause}.
*/
protected DeleteClause<JPADeleteClause> delete(EntityPath<?> path) {
return new JPADeleteClause(getRequiredEntityManager(), path);
}
/**
* Returns a fresh {@link UpdateClause}.
*
* @param path
* @return the Querydsl {@link UpdateClause}.
*/
protected UpdateClause<JPAUpdateClause> update(EntityPath<?> path) {
return new JPAUpdateClause(getRequiredEntityManager(), path);
}
/**
* Returns a {@link PathBuilder} for the configured domain type.
*
* @param <T>
* @return the Querdsl {@link PathBuilder}.
*/
@SuppressWarnings("unchecked")
protected <T> PathBuilder<T> getBuilder() {
return (PathBuilder<T>) builder;
}
/**
* Returns the underlying Querydsl helper instance.
*
* @return
*/
protected @Nullable Querydsl getQuerydsl() {
return this.querydsl;
}
private Querydsl getRequiredQuerydsl() {
if (querydsl == null) {
throw new IllegalStateException("Querydsl is null");
}
return querydsl;
}
private EntityManager getRequiredEntityManager() {
if (entityManager == null) {
throw new IllegalStateException("EntityManager is null");
}
return entityManager;
}
}
| must |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/joinedsubclassbatch/IdentityJoinedSubclassBatchingTest.java | {
"start": 4566,
"end": 5037
} | class ____ extends Person {
@ManyToOne(fetch = FetchType.LAZY)
private Employee salesperson;
private String comments;
public Employee getSalesperson() {
return salesperson;
}
public void setSalesperson(Employee salesperson) {
this.salesperson = salesperson;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
@Entity(name = "Employee")
public static | Customer |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java | {
"start": 4965,
"end": 38027
} | class ____ extends LdapTestCase {
public static final String VALID_USER_TEMPLATE = "cn={0},ou=people,o=sevenSeas";
public static final String VALID_USERNAME = "Thomas Masterman Hardy";
public static final String PASSWORD = "pass";
private ThreadPool threadPool;
private ResourceWatcherService resourceWatcherService;
private Settings defaultGlobalSettings;
private SSLService sslService;
private MockLicenseState licenseState;
@Before
public void init() throws Exception {
threadPool = new TestThreadPool("ldap realm tests");
resourceWatcherService = new ResourceWatcherService(Settings.EMPTY, threadPool);
defaultGlobalSettings = Settings.builder().put("path.home", createTempDir()).build();
sslService = new SSLService(TestEnvironment.newEnvironment(defaultGlobalSettings));
licenseState = mock(MockLicenseState.class);
when(licenseState.isAllowed(Security.DELEGATED_AUTHORIZATION_FEATURE)).thenReturn(true);
}
@After
public void shutdown() throws InterruptedException {
resourceWatcherService.close();
terminate(threadPool);
}
public void testAuthenticateSubTreeGroupSearch() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
LdapRealm ldap = new LdapRealm(config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result = future.actionGet();
assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
User user = result.getValue();
assertThat(user, notNullValue());
assertThat(user.roles(), arrayContaining("HMS Victory"));
assertThat(user.metadata(), notNullValue());
assertThat(user.metadata().get("ldap_dn"), equalTo("cn=" + VALID_USERNAME + ",ou=people,o=sevenSeas"));
assertThat(user.metadata().get("ldap_groups"), instanceOf(List.class));
assertThat(user.metadata().get("mail"), nullValue());
assertThat(user.metadata().get("cn"), nullValue());
assertThat((List<?>) user.metadata().get("ldap_groups"), contains("cn=HMS Victory,ou=crews,ou=groups,o=sevenSeas"));
assertThat(user.email(), equalTo("thardy@royalnavy.mod.uk"));
assertThat(user.fullName(), equalTo("Thomas Masterman Hardy"));
}
public void testAuthenticateMapFullNameAndEmailMetadata() throws Exception {
String groupSearchBase = "o=sevenSeas";
boolean misssingSetting = randomBoolean();
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), VALID_USER_TEMPLATE, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.put(
getFullSettingKey(REALM_IDENTIFIER, LdapMetadataResolverSettings.FULL_NAME_SETTING),
misssingSetting ? "thisdoesnotexist" : "description"
)
.put(getFullSettingKey(REALM_IDENTIFIER, LdapMetadataResolverSettings.EMAIL_SETTING), "uid")
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
SessionFactory ldapFactory = LdapRealm.sessionFactory(config, sslService, threadPool);
LdapRealm ldap = new LdapRealm(config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken("John Samuel", new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result = future.actionGet();
assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
User user = result.getValue();
assertThat(user, notNullValue());
assertThat(user.email(), equalTo("jsamuel@royalnavy.mod.uk"));
assertThat(user.fullName(), equalTo(misssingSetting ? null : "Clerk John Samuel"));
}
private RealmConfig getRealmConfig(RealmConfig.RealmIdentifier identifier, Settings settings) {
final Environment env = TestEnvironment.newEnvironment(settings);
return new RealmConfig(identifier, settings, env, new ThreadContext(settings));
}
public void testAuthenticateOneLevelGroupSearch() throws Exception {
String groupSearchBase = "ou=crews,ou=groups,o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.ONE_LEVEL))
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
LdapRealm ldap = new LdapRealm(config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result = future.actionGet();
assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
User user = result.getValue();
assertThat(user, notNullValue());
assertThat("For roles " + Arrays.toString(user.roles()), user.roles(), arrayContaining("HMS Victory"));
assertThat(user.metadata(), notNullValue());
assertThat(user.metadata().get("ldap_dn"), equalTo("cn=" + VALID_USERNAME + ",ou=people,o=sevenSeas"));
assertThat(user.metadata().get("ldap_groups"), instanceOf(List.class));
assertThat((List<?>) user.metadata().get("ldap_groups"), contains("cn=HMS Victory,ou=crews,ou=groups,o=sevenSeas"));
}
public void testAuthenticateCaching() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
ldapFactory = spy(ldapFactory);
LdapRealm ldap = new LdapRealm(config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
assertThat(future.actionGet().getStatus(), is(AuthenticationResult.Status.SUCCESS));
future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
assertThat(future.actionGet().getStatus(), is(AuthenticationResult.Status.SUCCESS));
// verify one and only one session -> caching is working
verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), anyActionListener());
}
public void testAuthenticateCachingRefresh() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(defaultGlobalSettings)
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
DnRoleMapper roleMapper = buildGroupAsRoleMapper(resourceWatcherService);
ldapFactory = spy(ldapFactory);
LdapRealm ldap = new LdapRealm(config, ldapFactory, roleMapper, threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
future.actionGet();
future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
future.actionGet();
// verify one and only one session -> caching is working
verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), anyActionListener());
roleMapper.clearRealmCachesOnLocalNode();
future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
future.actionGet();
// we need to session again
verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), anyActionListener());
}
public void testAuthenticateNoncaching() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(getFullSettingKey(REALM_IDENTIFIER, CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING), -1)
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
ldapFactory = spy(ldapFactory);
LdapRealm ldap = new LdapRealm(config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
future.actionGet();
future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
future.actionGet();
// verify two and only two binds -> caching is disabled
verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), anyActionListener());
}
public void testDelegatedAuthorization() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
final Settings.Builder builder = Settings.builder()
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.putList(getFullSettingKey(REALM_IDENTIFIER, DelegatedAuthorizationSettings.AUTHZ_REALMS), "mock_lookup");
if (randomBoolean()) {
// maybe disable caching
builder.put(getFullSettingKey(REALM_IDENTIFIER, CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING), -1);
}
builder.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0);
final Settings realmSettings = builder.build();
final Environment env = TestEnvironment.newEnvironment(defaultGlobalSettings);
RealmConfig config = new RealmConfig(REALM_IDENTIFIER, realmSettings, env, threadPool.getThreadContext());
final LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
final DnRoleMapper roleMapper = buildGroupAsRoleMapper(resourceWatcherService);
final LdapRealm ldap = new LdapRealm(config, ldapFactory, roleMapper, threadPool);
RealmConfig.RealmIdentifier realmIdentifier = new RealmConfig.RealmIdentifier("mock", "mock_lookup");
final MockLookupRealm mockLookup = new MockLookupRealm(
new RealmConfig(
realmIdentifier,
Settings.builder()
.put(defaultGlobalSettings)
.put(getFullSettingKey(realmIdentifier, RealmSettings.ORDER_SETTING), 0)
.build(),
env,
threadPool.getThreadContext()
)
);
ldap.initialize(Arrays.asList(ldap, mockLookup), licenseState);
mockLookup.initialize(Arrays.asList(ldap, mockLookup), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result1 = future.actionGet();
assertThat(result1.getStatus(), equalTo(AuthenticationResult.Status.CONTINUE));
assertThat(
result1.getMessage(),
equalTo("the principal [" + VALID_USERNAME + "] was authenticated, but no user could be found in realms [mock/mock_lookup]")
);
future = new PlainActionFuture<>();
final User fakeUser = new User(VALID_USERNAME, "fake_role");
mockLookup.registerUser(fakeUser);
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result2 = future.actionGet();
assertThat(result2.getStatus(), equalTo(AuthenticationResult.Status.SUCCESS));
assertThat(result2.getValue(), sameInstance(fakeUser));
}
public void testLdapRealmSelectsLdapSessionFactory() throws Exception {
final RealmConfig.RealmIdentifier identifier = new RealmConfig.RealmIdentifier(LdapRealmSettings.LDAP_TYPE, "test-ldap-realm");
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.putList(getFullSettingKey(identifier, URLS_SETTING), ldapUrls())
.putList(getFullSettingKey(identifier.getName(), USER_DN_TEMPLATES_SETTING), userTemplate)
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.BASE_DN), groupSearchBase)
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.SCOPE), LdapSearchScope.SUB_TREE)
.put(getFullSettingKey(identifier, VERIFICATION_MODE_SETTING_REALM), SslVerificationMode.CERTIFICATE)
.put(getFullSettingKey(identifier, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(identifier, settings);
final SSLService ssl = new SSLService(config.env());
SessionFactory sessionFactory = LdapRealm.sessionFactory(config, ssl, threadPool);
assertThat(sessionFactory, is(instanceOf(LdapSessionFactory.class)));
}
public void testLdapRealmSelectsLdapUserSearchSessionFactory() throws Exception {
final RealmConfig.RealmIdentifier identifier = new RealmConfig.RealmIdentifier(
LdapRealmSettings.LDAP_TYPE,
"test-ldap-realm-user-search"
);
String groupSearchBase = "o=sevenSeas";
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.putList(getFullSettingKey(identifier, URLS_SETTING), ldapUrls())
.put(getFullSettingKey(identifier.getName(), LdapUserSearchSessionFactorySettings.SEARCH_BASE_DN), "")
.put(getFullSettingKey(identifier, PoolingSessionFactorySettings.BIND_DN), "cn=Thomas Masterman Hardy,ou=people,o=sevenSeas")
.setSecureSettings(secureSettings(PoolingSessionFactorySettings.SECURE_BIND_PASSWORD, identifier, PASSWORD))
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.BASE_DN), groupSearchBase)
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.SCOPE), LdapSearchScope.SUB_TREE)
.put(getFullSettingKey(identifier, VERIFICATION_MODE_SETTING_REALM), SslVerificationMode.CERTIFICATE)
.put(getFullSettingKey(identifier, RealmSettings.ORDER_SETTING), 0)
.build();
final RealmConfig config = getRealmConfig(identifier, settings);
SessionFactory sessionFactory = LdapRealm.sessionFactory(config, new SSLService(config.env()), threadPool);
try {
assertThat(sessionFactory, is(instanceOf(LdapUserSearchSessionFactory.class)));
} finally {
((LdapUserSearchSessionFactory) sessionFactory).close();
}
}
public void testLdapRealmThrowsExceptionForUserTemplateAndSearchSettings() throws Exception {
final RealmConfig.RealmIdentifier identifier = new RealmConfig.RealmIdentifier(
LdapRealmSettings.LDAP_TYPE,
"test-ldap-realm-user-search"
);
final List<? extends Setting.AffixSetting<?>> userSearchSettings = List.of(
LdapUserSearchSessionFactorySettings.SEARCH_BASE_DN,
LdapUserSearchSessionFactorySettings.SEARCH_ATTRIBUTE,
LdapUserSearchSessionFactorySettings.SEARCH_SCOPE,
LdapUserSearchSessionFactorySettings.SEARCH_FILTER,
LdapUserSearchSessionFactorySettings.POOL_ENABLED
);
final List<? extends Setting.AffixSetting<?>> configuredUserSearchSettings = randomNonEmptySubsetOf(userSearchSettings).stream()
.sorted(Comparator.comparing(userSearchSettings::indexOf))
.toList();
final Settings.Builder settingsBuilder = Settings.builder()
.put(defaultGlobalSettings)
.putList(getFullSettingKey(identifier, URLS_SETTING), ldapUrls())
.putList(getFullSettingKey(identifier.getName(), USER_DN_TEMPLATES_SETTING), "cn=foo")
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.BASE_DN), "")
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.SCOPE), LdapSearchScope.SUB_TREE)
.put(getFullSettingKey(identifier, VERIFICATION_MODE_SETTING_REALM), SslVerificationMode.CERTIFICATE)
.put(getFullSettingKey(identifier, RealmSettings.ORDER_SETTING), 0);
configuredUserSearchSettings.forEach(s -> {
final String key = getFullSettingKey(identifier.getName(), s);
settingsBuilder.put(key, key.endsWith(".enabled") ? String.valueOf(randomBoolean()) : randomAlphaOfLengthBetween(8, 18));
});
RealmConfig config = getRealmConfig(identifier, settingsBuilder.build());
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> LdapRealm.sessionFactory(config, null, threadPool));
assertThat(
e.getMessage(),
containsString(
"settings were found for both"
+ " user search ["
+ configuredUserSearchSettings.stream()
.map(Setting::getKey)
.map(
key -> "xpack.security.authc.realms.ldap.test-ldap-realm-user-search"
+ key.substring(key.lastIndexOf(".user_search."))
)
.collect(Collectors.joining(","))
+ "] and"
+ " user template [xpack.security.authc.realms.ldap.test-ldap-realm-user-search.user_dn_templates]"
)
);
}
public void testLdapRealmThrowsExceptionWhenNeitherUserTemplateNorSearchSettingsProvided() throws Exception {
final RealmConfig.RealmIdentifier identifier = new RealmConfig.RealmIdentifier(
LdapRealmSettings.LDAP_TYPE,
"test-ldap-realm-user-search"
);
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.putList(getFullSettingKey(identifier, URLS_SETTING), ldapUrls())
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.BASE_DN), "")
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.SCOPE), LdapSearchScope.SUB_TREE)
.put(getFullSettingKey(identifier, VERIFICATION_MODE_SETTING_REALM), SslVerificationMode.CERTIFICATE)
.put(getFullSettingKey(identifier, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(identifier, settings);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> LdapRealm.sessionFactory(config, null, threadPool));
assertThat(
e.getMessage(),
containsString(
"settings were not found for either"
+ " user search [xpack.security.authc.realms.ldap.test-ldap-realm-user-search.user_search.base_dn] or"
+ " user template [xpack.security.authc.realms.ldap.test-ldap-realm-user-search.user_dn_templates]"
)
);
}
public void testLdapRealmMapsUserDNToRole() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(
getFullSettingKey(REALM_IDENTIFIER, DnRoleMapperSettings.ROLE_MAPPING_FILE_SETTING),
getDataPath("/org/elasticsearch/xpack/security/authc/support/role_mapping.yml")
)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
LdapRealm ldap = new LdapRealm(config, ldapFactory, new DnRoleMapper(config, resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken("Horatio Hornblower", new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result = future.actionGet();
assertThat(result, notNullValue());
assertThat(result.toString(), result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
User user = result.getValue();
assertThat(user, notNullValue());
assertThat(user.toString(), user.roles(), arrayContaining("avenger"));
}
/**
* This tests template role mappings (see
* {@link TemplateRoleName}) with an LDAP realm, using a additional
* metadata field (see {@link LdapMetadataResolverSettings#ADDITIONAL_METADATA_SETTING}).
*/
public void testLdapRealmWithTemplatedRoleMapping() throws Exception {
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(ldapUrls(), userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(
getFullSettingKey(
REALM_IDENTIFIER.getName(),
LdapMetadataResolverSettings.ADDITIONAL_METADATA_SETTING.apply(LdapRealmSettings.LDAP_TYPE)
),
"uid"
)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
SecurityIndexManager mockSecurityIndex = mock(SecurityIndexManager.class);
SecurityIndexManager.IndexState projectIndex = mock(SecurityIndexManager.IndexState.class);
when(mockSecurityIndex.forCurrentProject()).thenReturn(projectIndex);
when(projectIndex.isAvailable(SecurityIndexManager.Availability.PRIMARY_SHARDS)).thenReturn(true);
when(projectIndex.isAvailable(SecurityIndexManager.Availability.SEARCH_SHARDS)).thenReturn(true);
when(projectIndex.isIndexUpToDate()).thenReturn(true);
when(projectIndex.indexExists()).thenReturn(true);
Client mockClient = mock(Client.class);
when(mockClient.threadPool()).thenReturn(threadPool);
final ScriptService scriptService = new ScriptService(
defaultGlobalSettings,
Collections.singletonMap(MustacheScriptEngine.NAME, new MustacheScriptEngine(Settings.EMPTY)),
ScriptModule.CORE_CONTEXTS,
() -> 1L,
TestProjectResolvers.singleProject(randomProjectIdOrDefault())
);
NativeRoleMappingStore roleMapper = new NativeRoleMappingStore(
defaultGlobalSettings,
mockClient,
mockSecurityIndex,
scriptService
) {
@Override
protected void loadMappings(ActionListener<List<ExpressionRoleMapping>> listener) {
listener.onResponse(Arrays.asList(NativeRoleMappingStore.buildMapping("m1", new BytesArray("""
{
"role_templates": [ { "template": { "source": "_user_{{metadata.uid}}" } } ],
"enabled": true,
"rules": {
"any": [ { "field": { "realm.name": "ldap1" } }, { "field": { "realm.name": "ldap2" } } ]
}
}""")), NativeRoleMappingStore.buildMapping("m2", new BytesArray("""
{
"roles": [ "should_not_happen" ],
"enabled": true,
"rules": {
"all": [ { "field": { "realm.name": "ldap1" } }, { "field": { "realm.name": "ldap2" } } ]
}
}""")), NativeRoleMappingStore.buildMapping("m3", new BytesArray("""
{
"roles": [ "sales_admin" ],
"enabled": true,
"rules": {
"field": {
"dn": "*,ou=people,o=sevenSeas"
}
}
}"""))));
}
};
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
LdapRealm ldap = new LdapRealm(config, ldapFactory, roleMapper, threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken("Horatio Hornblower", new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result = future.actionGet();
assertThat(result, notNullValue());
assertThat(result.toString(), result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
User user = result.getValue();
assertThat(user, notNullValue());
assertThat(user.roles(), arrayContainingInAnyOrder("_user_hhornblo", "sales_admin"));
}
/**
* The contract for {@link Realm} implementations is that they should log-and-return-null (and
* not call {@link ActionListener#onFailure(Exception)}) if there is an internal exception that prevented them from performing an
* authentication.
* This method tests that when an LDAP server is unavailable (invalid hostname), there is a <code>null</code> result
* rather than an exception.
*/
public void testLdapConnectionFailureIsTreatedAsAuthenticationFailure() throws Exception {
LDAPURL url = new LDAPURL("ldap", "..", 12345, null, null, null, null);
String groupSearchBase = "o=sevenSeas";
String userTemplate = VALID_USER_TEMPLATE;
Settings settings = Settings.builder()
.put(defaultGlobalSettings)
.put(buildLdapSettings(new String[] { url.toString() }, userTemplate, groupSearchBase, LdapSearchScope.SUB_TREE))
.put(getFullSettingKey(REALM_IDENTIFIER, RealmSettings.ORDER_SETTING), 0)
.build();
RealmConfig config = getRealmConfig(REALM_IDENTIFIER, settings);
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, sslService, threadPool);
LdapRealm ldap = new LdapRealm(config, ldapFactory, buildGroupAsRoleMapper(resourceWatcherService), threadPool);
ldap.initialize(Collections.singleton(ldap), licenseState);
PlainActionFuture<AuthenticationResult<User>> future = new PlainActionFuture<>();
ldap.authenticate(new UsernamePasswordToken(VALID_USERNAME, new SecureString(PASSWORD)), future);
final AuthenticationResult<User> result = future.actionGet();
assertThat(result, notNullValue());
assertThat(result.toString(), result.getStatus(), is(AuthenticationResult.Status.CONTINUE));
assertThat(result.getValue(), nullValue());
assertThat(result.getMessage(), is("authenticate failed"));
assertThat(result.getException(), notNullValue());
assertThat(result.getException().getMessage(), containsString("UnknownHostException"));
}
public void testUsageStats() throws Exception {
final RealmConfig.RealmIdentifier identifier = new RealmConfig.RealmIdentifier(LdapRealmSettings.LDAP_TYPE, "ldap-realm");
String groupSearchBase = "o=sevenSeas";
Settings.Builder settings = Settings.builder()
.put(defaultGlobalSettings)
.putList(getFullSettingKey(identifier, URLS_SETTING), ldapUrls())
.put(getFullSettingKey(identifier, PoolingSessionFactorySettings.BIND_DN), "cn=Thomas Masterman Hardy,ou=people,o=sevenSeas")
.put(getFullSettingKey(identifier, PoolingSessionFactorySettings.LEGACY_BIND_PASSWORD), PASSWORD)
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.BASE_DN), groupSearchBase)
.put(getFullSettingKey(identifier, SearchGroupsResolverSettings.SCOPE), LdapSearchScope.SUB_TREE)
.put(getFullSettingKey(identifier.getName(), USER_DN_TEMPLATES_SETTING), "--")
.put(getFullSettingKey(identifier, VERIFICATION_MODE_SETTING_REALM), SslVerificationMode.CERTIFICATE);
int order = randomIntBetween(0, 10);
settings.put(getFullSettingKey(identifier, RealmSettings.ORDER_SETTING), order);
boolean userSearch = randomBoolean();
if (userSearch) {
settings.put(getFullSettingKey(identifier.getName(), LdapUserSearchSessionFactorySettings.SEARCH_BASE_DN), "");
}
RealmConfig config = getRealmConfig(identifier, settings.build());
LdapSessionFactory ldapFactory = new LdapSessionFactory(config, new SSLService(config.env()), threadPool);
LdapRealm realm = new LdapRealm(config, ldapFactory, new DnRoleMapper(config, resourceWatcherService), threadPool);
realm.initialize(Collections.singleton(realm), licenseState);
PlainActionFuture<Map<String, Object>> future = new PlainActionFuture<>();
realm.usageStats(future);
Map<String, Object> stats = future.get();
assertThat(stats, is(notNullValue()));
assertThat(stats, hasEntry("name", identifier.getName()));
assertThat(stats, hasEntry("order", realm.order()));
assertThat(stats, hasEntry("size", 0));
assertThat(stats, hasEntry("ssl", false));
assertThat(stats, hasEntry("user_search", userSearch));
}
private SecureSettings secureSettings(
Function<String, Setting.AffixSetting<SecureString>> settingFactory,
RealmConfig.RealmIdentifier identifier,
String value
) {
final MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setString(getFullSettingKey(identifier, settingFactory), value);
return secureSettings;
}
}
| LdapRealmTests |
java | apache__camel | components/camel-google/camel-google-bigquery/src/test/java/org/apache/camel/component/google/bigquery/integration/InsertIdIT.java | {
"start": 1651,
"end": 5178
} | class ____ extends BigQueryITSupport {
private static final String TABLE_ID = "insertId";
@EndpointInject("direct:withInsertId")
private Endpoint directInWithInsertId;
@EndpointInject("direct:in")
private Endpoint directIn;
@EndpointInject("google-bigquery:{{project.id}}:{{bigquery.datasetId}}:"
+ TABLE_ID + "?useAsInsertId=col1")
private Endpoint bigqueryEndpointWithInsertId;
@EndpointInject("google-bigquery:{{project.id}}:{{bigquery.datasetId}}:"
+ TABLE_ID)
private Endpoint bigqueryEndpoint;
@EndpointInject("mock:sendResult")
private MockEndpoint sendResult;
@EndpointInject("mock:sendResultWithInsertId")
private MockEndpoint sendResultWithInsertId;
@Produce("direct:withInsertId")
private ProducerTemplate producerWithInsertId;
@Produce("direct:in")
private ProducerTemplate producer;
@BeforeEach
public void init() throws Exception {
createBqTable(TABLE_ID);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(directInWithInsertId)
.routeId("SingleRowWithInsertId")
.to(bigqueryEndpointWithInsertId)
.to(sendResultWithInsertId);
from(directIn)
.routeId("SingleRow")
.to(bigqueryEndpoint)
.to(sendResult);
}
};
}
@Test
public void sendTwoMessagesExpectOneRowUsingConfig() throws Exception {
Exchange exchange = new DefaultExchange(context);
String uuidCol1 = UUID.randomUUID().toString();
String uuidCol2 = UUID.randomUUID().toString();
Map<String, String> object = new HashMap<>();
object.put("col1", uuidCol1);
object.put("col2", uuidCol2);
exchange.getIn().setBody(object);
Exchange exchange2 = new DefaultExchange(context);
String uuid2Col2 = UUID.randomUUID().toString();
object.put("col1", uuidCol1);
object.put("col2", uuid2Col2);
exchange2.getIn().setBody(object);
sendResultWithInsertId.expectedMessageCount(2);
producerWithInsertId.send(exchange);
producerWithInsertId.send(exchange2);
sendResultWithInsertId.assertIsSatisfied(4000);
assertRowExist(TABLE_ID, object);
}
@Test
public void sendTwoMessagesExpectOneRowUsingExchange() throws Exception {
Exchange exchange = new DefaultExchange(context);
String uuidCol1 = UUID.randomUUID().toString();
String uuidCol2 = UUID.randomUUID().toString();
Map<String, String> object = new HashMap<>();
object.put("col1", uuidCol1);
object.put("col2", uuidCol2);
exchange.getIn().setBody(object);
exchange.getIn().setHeader(GoogleBigQueryConstants.INSERT_ID, uuidCol1);
Exchange exchange2 = new DefaultExchange(context);
String uuid2Col2 = UUID.randomUUID().toString();
object.put("col1", uuidCol1);
object.put("col2", uuid2Col2);
exchange2.getIn().setBody(object);
exchange2.getIn().setHeader(GoogleBigQueryConstants.INSERT_ID, uuidCol1);
sendResult.expectedMessageCount(2);
producer.send(exchange);
producer.send(exchange2);
sendResult.assertIsSatisfied(4000);
assertRowExist(TABLE_ID, object);
}
}
| InsertIdIT |
java | apache__flink | flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/rest/header/util/GetApiVersionHeaders.java | {
"start": 1362,
"end": 2799
} | class ____
implements SqlGatewayMessageHeaders<
EmptyRequestBody, GetApiVersionResponseBody, EmptyMessageParameters> {
private static final String URL = "/api_versions";
private static final GetApiVersionHeaders INSTANCE = new GetApiVersionHeaders();
private GetApiVersionHeaders() {}
@Override
public HttpMethodWrapper getHttpMethod() {
return HttpMethodWrapper.GET;
}
@Override
public String getTargetRestEndpointURL() {
return URL;
}
@Override
public Class<GetApiVersionResponseBody> getResponseClass() {
return GetApiVersionResponseBody.class;
}
@Override
public HttpResponseStatus getResponseStatusCode() {
return HttpResponseStatus.OK;
}
@Override
public String getDescription() {
return "Get the current available versions for the Rest Endpoint. The client can choose one of the return version as the protocol for later communicate.";
}
@Override
public Class<EmptyRequestBody> getRequestClass() {
return EmptyRequestBody.class;
}
@Override
public EmptyMessageParameters getUnresolvedMessageParameters() {
return EmptyMessageParameters.getInstance();
}
public static GetApiVersionHeaders getInstance() {
return INSTANCE;
}
@Override
public String operationId() {
return "getApiVersion";
}
}
| GetApiVersionHeaders |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverterTests.java | {
"start": 1457,
"end": 5792
} | class ____ {
private ProtobufHttpMessageConverter converter = new ProtobufHttpMessageConverter();
private final ExtensionRegistry extensionRegistry = mock();
private final Msg testMsg = Msg.newBuilder().setFoo("Foo").setBlah(SecondMsg.newBuilder().setBlah(123).build()).build();
private final MediaType testPlusProtoMediaType = MediaType.parseMediaType("application/vnd.example.public.v1+x-protobuf");
@Test
void canRead() {
assertThat(this.converter.canRead(Msg.class, null)).isTrue();
assertThat(this.converter.canRead(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)).isTrue();
assertThat(this.converter.canRead(Msg.class, this.testPlusProtoMediaType)).isTrue();
assertThat(this.converter.canRead(Msg.class, MediaType.APPLICATION_JSON)).isTrue();
assertThat(this.converter.canRead(Msg.class, MediaType.TEXT_PLAIN)).isTrue();
}
@Test
void canWrite() {
assertThat(this.converter.canWrite(Msg.class, null)).isTrue();
assertThat(this.converter.canWrite(Msg.class, ProtobufHttpMessageConverter.PROTOBUF)).isTrue();
assertThat(this.converter.canWrite(Msg.class, this.testPlusProtoMediaType)).isTrue();
assertThat(this.converter.canWrite(Msg.class, MediaType.APPLICATION_JSON)).isTrue();
assertThat(this.converter.canWrite(Msg.class, MediaType.TEXT_PLAIN)).isTrue();
}
@Test
void read() throws IOException {
byte[] body = this.testMsg.toByteArray();
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
inputMessage.getHeaders().setContentType(ProtobufHttpMessageConverter.PROTOBUF);
Message result = this.converter.read(Msg.class, inputMessage);
assertThat(result).isEqualTo(this.testMsg);
}
@Test
void readNoContentType() throws IOException {
byte[] body = this.testMsg.toByteArray();
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
Message result = this.converter.read(Msg.class, inputMessage);
assertThat(result).isEqualTo(this.testMsg);
}
@Test
void writeProtobuf() throws IOException {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF;
this.converter.write(this.testMsg, contentType, outputMessage);
assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType);
assertThat(outputMessage.getBodyAsBytes().length).isGreaterThan(0);
Message result = Msg.parseFrom(outputMessage.getBodyAsBytes());
assertThat(result).isEqualTo(this.testMsg);
String messageHeader =
outputMessage.getHeaders().getFirst(ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER);
assertThat(messageHeader).isEqualTo("Msg");
String schemaHeader =
outputMessage.getHeaders().getFirst(ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER);
assertThat(schemaHeader).isEqualTo("sample.proto");
}
@Test
void writeJsonWithGoogleProtobuf() throws IOException {
this.converter = new ProtobufHttpMessageConverter(
new ProtobufHttpMessageConverter.ProtobufJavaUtilDelegate(null, null),
this.extensionRegistry);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MediaType contentType = MediaType.APPLICATION_JSON;
this.converter.write(this.testMsg, contentType, outputMessage);
assertThat(outputMessage.getHeaders().getContentType()).isEqualTo(contentType);
final String body = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertThat(body).as("body is empty").isNotEmpty();
Msg.Builder builder = Msg.newBuilder();
JsonFormat.parser().merge(body, builder);
assertThat(builder.build()).isEqualTo(this.testMsg);
assertThat(outputMessage.getHeaders().getFirst(
ProtobufHttpMessageConverter.X_PROTOBUF_MESSAGE_HEADER)).isNull();
assertThat(outputMessage.getHeaders().getFirst(
ProtobufHttpMessageConverter.X_PROTOBUF_SCHEMA_HEADER)).isNull();
}
@Test
void defaultContentType() {
assertThat(this.converter.getDefaultContentType(this.testMsg))
.isEqualTo(ProtobufHttpMessageConverter.PROTOBUF);
}
@Test
void getContentLength() throws IOException {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MediaType contentType = ProtobufHttpMessageConverter.PROTOBUF;
this.converter.write(this.testMsg, contentType, outputMessage);
assertThat(outputMessage.getHeaders().getContentLength()).isEqualTo(-1);
}
}
| ProtobufHttpMessageConverterTests |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/uri/UriTemplate.java | {
"start": 19920,
"end": 21090
} | interface ____ extends CharSequence {
/**
* @return Whether this segment is part of the query string
*/
default boolean isQuerySegment() {
return false;
}
/**
* If this path segment represents a variable returns the underlying variable name.
*
* @return The variable name if present
*/
default Optional<String> getVariable() {
return Optional.empty();
}
/**
* @return True if this is a variable segment
*/
default boolean isVariable() {
return getVariable().isPresent();
}
/**
* Expands the query segment.
*
* @param parameters The parameters
* @param previousHasContent Whether there was previous content
* @param anyPreviousHasOperator Whether an operator is present
* @return The expanded string
*/
String expand(Map<String, Object> parameters, boolean previousHasContent, boolean anyPreviousHasOperator);
}
/**
* An URI template parser.
*/
protected static | PathSegment |
java | quarkusio__quarkus | core/runtime/src/main/java/io/quarkus/runtime/logging/LogRuntimeConfig.java | {
"start": 13883,
"end": 15486
} | interface ____ {
/**
* If socket logging should be enabled
*/
@WithDefault("false")
boolean enabled();
/**
* If socket logging should be enabled
*
* @deprecated use {@code quarkus.log.socket.enabled} instead
*/
@Deprecated(since = "3.26", forRemoval = true)
Optional<Boolean> enable();
/**
*
* The IP address and port of the server receiving the logs
*/
@WithDefault("localhost:4560")
@WithConverter(InetSocketAddressConverter.class)
InetSocketAddress endpoint();
/**
* Sets the protocol used to connect to the syslog server
*/
@WithDefault("tcp")
SocketHandler.Protocol protocol();
/**
* Enables or disables blocking when attempting to reconnect a
* {@link Protocol#TCP
* TCP} or {@link Protocol#SSL_TCP SSL TCP} protocol
*/
@WithDefault("false")
boolean blockOnReconnect();
/**
* The log message format
*/
@WithDefault("%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n")
String format();
/**
* The log level specifying, which message levels will be logged by socket logger
*/
@WithDefault("ALL")
Level level();
/**
* The name of the filter to link to the file handler.
*/
Optional<String> filter();
/**
* Socket async logging config
*/
AsyncConfig async();
}
| SocketConfig |
java | elastic__elasticsearch | benchmarks/src/main/java/org/elasticsearch/benchmark/vector/scorer/VectorScorerInt4Benchmark.java | {
"start": 2226,
"end": 7426
} | class ____ {
static {
LogConfigurator.configureESLogging(); // native access requires logging to be initialized
}
@Param({ "384", "782", "1024" })
int dims;
int numVectors = 20 * ES91Int4VectorsScorer.BULK_SIZE;
int numQueries = 5;
byte[] scratch;
byte[][] binaryVectors;
byte[][] binaryQueries;
float[] scores = new float[ES91Int4VectorsScorer.BULK_SIZE];
float[] scratchFloats = new float[3];
ES91Int4VectorsScorer scorer;
Directory dir;
IndexInput in;
OptimizedScalarQuantizer.QuantizationResult queryCorrections;
float centroidDp;
@Setup
public void setup() throws IOException {
binaryVectors = new byte[numVectors][dims];
dir = new MMapDirectory(Files.createTempDirectory("vectorData"));
try (IndexOutput out = dir.createOutput("vectors", IOContext.DEFAULT)) {
for (byte[] binaryVector : binaryVectors) {
for (int i = 0; i < dims; i++) {
// 4-bit quantization
binaryVector[i] = (byte) ThreadLocalRandom.current().nextInt(16);
}
out.writeBytes(binaryVector, 0, binaryVector.length);
ThreadLocalRandom.current().nextBytes(binaryVector);
out.writeBytes(binaryVector, 0, 14); // corrections
}
}
queryCorrections = new OptimizedScalarQuantizer.QuantizationResult(
ThreadLocalRandom.current().nextFloat(),
ThreadLocalRandom.current().nextFloat(),
ThreadLocalRandom.current().nextFloat(),
Short.toUnsignedInt((short) ThreadLocalRandom.current().nextInt())
);
centroidDp = ThreadLocalRandom.current().nextFloat();
in = dir.openInput("vectors", IOContext.DEFAULT);
binaryQueries = new byte[numVectors][dims];
for (byte[] binaryVector : binaryVectors) {
for (int i = 0; i < dims; i++) {
// 4-bit quantization
binaryVector[i] = (byte) ThreadLocalRandom.current().nextInt(16);
}
}
scratch = new byte[dims];
scorer = ESVectorizationProvider.getInstance().newES91Int4VectorsScorer(in, dims);
}
@TearDown
public void teardown() throws IOException {
IOUtils.close(dir, in);
}
@Benchmark
@Fork(jvmArgsPrepend = { "--add-modules=jdk.incubator.vector" })
public void scoreFromArray(Blackhole bh) throws IOException {
for (int j = 0; j < numQueries; j++) {
in.seek(0);
for (int i = 0; i < numVectors; i++) {
in.readBytes(scratch, 0, dims);
int dp = VectorUtil.int4DotProduct(binaryQueries[j], scratch);
in.readFloats(scratchFloats, 0, 3);
float score = scorer.applyCorrections(
queryCorrections.lowerInterval(),
queryCorrections.upperInterval(),
queryCorrections.quantizedComponentSum(),
queryCorrections.additionalCorrection(),
VectorSimilarityFunction.EUCLIDEAN,
centroidDp, // assuming no centroid dot product for this benchmark
scratchFloats[0],
scratchFloats[1],
Short.toUnsignedInt(in.readShort()),
scratchFloats[2],
dp
);
bh.consume(score);
}
}
}
@Benchmark
@Fork(jvmArgsPrepend = { "--add-modules=jdk.incubator.vector" })
public void scoreFromMemorySegment(Blackhole bh) throws IOException {
for (int j = 0; j < numQueries; j++) {
in.seek(0);
for (int i = 0; i < numVectors; i++) {
bh.consume(
scorer.score(
binaryQueries[j],
queryCorrections.lowerInterval(),
queryCorrections.upperInterval(),
queryCorrections.quantizedComponentSum(),
queryCorrections.additionalCorrection(),
VectorSimilarityFunction.EUCLIDEAN,
centroidDp
)
);
}
}
}
@Benchmark
@Fork(jvmArgsPrepend = { "--add-modules=jdk.incubator.vector" })
public void scoreFromMemorySegmentBulk(Blackhole bh) throws IOException {
for (int j = 0; j < numQueries; j++) {
in.seek(0);
for (int i = 0; i < numVectors; i += ES91Int4VectorsScorer.BULK_SIZE) {
scorer.scoreBulk(
binaryQueries[j],
queryCorrections.lowerInterval(),
queryCorrections.upperInterval(),
queryCorrections.quantizedComponentSum(),
queryCorrections.additionalCorrection(),
VectorSimilarityFunction.EUCLIDEAN,
centroidDp,
scores
);
for (float score : scores) {
bh.consume(score);
}
}
}
}
}
| VectorScorerInt4Benchmark |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/parsing/PropertyParserTest.java | {
"start": 792,
"end": 3959
} | class ____ {
@Test
void replaceToVariableValue() {
Properties props = new Properties();
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
props.setProperty("key", "value");
props.setProperty("tableName", "members");
props.setProperty("orderColumn", "member_id");
props.setProperty("a:b", "c");
Assertions.assertThat(PropertyParser.parse("${key}", props)).isEqualTo("value");
Assertions.assertThat(PropertyParser.parse("${key:aaaa}", props)).isEqualTo("value");
Assertions.assertThat(PropertyParser.parse("SELECT * FROM ${tableName:users} ORDER BY ${orderColumn:id}", props))
.isEqualTo("SELECT * FROM members ORDER BY member_id");
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "false");
Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("c");
props.remove(PropertyParser.KEY_ENABLE_DEFAULT_VALUE);
Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("c");
}
@Test
void notReplace() {
Properties props = new Properties();
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
Assertions.assertThat(PropertyParser.parse("${key}", props)).isEqualTo("${key}");
Assertions.assertThat(PropertyParser.parse("${key}", null)).isEqualTo("${key}");
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "false");
Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("${a:b}");
props.remove(PropertyParser.KEY_ENABLE_DEFAULT_VALUE);
Assertions.assertThat(PropertyParser.parse("${a:b}", props)).isEqualTo("${a:b}");
}
@Test
void applyDefaultValue() {
Properties props = new Properties();
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
Assertions.assertThat(PropertyParser.parse("${key:default}", props)).isEqualTo("default");
Assertions.assertThat(PropertyParser.parse("SELECT * FROM ${tableName:users} ORDER BY ${orderColumn:id}", props))
.isEqualTo("SELECT * FROM users ORDER BY id");
Assertions.assertThat(PropertyParser.parse("${key:}", props)).isEmpty();
Assertions.assertThat(PropertyParser.parse("${key: }", props)).isEqualTo(" ");
Assertions.assertThat(PropertyParser.parse("${key::}", props)).isEqualTo(":");
}
@Test
void applyCustomSeparator() {
Properties props = new Properties();
props.setProperty(PropertyParser.KEY_ENABLE_DEFAULT_VALUE, "true");
props.setProperty(PropertyParser.KEY_DEFAULT_VALUE_SEPARATOR, "?:");
Assertions.assertThat(PropertyParser.parse("${key?:default}", props)).isEqualTo("default");
Assertions
.assertThat(PropertyParser.parse(
"SELECT * FROM ${schema?:prod}.${tableName == null ? 'users' : tableName} ORDER BY ${orderColumn}", props))
.isEqualTo("SELECT * FROM prod.${tableName == null ? 'users' : tableName} ORDER BY ${orderColumn}");
Assertions.assertThat(PropertyParser.parse("${key?:}", props)).isEmpty();
Assertions.assertThat(PropertyParser.parse("${key?: }", props)).isEqualTo(" ");
Assertions.assertThat(PropertyParser.parse("${key?::}", props)).isEqualTo(":");
}
}
| PropertyParserTest |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/BeanSerializer.java | {
"start": 547,
"end": 1092
} | class ____ can serialize Java objects that map
* to JSON Object output. Internally handling is mostly dealt with
* by a sequence of {@link BeanPropertyWriter}s that will handle
* access value to serialize and call appropriate serializers to
* write out JSON.
*<p>
* Implementation note: we will post-process resulting serializer,
* to figure out actual serializers for final types. This must be
* done from {@link #resolve} method, and NOT from constructor;
* otherwise we could end up with an infinite loop.
*/
@JacksonStdImpl
public | that |
java | netty__netty | transport-native-epoll/src/test/java/io/netty/channel/epoll/NativeTest.java | {
"start": 961,
"end": 1909
} | class ____ {
@Test
public void testAddressIpv4() throws Exception {
InetSocketAddress inetAddress = new InetSocketAddress(NetUtil.LOCALHOST4, 9999);
byte[] bytes = new byte[8];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.put(inetAddress.getAddress().getAddress());
buffer.putInt(inetAddress.getPort());
assertEquals(inetAddress, address(buffer.array(), 0, bytes.length));
}
@Test
public void testAddressIpv6() throws Exception {
Inet6Address address = NetUtil.LOCALHOST6;
InetSocketAddress inetAddress = new InetSocketAddress(address, 9999);
byte[] bytes = new byte[24];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.put(address.getAddress());
buffer.putInt(address.getScopeId());
buffer.putInt(inetAddress.getPort());
assertEquals(inetAddress, address(buffer.array(), 0, bytes.length));
}
}
| NativeTest |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/saml/SamlMessageBuilder.java | {
"start": 890,
"end": 2722
} | class ____ {
protected final Logger logger;
protected final Clock clock;
protected final SpConfiguration serviceProvider;
protected final EntityDescriptor identityProvider;
public SamlMessageBuilder(EntityDescriptor identityProvider, SpConfiguration serviceProvider, Clock clock) {
this.logger = LogManager.getLogger(getClass());
this.identityProvider = identityProvider;
this.serviceProvider = serviceProvider;
this.clock = clock;
}
protected String getIdentityProviderEndpoint(
String binding,
Function<IDPSSODescriptor, ? extends Collection<? extends Endpoint>> selector
) {
final List<String> locations = identityProvider.getRoleDescriptors(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)
.stream()
.map(rd -> (IDPSSODescriptor) rd)
.flatMap(idp -> selector.apply(idp).stream())
.filter(endp -> binding.equals(endp.getBinding()))
.map(Endpoint::getLocation)
.toList();
if (locations.isEmpty()) {
return null;
}
if (locations.size() > 1) {
throw new ElasticsearchException(
"Found multiple locations for binding [{}] in descriptor [{}] - [{}]",
binding,
identityProvider.getID(),
locations
);
}
return locations.get(0);
}
protected Issuer buildIssuer() {
Issuer issuer = SamlUtils.buildObject(Issuer.class, Issuer.DEFAULT_ELEMENT_NAME);
issuer.setValue(this.serviceProvider.getEntityId());
return issuer;
}
protected static String buildId() {
// 20 bytes (160 bits) of randomness as recommended by the SAML spec
return SamlUtils.generateSecureNCName(20);
}
}
| SamlMessageBuilder |
java | quarkusio__quarkus | integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/logging/CategoryConfiguredHandlerTest.java | {
"start": 716,
"end": 2837
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withConfigurationResource("application-category-configured-handlers-output.properties")
.withApplicationRoot((jar) -> jar
.addAsManifestResource("application.properties", "microprofile-config.properties"));
@Test
public void consoleOutputTest() {
LogManager logManager = LogManager.getLogManager();
assertThat(logManager).isInstanceOf(org.jboss.logmanager.LogManager.class);
QuarkusDelayedHandler delayedHandler = InitialConfigurator.DELAYED_HANDLER;
assertThat(Logger.getLogger("").getHandlers()).contains(delayedHandler);
Handler handler = Arrays.stream(delayedHandler.getHandlers()).filter(h -> (h instanceof ConsoleHandler))
.findFirst().get();
assertThat(handler).isNotNull();
assertThat(handler.getLevel()).isEqualTo(Level.WARNING);
Logger categoryLogger = logManager.getLogger("io.quarkus.category");
assertThat(categoryLogger).isNotNull();
assertThat(categoryLogger.getHandlers()).hasSize(2).extracting("class").containsExactlyInAnyOrder(ConsoleHandler.class,
SizeRotatingFileHandler.class);
Logger otherCategoryLogger = logManager.getLogger("io.quarkus.othercategory");
assertThat(otherCategoryLogger).isNotNull();
assertThat(otherCategoryLogger.getHandlers()).hasSize(1).extracting("class")
.containsExactlyInAnyOrder(ConsoleHandler.class);
Logger anotherCategoryLogger = logManager.getLogger("io.quarkus.anothercategory");
assertThat(anotherCategoryLogger).isNotNull();
assertThat(anotherCategoryLogger.getHandlers()).isEmpty();
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n");
}
}
| CategoryConfiguredHandlerTest |
java | resilience4j__resilience4j | resilience4j-spring/src/test/java/io/github/resilience4j/retry/configure/RetryConfigurationSpringTest.java | {
"start": 2573,
"end": 4105
} | class ____ {
private RetryRegistry retryRegistry;
private RetryAspect retryAspect;
private EventConsumerRegistry<RetryEvent> retryEventEventConsumerRegistry;
private RetryConfigurationProperties retryConfigurationProperties;
private ContextAwareScheduledThreadPoolExecutor contextAwareScheduledThreadPoolExecutor;
@Bean
public RetryRegistry retryRegistry() {
retryRegistry = RetryRegistry.ofDefaults();
return retryRegistry;
}
@Bean
public RetryAspect retryAspect(
RetryRegistry retryRegistry,
@Autowired(required = false) List<RetryAspectExt> retryAspectExts,
FallbackExecutor fallbackExecutor,
SpelResolver spelResolver
) {
retryAspect = new RetryAspect(retryConfigurationProperties(), retryRegistry,
retryAspectExts, fallbackExecutor, spelResolver,contextAwareScheduledThreadPoolExecutor);
return retryAspect;
}
@Bean
public EventConsumerRegistry<RetryEvent> eventConsumerRegistry() {
retryEventEventConsumerRegistry = new DefaultEventConsumerRegistry<>();
return retryEventEventConsumerRegistry;
}
@Bean
public RetryConfigurationProperties retryConfigurationProperties() {
retryConfigurationProperties = new RetryConfigurationPropertiesTest();
return retryConfigurationProperties;
}
private | ConfigWithOverrides |
java | apache__kafka | trogdor/src/main/java/org/apache/kafka/trogdor/fault/KiboshFaultController.java | {
"start": 974,
"end": 1277
} | class ____ implements TaskController {
private final Set<String> nodeNames;
public KiboshFaultController(Set<String> nodeNames) {
this.nodeNames = nodeNames;
}
@Override
public Set<String> targetNodes(Topology topology) {
return nodeNames;
}
}
| KiboshFaultController |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeIsEmpty.java | {
"start": 1313,
"end": 2372
} | class ____<T>
implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super Boolean> downstream;
Disposable upstream;
IsEmptyMaybeObserver(MaybeObserver<? super Boolean> downstream) {
this.downstream = downstream;
}
@Override
public void dispose() {
upstream.dispose();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
downstream.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
downstream.onSuccess(false);
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
@Override
public void onComplete() {
downstream.onSuccess(true);
}
}
}
| IsEmptyMaybeObserver |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/expressions/converter/converters/ReinterpretCastConverter.java | {
"start": 1330,
"end": 2299
} | class ____ extends CustomizedConverter {
@Override
public RexNode convert(CallExpression call, CallExpressionConvertRule.ConvertContext context) {
checkArgumentNumber(call, 3);
RexNode child = context.toRexNode(call.getChildren().get(0));
TypeLiteralExpression type = (TypeLiteralExpression) call.getChildren().get(1);
RexNode checkOverflow = context.toRexNode(call.getChildren().get(2));
return context.getRelBuilder()
.getRexBuilder()
.makeReinterpretCast(
context.getTypeFactory()
.createFieldTypeFromLogicalType(
type.getOutputDataType()
.getLogicalType()
.copy(child.getType().isNullable())),
child,
checkOverflow);
}
}
| ReinterpretCastConverter |
java | elastic__elasticsearch | libs/entitlement/src/main/java/org/elasticsearch/entitlement/runtime/policy/PolicyParser.java | {
"start": 3848,
"end": 16535
} | class ____ must end with 'Entitlement'"
);
}
var strippedClassName = entitlementClassName.substring(0, entitlementClassName.indexOf("Entitlement"));
return Arrays.stream(strippedClassName.split("(?=\\p{Lu})"))
.filter(Predicate.not(String::isEmpty))
.map(s -> s.toLowerCase(Locale.ROOT))
.collect(Collectors.joining("_"));
}
public static String getEntitlementName(Class<? extends Entitlement> entitlementClass) {
return EXTERNAL_ENTITLEMENT_NAMES_BY_CLASS.get(entitlementClass);
}
public PolicyParser(InputStream inputStream, String policyName, boolean isExternalPlugin) throws IOException {
this(inputStream, policyName, isExternalPlugin, EXTERNAL_ENTITLEMENT_CLASSES_BY_NAME);
}
// package private for tests
PolicyParser(
InputStream inputStream,
String policyName,
boolean isExternalPlugin,
Map<String, Class<? extends Entitlement>> externalEntitlements
) throws IOException {
this.policyParser = YamlXContent.yamlXContent.createParser(XContentParserConfiguration.EMPTY, Objects.requireNonNull(inputStream));
this.policyName = policyName;
this.isExternalPlugin = isExternalPlugin;
this.externalEntitlements = externalEntitlements;
}
public VersionedPolicy parseVersionedPolicy() {
Set<String> versions = Set.of();
Policy policy = emptyPolicy();
try {
if (policyParser.nextToken() != XContentParser.Token.START_OBJECT) {
throw newPolicyParserException("expected object <versioned policy>");
}
while (policyParser.nextToken() != XContentParser.Token.END_OBJECT) {
if (policyParser.currentToken() == XContentParser.Token.FIELD_NAME) {
if (policyParser.currentName().equals("versions")) {
versions = parseVersions();
} else if (policyParser.currentName().equals("policy")) {
policy = parsePolicy();
} else {
throw newPolicyParserException("expected either <version> or <policy> field");
}
} else {
throw newPolicyParserException("expected either <version> or <policy> field");
}
}
return new VersionedPolicy(policy, versions);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
private Policy emptyPolicy() {
return new Policy(policyName, List.of());
}
private Set<String> parseVersions() throws IOException {
try {
if (policyParser.nextToken() != XContentParser.Token.START_ARRAY) {
throw newPolicyParserException("expected array of <versions>");
}
Set<String> versions = new HashSet<>();
while (policyParser.nextToken() != XContentParser.Token.END_ARRAY) {
if (policyParser.currentToken() == XContentParser.Token.VALUE_STRING) {
String version = policyParser.text();
versions.add(version);
} else {
throw newPolicyParserException("expected <version>");
}
}
return versions;
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
public Policy parsePolicy() {
try {
if (policyParser.nextToken() != XContentParser.Token.START_OBJECT) {
throw newPolicyParserException("expected object <scope name>");
}
List<Scope> scopes = new ArrayList<>();
while (policyParser.nextToken() != XContentParser.Token.END_OBJECT) {
if (policyParser.currentToken() != XContentParser.Token.FIELD_NAME) {
throw newPolicyParserException("expected object <scope name>");
}
String scopeName = policyParser.currentName();
Scope scope = parseScope(scopeName);
scopes.add(scope);
}
return new Policy(policyName, scopes);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
protected Scope parseScope(String scopeName) throws IOException {
try {
if (policyParser.nextToken() != XContentParser.Token.START_ARRAY) {
throw newPolicyParserException(scopeName, "expected array of <entitlement type>");
}
List<Entitlement> entitlements = new ArrayList<>();
while (policyParser.nextToken() != XContentParser.Token.END_ARRAY) {
if (policyParser.currentToken() == XContentParser.Token.VALUE_STRING) {
String entitlementType = policyParser.text();
Entitlement entitlement = parseEntitlement(scopeName, entitlementType);
entitlements.add(entitlement);
} else if (policyParser.currentToken() == XContentParser.Token.START_OBJECT) {
if (policyParser.nextToken() != XContentParser.Token.FIELD_NAME) {
throw newPolicyParserException(scopeName, "expected object <entitlement type>");
}
String entitlementType = policyParser.currentName();
Entitlement entitlement = parseEntitlement(scopeName, entitlementType);
entitlements.add(entitlement);
if (policyParser.nextToken() != XContentParser.Token.END_OBJECT) {
throw newPolicyParserException(scopeName, "expected closing object");
}
} else {
throw newPolicyParserException(scopeName, "expected object <entitlement type>");
}
}
return new Scope(scopeName, entitlements);
} catch (IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
protected Entitlement parseEntitlement(String scopeName, String entitlementType) throws IOException {
XContentLocation startLocation = policyParser.getTokenLocation();
Class<?> entitlementClass = externalEntitlements.get(entitlementType);
if (entitlementClass == null) {
throw newPolicyParserException(scopeName, "unknown entitlement type [" + entitlementType + "]");
}
Constructor<?> entitlementConstructor = null;
Method entitlementMethod = null;
ExternalEntitlement entitlementMetadata = null;
for (var ctor : entitlementClass.getConstructors()) {
var metadata = ctor.getAnnotation(ExternalEntitlement.class);
if (metadata != null) {
if (entitlementMetadata != null) {
throw new IllegalStateException(
"entitlement class ["
+ entitlementClass.getName()
+ "] has more than one constructor annotated with ExternalEntitlement"
);
}
entitlementConstructor = ctor;
entitlementMetadata = metadata;
}
}
for (var method : entitlementClass.getMethods()) {
var metadata = method.getAnnotation(ExternalEntitlement.class);
if (metadata != null) {
if (Modifier.isStatic(method.getModifiers()) == false) {
throw new IllegalStateException(
"entitlement class [" + entitlementClass.getName() + "] has non-static method annotated with ExternalEntitlement"
);
}
if (entitlementMetadata != null) {
throw new IllegalStateException(
"entitlement class ["
+ entitlementClass.getName()
+ "] has more than one constructor and/or method annotated with ExternalEntitlement"
);
}
entitlementMethod = method;
entitlementMetadata = metadata;
}
}
if (entitlementMetadata == null) {
throw newPolicyParserException(scopeName, "unknown entitlement type [" + entitlementType + "]");
}
if (entitlementMetadata.esModulesOnly() && isExternalPlugin) {
throw newPolicyParserException("entitlement type [" + entitlementType + "] is allowed only on modules");
}
Class<?>[] parameterTypes = entitlementConstructor != null
? entitlementConstructor.getParameterTypes()
: entitlementMethod.getParameterTypes();
String[] parametersNames = entitlementMetadata.parameterNames();
Object[] parameterValues = new Object[parameterTypes.length];
if (parameterTypes.length != 0 || parametersNames.length != 0) {
if (policyParser.nextToken() == XContentParser.Token.START_OBJECT) {
Map<String, Object> parsedValues = policyParser.map();
for (int parameterIndex = 0; parameterIndex < parameterTypes.length; ++parameterIndex) {
String parameterName = parametersNames[parameterIndex];
Object parameterValue = parsedValues.remove(parameterName);
if (parameterValue == null) {
throw newPolicyParserException(scopeName, entitlementType, "missing entitlement parameter [" + parameterName + "]");
}
Class<?> parameterType = parameterTypes[parameterIndex];
if (parameterType.isAssignableFrom(parameterValue.getClass()) == false) {
throw newPolicyParserException(
scopeName,
entitlementType,
"unexpected parameter type ["
+ parameterType.getSimpleName()
+ "] for entitlement parameter ["
+ parameterName
+ "]"
);
}
parameterValues[parameterIndex] = parameterValue;
}
if (parsedValues.isEmpty() == false) {
throw newPolicyParserException(scopeName, entitlementType, "extraneous entitlement parameter(s) " + parsedValues);
}
} else if (policyParser.currentToken() == XContentParser.Token.START_ARRAY) {
List<Object> parsedValues = policyParser.list();
parameterValues[0] = parsedValues;
} else {
throw newPolicyParserException(scopeName, entitlementType, "expected entitlement parameters");
}
}
try {
if (entitlementConstructor != null) {
return (Entitlement) entitlementConstructor.newInstance(parameterValues);
} else {
return (Entitlement) entitlementMethod.invoke(null, parameterValues);
}
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
if (e.getCause() instanceof PolicyValidationException piae) {
throw newPolicyParserException(startLocation, scopeName, entitlementType, piae);
}
throw new IllegalStateException("internal error", e);
}
}
protected PolicyParserException newPolicyParserException(String message) {
return PolicyParserException.newPolicyParserException(policyParser.getTokenLocation(), policyName, message);
}
protected PolicyParserException newPolicyParserException(String scopeName, String message) {
return PolicyParserException.newPolicyParserException(policyParser.getTokenLocation(), policyName, scopeName, message);
}
protected PolicyParserException newPolicyParserException(String scopeName, String entitlementType, String message) {
return PolicyParserException.newPolicyParserException(
policyParser.getTokenLocation(),
policyName,
scopeName,
entitlementType,
message
);
}
protected PolicyParserException newPolicyParserException(
XContentLocation location,
String scopeName,
String entitlementType,
PolicyValidationException cause
) {
return PolicyParserException.newPolicyParserException(location, policyName, scopeName, entitlementType, cause);
}
}
| name |
java | apache__flink | flink-queryable-state/flink-queryable-state-runtime/src/test/java/org/apache/flink/queryablestate/network/KvStateClientHandlerTest.java | {
"start": 5135,
"end": 6414
} | class ____ implements ClientHandlerCallback {
private int onRequestCnt;
private long onRequestId;
private MessageBody onRequestBody;
private int onRequestFailureCnt;
private long onRequestFailureId;
private Throwable onRequestFailureBody;
private int onFailureCnt;
private Throwable onFailureBody;
@Override
public void onRequestResult(long requestId, MessageBody response) {
onRequestCnt++;
onRequestId = requestId;
onRequestBody = response;
}
@Override
public void onRequestFailure(long requestId, Throwable cause) {
onRequestFailureCnt++;
onRequestFailureId = requestId;
onRequestFailureBody = cause;
}
@Override
public void onFailure(Throwable cause) {
onFailureCnt++;
onFailureBody = cause;
}
public void reset() {
onRequestCnt = 0;
onRequestId = -1;
onRequestBody = null;
onRequestFailureCnt = 0;
onRequestFailureId = -1;
onRequestFailureBody = null;
onFailureCnt = 0;
onFailureBody = null;
}
}
}
| TestingClientHandlerCallback |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/AbstractGenericTypeComparatorTest.java | {
"start": 4257,
"end": 6063
} | class ____<T> extends ComparatorTestBase<T> {
private final T[] testData;
private final Class<T> type;
@SuppressWarnings("unchecked")
public ComparatorTestInstance(T[] testData) {
if (testData == null || testData.length == 0) {
throw new IllegalArgumentException();
}
this.testData = testData;
this.type = (Class<T>) testData[0].getClass();
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
protected TypeComparator<T> createComparator(boolean ascending) {
return new GenericTypeComparator(
ascending,
AbstractGenericTypeComparatorTest.this.createSerializer(this.type),
this.type);
}
@Override
protected TypeSerializer<T> createSerializer() {
return AbstractGenericTypeComparatorTest.this.createSerializer(this.type);
}
@Override
protected T[] getSortedTestData() {
return this.testData;
}
public void testAll() throws IOException {
testDuplicate();
testEquality();
testEqualityWithReference();
testInequality();
testInequalityWithReference();
testNormalizedKeysEqualsFullLength();
testNormalizedKeysEqualsHalfLength();
testNormalizedKeysGreatSmallFullLength();
testNormalizedKeysGreatSmallAscDescHalfLength();
testNormalizedKeyReadWriter();
}
}
// ------------------------------------------------------------------------
// test objects
// ------------------------------------------------------------------------
public static final | ComparatorTestInstance |
java | apache__rocketmq | client/src/main/java/org/apache/rocketmq/client/impl/consumer/PopRequest.java | {
"start": 1039,
"end": 3930
} | class ____ implements MessageRequest {
private String topic;
private String consumerGroup;
private MessageQueue messageQueue;
private PopProcessQueue popProcessQueue;
private boolean lockedFirst = false;
private int initMode = ConsumeInitMode.MAX;
public boolean isLockedFirst() {
return lockedFirst;
}
public void setLockedFirst(boolean lockedFirst) {
this.lockedFirst = lockedFirst;
}
public String getConsumerGroup() {
return consumerGroup;
}
public void setConsumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
}
public MessageQueue getMessageQueue() {
return messageQueue;
}
public void setMessageQueue(MessageQueue messageQueue) {
this.messageQueue = messageQueue;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public PopProcessQueue getPopProcessQueue() {
return popProcessQueue;
}
public void setPopProcessQueue(PopProcessQueue popProcessQueue) {
this.popProcessQueue = popProcessQueue;
}
public int getInitMode() {
return initMode;
}
public void setInitMode(int initMode) {
this.initMode = initMode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((topic == null) ? 0 : topic.hashCode());
result = prime * result + ((consumerGroup == null) ? 0 : consumerGroup.hashCode());
result = prime * result + ((messageQueue == null) ? 0 : messageQueue.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PopRequest other = (PopRequest) obj;
if (topic == null) {
if (other.topic != null)
return false;
} else if (!topic.equals(other.topic)) {
return false;
}
if (consumerGroup == null) {
if (other.consumerGroup != null)
return false;
} else if (!consumerGroup.equals(other.consumerGroup))
return false;
if (messageQueue == null) {
if (other.messageQueue != null)
return false;
} else if (!messageQueue.equals(other.messageQueue)) {
return false;
}
return true;
}
@Override
public String toString() {
return "PopRequest [topic=" + topic + ", consumerGroup=" + consumerGroup + ", messageQueue=" + messageQueue + "]";
}
@Override
public MessageRequestMode getMessageRequestMode() {
return MessageRequestMode.POP;
}
}
| PopRequest |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/ArgumentPreparedStatementSetter.java | {
"start": 934,
"end": 2435
} | class ____ implements PreparedStatementSetter, ParameterDisposer {
private final @Nullable Object @Nullable [] args;
/**
* Create a new {@code ArgumentPreparedStatementSetter} for the given arguments.
* @param args the arguments to set
*/
public ArgumentPreparedStatementSetter(@Nullable Object @Nullable [] args) {
this.args = args;
}
@Override
public void setValues(PreparedStatement ps) throws SQLException {
if (this.args != null) {
for (int i = 0; i < this.args.length; i++) {
Object arg = this.args[i];
doSetValue(ps, i + 1, arg);
}
}
}
/**
* Set the value for the prepared statement's specified parameter position
* using the supplied value.
* <p>This method can be overridden by subclasses if needed.
* @param ps the PreparedStatement
* @param parameterPosition index of the parameter position
* @param argValue the value to set
* @throws SQLException if thrown by PreparedStatement methods
*/
protected void doSetValue(PreparedStatement ps, int parameterPosition, @Nullable Object argValue)
throws SQLException {
if (argValue instanceof SqlParameterValue paramValue) {
StatementCreatorUtils.setParameterValue(ps, parameterPosition, paramValue, paramValue.getValue());
}
else {
StatementCreatorUtils.setParameterValue(ps, parameterPosition, SqlTypeValue.TYPE_UNKNOWN, argValue);
}
}
@Override
public void cleanupParameters() {
StatementCreatorUtils.cleanupParameters(this.args);
}
}
| ArgumentPreparedStatementSetter |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/support/ConventionUtilsTests.java | {
"start": 863,
"end": 2235
} | class ____ {
@Test
void toDashedCaseCamelCase() {
assertThat(toDashedCase("simpleCamelCase")).isEqualTo("simple-camel-case");
}
@Test
void toDashedCaseUpperCamelCaseSuffix() {
assertThat(toDashedCase("myDLQ")).isEqualTo("my-d-l-q");
}
@Test
void toDashedCaseUpperCamelCaseMiddle() {
assertThat(toDashedCase("someDLQKey")).isEqualTo("some-d-l-q-key");
}
@Test
void toDashedCaseWordsUnderscore() {
assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore");
}
@Test
void toDashedCaseWordsSeveralUnderscores() {
assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore");
}
@Test
void toDashedCaseLowerCaseUnderscore() {
assertThat(toDashedCase("lower_underscore")).isEqualTo("lower-underscore");
}
@Test
void toDashedCaseUpperUnderscoreSuffix() {
assertThat(toDashedCase("my_DLQ")).isEqualTo("my-d-l-q");
}
@Test
void toDashedCaseUpperUnderscoreMiddle() {
assertThat(toDashedCase("some_DLQ_key")).isEqualTo("some-d-l-q-key");
}
@Test
void toDashedCaseMultipleUnderscores() {
assertThat(toDashedCase("super___crazy")).isEqualTo("super---crazy");
}
@Test
void toDashedCaseLowercase() {
assertThat(toDashedCase("lowercase")).isEqualTo("lowercase");
}
private String toDashedCase(String name) {
return ConventionUtils.toDashedCase(name);
}
}
| ConventionUtilsTests |
java | junit-team__junit5 | junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/extension/TimeoutConfiguration.java | {
"start": 5869,
"end": 6227
} | enum ____ {
ENABLED {
@Override
boolean isTimeoutDisabled() {
return false;
}
},
DISABLED {
@Override
boolean isTimeoutDisabled() {
return true;
}
},
DISABLED_ON_DEBUG {
@Override
boolean isTimeoutDisabled() {
return RuntimeUtils.isDebugMode();
}
};
abstract boolean isTimeoutDisabled();
}
}
| TimeoutMode |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/ClassUtilsOssFuzzTest.java | {
"start": 981,
"end": 15821
} | class ____ {
/**
* Tests that no StackOverflowError is thrown.
* <p>
* OSS-Fuzz Issue 42522972: apache-commons-text:StringSubstitutorInterpolatorFuzzer: Security exception in org.apache.commons.lang3.ClassUtils.getClass
* </p>
*/
@Test
public void testGetClassLongIllegalName() throws Exception {
// Input from Commons Text clusterfuzz-testcase-StringSubstitutorInterpolatorFuzzer-5447769450741760
assertThrows(ClassNotFoundException.class, () -> ClassUtils.getClass(
"ˇda´~e]W] ~ t $t ${.u base64encoder{con+s {.u base64encoder{con+s ~ t .................... ................ˇˇˇˇˇˇˇˇˇˇ&${localhot:ˇˇˇˇˇˇ4ˇ......... .........................s${.!. ${.. \\E],${conÅ EEE]W€EÅE.! ${.u base64encoder{conÅ EEE]W€EÅE.! ${.u base64encoder{con+s ~ t ....................................ˇˇˇˇˇˇˇˇˇˇ&${localhot:ˇˇˇˇˇˇ-636ˇ............................................................... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - -...... t]V]W€EÅE.! $${.u - - }"));
}
/**
* Tests that no StackOverflowError is thrown.
*/
@Test
public void testGetClassLongName() throws Exception {
// Input from based on the above, without illegal characters.
assertThrows(ClassNotFoundException.class, () -> ClassUtils.getClass(StringUtils.repeat("a.", 5_000) + "b"));
}
}
| ClassUtilsOssFuzzTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.