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-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/StructuredFunctionsITCase.java
|
{
"start": 21707,
"end": 22709
}
|
class ____ {
private static final String TYPE_STRING =
String.format(
"STRUCTURED<'%s', n1 %s, n2 %s>",
NestedType.class.getName(), Type1.TYPE_STRING, Type2.TYPE_STRING);
public Type1 n1;
public Type2 n2;
public static NestedType of(final Type1 n1, final Type2 n2) {
final NestedType t = new NestedType();
t.n1 = n1;
t.n2 = n2;
return t;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NestedType that = (NestedType) o;
return Objects.equals(n1, that.n1) && Objects.equals(n2, that.n2);
}
@Override
public int hashCode() {
return Objects.hash(n1, n2);
}
public static
|
NestedType
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalHDRPercentiles.java
|
{
"start": 780,
"end": 2676
}
|
class ____ extends AbstractInternalHDRPercentiles implements Percentiles {
public static final String NAME = "hdr_percentiles";
public InternalHDRPercentiles(
String name,
double[] percents,
DoubleHistogram state,
boolean keyed,
DocValueFormat formatter,
Map<String, Object> metadata
) {
super(name, percents, state, keyed, formatter, metadata);
}
/**
* Read from a stream.
*/
public InternalHDRPercentiles(StreamInput in) throws IOException {
super(in);
}
@Override
public String getWriteableName() {
return NAME;
}
public static InternalHDRPercentiles empty(
String name,
double[] keys,
boolean keyed,
DocValueFormat format,
Map<String, Object> metadata
) {
return new InternalHDRPercentiles(name, keys, null, keyed, format, metadata);
}
@Override
public Iterator<Percentile> iterator() {
if (state == null) {
return EMPTY_ITERATOR;
}
return new Iter(keys, state);
}
@Override
public double percentile(double percent) {
if (state == null || state.getTotalCount() == 0) {
return Double.NaN;
}
return state.getValueAtPercentile(percent);
}
@Override
public String percentileAsString(double percent) {
return valueAsString(String.valueOf(percent));
}
@Override
public double value(double key) {
return percentile(key);
}
@Override
protected AbstractInternalHDRPercentiles createReduced(
String name,
double[] keys,
DoubleHistogram merged,
boolean keyed,
Map<String, Object> metadata
) {
return new InternalHDRPercentiles(name, keys, merged, keyed, format, metadata);
}
public static
|
InternalHDRPercentiles
|
java
|
apache__maven
|
impl/maven-core/src/main/java/org/apache/maven/plugin/PluginResolutionException.java
|
{
"start": 1010,
"end": 1956
}
|
class ____ extends Exception {
private final Plugin plugin;
public PluginResolutionException(Plugin plugin, Throwable cause) {
super(
"Plugin " + plugin.getId() + " or one of its dependencies could not be resolved: " + cause.getMessage(),
cause);
this.plugin = plugin;
}
public PluginResolutionException(Plugin plugin, List<Exception> exceptions, Throwable cause) {
super(
"Plugin " + plugin.getId() + " or one of its dependencies could not be resolved:"
+ System.lineSeparator() + "\t"
+ exceptions.stream()
.map(Throwable::getMessage)
.collect(Collectors.joining(System.lineSeparator() + "\t")),
cause);
this.plugin = plugin;
}
public Plugin getPlugin() {
return plugin;
}
}
|
PluginResolutionException
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/net/protocol/jar/JarFileUrlKeyTests.java
|
{
"start": 1015,
"end": 3284
}
|
class ____ {
@BeforeAll
static void setup() {
Handlers.register();
}
@Test
void equalsAndHashCode() throws Exception {
JarFileUrlKey k1 = key("jar:nested:/my.jar/!mynested.jar!/my/path");
JarFileUrlKey k2 = key("jar:nested:/my.jar/!mynested.jar!/my/path");
JarFileUrlKey k3 = key("jar:nested:/my.jar/!mynested.jar!/my/path2");
assertThat(k1.hashCode()).isEqualTo(k2.hashCode())
.isEqualTo("nested:/my.jar/!mynested.jar!/my/path".hashCode());
assertThat(k1).isEqualTo(k1).isEqualTo(k2).isNotEqualTo(k3);
}
@Test
void equalsWhenUppercaseAndLowercaseProtocol() throws Exception {
JarFileUrlKey k1 = key("JAR:nested:/my.jar/!mynested.jar!/my/path");
JarFileUrlKey k2 = key("jar:nested:/my.jar/!mynested.jar!/my/path");
assertThat(k1).isEqualTo(k2);
}
@Test
void equalsWhenHasHostAndPort() throws Exception {
JarFileUrlKey k1 = key("https://example.com:1234/test");
JarFileUrlKey k2 = key("https://example.com:1234/test");
assertThat(k1).isEqualTo(k2);
}
@Test
void equalsWhenHasUppercaseAndLowercaseHost() throws Exception {
JarFileUrlKey k1 = key("https://EXAMPLE.com:1234/test");
JarFileUrlKey k2 = key("https://example.com:1234/test");
assertThat(k1).isEqualTo(k2);
}
@Test
void equalsWhenHasNoPortUsesDefaultPort() throws Exception {
JarFileUrlKey k1 = key("https://EXAMPLE.com/test");
JarFileUrlKey k2 = key("https://example.com:443/test");
assertThat(k1).isEqualTo(k2);
}
@Test
void equalsWhenHasNoFile() throws Exception {
JarFileUrlKey k1 = key("https://EXAMPLE.com");
JarFileUrlKey k2 = key("https://example.com:443");
assertThat(k1).isEqualTo(k2);
}
@Test
void equalsWhenHasRuntimeRef() throws Exception {
JarFileUrlKey k1 = key("jar:nested:/my.jar/!mynested.jar!/my/path#runtime");
JarFileUrlKey k2 = key("jar:nested:/my.jar/!mynested.jar!/my/path#runtime");
assertThat(k1).isEqualTo(k2);
}
@Test
void equalsWhenHasOtherRefIgnoresRefs() throws Exception {
JarFileUrlKey k1 = key("jar:nested:/my.jar/!mynested.jar!/my/path#example");
JarFileUrlKey k2 = key("jar:nested:/my.jar/!mynested.jar!/my/path");
assertThat(k1).isEqualTo(k2);
}
private JarFileUrlKey key(String spec) throws MalformedURLException {
return new JarFileUrlKey(new URL(spec));
}
}
|
JarFileUrlKeyTests
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/core/type/classreading/MetadataReaderFactoryDelegate.java
|
{
"start": 1020,
"end": 1336
}
|
class ____ {
static MetadataReaderFactory create(@Nullable ResourceLoader resourceLoader) {
return new SimpleMetadataReaderFactory(resourceLoader);
}
static MetadataReaderFactory create(@Nullable ClassLoader classLoader) {
return new SimpleMetadataReaderFactory(classLoader);
}
}
|
MetadataReaderFactoryDelegate
|
java
|
quarkusio__quarkus
|
integration-tests/main/src/main/java/io/quarkus/it/arc/ProducerOfUnusedUnremovableBean.java
|
{
"start": 160,
"end": 327
}
|
class ____ {
@Unremovable
@Produces
public Bean produce() {
return new Bean();
}
@Dependent
public static
|
ProducerOfUnusedUnremovableBean
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
|
{
"start": 34117,
"end": 34456
}
|
interface ____");
});
}
@Test
public void multibindingContributionBetweenAncestorComponentAndEntrypointComponent() {
Source parent =
CompilerTests.javaSource(
"Parent",
"import dagger.Component;",
"",
"@Component(modules = ParentModule.class)",
"
|
Parent
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableScalarXMap.java
|
{
"start": 4168,
"end": 5582
}
|
class ____<T, R> extends Flowable<R> {
final T value;
final Function<? super T, ? extends Publisher<? extends R>> mapper;
ScalarXMapFlowable(T value,
Function<? super T, ? extends Publisher<? extends R>> mapper) {
this.value = value;
this.mapper = mapper;
}
@SuppressWarnings("unchecked")
@Override
public void subscribeActual(Subscriber<? super R> s) {
Publisher<? extends R> other;
try {
other = Objects.requireNonNull(mapper.apply(value), "The mapper returned a null Publisher");
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
EmptySubscription.error(e, s);
return;
}
if (other instanceof Supplier) {
R u;
try {
u = ((Supplier<R>)other).get();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, s);
return;
}
if (u == null) {
EmptySubscription.complete(s);
return;
}
s.onSubscribe(new ScalarSubscription<>(s, u));
} else {
other.subscribe(s);
}
}
}
}
|
ScalarXMapFlowable
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/NonApiTypeTest.java
|
{
"start": 8916,
"end": 9329
}
|
class ____ {
public Test(int a) {}
public int doSomething() {
return 42;
}
public void doSomething(int a) {}
}
""")
.doTest();
}
@Test
public void streams() {
helper
.addSourceLines(
"Test.java",
"""
import java.util.stream.Stream;
public
|
Test
|
java
|
apache__avro
|
lang/java/maven-plugin/src/main/java/org/apache/avro/mojo/IDLMojo.java
|
{
"start": 1440,
"end": 4448
}
|
class ____ extends AbstractAvroMojo {
/**
* A set of Ant-like inclusion patterns used to select files from the source
* directory for processing. By default, the pattern <code>**/*.avdl</code>
* is used to select IDL files.
*
* @parameter
*/
private String[] includes = new String[] { "**/*.avdl" };
/**
* A set of Ant-like inclusion patterns used to select files from the source
* directory for processing. By default, the pattern <code>**/*.avdl</code>
* is used to select IDL files.
*
* @parameter
*/
private String[] testIncludes = new String[] { "**/*.avdl" };
@Override
protected void doCompile(String filename, File sourceDirectory, File outputDirectory) throws IOException {
try {
@SuppressWarnings("rawtypes")
List runtimeClasspathElements = project.getRuntimeClasspathElements();
List<URL> runtimeUrls = new ArrayList<>();
// Add the source directory of avro files to the classpath so that
// imports can refer to other idl files as classpath resources
runtimeUrls.add(sourceDirectory.toURI().toURL());
// If runtimeClasspathElements is not empty values add its values to Idl path.
if (runtimeClasspathElements != null && !runtimeClasspathElements.isEmpty()) {
for (Object runtimeClasspathElement : runtimeClasspathElements) {
String element = (String) runtimeClasspathElement;
runtimeUrls.add(new File(element).toURI().toURL());
}
}
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader projPathLoader = new URLClassLoader(runtimeUrls.toArray(new URL[0]), contextClassLoader);
Thread.currentThread().setContextClassLoader(projPathLoader);
try {
IdlReader parser = new IdlReader();
Path sourceFilePath = sourceDirectory.toPath().resolve(filename);
IdlFile idlFile = parser.parse(sourceFilePath);
for (String warning : idlFile.getWarnings()) {
getLog().warn(warning);
}
final SpecificCompiler compiler;
final Protocol protocol = idlFile.getProtocol();
if (protocol != null) {
compiler = new SpecificCompiler(protocol);
} else {
compiler = new SpecificCompiler(idlFile.getNamedSchemas().values());
}
setCompilerProperties(compiler);
for (String customConversion : customConversions) {
compiler.addCustomConversion(projPathLoader.loadClass(customConversion));
}
compiler.compileToDestination(sourceFilePath.toFile(), outputDirectory);
} finally {
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
} catch (ClassNotFoundException | DependencyResolutionRequiredException e) {
throw new IOException(e);
}
}
@Override
protected String[] getIncludes() {
return includes;
}
@Override
protected String[] getTestIncludes() {
return testIncludes;
}
}
|
IDLMojo
|
java
|
spring-projects__spring-boot
|
buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/AutoConfigurationClass.java
|
{
"start": 3542,
"end": 4673
}
|
class ____ extends AnnotationVisitor {
private Map<String, List<String>> attributes = new HashMap<>();
private static final Set<String> INTERESTING_ATTRIBUTES = Set.of("before", "beforeName", "after",
"afterName");
private AutoConfigurationAnnotationVisitor() {
super(SpringAsmInfo.ASM_VERSION);
}
@Override
public void visitEnd() {
AutoConfigurationClassVisitor.this.autoConfigurationClass = new AutoConfigurationClass(
AutoConfigurationClassVisitor.this.name, this.attributes);
}
@Override
public AnnotationVisitor visitArray(String attributeName) {
if (INTERESTING_ATTRIBUTES.contains(attributeName)) {
return new AnnotationVisitor(SpringAsmInfo.ASM_VERSION) {
@Override
public void visit(String name, Object value) {
if (value instanceof Type type) {
value = type.getClassName();
}
AutoConfigurationAnnotationVisitor.this.attributes
.computeIfAbsent(attributeName, (n) -> new ArrayList<>())
.add(Objects.toString(value));
}
};
}
return null;
}
}
}
}
|
AutoConfigurationAnnotationVisitor
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleTimeout.java
|
{
"start": 2432,
"end": 5318
}
|
class ____<T> extends AtomicReference<Disposable>
implements SingleObserver<T> {
private static final long serialVersionUID = 2071387740092105509L;
final SingleObserver<? super T> downstream;
TimeoutFallbackObserver(SingleObserver<? super T> downstream) {
this.downstream = downstream;
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onSuccess(T t) {
downstream.onSuccess(t);
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
}
TimeoutMainObserver(SingleObserver<? super T> actual, SingleSource<? extends T> other, long timeout, TimeUnit unit) {
this.downstream = actual;
this.other = other;
this.timeout = timeout;
this.unit = unit;
this.task = new AtomicReference<>();
if (other != null) {
this.fallback = new TimeoutFallbackObserver<>(actual);
} else {
this.fallback = null;
}
}
@Override
public void run() {
if (DisposableHelper.dispose(this)) {
SingleSource<? extends T> other = this.other;
if (other == null) {
downstream.onError(new TimeoutException(timeoutMessage(timeout, unit)));
} else {
this.other = null;
other.subscribe(fallback);
}
}
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onSuccess(T t) {
Disposable d = get();
if (d != DisposableHelper.DISPOSED && compareAndSet(d, DisposableHelper.DISPOSED)) {
DisposableHelper.dispose(task);
downstream.onSuccess(t);
}
}
@Override
public void onError(Throwable e) {
Disposable d = get();
if (d != DisposableHelper.DISPOSED && compareAndSet(d, DisposableHelper.DISPOSED)) {
DisposableHelper.dispose(task);
downstream.onError(e);
} else {
RxJavaPlugins.onError(e);
}
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
DisposableHelper.dispose(task);
if (fallback != null) {
DisposableHelper.dispose(fallback);
}
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
}
}
|
TimeoutFallbackObserver
|
java
|
spring-projects__spring-boot
|
module/spring-boot-security/src/test/java/org/springframework/boot/security/autoconfigure/web/servlet/ServletWebSecurityAutoConfigurationTests.java
|
{
"start": 10376,
"end": 10825
}
|
class ____ {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@WithResource(name = "public-key-location", content = """
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdlatRjRjogo3WojgGHFHYLugd
UWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQs
HUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5D
o2kQ+X5xK9cipRgEKwIDAQAB
-----END PUBLIC KEY-----
""")
@
|
TargetType
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/ast/beans/BeanElement.java
|
{
"start": 1666,
"end": 2618
}
|
class ____ the bean.
*/
@NonNull
ClassElement getDeclaringClass();
/**
* The element that produces the bean, this could be a {@link ClassElement} for regular beans,
* or either a {@link io.micronaut.inject.ast.MethodElement} or {@link io.micronaut.inject.ast.FieldElement} for factory beans.
*
* @return The producing element
*/
@NonNull
Element getProducingElement();
/**
* The type names produced by the bean.
* @return A set of types
*/
@NonNull
Set<ClassElement> getBeanTypes();
/**
* The scope of the bean.
* @return The fully qualified name of the scope or empty if no scope is defined.
*/
@NonNull
Optional<String> getScope();
/**
* @return One or more fully qualified qualifier types defined by the bean.
*/
@NonNull
Collection<String> getQualifiers();
/**
* This method adds an associated bean using this
|
of
|
java
|
quarkusio__quarkus
|
integration-tests/devmode/src/test/java/io/quarkus/test/devui/DevUIHibernateOrmActiveFalseAndNamedPuActiveTrueTest.java
|
{
"start": 247,
"end": 1985
}
|
class ____ extends AbstractDevUIHibernateOrmTest {
@RegisterExtension
static final QuarkusDevModeTest test = new QuarkusDevModeTest()
.withApplicationRoot((jar) -> jar.addAsResource(
new StringAsset("quarkus.datasource.db-kind=h2\n"
+ "quarkus.datasource.jdbc.url=jdbc:h2:mem:test\n"
+ "quarkus.datasource.\"nameddatasource\".db-kind=h2\n"
+ "quarkus.datasource.\"nameddatasource\".jdbc.url=jdbc:h2:mem:test2\n"
+ "quarkus.datasource.\"nameddatasource\".reactive=false\n" // No H2 reactive driver!
// Hibernate ORM is inactive for the default PU
+ "quarkus.hibernate-orm.active=false\n"
+ "quarkus.hibernate-orm.datasource=<default>\n"
+ "quarkus.hibernate-orm.packages=io.quarkus.test.devui\n"
+ "quarkus.hibernate-orm.\"namedpu\".schema-management.strategy=drop-and-create\n"
// ... but it's (implicitly) active for a named PU
+ "quarkus.hibernate-orm.\"namedpu\".datasource=nameddatasource\n"
+ "quarkus.hibernate-orm.\"namedpu\".packages=io.quarkus.test.devui.namedpu\n"),
"application.properties")
.addClasses(MyEntity.class)
.addClasses(MyNamedPuEntity.class));
public DevUIHibernateOrmActiveFalseAndNamedPuActiveTrueTest() {
super("namedpu", "MyNamedPuEntity", "io.quarkus.test.devui.namedpu.MyNamedPuEntity", null, false);
}
}
|
DevUIHibernateOrmActiveFalseAndNamedPuActiveTrueTest
|
java
|
netty__netty
|
codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java
|
{
"start": 2710,
"end": 19663
}
|
class ____ implements StreamByteDistributor {
/**
* The initial size of the children map is chosen to be conservative on initial memory allocations under
* the assumption that most streams will have a small number of children. This choice may be
* sub-optimal if when children are present there are many children (i.e. a web page which has many
* dependencies to load).
*
* Visible only for testing!
*/
static final int INITIAL_CHILDREN_MAP_SIZE =
max(1, SystemPropertyUtil.getInt("io.netty.http2.childrenMapSize", 2));
/**
* FireFox currently uses 5 streams to establish QoS classes.
*/
private static final int DEFAULT_MAX_STATE_ONLY_SIZE = 5;
private final Http2Connection.PropertyKey stateKey;
/**
* If there is no Http2Stream object, but we still persist priority information then this is where the state will
* reside.
*/
private final IntObjectMap<State> stateOnlyMap;
/**
* This queue will hold streams that are not active and provides the capability to retain priority for streams which
* have no {@link Http2Stream} object. See {@link StateOnlyComparator} for the priority comparator.
*/
private final PriorityQueue<State> stateOnlyRemovalQueue;
private final Http2Connection connection;
private final State connectionState;
/**
* The minimum number of bytes that we will attempt to allocate to a stream. This is to
* help improve goodput on a per-stream basis.
*/
private int allocationQuantum = DEFAULT_MIN_ALLOCATION_CHUNK;
private final int maxStateOnlySize;
public WeightedFairQueueByteDistributor(Http2Connection connection) {
this(connection, DEFAULT_MAX_STATE_ONLY_SIZE);
}
public WeightedFairQueueByteDistributor(Http2Connection connection, int maxStateOnlySize) {
checkPositiveOrZero(maxStateOnlySize, "maxStateOnlySize");
if (maxStateOnlySize == 0) {
stateOnlyMap = IntCollections.emptyMap();
stateOnlyRemovalQueue = EmptyPriorityQueue.instance();
} else {
stateOnlyMap = new IntObjectHashMap<State>(maxStateOnlySize);
// +2 because we may exceed the limit by 2 if a new dependency has no associated Http2Stream object. We need
// to create the State objects to put them into the dependency tree, which then impacts priority.
stateOnlyRemovalQueue = new DefaultPriorityQueue<State>(StateOnlyComparator.INSTANCE, maxStateOnlySize + 2);
}
this.maxStateOnlySize = maxStateOnlySize;
this.connection = connection;
stateKey = connection.newKey();
final Http2Stream connectionStream = connection.connectionStream();
connectionStream.setProperty(stateKey, connectionState = new State(connectionStream, 16));
// Register for notification of new streams.
connection.addListener(new Http2ConnectionAdapter() {
@Override
public void onStreamAdded(Http2Stream stream) {
State state = stateOnlyMap.remove(stream.id());
if (state == null) {
state = new State(stream);
// Only the stream which was just added will change parents. So we only need an array of size 1.
List<ParentChangedEvent> events = new ArrayList<ParentChangedEvent>(1);
connectionState.takeChild(state, false, events);
notifyParentChanged(events);
} else {
stateOnlyRemovalQueue.removeTyped(state);
state.stream = stream;
}
switch (stream.state()) {
case RESERVED_REMOTE:
case RESERVED_LOCAL:
state.setStreamReservedOrActivated();
// wasStreamReservedOrActivated is part of the comparator for stateOnlyRemovalQueue there is no
// need to reprioritize here because it will not be in stateOnlyRemovalQueue.
break;
default:
break;
}
stream.setProperty(stateKey, state);
}
@Override
public void onStreamActive(Http2Stream stream) {
state(stream).setStreamReservedOrActivated();
// wasStreamReservedOrActivated is part of the comparator for stateOnlyRemovalQueue there is no need to
// reprioritize here because it will not be in stateOnlyRemovalQueue.
}
@Override
public void onStreamClosed(Http2Stream stream) {
state(stream).close();
}
@Override
public void onStreamRemoved(Http2Stream stream) {
// The stream has been removed from the connection. We can no longer rely on the stream's property
// storage to track the State. If we have room, and the precedence of the stream is sufficient, we
// should retain the State in the stateOnlyMap.
State state = state(stream);
// Typically the stream is set to null when the stream is closed because it is no longer needed to write
// data. However if the stream was not activated it may not be closed (reserved streams) so we ensure
// the stream reference is set to null to avoid retaining a reference longer than necessary.
state.stream = null;
if (WeightedFairQueueByteDistributor.this.maxStateOnlySize == 0) {
state.parent.removeChild(state);
return;
}
if (stateOnlyRemovalQueue.size() == WeightedFairQueueByteDistributor.this.maxStateOnlySize) {
State stateToRemove = stateOnlyRemovalQueue.peek();
if (StateOnlyComparator.INSTANCE.compare(stateToRemove, state) >= 0) {
// The "lowest priority" stream is a "higher priority" than the stream being removed, so we
// just discard the state.
state.parent.removeChild(state);
return;
}
stateOnlyRemovalQueue.poll();
stateToRemove.parent.removeChild(stateToRemove);
stateOnlyMap.remove(stateToRemove.streamId);
}
stateOnlyRemovalQueue.add(state);
stateOnlyMap.put(state.streamId, state);
}
});
}
@Override
public void updateStreamableBytes(StreamState state) {
state(state.stream()).updateStreamableBytes(streamableBytes(state),
state.hasFrame() && state.windowSize() >= 0);
}
@Override
public void updateDependencyTree(int childStreamId, int parentStreamId, short weight, boolean exclusive) {
State state = state(childStreamId);
if (state == null) {
// If there is no State object that means there is no Http2Stream object and we would have to keep the
// State object in the stateOnlyMap and stateOnlyRemovalQueue. However if maxStateOnlySize is 0 this means
// stateOnlyMap and stateOnlyRemovalQueue are empty collections and cannot be modified so we drop the State.
if (maxStateOnlySize == 0) {
return;
}
state = new State(childStreamId);
stateOnlyRemovalQueue.add(state);
stateOnlyMap.put(childStreamId, state);
}
State newParent = state(parentStreamId);
if (newParent == null) {
// If there is no State object that means there is no Http2Stream object and we would have to keep the
// State object in the stateOnlyMap and stateOnlyRemovalQueue. However if maxStateOnlySize is 0 this means
// stateOnlyMap and stateOnlyRemovalQueue are empty collections and cannot be modified so we drop the State.
if (maxStateOnlySize == 0) {
return;
}
newParent = new State(parentStreamId);
stateOnlyRemovalQueue.add(newParent);
stateOnlyMap.put(parentStreamId, newParent);
// Only the stream which was just added will change parents. So we only need an array of size 1.
List<ParentChangedEvent> events = new ArrayList<ParentChangedEvent>(1);
connectionState.takeChild(newParent, false, events);
notifyParentChanged(events);
}
// if activeCountForTree == 0 then it will not be in its parent's pseudoTimeQueue and thus should not be counted
// toward parent.totalQueuedWeights.
if (state.activeCountForTree != 0 && state.parent != null) {
state.parent.totalQueuedWeights += weight - state.weight;
}
state.weight = weight;
if (newParent != state.parent || exclusive && newParent.children.size() != 1) {
final List<ParentChangedEvent> events;
if (newParent.isDescendantOf(state)) {
events = new ArrayList<ParentChangedEvent>(2 + (exclusive ? newParent.children.size() : 0));
state.parent.takeChild(newParent, false, events);
} else {
events = new ArrayList<ParentChangedEvent>(1 + (exclusive ? newParent.children.size() : 0));
}
newParent.takeChild(state, exclusive, events);
notifyParentChanged(events);
}
// The location in the dependency tree impacts the priority in the stateOnlyRemovalQueue map. If we created new
// State objects we must check if we exceeded the limit after we insert into the dependency tree to ensure the
// stateOnlyRemovalQueue has been updated.
while (stateOnlyRemovalQueue.size() > maxStateOnlySize) {
State stateToRemove = stateOnlyRemovalQueue.poll();
stateToRemove.parent.removeChild(stateToRemove);
stateOnlyMap.remove(stateToRemove.streamId);
}
}
@Override
public boolean distribute(int maxBytes, Writer writer) throws Http2Exception {
// As long as there is some active frame we should write at least 1 time.
if (connectionState.activeCountForTree == 0) {
return false;
}
// The goal is to write until we write all the allocated bytes or are no longer making progress.
// We still attempt to write even after the number of allocated bytes has been exhausted to allow empty frames
// to be sent. Making progress means the active streams rooted at the connection stream has changed.
int oldIsActiveCountForTree;
do {
oldIsActiveCountForTree = connectionState.activeCountForTree;
// connectionState will never be active, so go right to its children.
maxBytes -= distributeToChildren(maxBytes, writer, connectionState);
} while (connectionState.activeCountForTree != 0 &&
(maxBytes > 0 || oldIsActiveCountForTree != connectionState.activeCountForTree));
return connectionState.activeCountForTree != 0;
}
/**
* Sets the amount of bytes that will be allocated to each stream. Defaults to 1KiB.
* @param allocationQuantum the amount of bytes that will be allocated to each stream. Must be > 0.
*/
public void allocationQuantum(int allocationQuantum) {
checkPositive(allocationQuantum, "allocationQuantum");
this.allocationQuantum = allocationQuantum;
}
private int distribute(int maxBytes, Writer writer, State state) throws Http2Exception {
if (state.isActive()) {
int nsent = min(maxBytes, state.streamableBytes);
state.write(nsent, writer);
if (nsent == 0 && maxBytes != 0) {
// If a stream sends zero bytes, then we gave it a chance to write empty frames and it is now
// considered inactive until the next call to updateStreamableBytes. This allows descendant streams to
// be allocated bytes when the parent stream can't utilize them. This may be as a result of the
// stream's flow control window being 0.
state.updateStreamableBytes(state.streamableBytes, false);
}
return nsent;
}
return distributeToChildren(maxBytes, writer, state);
}
/**
* It is a pre-condition that {@code state.poll()} returns a non-{@code null} value. This is a result of the way
* the allocation algorithm is structured and can be explained in the following cases:
* <h3>For the recursive case</h3>
* If a stream has no children (in the allocation tree) than that node must be active or it will not be in the
* allocation tree. If a node is active then it will not delegate to children and recursion ends.
* <h3>For the initial case</h3>
* We check connectionState.activeCountForTree == 0 before any allocation is done. So if the connection stream
* has no active children we don't get into this method.
*/
private int distributeToChildren(int maxBytes, Writer writer, State state) throws Http2Exception {
long oldTotalQueuedWeights = state.totalQueuedWeights;
State childState = state.pollPseudoTimeQueue();
State nextChildState = state.peekPseudoTimeQueue();
childState.setDistributing();
try {
assert nextChildState == null || nextChildState.pseudoTimeToWrite >= childState.pseudoTimeToWrite :
"nextChildState[" + nextChildState.streamId + "].pseudoTime(" + nextChildState.pseudoTimeToWrite +
") < " + " childState[" + childState.streamId + "].pseudoTime(" + childState.pseudoTimeToWrite + ')';
int nsent = distribute(nextChildState == null ? maxBytes :
min(maxBytes, (int) min((nextChildState.pseudoTimeToWrite - childState.pseudoTimeToWrite) *
childState.weight / oldTotalQueuedWeights + allocationQuantum, MAX_VALUE)
),
writer,
childState);
state.pseudoTime += nsent;
childState.updatePseudoTime(state, nsent, oldTotalQueuedWeights);
return nsent;
} finally {
childState.unsetDistributing();
// Do in finally to ensure the internal flags is not corrupted if an exception is thrown.
// The offer operation is delayed until we unroll up the recursive stack, so we don't have to remove from
// the priority pseudoTimeQueue due to a write operation.
if (childState.activeCountForTree != 0) {
state.offerPseudoTimeQueue(childState);
}
}
}
private State state(Http2Stream stream) {
return stream.getProperty(stateKey);
}
private State state(int streamId) {
Http2Stream stream = connection.stream(streamId);
return stream != null ? state(stream) : stateOnlyMap.get(streamId);
}
/**
* For testing only!
*/
boolean isChild(int childId, int parentId, short weight) {
State parent = state(parentId);
State child;
return parent.children.containsKey(childId) &&
(child = state(childId)).parent == parent && child.weight == weight;
}
/**
* For testing only!
*/
int numChildren(int streamId) {
State state = state(streamId);
return state == null ? 0 : state.children.size();
}
/**
* Notify all listeners of the priority tree change events (in ascending order)
* @param events The events (top down order) which have changed
*/
void notifyParentChanged(List<ParentChangedEvent> events) {
for (int i = 0; i < events.size(); ++i) {
ParentChangedEvent event = events.get(i);
stateOnlyRemovalQueue.priorityChanged(event.state);
if (event.state.parent != null && event.state.activeCountForTree != 0) {
event.state.parent.offerAndInitializePseudoTime(event.state);
event.state.parent.activeCountChangeForTree(event.state.activeCountForTree);
}
}
}
/**
* A comparator for {@link State} which has no associated {@link Http2Stream} object. The general precedence is:
* <ul>
* <li>Was a stream activated or reserved (streams only used for priority are higher priority)</li>
* <li>Depth in the priority tree (closer to root is higher priority></li>
* <li>Stream ID (higher stream ID is higher priority - used for tie breaker)</li>
* </ul>
*/
private static final
|
WeightedFairQueueByteDistributor
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests.java
|
{
"start": 19206,
"end": 19561
}
|
class ____ implements AuthorizationManager<MethodInvocation> {
@Override
public AuthorizationResult authorize(
Supplier<? extends @org.jspecify.annotations.Nullable Authentication> authentication,
MethodInvocation object) {
return new AuthorizationDecision("bob".equals(authentication.get().getName()));
}
}
static
|
MyAuthorizationManager
|
java
|
apache__camel
|
core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/GroupedExchangeAggregationStrategy.java
|
{
"start": 1842,
"end": 2505
}
|
class ____ extends AbstractListAggregationStrategy<Exchange> {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
// for the first time we must create a new empty exchange as the holder, as the outgoing exchange
// must not be one of the grouped exchanges, as that causes a endless circular reference
oldExchange = new DefaultExchange(newExchange);
}
return super.aggregate(oldExchange, newExchange);
}
@Override
public Exchange getValue(Exchange exchange) {
return exchange;
}
}
|
GroupedExchangeAggregationStrategy
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/groups/FieldsOrPropertiesExtractor_extract_Test.java
|
{
"start": 5162,
"end": 5413
}
|
class ____ extends Employee {
public EmployeeWithBrokenName(String name) {
super(1L, new Name(name), 0);
}
@Override
public Name getName() {
throw new IllegalStateException();
}
}
public static
|
EmployeeWithBrokenName
|
java
|
mockito__mockito
|
mockito-core/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java
|
{
"start": 633,
"end": 2746
}
|
class ____<V> implements Runnable, Iterable<V> {
final WeakConcurrentMap<V, Boolean> target;
public WeakConcurrentSet(Cleaner cleaner) {
switch (cleaner) {
case INLINE:
target = new WeakConcurrentMap.WithInlinedExpunction<>();
break;
case THREAD:
case MANUAL:
target = new WeakConcurrentMap<>(cleaner == Cleaner.THREAD);
break;
default:
throw new AssertionError();
}
}
/**
* @param value The value to add to the set.
* @return {@code true} if the value was added to the set and was not contained before.
*/
public boolean add(V value) {
return target.put(value, Boolean.TRUE) == null; // is null or Boolean.TRUE
}
/**
* @param value The value to check if it is contained in the set.
* @return {@code true} if the set contains the value.
*/
public boolean contains(V value) {
return target.containsKey(value);
}
/**
* @param value The value to remove from the set.
* @return {@code true} if the value is contained in the set.
*/
public boolean remove(V value) {
return target.remove(value) != null;
}
/**
* Clears the set.
*/
public void clear() {
target.clear();
}
/**
* Returns the approximate size of this set where the returned number is at least as big as the actual number of entries.
*
* @return The minimum size of this set.
*/
public int approximateSize() {
return target.approximateSize();
}
@Override
public void run() {
target.run();
}
/**
* Determines the cleaning format. A reference is removed either by an explicitly started cleaner thread
* associated with this instance ({@link Cleaner#THREAD}), as a result of interacting with this thread local
* from any thread ({@link Cleaner#INLINE} or manually by submitting the detached thread local to a thread
* ({@link Cleaner#MANUAL}).
*/
public
|
WeakConcurrentSet
|
java
|
apache__logging-log4j2
|
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/TextEncoderHelperBenchmark.java
|
{
"start": 1993,
"end": 2796
}
|
class ____ {
static final String STR = "AB!(%087936DZYXQWEIOP$#^~-=/><nb"; // length=32
static final String STR_TEXT =
"20:01:59.9876 INFO [org.apache.logging.log4j.perf.jmh.TextEncoderHelperBenchmark] AB!(%087936DZYXQWEIOP$#^~-=/><nb"; // length=32
static final StringBuilder BUFF_TEXT = new StringBuilder(STR_TEXT);
static final CharBuffer CHAR_BUFFER = CharBuffer.wrap(STR.toCharArray());
static final LogEvent EVENT = createLogEvent();
private static final Charset CHARSET_DEFAULT = Charset.defaultCharset();
private final PatternLayout PATTERN_M_C_D =
PatternLayout.createLayout("%d %c %m%n", null, null, null, CHARSET_DEFAULT, false, true, null, null);
private final Destination destination = new Destination();
|
TextEncoderHelperBenchmark
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/cte/CriteriaCteCopyTest.java
|
{
"start": 3917,
"end": 4521
}
|
interface ____<T> {
JpaCteCriteria<T> accept(HibernateCriteriaBuilder cb, JpaCriteriaQuery<Integer> cq);
}
@BeforeAll
public void setUp(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
entityManager.persist( new BasicEntity( 1, "data_1" ) );
entityManager.persist( new BasicEntity( 2, "data_2" ) );
entityManager.persist( new BasicEntity( 3, "data_3" ) );
} );
}
@AfterAll
public void tearDown(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> entityManager.createQuery( "delete from BasicEntity" ).executeUpdate() );
}
}
|
CteConsumer
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/net/SSLOptions.java
|
{
"start": 1032,
"end": 11824
}
|
class ____ {
/**
* Default use alpn = false
*/
public static final boolean DEFAULT_USE_ALPN = false;
/**
* The default value of SSL handshake timeout = 10
*/
public static final long DEFAULT_SSL_HANDSHAKE_TIMEOUT = 10L;
/**
* Default SSL handshake time unit = SECONDS
*/
public static final TimeUnit DEFAULT_SSL_HANDSHAKE_TIMEOUT_TIME_UNIT = TimeUnit.SECONDS;
/**
* The default ENABLED_SECURE_TRANSPORT_PROTOCOLS value = { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }
* <p/>
* SSLv3 is NOT enabled due to POODLE vulnerability http://en.wikipedia.org/wiki/POODLE
* <p/>
* "SSLv2Hello" is NOT enabled since it's disabled by default since JDK7
*/
public static final List<String> DEFAULT_ENABLED_SECURE_TRANSPORT_PROTOCOLS = Collections.unmodifiableList(Arrays.asList("TLSv1.2", "TLSv1.3"));
private long sslHandshakeTimeout;
private TimeUnit sslHandshakeTimeoutUnit;
private KeyCertOptions keyCertOptions;
private TrustOptions trustOptions;
Set<String> enabledCipherSuites;
List<String> crlPaths;
List<Buffer> crlValues;
private boolean useAlpn;
private Set<String> enabledSecureTransportProtocols;
private List<String> applicationLayerProtocols;
/**
* Default constructor
*/
public SSLOptions() {
init();
}
/**
* Copy constructor
*
* @param other the options to copy
*/
public SSLOptions(SSLOptions other) {
this.sslHandshakeTimeout = other.sslHandshakeTimeout;
this.sslHandshakeTimeoutUnit = other.getSslHandshakeTimeoutUnit() != null ? other.getSslHandshakeTimeoutUnit() : DEFAULT_SSL_HANDSHAKE_TIMEOUT_TIME_UNIT;
this.keyCertOptions = other.getKeyCertOptions() != null ? other.getKeyCertOptions().copy() : null;
this.trustOptions = other.getTrustOptions() != null ? other.getTrustOptions().copy() : null;
this.enabledCipherSuites = other.getEnabledCipherSuites() == null ? new LinkedHashSet<>() : new LinkedHashSet<>(other.getEnabledCipherSuites());
this.crlPaths = new ArrayList<>(other.getCrlPaths());
this.crlValues = new ArrayList<>(other.getCrlValues());
this.useAlpn = other.useAlpn;
this.enabledSecureTransportProtocols = other.getEnabledSecureTransportProtocols() == null ? new LinkedHashSet<>() : new LinkedHashSet<>(other.getEnabledSecureTransportProtocols());
this.applicationLayerProtocols = other.getApplicationLayerProtocols() != null ? new ArrayList<>(other.getApplicationLayerProtocols()) : null;
}
/**
* Create options from JSON
*
* @param json the JSON
*/
public SSLOptions(JsonObject json) {
this();
SSLOptionsConverter.fromJson(json ,this);
}
protected void init() {
sslHandshakeTimeout = DEFAULT_SSL_HANDSHAKE_TIMEOUT;
sslHandshakeTimeoutUnit = DEFAULT_SSL_HANDSHAKE_TIMEOUT_TIME_UNIT;
enabledCipherSuites = new LinkedHashSet<>();
crlPaths = new ArrayList<>();
crlValues = new ArrayList<>();
useAlpn = DEFAULT_USE_ALPN;
enabledSecureTransportProtocols = new LinkedHashSet<>(DEFAULT_ENABLED_SECURE_TRANSPORT_PROTOCOLS);
applicationLayerProtocols = null;
}
public SSLOptions copy() {
return new SSLOptions(this);
}
/**
* @return the key/cert options
*/
@GenIgnore
public KeyCertOptions getKeyCertOptions() {
return keyCertOptions;
}
/**
* Set the key/cert options.
*
* @param options the key store options
* @return a reference to this, so the API can be used fluently
*/
@GenIgnore
public SSLOptions setKeyCertOptions(KeyCertOptions options) {
this.keyCertOptions = options;
return this;
}
/**
* @return the trust options
*/
public TrustOptions getTrustOptions() {
return trustOptions;
}
/**
* Set the trust options.
* @param options the trust options
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions setTrustOptions(TrustOptions options) {
this.trustOptions = options;
return this;
}
/**
* Add an enabled cipher suite, appended to the ordered suites.
*
* @param suite the suite
* @return a reference to this, so the API can be used fluently
* @see #getEnabledCipherSuites()
*/
public SSLOptions addEnabledCipherSuite(String suite) {
enabledCipherSuites.add(suite);
return this;
}
/**
* Removes an enabled cipher suite from the ordered suites.
*
* @param suite the suite
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions removeEnabledCipherSuite(String suite) {
enabledCipherSuites.remove(suite);
return this;
}
/**
* Return an ordered set of the cipher suites.
*
* <p> The set is initially empty and suite should be added to this set in the desired order.
*
* <p> When suites are added and therefore the list is not empty, it takes precedence over the
* default suite defined by the {@link SSLEngineOptions} in use.
*
* @return the enabled cipher suites
*/
public Set<String> getEnabledCipherSuites() {
return enabledCipherSuites;
}
/**
*
* @return the CRL (Certificate revocation list) paths
*/
public List<String> getCrlPaths() {
return crlPaths;
}
/**
* Add a CRL path
* @param crlPath the path
* @return a reference to this, so the API can be used fluently
* @throws NullPointerException
*/
public SSLOptions addCrlPath(String crlPath) throws NullPointerException {
Objects.requireNonNull(crlPath, "No null crl accepted");
crlPaths.add(crlPath);
return this;
}
/**
* Get the CRL values
*
* @return the list of values
*/
public List<Buffer> getCrlValues() {
return crlValues;
}
/**
* Add a CRL value
*
* @param crlValue the value
* @return a reference to this, so the API can be used fluently
* @throws NullPointerException
*/
public SSLOptions addCrlValue(Buffer crlValue) throws NullPointerException {
Objects.requireNonNull(crlValue, "No null crl accepted");
crlValues.add(crlValue);
return this;
}
/**
* @return whether to use or not Application-Layer Protocol Negotiation
*/
public boolean isUseAlpn() {
return useAlpn;
}
/**
* Set the ALPN usage.
*
* @param useAlpn true when Application-Layer Protocol Negotiation should be used
*/
public SSLOptions setUseAlpn(boolean useAlpn) {
this.useAlpn = useAlpn;
return this;
}
/**
* Returns the enabled SSL/TLS protocols
* @return the enabled protocols
*/
public Set<String> getEnabledSecureTransportProtocols() {
return new LinkedHashSet<>(enabledSecureTransportProtocols);
}
/**
* @return the SSL handshake timeout, in time unit specified by {@link #getSslHandshakeTimeoutUnit()}.
*/
public long getSslHandshakeTimeout() {
return sslHandshakeTimeout;
}
/**
* Set the SSL handshake timeout, default time unit is seconds.
*
* @param sslHandshakeTimeout the SSL handshake timeout to set, in milliseconds
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions setSslHandshakeTimeout(long sslHandshakeTimeout) {
if (sslHandshakeTimeout < 0) {
throw new IllegalArgumentException("sslHandshakeTimeout must be >= 0");
}
this.sslHandshakeTimeout = sslHandshakeTimeout;
return this;
}
/**
* Set the SSL handshake timeout unit. If not specified, default is seconds.
*
* @param sslHandshakeTimeoutUnit specify time unit.
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions setSslHandshakeTimeoutUnit(TimeUnit sslHandshakeTimeoutUnit) {
this.sslHandshakeTimeoutUnit = sslHandshakeTimeoutUnit;
return this;
}
/**
* @return the SSL handshake timeout unit.
*/
public TimeUnit getSslHandshakeTimeoutUnit() {
return sslHandshakeTimeoutUnit;
}
/**
* Sets the list of enabled SSL/TLS protocols.
*
* @param enabledSecureTransportProtocols the SSL/TLS protocols to enable
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions setEnabledSecureTransportProtocols(Set<String> enabledSecureTransportProtocols) {
this.enabledSecureTransportProtocols = enabledSecureTransportProtocols;
return this;
}
/**
* Add an enabled SSL/TLS protocols, appended to the ordered protocols.
*
* @param protocol the SSL/TLS protocol to enable
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions addEnabledSecureTransportProtocol(String protocol) {
enabledSecureTransportProtocols.add(protocol);
return this;
}
/**
* Removes an enabled SSL/TLS protocol from the ordered protocols.
*
* @param protocol the SSL/TLS protocol to disable
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions removeEnabledSecureTransportProtocol(String protocol) {
enabledSecureTransportProtocols.remove(protocol);
return this;
}
/**
* @return the list of application-layer protocols send during the Application-Layer Protocol Negotiation.
*/
public List<String> getApplicationLayerProtocols() {
return applicationLayerProtocols;
}
/**
* Set the list of application-layer protocols to provide to the server during the Application-Layer Protocol Negotiation.
*
* @param protocols the protocols
* @return a reference to this, so the API can be used fluently
*/
public SSLOptions setApplicationLayerProtocols(List<String> protocols) {
this.applicationLayerProtocols = protocols;
return this;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof SSLOptions) {
SSLOptions that = (SSLOptions) obj;
return sslHandshakeTimeoutUnit.toNanos(sslHandshakeTimeout) == that.sslHandshakeTimeoutUnit.toNanos(that.sslHandshakeTimeout) &&
Objects.equals(keyCertOptions, that.keyCertOptions) &&
Objects.equals(trustOptions, that.trustOptions) &&
Objects.equals(enabledCipherSuites, that.enabledCipherSuites) &&
Objects.equals(crlPaths, that.crlPaths) &&
Objects.equals(crlValues, that.crlValues) &&
useAlpn == that.useAlpn &&
Objects.equals(enabledSecureTransportProtocols, that.enabledSecureTransportProtocols);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(sslHandshakeTimeoutUnit.toNanos(sslHandshakeTimeout), keyCertOptions, trustOptions, enabledCipherSuites, crlPaths, crlValues, useAlpn, enabledSecureTransportProtocols);
}
/**
* Convert to JSON
*
* @return the JSON
*/
public JsonObject toJson() {
JsonObject json = new JsonObject();
SSLOptionsConverter.toJson(this, json);
return json;
}
}
|
SSLOptions
|
java
|
apache__avro
|
lang/java/mapred/src/main/java/org/apache/avro/mapreduce/AvroKeyOutputFormat.java
|
{
"start": 2236,
"end": 4022
}
|
class ____<T> {
/**
* Creates a new record writer instance.
*
* @param writerSchema The writer schema for the records to write.
* @param compressionCodec The compression type for the writer file.
* @param outputStream The target output stream for the records.
* @param syncInterval The sync interval for the writer file.
*/
protected RecordWriter<AvroKey<T>, NullWritable> create(Schema writerSchema, GenericData dataModel,
CodecFactory compressionCodec, OutputStream outputStream, int syncInterval) throws IOException {
return new AvroKeyRecordWriter<>(writerSchema, dataModel, compressionCodec, outputStream, syncInterval);
}
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public RecordWriter<AvroKey<T>, NullWritable> getRecordWriter(TaskAttemptContext context) throws IOException {
Configuration conf = context.getConfiguration();
// Get the writer schema.
Schema writerSchema = AvroJob.getOutputKeySchema(conf);
boolean isMapOnly = context.getNumReduceTasks() == 0;
if (isMapOnly) {
Schema mapOutputSchema = AvroJob.getMapOutputKeySchema(conf);
if (mapOutputSchema != null) {
writerSchema = mapOutputSchema;
}
}
if (null == writerSchema) {
throw new IOException("AvroKeyOutputFormat requires an output schema. Use AvroJob.setOutputKeySchema().");
}
GenericData dataModel = AvroSerialization.createDataModel(conf);
OutputStream out = getAvroFileOutputStream(context);
try {
return mRecordWriterFactory.create(writerSchema, dataModel, getCompressionCodec(context), out,
getSyncInterval(context));
} catch (IOException e) {
out.close();
throw e;
}
}
}
|
RecordWriterFactory
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/TreeToStringTest.java
|
{
"start": 869,
"end": 1738
}
|
class ____ {
private final CompilationTestHelper testHelper =
CompilationTestHelper.newInstance(TreeToString.class, getClass());
@Test
public void noMatch() {
testHelper
.addSourceLines(
"ExampleChecker.java",
"""
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.ClassTree;
import com.sun.tools.javac.code.Types;
@BugPattern(name = "Example", summary = "", severity = SeverityLevel.ERROR)
public
|
TreeToStringTest
|
java
|
apache__camel
|
core/camel-core-model/src/main/java/org/apache/camel/model/rest/ParamDefinition.java
|
{
"start": 7590,
"end": 7958
}
|
enum ____
*/
public ParamDefinition allowableValues(String... allowableValues) {
List<ValueDefinition> list = new ArrayList<>();
for (String av : allowableValues) {
list.add(new ValueDefinition(av));
}
setAllowableValues(list);
return this;
}
/**
* Allowed values of the parameter when its an
|
type
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/connection/TransactionAwareConnectionFactoryProxy.java
|
{
"start": 3176,
"end": 3512
}
|
interface ____ allow for access to the underlying target Session. This is only
* intended for accessing vendor-specific Session API or for testing purposes
* (for example, to perform manual transaction control). For typical application purposes,
* simply use the standard JMS Session interface.
*
* <p>As of Spring Framework 5, this
|
to
|
java
|
spring-projects__spring-boot
|
module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/autoconfigure/WebMvcProperties.java
|
{
"start": 7690,
"end": 9159
}
|
class ____ {
/**
* Whether a request parameter ("format" by default) should be used to determine
* the requested media type.
*/
private boolean favorParameter;
/**
* Query parameter name to use when "favor-parameter" is enabled.
*/
private @Nullable String parameterName;
/**
* Map file extensions to media types for content negotiation. For instance, yml
* to text/yaml.
*/
private Map<String, MediaType> mediaTypes = new LinkedHashMap<>();
/**
* List of default content types to be used when no specific content type is
* requested.
*/
private List<MediaType> defaultContentTypes = new ArrayList<>();
public boolean isFavorParameter() {
return this.favorParameter;
}
public void setFavorParameter(boolean favorParameter) {
this.favorParameter = favorParameter;
}
public @Nullable String getParameterName() {
return this.parameterName;
}
public void setParameterName(@Nullable String parameterName) {
this.parameterName = parameterName;
}
public Map<String, MediaType> getMediaTypes() {
return this.mediaTypes;
}
public void setMediaTypes(Map<String, MediaType> mediaTypes) {
this.mediaTypes = mediaTypes;
}
public List<MediaType> getDefaultContentTypes() {
return this.defaultContentTypes;
}
public void setDefaultContentTypes(List<MediaType> defaultContentTypes) {
this.defaultContentTypes = defaultContentTypes;
}
}
public static
|
Contentnegotiation
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/service/scheduler/TestSchedulerService.java
|
{
"start": 1372,
"end": 1973
}
|
class ____ extends HTestCase {
@Test
@TestDir
public void service() throws Exception {
String dir = TestDirHelper.getTestDir().getAbsolutePath();
Configuration conf = new Configuration(false);
conf.set("server.services", StringUtils.join(",", Arrays.asList(InstrumentationService.class.getName(),
SchedulerService.class.getName())));
Server server = new Server("server", dir, dir, dir, dir, conf);
server.init();
assertNotNull(server.get(Scheduler.class));
server.destroy();
}
}
|
TestSchedulerService
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/web/context/request/async/AsyncRequestNotUsableTests.java
|
{
"start": 9868,
"end": 11758
}
|
class ____ {
@Test
void useWriter() throws IOException {
testUseWriter();
}
@Test
void useWriterInAsyncState() throws IOException {
asyncRequest.startAsync();
testUseWriter();
}
private void testUseWriter() throws IOException {
PrintWriter wrapped = getWrappedWriter();
wrapped.write('a');
wrapped.write(new char[0], 1, 2);
wrapped.write("abc", 1, 2);
wrapped.flush();
wrapped.close();
verify(writer).write('a');
verify(writer).write(new char[0], 1, 2);
verify(writer).write("abc", 1, 2);
verify(writer).flush();
verify(writer).close();
}
@Test
void writerNotUsableAfterCompletion() throws IOException {
asyncRequest.startAsync();
PrintWriter wrapped = getWrappedWriter();
asyncRequest.onComplete(new AsyncEvent(new MockAsyncContext(request, response)));
char[] chars = new char[0];
wrapped.write('a');
wrapped.write(chars, 1, 2);
wrapped.flush();
wrapped.close();
verifyNoInteractions(writer);
}
@Test
void lockingNotUsed() throws IOException {
AtomicInteger count = new AtomicInteger(-1);
doAnswer((Answer<Void>) invocation -> {
count.set(asyncRequest.stateLock().getHoldCount());
return null;
}).when(writer).write('a');
// Use Writer in NEW state (no async handling) without locking
PrintWriter wrapped = getWrappedWriter();
wrapped.write('a');
assertThat(count.get()).isEqualTo(0);
}
@Test
void lockingUsedInAsyncState() throws IOException {
AtomicInteger count = new AtomicInteger(-1);
doAnswer((Answer<Void>) invocation -> {
count.set(asyncRequest.stateLock().getHoldCount());
return null;
}).when(writer).write('a');
// Use Writer in ASYNC state with locking
asyncRequest.startAsync();
PrintWriter wrapped = getWrappedWriter();
wrapped.write('a');
assertThat(count.get()).isEqualTo(1);
}
}
}
|
WriterTests
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/offsettime/OffsetTimeAssert_isBetween_with_String_parameters_Test.java
|
{
"start": 982,
"end": 2158
}
|
class ____
extends org.assertj.core.api.OffsetTimeAssertBaseTest {
private OffsetTime before = now.minusSeconds(1);
private OffsetTime after = now.plusSeconds(1);
@Override
protected OffsetTimeAssert invoke_api_method() {
return assertions.isBetween(before.toString(), after.toString());
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), before, after, true, true);
}
@Test
void should_throw_a_TimeParseException_if_start_String_parameter_cant_be_converted() {
// GIVEN
String abc = "abc";
// WHEN
Throwable thrown = catchThrowable(() -> assertions.isBetween(abc, after.toString()));
// THEN
assertThat(thrown).isInstanceOf(DateTimeParseException.class);
}
@Test
void should_throw_a_TimeParseException_if_end_String_parameter_cant_be_converted() {
// GIVEN
String abc = "abc";
// WHEN
Throwable thrown = catchThrowable(() -> assertions.isBetween(before.toString(), abc));
// THEN
assertThat(thrown).isInstanceOf(DateTimeParseException.class);
}
}
|
OffsetTimeAssert_isBetween_with_String_parameters_Test
|
java
|
quarkusio__quarkus
|
integration-tests/main/src/main/java/io/quarkus/it/rest/ResourceC.java
|
{
"start": 166,
"end": 371
}
|
class ____ won't be registered by this, only target will be registered without registering nested classes
*/
@RegisterForReflection(targets = ResourceD.StaticClassOfD.class, ignoreNested = true)
public
|
itself
|
java
|
google__guava
|
android/guava-testlib/src/com/google/common/collect/testing/testers/CollectionAddTester.java
|
{
"start": 2297,
"end": 6094
}
|
class ____<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAdd_supportedNotPresent() {
assertTrue("add(notPresent) should return true", collection.add(e3()));
expectAdded(e3());
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAdd_unsupportedNotPresent() {
assertThrows(UnsupportedOperationException.class, () -> collection.add(e3()));
expectUnchanged();
expectMissing(e3());
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_unsupportedPresent() {
try {
assertFalse("add(present) should return false or throw", collection.add(e0()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(
value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testAdd_nullSupported() {
assertTrue("add(null) should return true", collection.add(null));
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES)
public void testAdd_nullUnsupported() {
assertThrows(NullPointerException.class, () -> collection.add(null));
expectUnchanged();
expectNullMissingWhenNullUnsupported("Should not contain null after unsupported add(null)");
}
@CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddConcurrentWithIteration() {
assertThrows(
ConcurrentModificationException.class,
() -> {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.add(e3()));
iterator.next();
});
}
/**
* Returns the {@link Method} instance for {@link #testAdd_nullSupported()} so that tests of
* {@link java.util.Collections#checkedCollection(java.util.Collection, Class)} can suppress it
* with {@code FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="https://bugs.openjdk.org/browse/JDK-6409434">JDK-6409434</a> is fixed. It's unclear
* whether nulls were to be permitted or forbidden, but presumably the eventual fix will be to
* permit them, as it seems more likely that code would depend on that behavior than on the other.
* Thus, we say the bug is in add(), which fails to support null.
*/
@J2ktIncompatible
@GwtIncompatible // reflection
public static Method getAddNullSupportedMethod() {
return getMethod(CollectionAddTester.class, "testAdd_nullSupported");
}
/**
* Returns the {@link Method} instance for {@link #testAdd_nullSupported()} so that tests of
* {@link java.util.TreeSet} can suppress it with {@code
* FeatureSpecificTestSuiteBuilder.suppressing()} until <a
* href="https://bugs.openjdk.org/browse/JDK-5045147">JDK-5045147</a> is fixed.
*/
@J2ktIncompatible
@GwtIncompatible // reflection
public static Method getAddNullUnsupportedMethod() {
return getMethod(CollectionAddTester.class, "testAdd_nullUnsupported");
}
/**
* Returns the {@link Method} instance for {@link #testAdd_unsupportedNotPresent()} so that tests
* can suppress it with {@code FeatureSpecificTestSuiteBuilder.suppressing()} while we figure out
* what to do with <a
* href="https://github.com/openjdk/jdk/blob/c25c4896ad9ef031e3cddec493aef66ff87c48a7/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java#L4830">{@code
* ConcurrentHashMap} support for {@code entrySet().add()}</a>.
*/
@J2ktIncompatible
@GwtIncompatible // reflection
public static Method getAddUnsupportedNotPresentMethod() {
return getMethod(CollectionAddTester.class, "testAdd_unsupportedNotPresent");
}
}
|
CollectionAddTester
|
java
|
apache__kafka
|
storage/src/main/java/org/apache/kafka/server/log/remote/storage/RemoteLogManagerConfig.java
|
{
"start": 4414,
"end": 4648
}
|
class ____ string.";
public static final String REMOTE_LOG_METADATA_MANAGER_CLASS_NAME_PROP = "remote.log.metadata.manager.class.name";
public static final String REMOTE_LOG_METADATA_MANAGER_CLASS_NAME_DOC = "Fully qualified
|
path
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/JobMasterTest.java
|
{
"start": 58462,
"end": 59208
}
|
class ____
implements InputSplitSource<TestingInputSplit> {
private static final long serialVersionUID = -2344684048759139086L;
private final List<TestingInputSplit> inputSplits;
private TestingInputSplitSource(List<TestingInputSplit> inputSplits) {
this.inputSplits = inputSplits;
}
@Override
public TestingInputSplit[] createInputSplits(int minNumSplits) {
return inputSplits.toArray(EMPTY_TESTING_INPUT_SPLITS);
}
@Override
public InputSplitAssigner getInputSplitAssigner(TestingInputSplit[] inputSplits) {
return new DefaultInputSplitAssigner(inputSplits);
}
}
private static final
|
TestingInputSplitSource
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitchTest.java
|
{
"start": 2850,
"end": 3442
}
|
enum ____ {
ONE,
TWO,
THREE
}
void m(Case c) {
switch (c) {
case ONE:
case TWO:
System.err.println("found it!");
break;
default:
break;
}
}
}
""")
.doTest();
}
@Test
public void nonExhaustive_withCombinedDefault() {
compilationHelper
.addSourceLines(
"Test.java",
"""
|
Case
|
java
|
apache__camel
|
core/camel-main/src/test/java/org/apache/camel/main/MainTemplatedRouteGroupTest.java
|
{
"start": 1017,
"end": 2694
}
|
class ____ {
@Test
void testMain() {
Main main = new Main();
main.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
routeTemplate("myTemplate")
.templateParameter("foo")
.templateParameter("bar")
.from("direct:{{foo}}")
.choice()
.when(header("foo"))
.log("${body}").id("myLog")
.otherwise()
.to("mock:{{bar}}").id("end");
templatedRoute("myTemplate")
.routeId("my-route")
.group("cheese")
.parameter("foo", "fooVal")
.parameter("bar", "barVal");
templatedRoute("myTemplate")
.routeId("my-route2")
.group("cheese")
.parameter("foo", "fooVal2")
.parameter("bar", "barVal2");
templatedRoute("myTemplate")
.routeId("my-route3")
.group("cake")
.parameter("foo", "fooVal3")
.parameter("bar", "barVal3");
}
});
main.start();
CamelContext context = main.getCamelContext();
assertEquals(3, context.getRoutes().size());
assertEquals(2, context.getRoutesByGroup("cheese").size());
assertEquals(1, context.getRoutesByGroup("cake").size());
main.stop();
}
}
|
MainTemplatedRouteGroupTest
|
java
|
apache__camel
|
core/camel-core-reifier/src/main/java/org/apache/camel/reifier/language/TokenizerExpressionReifier.java
|
{
"start": 1014,
"end": 2334
}
|
class ____ extends SingleInputTypedExpressionReifier<TokenizerExpression> {
public TokenizerExpressionReifier(CamelContext camelContext, ExpressionDefinition definition) {
super(camelContext, definition);
}
protected Object[] createProperties() {
Object[] properties = new Object[11];
properties[0] = asResultType();
properties[1] = parseString(definition.getSource());
// special for new line tokens, if defined from XML then its 2
// characters, so we replace that back to a single char
String token = definition.getToken();
if (token.startsWith("\\n")) {
token = '\n' + token.substring(2);
}
properties[2] = parseString(token);
properties[3] = parseString(definition.getEndToken());
properties[4] = parseString(definition.getInheritNamespaceTagName());
properties[5] = parseString(definition.getGroupDelimiter());
properties[6] = parseBoolean(definition.getRegex());
properties[7] = parseBoolean(definition.getXml());
properties[8] = parseBoolean(definition.getIncludeTokens());
properties[9] = parseString(definition.getGroup());
properties[10] = parseBoolean(definition.getSkipFirst());
return properties;
}
}
|
TokenizerExpressionReifier
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/DerivDoubleAggregatorFunctionSupplier.java
|
{
"start": 650,
"end": 1615
}
|
class ____ implements AggregatorFunctionSupplier {
public DerivDoubleAggregatorFunctionSupplier() {
}
@Override
public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() {
return DerivDoubleAggregatorFunction.intermediateStateDesc();
}
@Override
public List<IntermediateStateDesc> groupingIntermediateStateDesc() {
return DerivDoubleGroupingAggregatorFunction.intermediateStateDesc();
}
@Override
public DerivDoubleAggregatorFunction aggregator(DriverContext driverContext,
List<Integer> channels) {
return DerivDoubleAggregatorFunction.create(driverContext, channels);
}
@Override
public DerivDoubleGroupingAggregatorFunction groupingAggregator(DriverContext driverContext,
List<Integer> channels) {
return DerivDoubleGroupingAggregatorFunction.create(channels, driverContext);
}
@Override
public String describe() {
return "deriv of doubles";
}
}
|
DerivDoubleAggregatorFunctionSupplier
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/LowerCaseTokenFilterFactory.java
|
{
"start": 1363,
"end": 2335
}
|
class ____ extends AbstractTokenFilterFactory implements NormalizingTokenFilterFactory {
private final String lang;
LowerCaseTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) {
super(name);
this.lang = settings.get("language", null);
}
@Override
public TokenStream create(TokenStream tokenStream) {
if (lang == null) {
return new LowerCaseFilter(tokenStream);
} else if (lang.equalsIgnoreCase("greek")) {
return new GreekLowerCaseFilter(tokenStream);
} else if (lang.equalsIgnoreCase("irish")) {
return new IrishLowerCaseFilter(tokenStream);
} else if (lang.equalsIgnoreCase("turkish")) {
return new TurkishLowerCaseFilter(tokenStream);
} else {
throw new IllegalArgumentException("language [" + lang + "] not support for lower case");
}
}
}
|
LowerCaseTokenFilterFactory
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2AuthorizationCodeGrantTests.java
|
{
"start": 73146,
"end": 73780
}
|
class ____
extends AuthorizationServerConfiguration {
// @formatter:off
@Bean
SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2AuthorizationServer((authorizationServer) ->
authorizationServer
.pushedAuthorizationRequestEndpoint(Customizer.withDefaults())
)
.authorizeHttpRequests((authorize) ->
authorize.anyRequest().authenticated()
);
return http.build();
}
// @formatter:on
}
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
static
|
AuthorizationServerConfigurationWithPushedAuthorizationRequests
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java
|
{
"start": 16330,
"end": 16687
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout((logout) -> logout.defaultLogoutSuccessHandlerFor(null, mock(RequestMatcher.class))
);
return http.build();
// @formatter:on
}
}
@Configuration
@EnableWebSecurity
static
|
NullLogoutSuccessHandlerInLambdaConfig
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/stream/StreamMultiReadArgs.java
|
{
"start": 888,
"end": 5685
}
|
interface ____ {
/**
* Defines stream data size limit.
*
* @param count stream data size limit
* @return arguments object
*/
StreamMultiReadArgs count(int count);
/**
* Defines time interval to wait for stream data availability.
* <code>0</code> is used to wait infinitely.
*
* @param timeout timeout duration
* @return arguments object
*/
StreamMultiReadArgs timeout(Duration timeout);
/**
* Defines last stream ids received from all Streams
* including current one.
* <p>
* Read stream data from all defined streams
* with ids greater than defined ids.
*
* @param id1 last stream id of current stream
* @param stream2 name of 2nd stream
* @param id2 last stream id of 2nd stream
* @return arguments object
*/
static StreamMultiReadArgs greaterThan(StreamMessageId id1,
String stream2, StreamMessageId id2) {
return greaterThan(id1, Collections.singletonMap(stream2, id2));
}
/**
* Defines last stream ids received from all Streams
* including current one.
* <p>
* Read stream data from all defined streams
* with ids greater than defined ids.
*
* @param id1 last stream id of current stream
* @param stream2 name of 2nd stream
* @param id2 last stream id of 2nd stream
* @param stream3 name of 3rd stream
* @param id3 last stream id of 3rd stream
* @return arguments object
*/
static StreamMultiReadArgs greaterThan(StreamMessageId id1,
String stream2, StreamMessageId id2,
String stream3, StreamMessageId id3) {
Map<String, StreamMessageId> map = new HashMap<>();
map.put(stream2, id2);
map.put(stream3, id3);
return greaterThan(id1, map);
}
/**
* Defines last stream ids received from all Streams
* including current one.
* <p>
* Read stream data from all defined streams
* with ids greater than defined ids.
*
* @param id1 last stream id of current stream
* @param stream2 name of 2nd stream
* @param id2 last stream id of 2nd stream
* @param stream3 name of 3rd stream
* @param id3 last stream id of 3rd stream
* @param stream4 name of 4th stream
* @param id4 last stream id of 4th stream
* @return arguments object
*/
static StreamMultiReadArgs greaterThan(StreamMessageId id1,
String stream2, StreamMessageId id2,
String stream3, StreamMessageId id3,
String stream4, StreamMessageId id4) {
Map<String, StreamMessageId> map = new HashMap<>();
map.put(stream2, id2);
map.put(stream3, id3);
map.put(stream4, id4);
return greaterThan(id1, map);
}
/**
* Defines last stream ids received from all Streams
* including current one.
* <p>
* Read stream data from all defined streams
* with ids greater than defined ids.
*
* @param id1 last stream id of current stream
* @param stream2 name of 2nd stream
* @param id2 last stream id of 2nd stream
* @param stream3 name of 3rd stream
* @param id3 last stream id of 3rd stream
* @param stream4 name of 4th stream
* @param id4 last stream id of 4th stream
* @param stream5 name of 4th stream
* @param id5 last stream id of 4th stream
* @return arguments object
*/
static StreamMultiReadArgs greaterThan(StreamMessageId id1,
String stream2, StreamMessageId id2,
String stream3, StreamMessageId id3,
String stream4, StreamMessageId id4,
String stream5, StreamMessageId id5) {
Map<String, StreamMessageId> map = new HashMap<>();
map.put(stream2, id2);
map.put(stream3, id3);
map.put(stream4, id4);
map.put(stream5, id5);
return greaterThan(id1, map);
}
/**
* Defines last stream ids received from all Streams
* including current one.
* <p>
* Read stream data from all defined streams
* with ids greater than defined ids.
*
* @param id1 last stream id of current stream
* @param offsets last stream id mapped by stream name
* @return arguments object
*/
static StreamMultiReadArgs greaterThan(StreamMessageId id1, Map<String, StreamMessageId> offsets) {
return new StreamMultiReadParams(id1, offsets);
}
}
|
StreamMultiReadArgs
|
java
|
apache__kafka
|
streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
|
{
"start": 25238,
"end": 25816
}
|
class ____ implements the <code>org.apache.kafka.streams.KafkaClientSupplier</code> interface.";
/**
* {@code default.deserialization.exception.handler}
* @deprecated Since 4.0. Use {@link #DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG} instead.
*/
@SuppressWarnings("WeakerAccess")
@Deprecated
public static final String DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG = "default.deserialization.exception.handler";
@Deprecated
public static final String DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_DOC = "Exception handling
|
that
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/EnvironmentInfoTest.java
|
{
"start": 1076,
"end": 1403
}
|
class ____ extends RestResponseMarshallingTestBase<EnvironmentInfo> {
@Override
protected Class<EnvironmentInfo> getTestResponseClass() {
return EnvironmentInfo.class;
}
@Override
protected EnvironmentInfo getTestResponseInstance() {
return EnvironmentInfo.create();
}
}
|
EnvironmentInfoTest
|
java
|
apache__kafka
|
server-common/src/main/java/org/apache/kafka/server/util/json/DecodeJson.java
|
{
"start": 1588,
"end": 1937
}
|
class ____ implements DecodeJson<Boolean> {
@Override
public Boolean decode(JsonNode node) throws JsonMappingException {
if (node.isBoolean()) {
return node.booleanValue();
}
throw throwJsonMappingException(Boolean.class.getSimpleName(), node);
}
}
final
|
DecodeBoolean
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/annotation/AnnotationCustomizableTypeExcludeFilter.java
|
{
"start": 1405,
"end": 1553
}
|
class ____ a {@link TypeExcludeFilter} that can be customized using an
* annotation.
*
* @author Phillip Webb
* @since 4.0.0
*/
public abstract
|
for
|
java
|
apache__camel
|
components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusConfiguration.java
|
{
"start": 1530,
"end": 14189
}
|
class ____ implements Cloneable, HeaderFilterStrategyAware {
@UriPath
private String topicOrQueueName;
@UriParam(label = "common", defaultValue = "queue")
@Metadata(required = true)
private ServiceBusType serviceBusType = ServiceBusType.queue;
@UriParam(label = "security", secret = true)
private String connectionString;
@UriParam(label = "security")
private String fullyQualifiedNamespace;
@Metadata(autowired = true)
@UriParam(label = "security", secret = true)
private TokenCredential tokenCredential;
@UriParam(label = "common")
private ClientOptions clientOptions;
@UriParam(label = "common")
private ProxyOptions proxyOptions;
@UriParam(label = "common")
private AmqpRetryOptions amqpRetryOptions;
@UriParam(label = "common", defaultValue = "AMQP")
private AmqpTransportType amqpTransportType = AmqpTransportType.AMQP;
@UriParam(label = "common",
description = "To use a custom HeaderFilterStrategy to filter Service Bus application properties to and from Camel message headers.")
private HeaderFilterStrategy headerFilterStrategy = new ServiceBusHeaderFilterStrategy();
@UriParam(label = "consumer")
@Metadata(autowired = true)
private ServiceBusProcessorClient processorClient;
@UriParam(label = "consumer")
private String subscriptionName;
@UriParam(label = "consumer")
private boolean enableDeadLettering;
@UriParam(label = "consumer", defaultValue = "PEEK_LOCK")
private ServiceBusReceiveMode serviceBusReceiveMode = ServiceBusReceiveMode.PEEK_LOCK;
@UriParam(label = "consumer", defaultValue = "300000", javaType = "java.time.Duration")
private long maxAutoLockRenewDuration = 300000L;
@UriParam(label = "consumer")
private int prefetchCount;
@UriParam(label = "consumer")
private SubQueue subQueue;
@UriParam(label = "consumer", defaultValue = "1")
private int maxConcurrentCalls = 1;
@UriParam(label = "producer", defaultValue = "sendMessages")
private ServiceBusProducerOperationDefinition producerOperation = ServiceBusProducerOperationDefinition.sendMessages;
@UriParam(label = "producer")
@Metadata(autowired = true)
private ServiceBusSenderClient senderClient;
@UriParam(label = "producer")
private ServiceBusTransactionContext serviceBusTransactionContext;
@UriParam(label = "producer")
private OffsetDateTime scheduledEnqueueTime;
@UriParam(label = "producer")
private boolean binary;
@UriParam(label = "security", enums = "AZURE_IDENTITY,CONNECTION_STRING,TOKEN_CREDENTIAL",
defaultValue = "CONNECTION_STRING")
private CredentialType credentialType;
// New fields for session support
@UriParam(label = "consumer", defaultValue = "false", description = "Enable session support")
private boolean sessionEnabled;
@UriParam(label = "producer", description = "Session ID for session-enabled queues or topics.")
private String sessionId;
/**
* Flag to enable sessions. Default is false. Used to create processor client for message consumer
*/
public boolean isSessionEnabled() {
return sessionEnabled;
}
public void setSessionEnabled(boolean sessionEnabled) {
this.sessionEnabled = sessionEnabled;
}
/**
* SessionId for the message. To set this field, sessionEnabled should be set to true.
*/
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
/**
* Selected topic name or the queue name, that is depending on serviceBusType config. For example if
* serviceBusType=queue, then this will be the queue name and if serviceBusType=topic, this will be the topic name.
*/
public String getTopicOrQueueName() {
return topicOrQueueName;
}
public void setTopicOrQueueName(String topicOrQueueName) {
this.topicOrQueueName = topicOrQueueName;
}
/**
* The service bus type of connection to execute. Queue is for typical queue option and topic for subscription based
* model.
*/
public ServiceBusType getServiceBusType() {
return serviceBusType;
}
public void setServiceBusType(ServiceBusType serviceBusType) {
this.serviceBusType = serviceBusType;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*/
public String getConnectionString() {
return connectionString;
}
public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}
/**
* Sets the name of the subscription in the topic to listen to. topicOrQueueName and serviceBusType=topic must also
* be set. This property is required if serviceBusType=topic and the consumer is in use.
*/
public String getSubscriptionName() {
return subscriptionName;
}
public void setSubscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
}
/**
* Sets the ClientOptions to be sent from the client built from this builder, enabling customization of certain
* properties, as well as support the addition of custom header information.
*/
public ClientOptions getClientOptions() {
return clientOptions;
}
public void setClientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
}
/**
* Sets the proxy configuration to use for ServiceBusSenderClient. When a proxy is configured, AMQP_WEB_SOCKETS must
* be used for the transport type.
*/
public ProxyOptions getProxyOptions() {
return proxyOptions;
}
public void setProxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*/
public AmqpRetryOptions getAmqpRetryOptions() {
return amqpRetryOptions;
}
public void setAmqpRetryOptions(AmqpRetryOptions amqpRetryOptions) {
this.amqpRetryOptions = amqpRetryOptions;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is AMQP.
*/
public AmqpTransportType getAmqpTransportType() {
return amqpTransportType;
}
public void setAmqpTransportType(AmqpTransportType amqpTransportType) {
this.amqpTransportType = amqpTransportType;
}
/**
* To use a custom HeaderFilterStrategy to filter headers (application properties) to and from the Camel message.
*/
public HeaderFilterStrategy getHeaderFilterStrategy() {
return headerFilterStrategy;
}
public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) {
this.headerFilterStrategy = headerFilterStrategy;
}
/**
* Sets the processorClient in order to consume messages by the consumer
*/
public ServiceBusProcessorClient getProcessorClient() {
return processorClient;
}
public void setProcessorClient(ServiceBusProcessorClient processorClient) {
this.processorClient = processorClient;
}
/**
* Enable application level deadlettering to the subscription deadletter subqueue if deadletter related headers are
* set.
*/
public boolean isEnableDeadLettering() {
return enableDeadLettering;
}
public void setEnableDeadLettering(boolean enableDeadLettering) {
this.enableDeadLettering = enableDeadLettering;
}
/**
* Sets the receive mode for the receiver.
*/
public ServiceBusReceiveMode getServiceBusReceiveMode() {
return serviceBusReceiveMode;
}
public void setServiceBusReceiveMode(ServiceBusReceiveMode serviceBusReceiveMode) {
this.serviceBusReceiveMode = serviceBusReceiveMode;
}
/**
* Sets the amount of time (millis) to continue auto-renewing the lock. Setting ZERO disables auto-renewal. For
* ServiceBus receive mode (RECEIVE_AND_DELETE RECEIVE_AND_DELETE), auto-renewal is disabled.
*/
public long getMaxAutoLockRenewDuration() {
return maxAutoLockRenewDuration;
}
public void setMaxAutoLockRenewDuration(long maxAutoLockRenewDuration) {
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
}
/**
* Sets the prefetch count of the receiver. For both PEEK_LOCK PEEK_LOCK and RECEIVE_AND_DELETE RECEIVE_AND_DELETE
* receive modes the default value is 1.
* <p>
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and
* before the application asks for one using receive message. Setting a non-zero value will prefetch that number of
* messages. Setting the value to zero turns prefetch off.
*/
public int getPrefetchCount() {
return prefetchCount;
}
public void setPrefetchCount(int prefetchCount) {
this.prefetchCount = prefetchCount;
}
/**
* Sets the type of the SubQueue to connect to.
*/
public SubQueue getSubQueue() {
return subQueue;
}
public void setSubQueue(SubQueue subQueue) {
this.subQueue = subQueue;
}
/**
* Sets maximum number of concurrent calls
*/
public int getMaxConcurrentCalls() {
return maxConcurrentCalls;
}
public void setMaxConcurrentCalls(int maxConcurrentCalls) {
this.maxConcurrentCalls = maxConcurrentCalls;
}
/**
* Sets senderClient to be used in the producer.
*/
public ServiceBusSenderClient getSenderClient() {
return senderClient;
}
public void setSenderClient(ServiceBusSenderClient senderClient) {
this.senderClient = senderClient;
}
/**
* Fully Qualified Namespace of the service bus
*/
public String getFullyQualifiedNamespace() {
return fullyQualifiedNamespace;
}
public void setFullyQualifiedNamespace(String fullyQualifiedNamespace) {
this.fullyQualifiedNamespace = fullyQualifiedNamespace;
}
/**
* A TokenCredential for Azure AD authentication.
*/
public TokenCredential getTokenCredential() {
return tokenCredential;
}
public void setTokenCredential(TokenCredential tokenCredential) {
this.tokenCredential = tokenCredential;
}
/**
* Sets the desired operation to be used in the producer
*/
public ServiceBusProducerOperationDefinition getProducerOperation() {
return producerOperation;
}
public void setProducerOperation(ServiceBusProducerOperationDefinition producerOperation) {
this.producerOperation = producerOperation;
}
/**
* Represents transaction in service. This object just contains transaction id.
*/
public ServiceBusTransactionContext getServiceBusTransactionContext() {
return serviceBusTransactionContext;
}
public void setServiceBusTransactionContext(ServiceBusTransactionContext serviceBusTransactionContext) {
this.serviceBusTransactionContext = serviceBusTransactionContext;
}
/**
* Sets OffsetDateTime at which the message should appear in the Service Bus queue or topic.
*/
public OffsetDateTime getScheduledEnqueueTime() {
return scheduledEnqueueTime;
}
public void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
this.scheduledEnqueueTime = scheduledEnqueueTime;
}
/**
* Set binary mode. If true, message body will be sent as byte[]. By default, it is false.
*/
public boolean isBinary() {
return binary;
}
public void setBinary(boolean binary) {
this.binary = binary;
}
public CredentialType getCredentialType() {
return credentialType;
}
/**
* Determines the credential strategy to adopt
*/
public void setCredentialType(CredentialType credentialType) {
this.credentialType = credentialType;
}
// *************************************************
//
// *************************************************
public org.apache.camel.component.azure.servicebus.ServiceBusConfiguration copy() {
try {
return (org.apache.camel.component.azure.servicebus.ServiceBusConfiguration) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeCamelException(e);
}
}
}
|
ServiceBusConfiguration
|
java
|
apache__camel
|
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/support/resume/ResumeRebalanceListener.java
|
{
"start": 1302,
"end": 2832
}
|
class ____ implements ConsumerRebalanceListener {
private static final Logger LOG = LoggerFactory.getLogger(ResumeRebalanceListener.class);
private final String threadId;
private final KafkaConfiguration configuration;
private final CommitManager commitManager;
private final KafkaResumeAdapter resumeAdapter;
public ResumeRebalanceListener(String threadId, KafkaConfiguration configuration,
CommitManager commitManager, Consumer<?, ?> consumer, ResumeStrategy resumeStrategy) {
this.threadId = threadId;
this.configuration = configuration;
this.commitManager = commitManager;
resumeAdapter = resumeStrategy.getAdapter(KafkaResumeAdapter.class);
resumeAdapter.setConsumer(consumer);
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
for (TopicPartition partition : partitions) {
LOG.debug("onPartitionsRevoked: {} from {}", threadId, partition.topic());
// only commit offsets if the component has control
if (!configuration.getAutoCommitEnable()) {
commitManager.commit(partition);
}
}
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
if (LOG.isDebugEnabled()) {
partitions.forEach(p -> LOG.debug("onPartitionsAssigned: {} from {}", threadId, p.topic()));
}
resumeAdapter.resume();
}
}
|
ResumeRebalanceListener
|
java
|
apache__maven
|
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategyTest.java
|
{
"start": 21672,
"end": 23112
}
|
class ____ {
@Test
@DisplayName("should handle malformed POM gracefully")
void shouldHandleMalformedPOMGracefully() throws Exception {
String malformedPomXml = """
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test</artifactId>
<version>1.0.0</version>
<build>
<plugins>
<plugin>
<!-- Missing required elements -->
</plugin>
</plugins>
</build>
</project>
""";
Document document = Document.of(malformedPomXml);
Map<Path, Document> pomMap = Map.of(Paths.get("pom.xml"), document);
UpgradeContext context = createMockContext();
UpgradeResult result = strategy.doApply(context, pomMap);
// Strategy should handle malformed POMs gracefully
assertNotNull(result, "Result should not be null");
assertTrue(result.processedPoms().contains(Paths.get("pom.xml")), "POM should be marked as processed");
}
}
@Nested
@DisplayName("Strategy Description")
|
ErrorHandlingTests
|
java
|
quarkusio__quarkus
|
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/propagation/OpenTelemetryTextMapPropagatorCustomizerTest.java
|
{
"start": 3524,
"end": 4307
}
|
class ____ implements TextMapPropagatorCustomizer {
// just to understand this was actually called.
public static final Set<String> PROPAGATORS_USED = ConcurrentHashMap.newKeySet();
public static final Set<String> PROPAGATORS_DISCARDED = ConcurrentHashMap.newKeySet();
@Override
public TextMapPropagator customize(Context context) {
TextMapPropagator propagator = context.propagator();
if (propagator instanceof W3CBaggagePropagator) {
PROPAGATORS_DISCARDED.add(propagator.getClass().getName());
return TextMapPropagator.noop();
}
PROPAGATORS_USED.add(propagator.getClass().getName());
return propagator;
}
}
}
|
TestTextMapPropagatorCustomizer
|
java
|
apache__camel
|
components/camel-huawei/camel-huaweicloud-frs/src/generated/java/org/apache/camel/component/huaweicloud/frs/FaceRecognitionComponentConfigurer.java
|
{
"start": 742,
"end": 2353
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
FaceRecognitionComponent target = (FaceRecognitionComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
FaceRecognitionComponent target = (FaceRecognitionComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
default: return null;
}
}
}
|
FaceRecognitionComponentConfigurer
|
java
|
apache__flink
|
flink-formats/flink-json/src/test/java/org/apache/flink/formats/json/ogg/OggJsonSerDeSchemaTest.java
|
{
"start": 2449,
"end": 15851
}
|
class ____ {
private static final DataType PHYSICAL_DATA_TYPE =
ROW(
FIELD("id", INT().notNull()),
FIELD("name", STRING()),
FIELD("description", STRING()),
FIELD("weight", FLOAT()));
private static List<String> readLines(String resource) throws IOException {
final URL url = OggJsonSerDeSchemaTest.class.getClassLoader().getResource(resource);
assert url != null;
Path path = new File(url.getFile()).toPath();
return Files.readAllLines(path);
}
@Test
void testSerializationAndDeserialization() throws Exception {
testSerializationDeserialization("ogg-data.txt");
}
@Test
void testDeserializationWithMetadata() throws Exception {
testDeserializationWithMetadata("ogg-data.txt");
}
@Test
void testIgnoreParseErrors() throws Exception {
List<String> lines = readLines("ogg-data.txt");
OggJsonDeserializationSchema deserializationSchema =
new OggJsonDeserializationSchema(
PHYSICAL_DATA_TYPE,
Collections.emptyList(),
InternalTypeInfo.of(PHYSICAL_DATA_TYPE.getLogicalType()),
true,
TimestampFormat.ISO_8601);
open(deserializationSchema);
ThrowingExceptionCollector collector = new ThrowingExceptionCollector();
assertThatThrownBy(
() -> {
for (String line : lines) {
deserializationSchema.deserialize(
line.getBytes(StandardCharsets.UTF_8), collector);
}
})
.isInstanceOf(RuntimeException.class)
.satisfies(
anyCauseMatches(
RuntimeException.class,
"An error occurred while collecting data."));
}
@Test
void testTombstoneMessages() throws Exception {
OggJsonDeserializationSchema deserializationSchema =
new OggJsonDeserializationSchema(
PHYSICAL_DATA_TYPE,
Collections.emptyList(),
InternalTypeInfo.of(PHYSICAL_DATA_TYPE.getLogicalType()),
false,
TimestampFormat.ISO_8601);
open(deserializationSchema);
SimpleCollector collector = new SimpleCollector();
deserializationSchema.deserialize(null, collector);
deserializationSchema.deserialize(new byte[] {}, collector);
assertThat(collector.list).isEmpty();
}
public void testDeserializationWithMetadata(String resourceFile) throws Exception {
// we only read the first line for keeping the test simple
final String firstLine = readLines(resourceFile).get(0);
final List<ReadableMetadata> requestedMetadata = Arrays.asList(ReadableMetadata.values());
final DataType producedDataTypes =
DataTypeUtils.appendRowFields(
PHYSICAL_DATA_TYPE,
requestedMetadata.stream()
.map(m -> DataTypes.FIELD(m.key, m.dataType))
.collect(Collectors.toList()));
final OggJsonDeserializationSchema deserializationSchema =
new OggJsonDeserializationSchema(
PHYSICAL_DATA_TYPE,
requestedMetadata,
InternalTypeInfo.of(producedDataTypes.getLogicalType()),
false,
TimestampFormat.ISO_8601);
open(deserializationSchema);
final SimpleCollector collector = new SimpleCollector();
deserializationSchema.deserialize(firstLine.getBytes(StandardCharsets.UTF_8), collector);
assertThat(collector.list).hasSize(1);
assertThat(collector.list.get(0))
.satisfies(
row -> {
assertThat(row.getInt(0)).isEqualTo(101);
assertThat(row.getString(1).toString()).isEqualTo("scooter");
assertThat(row.getString(2).toString())
.isEqualTo("Small 2-wheel scooter");
assertThat(row.getFloat(3))
.isCloseTo(
3.140000104904175f, Percentage.withPercentage(1e-15));
assertThat(row.getString(4).toString()).isEqualTo("OGG.TBL_TEST");
assertThat(row.getArray(5).getString(0).toString()).isEqualTo("id");
assertThat(row.getTimestamp(6, 6).getMillisecond())
.isEqualTo(1589377175766L);
assertThat(row.getTimestamp(7, 6).getMillisecond())
.isEqualTo(1589384406000L);
});
}
private void testSerializationDeserialization(String resourceFile) throws Exception {
List<String> lines = readLines(resourceFile);
OggJsonDeserializationSchema deserializationSchema =
new OggJsonDeserializationSchema(
PHYSICAL_DATA_TYPE,
Collections.emptyList(),
InternalTypeInfo.of(PHYSICAL_DATA_TYPE.getLogicalType()),
false,
TimestampFormat.ISO_8601);
open(deserializationSchema);
SimpleCollector collector = new SimpleCollector();
for (String line : lines) {
deserializationSchema.deserialize(line.getBytes(StandardCharsets.UTF_8), collector);
}
// Ogg captures change data (`ogg-data.txt`) on the `product`
// table:
//
// CREATE TABLE product (
// id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
// name VARCHAR(255),
// description VARCHAR(512),
// weight FLOAT
// );
// ALTER TABLE product AUTO_INCREMENT = 101;
//
// INSERT INTO product
// VALUES (default,"scooter","Small 2-wheel scooter",3.14),
// (default,"car battery","12V car battery",8.1),
// (default,"12-pack drill bits","12-pack of drill bits with sizes ranging from #40
// to #3",0.8),
// (default,"hammer","12oz carpenter's hammer",0.75),
// (default,"hammer","14oz carpenter's hammer",0.875),
// (default,"hammer","16oz carpenter's hammer",1.0),
// (default,"rocks","box of assorted rocks",5.3),
// (default,"jacket","water resistent black wind breaker",0.1),
// (default,"spare tire","24 inch spare tire",22.2);
// UPDATE product SET description='18oz carpenter hammer' WHERE id=106;
// UPDATE product SET weight='5.1' WHERE id=107;
// INSERT INTO product VALUES (default,"jacket","water resistent white wind breaker",0.2);
// INSERT INTO product VALUES (default,"scooter","Big 2-wheel scooter ",5.18);
// UPDATE product SET description='new water resistent white wind breaker', weight='0.5'
// WHERE id=110;
// UPDATE product SET weight='5.17' WHERE id=111;
// DELETE FROM product WHERE id=111;
List<String> expected =
Arrays.asList(
"+I(101,scooter,Small 2-wheel scooter,3.14)",
"+I(102,car battery,12V car battery,8.1)",
"+I(103,12-pack drill bits,12-pack of drill bits with sizes ranging from #40 to #3,0.8)",
"+I(104,hammer,12oz carpenter's hammer,0.75)",
"+I(105,hammer,14oz carpenter's hammer,0.875)",
"+I(106,hammer,16oz carpenter's hammer,1.0)",
"+I(107,rocks,box of assorted rocks,5.3)",
"+I(108,jacket,water resistent black wind breaker,0.1)",
"+I(109,spare tire,24 inch spare tire,22.2)",
"-U(106,hammer,16oz carpenter's hammer,1.0)",
"+U(106,hammer,18oz carpenter hammer,1.0)",
"-U(107,rocks,box of assorted rocks,5.3)",
"+U(107,rocks,box of assorted rocks,5.1)",
"+I(110,jacket,water resistent white wind breaker,0.2)",
"+I(111,scooter,Big 2-wheel scooter ,5.18)",
"-U(110,jacket,water resistent white wind breaker,0.2)",
"+U(110,jacket,new water resistent white wind breaker,0.5)",
"-U(111,scooter,Big 2-wheel scooter ,5.18)",
"+U(111,scooter,Big 2-wheel scooter ,5.17)",
"-D(111,scooter,Big 2-wheel scooter ,5.17)");
List<String> actual =
collector.list.stream().map(Object::toString).collect(Collectors.toList());
assertThat(expected).containsExactlyElementsOf(actual);
OggJsonSerializationSchema serializationSchema =
new OggJsonSerializationSchema(
(RowType) PHYSICAL_DATA_TYPE.getLogicalType(),
TimestampFormat.SQL,
JsonFormatOptions.MapNullKeyMode.LITERAL,
"null",
true,
false);
open(serializationSchema);
actual = new ArrayList<>();
for (RowData rowData : collector.list) {
actual.add(new String(serializationSchema.serialize(rowData), StandardCharsets.UTF_8));
}
expected =
Arrays.asList(
"{\"before\":null,\"after\":{\"id\":101,\"name\":\"scooter\",\"description\":\"Small 2-wheel scooter\",\"weight\":3.14},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":102,\"name\":\"car battery\",\"description\":\"12V car battery\",\"weight\":8.1},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":103,\"name\":\"12-pack drill bits\",\"description\":\"12-pack of drill bits with sizes ranging from #40 to #3\",\"weight\":0.8},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":104,\"name\":\"hammer\",\"description\":\"12oz carpenter's hammer\",\"weight\":0.75},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":105,\"name\":\"hammer\",\"description\":\"14oz carpenter's hammer\",\"weight\":0.875},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":106,\"name\":\"hammer\",\"description\":\"16oz carpenter's hammer\",\"weight\":1.0},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":107,\"name\":\"rocks\",\"description\":\"box of assorted rocks\",\"weight\":5.3},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":108,\"name\":\"jacket\",\"description\":\"water resistent black wind breaker\",\"weight\":0.1},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":109,\"name\":\"spare tire\",\"description\":\"24 inch spare tire\",\"weight\":22.2},\"op_type\":\"I\"}",
"{\"before\":{\"id\":106,\"name\":\"hammer\",\"description\":\"16oz carpenter's hammer\",\"weight\":1.0},\"after\":null,\"op_type\":\"D\"}",
"{\"before\":null,\"after\":{\"id\":106,\"name\":\"hammer\",\"description\":\"18oz carpenter hammer\",\"weight\":1.0},\"op_type\":\"I\"}",
"{\"before\":{\"id\":107,\"name\":\"rocks\",\"description\":\"box of assorted rocks\",\"weight\":5.3},\"after\":null,\"op_type\":\"D\"}",
"{\"before\":null,\"after\":{\"id\":107,\"name\":\"rocks\",\"description\":\"box of assorted rocks\",\"weight\":5.1},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":110,\"name\":\"jacket\",\"description\":\"water resistent white wind breaker\",\"weight\":0.2},\"op_type\":\"I\"}",
"{\"before\":null,\"after\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.18},\"op_type\":\"I\"}",
"{\"before\":{\"id\":110,\"name\":\"jacket\",\"description\":\"water resistent white wind breaker\",\"weight\":0.2},\"after\":null,\"op_type\":\"D\"}",
"{\"before\":null,\"after\":{\"id\":110,\"name\":\"jacket\",\"description\":\"new water resistent white wind breaker\",\"weight\":0.5},\"op_type\":\"I\"}",
"{\"before\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.18},\"after\":null,\"op_type\":\"D\"}",
"{\"before\":null,\"after\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.17},\"op_type\":\"I\"}",
"{\"before\":{\"id\":111,\"name\":\"scooter\",\"description\":\"Big 2-wheel scooter \",\"weight\":5.17},\"after\":null,\"op_type\":\"D\"}");
assertThat(expected).containsExactlyElementsOf(actual);
}
private static
|
OggJsonSerDeSchemaTest
|
java
|
apache__thrift
|
lib/java/src/main/java/org/apache/thrift/server/TNonblockingServer.java
|
{
"start": 1630,
"end": 1708
}
|
class ____ extends AbstractNonblockingServer {
public static
|
TNonblockingServer
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/streams/StreamFactoryRequirements.java
|
{
"start": 1290,
"end": 4001
}
|
class ____ {
/**
* Number of shared threads to included in the bounded pool.
*/
private final int sharedThreads;
/**
* How many threads per stream, ignoring vector IO requirements?
*/
private final int streamThreads;
/**
* VectoredIO behaviour.
*/
private final VectoredIOContext vectoredIOContext;
/**
* Set of requirement flags.
*/
private final EnumSet<Requirements> requirementFlags;
/**
* Create the thread options.
* @param sharedThreads Number of shared threads to included in the bounded pool.
* @param streamThreads How many threads per stream, ignoring vector IO requirements.
* @param vectoredIOContext vector IO settings -made immutable if not already done.
* @param requirements requirement flags of the factory and stream.
*/
public StreamFactoryRequirements(
final int sharedThreads,
final int streamThreads,
final VectoredIOContext vectoredIOContext,
final Requirements...requirements) {
this.sharedThreads = sharedThreads;
this.streamThreads = streamThreads;
this.vectoredIOContext = vectoredIOContext.build();
if (requirements.length == 0) {
this.requirementFlags = EnumSet.noneOf(Requirements.class);
} else {
this.requirementFlags = EnumSet.copyOf((Arrays.asList(requirements)));
}
}
/**
* Number of shared threads to included in the bounded pool.
* @return extra threads to be created in the FS thread pool.
*/
public int sharedThreads() {
return sharedThreads;
}
/**
* The maximum number of threads which can be used should by a single input stream.
* @return thread pool requirements.
*/
public int streamThreads() {
return streamThreads;
}
/**
* Should the future pool be created?
* @return true if the future pool is required.
*/
public boolean requiresFuturePool() {
return requires(Requirements.RequiresFuturePool);
}
/**
* The VectorIO requirements of streams.
* @return vector IO context.
*/
public VectoredIOContext vectoredIOContext() {
return vectoredIOContext;
}
/**
* Does this factory have this requirement?
* @param r requirement to probe for.
* @return true if this is a requirement.
*/
public boolean requires(Requirements r) {
return requirementFlags.contains(r);
}
@Override
public String toString() {
return "StreamFactoryRequirements{" +
"sharedThreads=" + sharedThreads +
", streamThreads=" + streamThreads +
", requirementFlags=" + requirementFlags +
", vectoredIOContext=" + vectoredIOContext +
'}';
}
/**
* Requirements a factory may have.
*/
public
|
StreamFactoryRequirements
|
java
|
apache__camel
|
components/camel-twitter/src/generated/java/org/apache/camel/component/twitter/search/TwitterSearchEndpointConfigurer.java
|
{
"start": 741,
"end": 15943
}
|
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
TwitterSearchEndpoint target = (TwitterSearchEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": target.getProperties().setAccessToken(property(camelContext, java.lang.String.class, value)); return true;
case "accesstokensecret":
case "accessTokenSecret": target.getProperties().setAccessTokenSecret(property(camelContext, java.lang.String.class, value)); return true;
case "backofferrorthreshold":
case "backoffErrorThreshold": target.setBackoffErrorThreshold(property(camelContext, int.class, value)); return true;
case "backoffidlethreshold":
case "backoffIdleThreshold": target.setBackoffIdleThreshold(property(camelContext, int.class, value)); return true;
case "backoffmultiplier":
case "backoffMultiplier": target.setBackoffMultiplier(property(camelContext, int.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "consumerkey":
case "consumerKey": target.getProperties().setConsumerKey(property(camelContext, java.lang.String.class, value)); return true;
case "consumersecret":
case "consumerSecret": target.getProperties().setConsumerSecret(property(camelContext, java.lang.String.class, value)); return true;
case "count": target.getProperties().setCount(property(camelContext, java.lang.Integer.class, value)); return true;
case "delay": target.setDelay(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "distancemetric":
case "distanceMetric": target.getProperties().setDistanceMetric(property(camelContext, java.lang.String.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "extendedmode":
case "extendedMode": target.getProperties().setExtendedMode(property(camelContext, boolean.class, value)); return true;
case "filterold":
case "filterOld": target.getProperties().setFilterOld(property(camelContext, boolean.class, value)); return true;
case "greedy": target.setGreedy(property(camelContext, boolean.class, value)); return true;
case "httpproxyhost":
case "httpProxyHost": target.getProperties().setHttpProxyHost(property(camelContext, java.lang.String.class, value)); return true;
case "httpproxypassword":
case "httpProxyPassword": target.getProperties().setHttpProxyPassword(property(camelContext, java.lang.String.class, value)); return true;
case "httpproxyport":
case "httpProxyPort": target.getProperties().setHttpProxyPort(property(camelContext, java.lang.Integer.class, value)); return true;
case "httpproxyuser":
case "httpProxyUser": target.getProperties().setHttpProxyUser(property(camelContext, java.lang.String.class, value)); return true;
case "initialdelay":
case "initialDelay": target.setInitialDelay(property(camelContext, long.class, value)); return true;
case "lang": target.getProperties().setLang(property(camelContext, java.lang.String.class, value)); return true;
case "latitude": target.getProperties().setLatitude(property(camelContext, java.lang.Double.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "locations": target.getProperties().setLocations(property(camelContext, java.lang.String.class, value)); return true;
case "longitude": target.getProperties().setLongitude(property(camelContext, java.lang.Double.class, value)); return true;
case "numberofpages":
case "numberOfPages": target.getProperties().setNumberOfPages(property(camelContext, java.lang.Integer.class, value)); return true;
case "pollstrategy":
case "pollStrategy": target.setPollStrategy(property(camelContext, org.apache.camel.spi.PollingConsumerPollStrategy.class, value)); return true;
case "radius": target.getProperties().setRadius(property(camelContext, java.lang.Double.class, value)); return true;
case "repeatcount":
case "repeatCount": target.setRepeatCount(property(camelContext, long.class, value)); return true;
case "runlogginglevel":
case "runLoggingLevel": target.setRunLoggingLevel(property(camelContext, org.apache.camel.LoggingLevel.class, value)); return true;
case "scheduledexecutorservice":
case "scheduledExecutorService": target.setScheduledExecutorService(property(camelContext, java.util.concurrent.ScheduledExecutorService.class, value)); return true;
case "scheduler": target.setScheduler(property(camelContext, java.lang.Object.class, value)); return true;
case "schedulerproperties":
case "schedulerProperties": target.setSchedulerProperties(property(camelContext, java.util.Map.class, value)); return true;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": target.setSendEmptyMessageWhenIdle(property(camelContext, boolean.class, value)); return true;
case "sinceid":
case "sinceId": target.getProperties().setSinceId(property(camelContext, long.class, value)); return true;
case "sortbyid":
case "sortById": target.getProperties().setSortById(property(camelContext, boolean.class, value)); return true;
case "startscheduler":
case "startScheduler": target.setStartScheduler(property(camelContext, boolean.class, value)); return true;
case "timeunit":
case "timeUnit": target.setTimeUnit(property(camelContext, java.util.concurrent.TimeUnit.class, value)); return true;
case "type": target.getProperties().setType(property(camelContext, org.apache.camel.component.twitter.data.EndpointType.class, value)); return true;
case "usefixeddelay":
case "useFixedDelay": target.setUseFixedDelay(property(camelContext, boolean.class, value)); return true;
case "userids":
case "userIds": target.getProperties().setUserIds(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return java.lang.String.class;
case "accesstokensecret":
case "accessTokenSecret": return java.lang.String.class;
case "backofferrorthreshold":
case "backoffErrorThreshold": return int.class;
case "backoffidlethreshold":
case "backoffIdleThreshold": return int.class;
case "backoffmultiplier":
case "backoffMultiplier": return int.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "consumerkey":
case "consumerKey": return java.lang.String.class;
case "consumersecret":
case "consumerSecret": return java.lang.String.class;
case "count": return java.lang.Integer.class;
case "delay": return long.class;
case "distancemetric":
case "distanceMetric": return java.lang.String.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "extendedmode":
case "extendedMode": return boolean.class;
case "filterold":
case "filterOld": return boolean.class;
case "greedy": return boolean.class;
case "httpproxyhost":
case "httpProxyHost": return java.lang.String.class;
case "httpproxypassword":
case "httpProxyPassword": return java.lang.String.class;
case "httpproxyport":
case "httpProxyPort": return java.lang.Integer.class;
case "httpproxyuser":
case "httpProxyUser": return java.lang.String.class;
case "initialdelay":
case "initialDelay": return long.class;
case "lang": return java.lang.String.class;
case "latitude": return java.lang.Double.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "locations": return java.lang.String.class;
case "longitude": return java.lang.Double.class;
case "numberofpages":
case "numberOfPages": return java.lang.Integer.class;
case "pollstrategy":
case "pollStrategy": return org.apache.camel.spi.PollingConsumerPollStrategy.class;
case "radius": return java.lang.Double.class;
case "repeatcount":
case "repeatCount": return long.class;
case "runlogginglevel":
case "runLoggingLevel": return org.apache.camel.LoggingLevel.class;
case "scheduledexecutorservice":
case "scheduledExecutorService": return java.util.concurrent.ScheduledExecutorService.class;
case "scheduler": return java.lang.Object.class;
case "schedulerproperties":
case "schedulerProperties": return java.util.Map.class;
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": return boolean.class;
case "sinceid":
case "sinceId": return long.class;
case "sortbyid":
case "sortById": return boolean.class;
case "startscheduler":
case "startScheduler": return boolean.class;
case "timeunit":
case "timeUnit": return java.util.concurrent.TimeUnit.class;
case "type": return org.apache.camel.component.twitter.data.EndpointType.class;
case "usefixeddelay":
case "useFixedDelay": return boolean.class;
case "userids":
case "userIds": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
TwitterSearchEndpoint target = (TwitterSearchEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "accesstoken":
case "accessToken": return target.getProperties().getAccessToken();
case "accesstokensecret":
case "accessTokenSecret": return target.getProperties().getAccessTokenSecret();
case "backofferrorthreshold":
case "backoffErrorThreshold": return target.getBackoffErrorThreshold();
case "backoffidlethreshold":
case "backoffIdleThreshold": return target.getBackoffIdleThreshold();
case "backoffmultiplier":
case "backoffMultiplier": return target.getBackoffMultiplier();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "consumerkey":
case "consumerKey": return target.getProperties().getConsumerKey();
case "consumersecret":
case "consumerSecret": return target.getProperties().getConsumerSecret();
case "count": return target.getProperties().getCount();
case "delay": return target.getDelay();
case "distancemetric":
case "distanceMetric": return target.getProperties().getDistanceMetric();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "extendedmode":
case "extendedMode": return target.getProperties().isExtendedMode();
case "filterold":
case "filterOld": return target.getProperties().isFilterOld();
case "greedy": return target.isGreedy();
case "httpproxyhost":
case "httpProxyHost": return target.getProperties().getHttpProxyHost();
case "httpproxypassword":
case "httpProxyPassword": return target.getProperties().getHttpProxyPassword();
case "httpproxyport":
case "httpProxyPort": return target.getProperties().getHttpProxyPort();
case "httpproxyuser":
case "httpProxyUser": return target.getProperties().getHttpProxyUser();
case "initialdelay":
case "initialDelay": return target.getInitialDelay();
case "lang": return target.getProperties().getLang();
case "latitude": return target.getProperties().getLatitude();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "locations": return target.getProperties().getLocations();
case "longitude": return target.getProperties().getLongitude();
case "numberofpages":
case "numberOfPages": return target.getProperties().getNumberOfPages();
case "pollstrategy":
case "pollStrategy": return target.getPollStrategy();
case "radius": return target.getProperties().getRadius();
case "repeatcount":
case "repeatCount": return target.getRepeatCount();
case "runlogginglevel":
case "runLoggingLevel": return target.getRunLoggingLevel();
case "scheduledexecutorservice":
case "scheduledExecutorService": return target.getScheduledExecutorService();
case "scheduler": return target.getScheduler();
case "schedulerproperties":
case "schedulerProperties": return target.getSchedulerProperties();
case "sendemptymessagewhenidle":
case "sendEmptyMessageWhenIdle": return target.isSendEmptyMessageWhenIdle();
case "sinceid":
case "sinceId": return target.getProperties().getSinceId();
case "sortbyid":
case "sortById": return target.getProperties().isSortById();
case "startscheduler":
case "startScheduler": return target.isStartScheduler();
case "timeunit":
case "timeUnit": return target.getTimeUnit();
case "type": return target.getProperties().getType();
case "usefixeddelay":
case "useFixedDelay": return target.isUseFixedDelay();
case "userids":
case "userIds": return target.getProperties().getUserIds();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "schedulerproperties":
case "schedulerProperties": return java.lang.Object.class;
default: return null;
}
}
}
|
TwitterSearchEndpointConfigurer
|
java
|
quarkusio__quarkus
|
extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayCreator.java
|
{
"start": 577,
"end": 6983
}
|
class ____ {
private static final String[] EMPTY_ARRAY = new String[0];
public static final Duration DEFAULT_CONNECT_RETRIES_INTERVAL = Duration.ofSeconds(120L);
private final FlywayDataSourceRuntimeConfig flywayRuntimeConfig;
private final FlywayDataSourceBuildTimeConfig flywayBuildTimeConfig;
private final List<FlywayConfigurationCustomizer> customizers;
private Collection<Callback> callbacks = Collections.emptyList();
// only used for tests
public FlywayCreator(FlywayDataSourceRuntimeConfig flywayRuntimeConfig,
FlywayDataSourceBuildTimeConfig flywayBuildTimeConfig) {
this.flywayRuntimeConfig = flywayRuntimeConfig;
this.flywayBuildTimeConfig = flywayBuildTimeConfig;
this.customizers = Collections.emptyList();
}
public FlywayCreator(FlywayDataSourceRuntimeConfig flywayRuntimeConfig,
FlywayDataSourceBuildTimeConfig flywayBuildTimeConfig,
List<FlywayConfigurationCustomizer> customizers) {
this.flywayRuntimeConfig = flywayRuntimeConfig;
this.flywayBuildTimeConfig = flywayBuildTimeConfig;
this.customizers = customizers;
}
public FlywayCreator withCallbacks(Collection<Callback> callbacks) {
this.callbacks = callbacks;
return this;
}
public Flyway createFlyway(DataSource dataSource) {
FluentConfiguration configure = Flyway.configure();
if (flywayRuntimeConfig.jdbcUrl().isPresent()) {
if (flywayRuntimeConfig.username().isPresent() && flywayRuntimeConfig.password().isPresent()) {
configure.dataSource(flywayRuntimeConfig.jdbcUrl().get(), flywayRuntimeConfig.username().get(),
flywayRuntimeConfig.password().get());
} else {
throw new ConfigurationException(
"Username and password must be defined when a JDBC URL is provided in the Flyway configuration");
}
} else {
if (flywayRuntimeConfig.username().isPresent() && flywayRuntimeConfig.password().isPresent()) {
AgroalDataSource agroalDataSource = (AgroalDataSource) dataSource;
String jdbcUrl = agroalDataSource.getConfiguration().connectionPoolConfiguration()
.connectionFactoryConfiguration().jdbcUrl();
configure.dataSource(jdbcUrl, flywayRuntimeConfig.username().get(),
flywayRuntimeConfig.password().get());
} else if (dataSource != null) {
configure.dataSource(dataSource);
}
}
if (flywayRuntimeConfig.initSql().isPresent()) {
configure.initSql(flywayRuntimeConfig.initSql().get());
}
if (flywayRuntimeConfig.connectRetries().isPresent()) {
configure.connectRetries(flywayRuntimeConfig.connectRetries().getAsInt());
}
configure.connectRetriesInterval(
(int) flywayRuntimeConfig.connectRetriesInterval().orElse(DEFAULT_CONNECT_RETRIES_INTERVAL).toSeconds());
if (flywayRuntimeConfig.defaultSchema().isPresent()) {
configure.defaultSchema(flywayRuntimeConfig.defaultSchema().get());
}
if (flywayRuntimeConfig.schemas().isPresent()) {
configure.schemas(flywayRuntimeConfig.schemas().get().toArray(EMPTY_ARRAY));
}
if (flywayRuntimeConfig.table().isPresent()) {
configure.table(flywayRuntimeConfig.table().get());
}
configure.locations(flywayBuildTimeConfig.locations().toArray(EMPTY_ARRAY));
if (flywayRuntimeConfig.sqlMigrationPrefix().isPresent()) {
configure.sqlMigrationPrefix(flywayRuntimeConfig.sqlMigrationPrefix().get());
}
if (flywayRuntimeConfig.repeatableSqlMigrationPrefix().isPresent()) {
configure.repeatableSqlMigrationPrefix(flywayRuntimeConfig.repeatableSqlMigrationPrefix().get());
}
configure.cleanDisabled(flywayRuntimeConfig.cleanDisabled());
configure.baselineOnMigrate(flywayRuntimeConfig.baselineOnMigrate());
configure.validateOnMigrate(flywayRuntimeConfig.validateOnMigrate());
configure.validateMigrationNaming(flywayRuntimeConfig.validateMigrationNaming());
final String[] ignoreMigrationPatterns;
if (flywayRuntimeConfig.ignoreMigrationPatterns().isPresent()) {
ignoreMigrationPatterns = flywayRuntimeConfig.ignoreMigrationPatterns().get();
} else {
List<String> patterns = new ArrayList<>(2);
if (flywayRuntimeConfig.ignoreMissingMigrations()) {
patterns.add("*:Missing");
}
if (flywayRuntimeConfig.ignoreFutureMigrations()) {
patterns.add("*:Future");
}
// Default is *:Future
ignoreMigrationPatterns = patterns.toArray(new String[0]);
}
configure.ignoreMigrationPatterns(ignoreMigrationPatterns);
configure.outOfOrder(flywayRuntimeConfig.outOfOrder());
if (flywayRuntimeConfig.baselineVersion().isPresent()) {
configure.baselineVersion(flywayRuntimeConfig.baselineVersion().get());
}
if (flywayRuntimeConfig.baselineDescription().isPresent()) {
configure.baselineDescription(flywayRuntimeConfig.baselineDescription().get());
}
configure.placeholders(flywayRuntimeConfig.placeholders());
configure.createSchemas(flywayRuntimeConfig.createSchemas());
if (flywayRuntimeConfig.placeholderPrefix().isPresent()) {
configure.placeholderPrefix(flywayRuntimeConfig.placeholderPrefix().get());
}
if (flywayRuntimeConfig.placeholderSuffix().isPresent()) {
configure.placeholderSuffix(flywayRuntimeConfig.placeholderSuffix().get());
}
if (!callbacks.isEmpty()) {
configure.callbacks(callbacks.toArray(new Callback[0]));
}
/*
* Ensure that no classpath scanning takes place by setting the ClassProvider and the ResourceProvider
* (see Flyway#createResourceAndClassProviders)
*/
// this configuration is important for the scanner
configure.encoding(StandardCharsets.UTF_8);
configure.detectEncoding(false);
configure.failOnMissingLocations(false);
// the static fields of this
|
FlywayCreator
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/BindsInstanceValidationTest.java
|
{
"start": 1613,
"end": 2404
}
|
class ____ {",
" @BindsInstance abstract void str(String string);",
"}");
CompilerTests.daggerCompiler(testModule)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
"@BindsInstance methods should not be included in @Modules. Did you mean @Binds");
});
}
@Test
public void bindsInstanceInComponent() {
Source testComponent =
CompilerTests.javaSource(
"test.TestComponent",
"package test;",
"",
"import dagger.BindsInstance;",
"import dagger.Component;",
"",
"@Component",
"
|
TestModule
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/refresh/JPARefreshTest.java
|
{
"start": 951,
"end": 2085
}
|
class ____ {
@Test
public void testDelete(EntityManagerFactoryScope scope) {
scope.inEntityManager(
entityManager -> {
entityManager.getTransaction().begin();
try {
RealmEntity realm = new RealmEntity();
realm.setId( "id" );
realm.setName( "realm" );
ComponentEntity c1 = new ComponentEntity();
c1.setId( "c1" );
c1.setRealm( realm );
ComponentEntity c2 = new ComponentEntity();
c2.setId( "c2" );
c2.setRealm( realm );
realm.setComponents( Set.of( c1, c2 ) );
entityManager.persist( realm );
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
RealmEntity find = entityManager.find( RealmEntity.class, "id" );
entityManager.refresh( realm );
entityManager.remove( find );
entityManager.getTransaction().commit();
}
catch (Exception e) {
if ( entityManager.getTransaction().isActive() ) {
entityManager.getTransaction().rollback();
}
throw e;
}
}
);
}
@Table(name="REALM")
@Entity(name = "RealmEntity")
public static
|
JPARefreshTest
|
java
|
apache__kafka
|
connect/runtime/src/test/java/org/apache/kafka/connect/integration/ErrantRecordSinkConnector.java
|
{
"start": 1308,
"end": 1502
}
|
class ____ extends TestableSinkConnector {
@Override
public Class<? extends Task> taskClass() {
return ErrantRecordSinkTask.class;
}
public static
|
ErrantRecordSinkConnector
|
java
|
apache__camel
|
test-infra/camel-test-infra-neo4j/src/main/java/org/apache/camel/test/infra/neo4j/services/Neo4jInfraService.java
|
{
"start": 938,
"end": 1111
}
|
interface ____ extends InfrastructureService {
String getNeo4jDatabaseUri();
String getNeo4jDatabaseUser();
String getNeo4jDatabasePassword();
}
|
Neo4jInfraService
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SlackEndpointBuilderFactory.java
|
{
"start": 37633,
"end": 37925
}
|
interface ____
extends
AdvancedSlackEndpointConsumerBuilder,
AdvancedSlackEndpointProducerBuilder {
default SlackEndpointBuilder basic() {
return (SlackEndpointBuilder) this;
}
}
public
|
AdvancedSlackEndpointBuilder
|
java
|
grpc__grpc-java
|
istio-interop-testing/src/generated/main/grpc/io/istio/test/EchoTestServiceGrpc.java
|
{
"start": 15330,
"end": 16517
}
|
class ____
extends EchoTestServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
EchoTestServiceMethodDescriptorSupplier(java.lang.String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (EchoTestServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new EchoTestServiceFileDescriptorSupplier())
.addMethod(getEchoMethod())
.addMethod(getForwardEchoMethod())
.build();
}
}
}
return result;
}
}
|
EchoTestServiceMethodDescriptorSupplier
|
java
|
resilience4j__resilience4j
|
resilience4j-bulkhead/src/test/java/io/github/resilience4j/bulkhead/ThreadPoolBulkheadRegistryTest.java
|
{
"start": 1093,
"end": 9968
}
|
class ____ {
private ThreadPoolBulkheadConfig config;
private ThreadPoolBulkheadRegistry registry;
private static Optional<EventProcessor<?>> getEventProcessor(
Registry.EventPublisher<ThreadPoolBulkhead> ep) {
return ep instanceof EventProcessor<?> ? Optional.of((EventProcessor<?>) ep)
: Optional.empty();
}
@Before
public void setUp() {
registry = ThreadPoolBulkheadRegistry.ofDefaults();
config = ThreadPoolBulkheadConfig.custom()
.maxThreadPoolSize(100)
.build();
}
@Test
public void shouldReturnCustomConfig() {
ThreadPoolBulkheadRegistry registry = ThreadPoolBulkheadRegistry.of(config);
ThreadPoolBulkheadConfig bulkheadConfig = registry.getDefaultConfig();
assertThat(bulkheadConfig).isSameAs(config);
}
@Test
public void shouldReturnTheCorrectName() {
ThreadPoolBulkhead bulkhead = registry.bulkhead("test");
assertThat(bulkhead).isNotNull();
assertThat(bulkhead.getName()).isEqualTo("test");
assertThat(bulkhead.getBulkheadConfig().getMaxThreadPoolSize())
.isEqualTo(Runtime.getRuntime().availableProcessors());
}
@Test
public void shouldBeTheSameInstance() {
ThreadPoolBulkhead bulkhead1 = registry.bulkhead("test", config);
ThreadPoolBulkhead bulkhead2 = registry.bulkhead("test", config);
assertThat(bulkhead1).isSameAs(bulkhead2);
assertThat(registry.getAllBulkheads()).hasSize(1);
}
@Test
public void shouldBeNotTheSameInstance() {
ThreadPoolBulkhead bulkhead1 = registry.bulkhead("test1");
ThreadPoolBulkhead bulkhead2 = registry.bulkhead("test2");
assertThat(bulkhead1).isNotSameAs(bulkhead2);
assertThat(registry.getAllBulkheads()).hasSize(2);
}
// @Test
// public void tagsOfRegistryAddedToInstance() {
// ThreadPoolBulkhead retryConfig = ThreadPoolBulkhead.ofDefaults();
// Map<String, RetryConfig> retryConfigs = Collections.singletonMap("default", retryConfig);
// Map<String, String> retryTags = Map.of("key1","value1", "key2", "value2");
// RetryRegistry retryRegistry = RetryRegistry.of(retryConfigs, retryTags);
// Retry retry = retryRegistry.retry("testName");
//
// Assertions.assertThat(retry.getTags()).containsOnlyElementsOf(retryTags);
// }
@Test
public void noTagsByDefault() {
ThreadPoolBulkhead bulkhead = registry.bulkhead("testName");
assertThat(bulkhead.getTags()).isEmpty();
}
@Test
public void tagsAddedToInstance() {
Map<String, String> bulkheadTags = Map.of("key1", "value1", "key2", "value2");
ThreadPoolBulkhead bulkhead = registry.bulkhead("testName", bulkheadTags);
assertThat(bulkhead.getTags()).containsAllEntriesOf(bulkheadTags);
}
@Test
public void tagsOfRetriesShouldNotBeMixed() {
ThreadPoolBulkheadConfig config = ThreadPoolBulkheadConfig.ofDefaults();
Map<String, String> bulkheadTags = Map.of("key1", "value1", "key2", "value2");
ThreadPoolBulkhead bulkhead = registry.bulkhead("testName", config, bulkheadTags);
Map<String, String> bulkheadTags2 = Map.of("key3", "value3", "key4", "value4");
ThreadPoolBulkhead bulkhead2 = registry.bulkhead("otherTestName", config, bulkheadTags2);
assertThat(bulkhead.getTags()).containsAllEntriesOf(bulkheadTags);
assertThat(bulkhead2.getTags()).containsAllEntriesOf(bulkheadTags2);
}
@Test
public void tagsOfInstanceTagsShouldOverrideRegistryTags() {
ThreadPoolBulkheadConfig bulkheadConfig = ThreadPoolBulkheadConfig.ofDefaults();
Map<String, ThreadPoolBulkheadConfig> bulkheadConfigs = Collections
.singletonMap("default", bulkheadConfig);
Map<String, String> registryTags = Map.of("key1", "value1", "key2", "value2");
Map<String, String> instanceTags = Map.of("key1", "value3", "key4", "value4");
ThreadPoolBulkheadRegistry bulkheadRegistry = ThreadPoolBulkheadRegistry
.of(bulkheadConfigs, registryTags);
ThreadPoolBulkhead bulkhead = bulkheadRegistry
.bulkhead("testName", bulkheadConfig, instanceTags);
Map<String, String> expectedTags = Map.of("key1", "value3", "key2", "value2", "key4", "value4");
assertThat(bulkhead.getTags()).containsAllEntriesOf(expectedTags);
}
@Test
public void testCreateWithConfigurationMap() {
Map<String, ThreadPoolBulkheadConfig> configs = new HashMap<>();
configs.put("default", ThreadPoolBulkheadConfig.ofDefaults());
configs.put("custom", ThreadPoolBulkheadConfig.ofDefaults());
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry = ThreadPoolBulkheadRegistry
.of(configs);
assertThat(threadPoolBulkheadRegistry.getDefaultConfig()).isNotNull();
assertThat(threadPoolBulkheadRegistry.getConfiguration("custom")).isNotNull();
}
@Test
public void testCreateWithConfigurationMapWithoutDefaultConfig() {
Map<String, ThreadPoolBulkheadConfig> configs = new HashMap<>();
configs.put("custom", ThreadPoolBulkheadConfig.ofDefaults());
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry = ThreadPoolBulkheadRegistry
.of(configs);
assertThat(threadPoolBulkheadRegistry.getDefaultConfig()).isNotNull();
assertThat(threadPoolBulkheadRegistry.getConfiguration("custom")).isNotNull();
}
@Test
public void testCreateWithSingleRegistryEventConsumer() {
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry =
ThreadPoolBulkheadRegistry.of(ThreadPoolBulkheadConfig.ofDefaults(),
new NoOpThreadPoolBulkheadEventConsumer());
getEventProcessor(threadPoolBulkheadRegistry.getEventPublisher())
.ifPresent(eventProcessor -> assertThat(eventProcessor.hasConsumers()).isTrue());
}
@Test
public void testCreateWithMultipleRegistryEventConsumer() {
List<RegistryEventConsumer<ThreadPoolBulkhead>> registryEventConsumers = new ArrayList<>();
registryEventConsumers.add(new NoOpThreadPoolBulkheadEventConsumer());
registryEventConsumers.add(new NoOpThreadPoolBulkheadEventConsumer());
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry =
ThreadPoolBulkheadRegistry
.of(ThreadPoolBulkheadConfig.ofDefaults(), registryEventConsumers);
getEventProcessor(threadPoolBulkheadRegistry.getEventPublisher())
.ifPresent(eventProcessor -> assertThat(eventProcessor.hasConsumers()).isTrue());
}
@Test
public void testCreateWithConfigurationMapWithSingleRegistryEventConsumer() {
Map<String, ThreadPoolBulkheadConfig> configs = new HashMap<>();
configs.put("custom", ThreadPoolBulkheadConfig.ofDefaults());
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry =
ThreadPoolBulkheadRegistry.of(configs, new NoOpThreadPoolBulkheadEventConsumer());
getEventProcessor(threadPoolBulkheadRegistry.getEventPublisher())
.ifPresent(eventProcessor -> assertThat(eventProcessor.hasConsumers()).isTrue());
}
@Test
public void testCreateWithConfigurationMapWithMultiRegistryEventConsumer() {
Map<String, ThreadPoolBulkheadConfig> configs = new HashMap<>();
configs.put("custom", ThreadPoolBulkheadConfig.ofDefaults());
List<RegistryEventConsumer<ThreadPoolBulkhead>> registryEventConsumers = new ArrayList<>();
registryEventConsumers.add(new NoOpThreadPoolBulkheadEventConsumer());
registryEventConsumers.add(new NoOpThreadPoolBulkheadEventConsumer());
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry =
ThreadPoolBulkheadRegistry.of(configs, registryEventConsumers);
getEventProcessor(threadPoolBulkheadRegistry.getEventPublisher())
.ifPresent(eventProcessor -> assertThat(eventProcessor.hasConsumers()).isTrue());
}
@Test
public void testWithNotExistingConfig() {
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry = ThreadPoolBulkheadRegistry
.ofDefaults();
assertThatThrownBy(() -> threadPoolBulkheadRegistry.bulkhead("test", "doesNotExist"))
.isInstanceOf(ConfigurationNotFoundException.class);
}
@Test
public void testAddConfiguration() {
ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry = ThreadPoolBulkheadRegistry
.ofDefaults();
threadPoolBulkheadRegistry
.addConfiguration("custom", ThreadPoolBulkheadConfig.custom().build());
assertThat(threadPoolBulkheadRegistry.getDefaultConfig()).isNotNull();
assertThat(threadPoolBulkheadRegistry.getConfiguration("custom")).isNotNull();
}
private static
|
ThreadPoolBulkheadRegistryTest
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/CatalogTable.java
|
{
"start": 1466,
"end": 1718
}
|
interface ____ a {@link ResolvedCatalogTable} before
* passing it to a {@link DynamicTableFactory} for creating a connector to an external system.
*
* <p>A catalog implementer can either use {@link #newBuilder()} for a basic implementation of this
*
|
to
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/ClientReaderInterceptorContextImpl.java
|
{
"start": 1025,
"end": 6112
}
|
class ____ extends AbstractClientInterceptorContextImpl
implements ReaderInterceptorContext {
private static final List<MissingMessageBodyReaderErrorMessageContextualizer> contextualizers;
static {
var loader = ServiceLoader.load(MissingMessageBodyReaderErrorMessageContextualizer.class, Thread.currentThread()
.getContextClassLoader());
if (!loader.iterator().hasNext()) {
contextualizers = Collections.emptyList();
} else {
contextualizers = new ArrayList<>(1);
for (var entry : loader) {
contextualizers.add(entry);
}
}
}
final RestClientRequestContext clientRequestContext;
final ConfigurationImpl configuration;
final Serialisers serialisers;
InputStream inputStream;
private int index = 0;
private final ReaderInterceptor[] interceptors;
private final MultivaluedMap<String, String> headers = new CaseInsensitiveMap<>();
public ClientReaderInterceptorContextImpl(Annotation[] annotations, Class<?> entityClass, Type entityType,
MediaType mediaType, Map<String, Object> properties,
RestClientRequestContext clientRequestContext,
MultivaluedMap<String, String> headers,
ConfigurationImpl configuration, Serialisers serialisers, InputStream inputStream,
ReaderInterceptor[] interceptors) {
super(annotations, entityClass, entityType, mediaType, properties);
this.clientRequestContext = clientRequestContext;
this.configuration = configuration;
this.serialisers = serialisers;
this.inputStream = inputStream;
this.interceptors = interceptors;
this.headers.putAll(headers);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Object proceed() throws IOException, WebApplicationException {
if (index == interceptors.length) {
List<MessageBodyReader<?>> readers = serialisers.findReaders(configuration, entityClass, mediaType,
RuntimeType.CLIENT);
for (MessageBodyReader<?> reader : readers) {
if (reader.isReadable(entityClass, entityType, annotations, mediaType)) {
try {
if (reader instanceof ClientMessageBodyReader) {
return ((ClientMessageBodyReader) reader).readFrom(entityClass, entityType, annotations, mediaType,
headers,
inputStream, clientRequestContext);
} else {
return ((MessageBodyReader) reader).readFrom(entityClass, entityType, annotations, mediaType,
headers,
inputStream);
}
} catch (IOException e) {
throw new ProcessingException(e);
}
}
}
StringBuilder errorMessage = new StringBuilder(
"Response could not be mapped to type " + entityType + " for response with media type " + mediaType);
if (!contextualizers.isEmpty()) {
var input = new MissingMessageBodyReaderErrorMessageContextualizer.Input() {
@Override
public Class<?> type() {
return entityClass;
}
@Override
public Type genericType() {
return entityType;
}
@Override
public Annotation[] annotations() {
return annotations;
}
@Override
public MediaType mediaType() {
return mediaType;
}
};
List<String> contextMessages = new ArrayList<>(contextualizers.size());
for (var contextualizer : contextualizers) {
String contextMessage = contextualizer.provideContextMessage(input);
if (contextMessage != null) {
contextMessages.add(contextMessage);
}
}
if (!contextMessages.isEmpty()) {
errorMessage.append(". Hints: ");
errorMessage.append(String.join(",", contextMessages));
}
}
// Spec says to throw this
throw new ProcessingException(errorMessage.toString());
} else {
return interceptors[index++].aroundReadFrom(this);
}
}
@Override
public InputStream getInputStream() {
return inputStream;
}
@Override
public void setInputStream(InputStream is) {
this.inputStream = is;
}
@Override
public MultivaluedMap<String, String> getHeaders() {
return headers;
}
}
|
ClientReaderInterceptorContextImpl
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/reventity/LongRevNumberRevEntity.java
|
{
"start": 1024,
"end": 2092
}
|
class ____ {
@Id
@GeneratedValue(generator = "EnversTestingRevisionGenerator")
@RevisionNumber
@Column(columnDefinition = "int")
private long customId;
@RevisionTimestamp
private long customTimestamp;
public long getCustomId() {
return customId;
}
public void setCustomId(long customId) {
this.customId = customId;
}
public long getCustomTimestamp() {
return customTimestamp;
}
public void setCustomTimestamp(long customTimestamp) {
this.customTimestamp = customTimestamp;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof LongRevNumberRevEntity) ) {
return false;
}
LongRevNumberRevEntity that = (LongRevNumberRevEntity) o;
if ( customId != that.customId ) {
return false;
}
if ( customTimestamp != that.customTimestamp ) {
return false;
}
return true;
}
public int hashCode() {
int result;
result = (int) (customId ^ (customId >>> 32));
result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32));
return result;
}
}
|
LongRevNumberRevEntity
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java
|
{
"start": 465,
"end": 1762
}
|
class ____ extends TestBase {
@Test
public void should_not_allow_Mock_and_Spy() {
assertThatThrownBy(
() -> {
MockitoAnnotations.openMocks(
new Object() {
@Mock @Spy List<?> mock;
});
})
.isInstanceOf(MockitoException.class)
.hasMessage(
"This combination of annotations is not permitted on a single field:\n"
+ "@Spy and @Mock");
}
@Test
public void should_not_allow_Spy_and_InjectMocks_on_interfaces() {
try {
MockitoAnnotations.openMocks(
new Object() {
@InjectMocks @Spy List<?> mock;
});
fail();
} catch (MockitoException me) {
Assertions.assertThat(me.getMessage()).contains("'List' is an interface");
}
}
@Test
public void should_allow_Spy_and_InjectMocks() {
MockitoAnnotations.openMocks(
new Object() {
@InjectMocks @Spy WithDependency mock;
});
}
static
|
WrongSetOfAnnotationsTest
|
java
|
google__gson
|
gson/src/main/java/com/google/gson/internal/bind/TreeTypeAdapter.java
|
{
"start": 5323,
"end": 6946
}
|
class ____ implements TypeAdapterFactory {
private final TypeToken<?> exactType;
private final boolean matchRawType;
private final Class<?> hierarchyType;
private final JsonSerializer<?> serializer;
private final JsonDeserializer<?> deserializer;
SingleTypeFactory(
Object typeAdapter, TypeToken<?> exactType, boolean matchRawType, Class<?> hierarchyType) {
serializer = typeAdapter instanceof JsonSerializer ? (JsonSerializer<?>) typeAdapter : null;
deserializer =
typeAdapter instanceof JsonDeserializer ? (JsonDeserializer<?>) typeAdapter : null;
if (serializer == null && deserializer == null) {
Objects.requireNonNull(typeAdapter);
throw new IllegalArgumentException(
"Type adapter "
+ typeAdapter.getClass().getName()
+ " must implement JsonSerializer or JsonDeserializer");
}
this.exactType = exactType;
this.matchRawType = matchRawType;
this.hierarchyType = hierarchyType;
}
@SuppressWarnings("unchecked") // guarded by typeToken.equals() call
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
boolean matches =
exactType != null
? exactType.equals(type) || (matchRawType && exactType.getType() == type.getRawType())
: hierarchyType.isAssignableFrom(type.getRawType());
return matches
? new TreeTypeAdapter<>(
(JsonSerializer<T>) serializer, (JsonDeserializer<T>) deserializer, gson, type, this)
: null;
}
}
private final
|
SingleTypeFactory
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/ser/jdk/JDKArraySerializers.java
|
{
"start": 4007,
"end": 6597
}
|
class ____
extends ArraySerializerBase<boolean[]>
{
// as above, assuming no one re-defines primitive/wrapper types
private final static JavaType VALUE_TYPE = simpleElementType(Boolean.TYPE);
public BooleanArraySerializer() { super(boolean[].class); }
protected BooleanArraySerializer(BooleanArraySerializer src,
BeanProperty prop, Boolean unwrapSingle) {
super(src, prop, unwrapSingle);
}
@Override
public ValueSerializer<?> _withResolved(BeanProperty prop, Boolean unwrapSingle) {
return new BooleanArraySerializer(this, prop, unwrapSingle);
}
/**
* Booleans never add type info; hence, even if type serializer is suggested,
* we'll ignore it...
*/
@Override
public StdContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts) {
return this;
}
@Override
public JavaType getContentType() {
return VALUE_TYPE;
}
@Override
public ValueSerializer<?> getContentSerializer() {
// 14-Jan-2012, tatu: We could refer to an actual serializer if absolutely necessary
return null;
}
@Override
public boolean isEmpty(SerializationContext prov, boolean[] value) {
return value.length == 0;
}
@Override
public boolean hasSingleElement(boolean[] value) {
return (value.length == 1);
}
@Override
public final void serialize(boolean[] value, JsonGenerator g, SerializationContext provider) throws JacksonException
{
final int len = value.length;
if ((len == 1) && _shouldUnwrapSingle(provider)) {
serializeContents(value, g, provider);
return;
}
g.writeStartArray(value, len);
serializeContents(value, g, provider);
g.writeEndArray();
}
@Override
public void serializeContents(boolean[] value, JsonGenerator g, SerializationContext provider)
throws JacksonException
{
for (int i = 0, len = value.length; i < len; ++i) {
g.writeBoolean(value[i]);
}
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
{
visitArrayFormat(visitor, typeHint, JsonFormatTypes.BOOLEAN);
}
}
@JacksonStdImpl
public static
|
BooleanArraySerializer
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/factory/CacheRequestBodyGatewayFilterFactoryTests.java
|
{
"start": 2227,
"end": 4500
}
|
class ____ extends BaseWebClientTests {
private static final String BODY_VALUE = "here is request body";
private static final String BODY_EMPTY = "";
private static final String BODY_CACHED_EXISTS = "BODY_CACHED_EXISTS";
private static final String LARGE_BODY_VALUE = "here is request body which will cause payload size failure";
@Test
public void cacheRequestBodyWorks() {
testClient.post()
.uri("/post")
.header("Host", "www.cacherequestbody.org")
.bodyValue(BODY_VALUE)
.exchange()
.expectStatus()
.isOk()
.expectBody(Map.class)
.consumeWith(result -> {
Map<?, ?> response = result.getResponseBody();
assertThat(response).isNotNull();
String responseBody = (String) response.get("data");
assertThat(responseBody).isEqualTo(BODY_VALUE);
});
}
@Test
public void cacheRequestBodyDoesntWorkForLargePayload() {
testClient.post()
.uri("/post")
.header("Host", "www.cacherequestbody.org")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.bodyValue(LARGE_BODY_VALUE)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
.expectBody()
.jsonPath("message")
.isEqualTo("Exceeded limit on max bytes to buffer : 25");
}
@Test
public void cacheRequestBodyEmpty() {
testClient.post()
.uri("/post")
.header("Host", "www.cacherequestbodyempty.org")
.exchange()
.expectStatus()
.isOk()
.expectBody(Map.class)
.consumeWith(result -> {
Map<?, ?> response = result.getResponseBody();
assertThat(response).isNotNull();
assertThat(response.get("data")).isNull();
});
}
@Test
public void cacheRequestBodyExists() {
testClient.post()
.uri("/post")
.header("Host", "www.cacherequestbodyexists.org")
.exchange()
.expectStatus()
.isOk();
}
@Test
public void toStringFormat() {
CacheRequestBodyGatewayFilterFactory.Config config = new CacheRequestBodyGatewayFilterFactory.Config();
config.setBodyClass(String.class);
GatewayFilter filter = new CacheRequestBodyGatewayFilterFactory().apply(config);
assertThat(filter.toString()).contains("String");
}
@EnableAutoConfiguration
@SpringBootConfiguration
@Import(DefaultTestConfig.class)
public static
|
CacheRequestBodyGatewayFilterFactoryTests
|
java
|
bumptech__glide
|
annotation/compiler/test/src/test/java/com/bumptech/glide/annotation/compiler/test/RegenerateResourcesRule.java
|
{
"start": 891,
"end": 931
}
|
class ____ do nothing.
*/
public final
|
will
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/registry/StandardServiceRegistryBuilder.java
|
{
"start": 1379,
"end": 4152
}
|
class ____ {
/**
* Creates a {@code StandardServiceRegistryBuilder} specific to the needs
* of bootstrapping JPA.
* <p>
* Intended only for use from
* {@link org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl}.
* <p>
* In particular, we ignore properties found in {@code cfg.xml} files.
* {@code EntityManagerFactoryBuilderImpl} collects these properties later.
*
* @see org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl
*/
public static StandardServiceRegistryBuilder forJpa(BootstrapServiceRegistry bootstrapServiceRegistry) {
return new StandardServiceRegistryBuilder(
bootstrapServiceRegistry,
new HashMap<>(),
new LoadedConfig( null ) {
@Override
protected void addConfigurationValues(Map<String,Object> configurationValues) {
// here, do nothing
}
}
) {
@Override
public StandardServiceRegistryBuilder configure(LoadedConfig loadedConfig) {
getAggregatedCfgXml().merge( loadedConfig );
// super also collects the properties - here we skip that part
return this;
}
};
}
/**
* The default resource name for a Hibernate configuration XML file.
*/
public static final String DEFAULT_CFG_RESOURCE_NAME = "hibernate.cfg.xml";
private final Map<String,Object> settings;
private final List<StandardServiceInitiator<?>> initiators;
private final List<ProvidedService<?>> providedServices = new ArrayList<>();
private boolean autoCloseRegistry = true;
private final BootstrapServiceRegistry bootstrapServiceRegistry;
private final ConfigLoader configLoader;
private final LoadedConfig aggregatedCfgXml;
/**
* Create a default builder.
*/
public StandardServiceRegistryBuilder() {
this( new BootstrapServiceRegistryBuilder().enableAutoClose().build() );
}
/**
* Create a builder with the specified bootstrap services.
*
* @param bootstrapServiceRegistry Provided bootstrap registry to use.
*/
public StandardServiceRegistryBuilder(BootstrapServiceRegistry bootstrapServiceRegistry) {
this( bootstrapServiceRegistry, LoadedConfig.baseline() );
}
/**
* Intended for use exclusively from JPA bootstrapping, or extensions of this
* class.
*
* Consider this an SPI.
*
* @see #forJpa
*/
protected StandardServiceRegistryBuilder(
BootstrapServiceRegistry bootstrapServiceRegistry,
Map<String,Object> settings,
LoadedConfig loadedConfig) {
this.bootstrapServiceRegistry = bootstrapServiceRegistry;
this.configLoader = new ConfigLoader( bootstrapServiceRegistry );
this.settings = settings;
this.aggregatedCfgXml = loadedConfig;
this.initiators = standardInitiatorList();
}
/**
* Intended for use exclusively from Quarkus bootstrapping, or extensions of
* this
|
StandardServiceRegistryBuilder
|
java
|
netty__netty
|
codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoderTest.java
|
{
"start": 2526,
"end": 24497
}
|
class ____ {
@Test
public void testAllowedMethods() throws Exception {
shouldThrowExceptionIfNotAllowed(HttpMethod.CONNECT);
shouldThrowExceptionIfNotAllowed(HttpMethod.PUT);
shouldThrowExceptionIfNotAllowed(HttpMethod.POST);
shouldThrowExceptionIfNotAllowed(HttpMethod.PATCH);
shouldThrowExceptionIfNotAllowed(HttpMethod.DELETE);
shouldThrowExceptionIfNotAllowed(HttpMethod.GET);
shouldThrowExceptionIfNotAllowed(HttpMethod.HEAD);
shouldThrowExceptionIfNotAllowed(HttpMethod.OPTIONS);
try {
shouldThrowExceptionIfNotAllowed(HttpMethod.TRACE);
fail("Should raised an exception with TRACE method");
} catch (ErrorDataEncoderException e) {
// Exception is willing
}
}
private void shouldThrowExceptionIfNotAllowed(HttpMethod method) throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
method, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
encoder.addBodyAttribute("foo", "bar");
encoder.addBodyFileUpload("quux", file1, "text/plain", false);
String multipartDataBoundary = encoder.multipartDataBoundary;
String content = getRequestBody(encoder);
String expected = "--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
CONTENT_LENGTH + ": 3" + "\r\n" +
CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
"\r\n" +
"bar" +
"\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"; filename=\"file-01.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 01" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartDataBoundary + "--" + "\r\n";
assertEquals(expected, content);
}
@Test
public void testSingleFileUploadNoName() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
encoder.addBodyAttribute("foo", "bar");
encoder.addBodyFileUpload("quux", "", file1, "text/plain", false);
String multipartDataBoundary = encoder.multipartDataBoundary;
String content = getRequestBody(encoder);
String expected = "--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
CONTENT_LENGTH + ": 3" + "\r\n" +
CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
"\r\n" +
"bar" +
"\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"\r\n" +
CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 01" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartDataBoundary + "--" + "\r\n";
assertEquals(expected, content);
}
@Test
public void testMultiFileUploadInMixedMode() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
File file2 = new File(getClass().getResource("/file-02.txt").toURI());
File file3 = new File(getClass().getResource("/file-03.txt").toURI());
encoder.addBodyAttribute("foo", "bar");
encoder.addBodyFileUpload("quux", file1, "text/plain", false);
encoder.addBodyFileUpload("quux", file2, "text/plain", false);
encoder.addBodyFileUpload("quux", file3, "text/plain", false);
// We have to query the value of these two fields before finalizing
// the request, which unsets one of them.
String multipartDataBoundary = encoder.multipartDataBoundary;
String multipartMixedBoundary = encoder.multipartMixedBoundary;
String content = getRequestBody(encoder);
String expected = "--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
CONTENT_LENGTH + ": 3" + "\r\n" +
CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
"\r\n" +
"bar" + "\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"" + "\r\n" +
CONTENT_TYPE + ": multipart/mixed; boundary=" + multipartMixedBoundary + "\r\n" +
"\r\n" +
"--" + multipartMixedBoundary + "\r\n" +
CONTENT_DISPOSITION + ": attachment; filename=\"file-01.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 01" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartMixedBoundary + "\r\n" +
CONTENT_DISPOSITION + ": attachment; filename=\"file-02.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file2.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 02" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartMixedBoundary + "\r\n" +
CONTENT_DISPOSITION + ": attachment; filename=\"file-03.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file3.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 03" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartMixedBoundary + "--" + "\r\n" +
"--" + multipartDataBoundary + "--" + "\r\n";
assertEquals(expected, content);
}
@Test
public void testMultiFileUploadInMixedModeNoName() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
File file2 = new File(getClass().getResource("/file-02.txt").toURI());
encoder.addBodyAttribute("foo", "bar");
encoder.addBodyFileUpload("quux", "", file1, "text/plain", false);
encoder.addBodyFileUpload("quux", "", file2, "text/plain", false);
// We have to query the value of these two fields before finalizing
// the request, which unsets one of them.
String multipartDataBoundary = encoder.multipartDataBoundary;
String multipartMixedBoundary = encoder.multipartMixedBoundary;
String content = getRequestBody(encoder);
String expected = "--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
CONTENT_LENGTH + ": 3" + "\r\n" +
CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
"\r\n" +
"bar" + "\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"" + "\r\n" +
CONTENT_TYPE + ": multipart/mixed; boundary=" + multipartMixedBoundary + "\r\n" +
"\r\n" +
"--" + multipartMixedBoundary + "\r\n" +
CONTENT_DISPOSITION + ": attachment\r\n" +
CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 01" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartMixedBoundary + "\r\n" +
CONTENT_DISPOSITION + ": attachment\r\n" +
CONTENT_LENGTH + ": " + file2.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 02" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartMixedBoundary + "--" + "\r\n" +
"--" + multipartDataBoundary + "--" + "\r\n";
assertEquals(expected, content);
}
@Test
public void testSingleFileUploadInHtml5Mode() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory,
request, true, CharsetUtil.UTF_8, EncoderMode.HTML5);
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
File file2 = new File(getClass().getResource("/file-02.txt").toURI());
encoder.addBodyAttribute("foo", "bar");
encoder.addBodyFileUpload("quux", file1, "text/plain", false);
encoder.addBodyFileUpload("quux", file2, "text/plain", false);
String multipartDataBoundary = encoder.multipartDataBoundary;
String content = getRequestBody(encoder);
String expected = "--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
CONTENT_LENGTH + ": 3" + "\r\n" +
CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
"\r\n" +
"bar" + "\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"; filename=\"file-01.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 01" + StringUtil.NEWLINE + "\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"; filename=\"file-02.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file2.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 02" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartDataBoundary + "--" + "\r\n";
assertEquals(expected, content);
}
@Test
public void testMultiFileUploadInHtml5Mode() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory,
request, true, CharsetUtil.UTF_8, EncoderMode.HTML5);
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
encoder.addBodyAttribute("foo", "bar");
encoder.addBodyFileUpload("quux", file1, "text/plain", false);
String multipartDataBoundary = encoder.multipartDataBoundary;
String content = getRequestBody(encoder);
String expected = "--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"foo\"" + "\r\n" +
CONTENT_LENGTH + ": 3" + "\r\n" +
CONTENT_TYPE + ": text/plain; charset=UTF-8" + "\r\n" +
"\r\n" +
"bar" +
"\r\n" +
"--" + multipartDataBoundary + "\r\n" +
CONTENT_DISPOSITION + ": form-data; name=\"quux\"; filename=\"file-01.txt\"" + "\r\n" +
CONTENT_LENGTH + ": " + file1.length() + "\r\n" +
CONTENT_TYPE + ": text/plain" + "\r\n" +
CONTENT_TRANSFER_ENCODING + ": binary" + "\r\n" +
"\r\n" +
"File 01" + StringUtil.NEWLINE +
"\r\n" +
"--" + multipartDataBoundary + "--" + "\r\n";
assertEquals(expected, content);
}
@Test
public void testHttpPostRequestEncoderSlicedBuffer() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
// add Form attribute
encoder.addBodyAttribute("getform", "POST");
encoder.addBodyAttribute("info", "first value");
encoder.addBodyAttribute("secondinfo", "secondvalue a&");
encoder.addBodyAttribute("thirdinfo", "short text");
int length = 100000;
char[] array = new char[length];
Arrays.fill(array, 'a');
String longText = new String(array);
encoder.addBodyAttribute("fourthinfo", longText.substring(0, 7470));
File file1 = new File(getClass().getResource("/file-01.txt").toURI());
encoder.addBodyFileUpload("myfile", file1, "application/x-zip-compressed", false);
encoder.finalizeRequest();
while (! encoder.isEndOfInput()) {
HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
ByteBuf content = httpContent.content();
int refCnt = content.refCnt();
assertTrue((content.unwrap() == content || content.unwrap() == null) && refCnt == 1 ||
content.unwrap() != content && refCnt == 2,
"content: " + content + " content.unwrap(): " + content.unwrap() + " refCnt: " + refCnt);
httpContent.release();
}
encoder.cleanFiles();
encoder.close();
}
private static String getRequestBody(HttpPostRequestEncoder encoder) throws Exception {
encoder.finalizeRequest();
List<InterfaceHttpData> chunks = encoder.multipartHttpDatas;
ByteBuf[] buffers = new ByteBuf[chunks.size()];
for (int i = 0; i < buffers.length; i++) {
InterfaceHttpData data = chunks.get(i);
if (data instanceof InternalAttribute) {
buffers[i] = ((InternalAttribute) data).toByteBuf();
} else if (data instanceof HttpData) {
buffers[i] = ((HttpData) data).getByteBuf();
}
}
ByteBuf content = Unpooled.wrappedBuffer(buffers);
String contentStr = content.toString(CharsetUtil.UTF_8);
content.release();
return contentStr;
}
@Test
public void testDataIsMultipleOfChunkSize1() throws Exception {
DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory, request, true,
HttpConstants.DEFAULT_CHARSET, HttpPostRequestEncoder.EncoderMode.RFC1738);
MemoryFileUpload first = new MemoryFileUpload("resources", "", "application/json", null,
CharsetUtil.UTF_8, -1);
first.setMaxSize(-1);
first.setContent(new ByteArrayInputStream(new byte[7955]));
encoder.addBodyHttpData(first);
MemoryFileUpload second = new MemoryFileUpload("resources2", "", "application/json", null,
CharsetUtil.UTF_8, -1);
second.setMaxSize(-1);
second.setContent(new ByteArrayInputStream(new byte[7928]));
encoder.addBodyHttpData(second);
assertNotNull(encoder.finalizeRequest());
checkNextChunkSize(encoder, 8080);
checkNextChunkSize(encoder, 8080);
HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
assertTrue(httpContent instanceof LastHttpContent, "Expected LastHttpContent is not received");
httpContent.release();
assertTrue(encoder.isEndOfInput(), "Expected end of input is not receive");
}
@Test
public void testDataIsMultipleOfChunkSize2() throws Exception {
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
HttpMethod.POST, "http://localhost");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);
int length = 7943;
char[] array = new char[length];
Arrays.fill(array, 'a');
String longText = new String(array);
encoder.addBodyAttribute("foo", longText);
assertNotNull(encoder.finalizeRequest());
checkNextChunkSize(encoder, 8080);
HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
assertTrue(httpContent instanceof LastHttpContent, "Expected LastHttpContent is not received");
httpContent.release();
assertTrue(encoder.isEndOfInput(), "Expected end of input is not receive");
}
private static void checkNextChunkSize(HttpPostRequestEncoder encoder, int sizeWithoutDelimiter) throws Exception {
// 16 bytes as HttpPostRequestEncoder uses Long.toHexString(...) to generate a hex-string which will be between
// 2 and 16 bytes.
// See https://github.com/netty/netty/blob/4.1/codec-http/src/main/java/io/netty/handler/
// codec/http/multipart/HttpPostRequestEncoder.java#L291
int expectedSizeMin = sizeWithoutDelimiter + 2;
int expectedSizeMax = sizeWithoutDelimiter + 16;
HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
int readable = httpContent.content().readableBytes();
boolean expectedSize = readable >= expectedSizeMin && readable <= expectedSizeMax;
assertTrue(expectedSize, "Chunk size is not in expected range (" + expectedSizeMin + " - "
+ expectedSizeMax + "), was: " + readable);
httpContent.release();
}
@Test
public void testEncodeChunkedContent() throws Exception {
HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false);
int length = 8077 + 8096;
char[] array = new char[length];
Arrays.fill(array, 'a');
String longText = new String(array);
encoder.addBodyAttribute("data", longText);
encoder.addBodyAttribute("moreData", "abcd");
assertNotNull(encoder.finalizeRequest());
while (!encoder.isEndOfInput()) {
encoder.readChunk((ByteBufAllocator) null).release();
}
assertTrue(encoder.isEndOfInput());
encoder.cleanFiles();
}
@Test
public void testEncodeChunkedContentV2() throws Exception {
final Map<String, String> params = new LinkedHashMap<String, String>();
params.put("data", largeText("data", 3));
params.put("empty", "");
params.put("tiny", "a");
params.put("large", generateString(chunkSize - 7 - 7 - 1 - 8));
params.put("huge", largeText("huge", 8));
params.put("small", "abcd");
final StringBuilder expectQueryStr = new StringBuilder();
final HttpRequest req = new DefaultHttpRequest(HTTP_1_1, POST, "/");
final HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false);
for (Entry<String, String> entry : params.entrySet()) {
final String key = entry.getKey();
final String value = entry.getValue();
encoder.addBodyAttribute(key, value);
expectQueryStr.append(key).append('=').append(value).append('&');
}
expectQueryStr.setLength(expectQueryStr.length() - 1); //remove last '&'
assertNotNull(encoder.finalizeRequest());
final StringBuilder chunks = new StringBuilder();
while (!encoder.isEndOfInput()) {
final HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null);
chunks.append(httpContent.content().toString(UTF_8));
httpContent.release();
}
assertTrue(encoder.isEndOfInput());
assertEquals(expectQueryStr.toString(), chunks.toString());
encoder.cleanFiles();
}
private String largeText(String key, int multipleChunks) {
return generateString(chunkSize * multipleChunks - key.length() - 2); // 2 is '=' and '&'
}
private String generateString(int length) {
final char[] array = new char[length];
Arrays.fill(array, 'a');
return new String(array);
}
}
|
HttpPostRequestEncoderTest
|
java
|
apache__camel
|
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpReadLockNotStartedIT.java
|
{
"start": 1799,
"end": 3861
}
|
class ____ extends FtpServerTestSupport {
@TempDir
Path testDirectory;
@BindToRegistry("myLock")
private final GenericFileProcessStrategy lock = new MyReadLock();
protected String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}"
+ "/notstarted?password=admin&processStrategy=#myLock&idempotent=true";
}
@Test
public void testIdempotentEager() throws Exception {
FtpConsumer consumer = (FtpConsumer) context.getRoute("myRoute").getConsumer();
Assertions.assertTrue(consumer.getEndpoint().isIdempotent());
Assertions.assertTrue(consumer.getEndpoint().getIdempotentEager());
MemoryIdempotentRepository repo = (MemoryIdempotentRepository) consumer.getEndpoint().getIdempotentRepository();
Assertions.assertEquals(0, repo.getCacheSize());
context.getRouteController().startAllRoutes();
// this file is not okay and is not started
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
template.sendBodyAndHeader("file:{{ftp.root.dir}}/notstarted", "Bye World", Exchange.FILE_NAME,
"bye.txt");
mock.assertIsSatisfied(2000);
Assertions.assertEquals(0, repo.getCacheSize());
// this file is okay
mock.reset();
mock.expectedMessageCount(1);
template.sendBodyAndHeader("file:{{ftp.root.dir}}/notstarted", "Hello World", Exchange.FILE_NAME,
"hello.txt");
mock.assertIsSatisfied();
Awaitility.await().untilAsserted(() -> {
Assertions.assertEquals(1, repo.getCacheSize());
});
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(getFtpUrl()).routeId("myRoute").autoStartup(false)
.to(TestSupport.fileUri(testDirectory, "out"), "mock:result");
}
};
}
private static
|
FtpReadLockNotStartedIT
|
java
|
quarkusio__quarkus
|
integration-tests/opentelemetry-vertx-exporter/src/main/java/io/quarkus/it/opentelemetry/vertx/exporter/HelloResource.java
|
{
"start": 357,
"end": 701
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(HelloResource.class);
@Inject
Meter meter;
@GET
public String get() {
meter.counterBuilder("hello").build().add(1, Attributes.of(AttributeKey.stringKey("key"), "value"));
LOG.info("Hello World");
return "get";
}
}
|
HelloResource
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/instance/illegal/WildcardInstanceInjectionPointTest.java
|
{
"start": 1197,
"end": 1282
}
|
class ____ {
@Inject
Instance<? extends Number> instance;
}
}
|
Head
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/InvalidPatternSyntaxTest.java
|
{
"start": 1434,
"end": 1613
}
|
class ____ {
public static final String INVALID = "*";
{
// BUG: Diagnostic contains: Unclosed character
|
InvalidPatternSyntaxPositiveCases
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/inheritedmappingmethod/CarMapper.java
|
{
"start": 435,
"end": 576
}
|
interface ____ extends UnboundMappable<CarDto, Car> {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
}
// CHECKSTYLE:ON
|
CarMapper
|
java
|
alibaba__nacos
|
console/src/test/java/com/alibaba/nacos/console/handler/impl/inner/config/HistoryInnerHandlerTest.java
|
{
"start": 1839,
"end": 6931
}
|
class ____ {
@Mock
HistoryService historyService;
HistoryInnerHandler historyInnerHandler;
@BeforeEach
void setUp() {
historyInnerHandler = new HistoryInnerHandler(historyService);
}
@AfterEach
void tearDown() {
}
@Test
void getConfigHistoryInfo() throws NacosException {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
injectMockDataToHistoryInfo(configHistoryInfo);
when(historyService.getConfigHistoryInfo("dataId", "group", "tenant", 1L)).thenReturn(configHistoryInfo);
assertNotNull(historyInnerHandler.getConfigHistoryInfo("dataId", "group", "tenant", 1L));
}
@Test
void getConfigHistoryInfoNotFound() throws NacosException {
when(historyService.getConfigHistoryInfo("dataId", "group", "tenant", 1L)).thenThrow(
new EmptyResultDataAccessException(1));
assertThrows(NacosApiException.class,
() -> historyInnerHandler.getConfigHistoryInfo("dataId", "group", "tenant", 1L),
"certain config history for nid = 1 not exist");
}
@Test
void listConfigHistory() throws NacosException {
Page<ConfigHistoryInfo> mockPage = new Page<>();
mockPage.setPageNumber(1);
mockPage.setPagesAvailable(1);
mockPage.setTotalCount(1);
ConfigHistoryInfo mockConfigHistoryInfo = new ConfigHistoryInfo();
injectMockDataToHistoryInfo(mockConfigHistoryInfo);
mockPage.setPageItems(Collections.singletonList(mockConfigHistoryInfo));
when(historyService.listConfigHistory("dataId", "group", "tenant", 1, 1)).thenReturn(mockPage);
Page<ConfigHistoryBasicInfo> actual = historyInnerHandler.listConfigHistory("dataId", "group", "tenant", 1, 1);
assertNotNull(actual);
assertEquals(1, actual.getPageNumber());
assertEquals(1, actual.getPagesAvailable());
assertEquals(1, actual.getTotalCount());
assertEquals(1, actual.getPageItems().size());
assertEquals(mockConfigHistoryInfo.getId(), actual.getPageItems().get(0).getId());
assertEquals(mockConfigHistoryInfo.getDataId(), actual.getPageItems().get(0).getDataId());
assertEquals(mockConfigHistoryInfo.getGroup(), actual.getPageItems().get(0).getGroupName());
assertEquals(mockConfigHistoryInfo.getTenant(), actual.getPageItems().get(0).getNamespaceId());
}
@Test
void getPreviousConfigHistoryInfo() throws NacosException {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
injectMockDataToHistoryInfo(configHistoryInfo);
when(historyService.getPreviousConfigHistoryInfo("dataId", "group", "tenant", 1L)).thenReturn(
configHistoryInfo);
assertNotNull(historyInnerHandler.getPreviousConfigHistoryInfo("dataId", "group", "tenant", 1L));
}
@Test
void getPreviousConfigHistoryInfoNotFound() throws AccessException {
when(historyService.getPreviousConfigHistoryInfo("dataId", "group", "tenant", 1L)).thenThrow(
new EmptyResultDataAccessException(1));
assertThrows(NacosApiException.class,
() -> historyInnerHandler.getPreviousConfigHistoryInfo("dataId", "group", "tenant", 1L),
"previous config history for id = 1 not exist");
}
@Test
void getConfigsByTenant() {
ConfigInfoWrapper configInfoWrapper = new ConfigInfoWrapper();
configInfoWrapper.setId(1L);
configInfoWrapper.setDataId("dataId");
configInfoWrapper.setGroup("group");
configInfoWrapper.setTenant("tenant");
when(historyService.getConfigListByNamespace("tenant")).thenReturn(
Collections.singletonList(configInfoWrapper));
List<ConfigBasicInfo> actual = historyInnerHandler.getConfigsByTenant("tenant");
assertEquals(1, actual.size());
assertEquals(configInfoWrapper.getId(), actual.get(0).getId());
assertEquals(configInfoWrapper.getDataId(), actual.get(0).getDataId());
assertEquals(configInfoWrapper.getGroup(), actual.get(0).getGroupName());
assertEquals(configInfoWrapper.getTenant(), actual.get(0).getNamespaceId());
}
private void injectMockDataToHistoryInfo(ConfigHistoryInfo configHistoryInfo) {
configHistoryInfo.setId(1L);
configHistoryInfo.setDataId("dataId");
configHistoryInfo.setGroup("group");
configHistoryInfo.setTenant("tenant");
configHistoryInfo.setContent("content");
configHistoryInfo.setSrcIp("srcIp");
configHistoryInfo.setSrcUser("srcUser");
configHistoryInfo.setOpType("opType");
configHistoryInfo.setPublishType("publishType");
configHistoryInfo.setGrayName("grayName");
configHistoryInfo.setExtInfo("extInfo");
configHistoryInfo.setCreatedTime(new java.sql.Timestamp(System.currentTimeMillis()));
configHistoryInfo.setLastModifiedTime(new java.sql.Timestamp(System.currentTimeMillis()));
}
}
|
HistoryInnerHandlerTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/naturalid/NaturalIdAndLazyLoadingTest.java
|
{
"start": 1312,
"end": 2735
}
|
class ____ {
@BeforeEach
public void setUp(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
Currency currency = new Currency( 1, "GPB" );
Wallet position = new Wallet( 1, new BigDecimal( 1 ), currency );
entityManager.persist( currency );
entityManager.persist( position );
}
);
}
@Test
public void testCriteriaQuery(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Wallet> criteriaQuery = criteriaBuilder.createQuery( Wallet.class );
Root<Wallet> walletRoot = criteriaQuery.from( Wallet.class );
ParameterExpression<Integer> parameter = criteriaBuilder.parameter( Integer.class, "p" );
criteriaQuery.where( walletRoot.get( "id" ).in( parameter ) );
TypedQuery<Wallet> query = entityManager.createQuery( criteriaQuery );
query.setParameter( "p", 1 );
List<Wallet> wallets = query.getResultList();
assertThat( wallets.size() ).isEqualTo( 1 );
// Currency cannot be lazy initialized without Bytecode Enhancement because of the @JoinColumn(referencedColumnName = "isoCode", nullable = false)
assertThat( Hibernate.isInitialized( wallets.get( 0 ).getCurrency() ) ).isTrue();
}
);
}
@Entity(name = "Wallet")
@Table(name = "WALLET_TABLE")
public static
|
NaturalIdAndLazyLoadingTest
|
java
|
quarkusio__quarkus
|
extensions/spring-data-jpa/deployment/src/main/java/io/quarkus/spring/data/deployment/generate/SpringDataRepositoryCreator.java
|
{
"start": 7688,
"end": 9126
}
|
class ____");
}
DotName newEntityDotName = types.get(0).name();
if ((entityDotName != null) && !newEntityDotName.equals(entityDotName)) {
throw new IllegalArgumentException("Repository " + repositoryToImplement + " specifies multiple Entity types");
}
entityDotName = newEntityDotName;
DotName newIdDotName = types.get(1).name();
if ((idDotName != null) && !newIdDotName.equals(idDotName)) {
throw new IllegalArgumentException("Repository " + repositoryToImplement + " specifies multiple ID types");
}
idDotName = newIdDotName;
}
if (idDotName == null || entityDotName == null) {
throw new IllegalArgumentException(
"Repository " + repositoryToImplement + " does not specify ID and/or Entity type");
}
return new AbstractMap.SimpleEntry<>(idDotName, entityDotName);
}
private void createCustomImplFields(ClassCreator repositoryImpl, List<DotName> customInterfaceNamesToImplement,
IndexView index, Map<String, FieldDescriptor> customImplNameToFieldDescriptor) {
Set<String> customImplClassNames = new HashSet<>(customInterfaceNamesToImplement.size());
// go through the interfaces and collect the implementing classes in a Set
// this is done because it is possible for an implementing
|
type
|
java
|
alibaba__nacos
|
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/proxy/MapperProxy.java
|
{
"start": 1261,
"end": 1611
}
|
class ____ implements InvocationHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MapperProxy.class);
private Mapper mapper;
private static final Map<String, Mapper> SINGLE_MAPPER_PROXY_MAP = new ConcurrentHashMap<>(16);
/**
* Creates a proxy instance for the sub-interfaces of Mapper.
|
MapperProxy
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/bytecode/spi/BytecodeEnhancementMetadata.java
|
{
"start": 996,
"end": 1093
}
|
class ____ bytecode enhanced for lazy loading?
*
* @return {@code true} indicates the entity
|
been
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_isPositive_Test.java
|
{
"start": 878,
"end": 1182
}
|
class ____ extends LongAssertBaseTest {
@Override
protected LongAssert invoke_api_method() {
return assertions.isPositive();
}
@Override
protected void verify_internal_effects() {
verify(longs).assertIsPositive(getInfo(assertions), getActual(assertions));
}
}
|
LongAssert_isPositive_Test
|
java
|
netty__netty
|
codec-http/src/test/java/io/netty/handler/codec/http/EmptyHttpHeadersInitializationTest.java
|
{
"start": 1101,
"end": 1468
}
|
class ____ {
@Test
public void testEmptyHttpHeadersFirst() {
assertNotNull(EmptyHttpHeaders.INSTANCE);
assertNotNull(HttpHeaders.EMPTY_HEADERS);
}
@Test
public void testHttpHeadersFirst() {
assertNotNull(HttpHeaders.EMPTY_HEADERS);
assertNotNull(EmptyHttpHeaders.INSTANCE);
}
}
|
EmptyHttpHeadersInitializationTest
|
java
|
spring-projects__spring-security
|
core/src/main/java/org/springframework/security/authentication/jaas/AbstractJaasAuthenticationProvider.java
|
{
"start": 15105,
"end": 15652
}
|
class ____ implements CallbackHandler {
private final Authentication authentication;
InternalCallbackHandler(Authentication authentication) {
this.authentication = authentication;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (JaasAuthenticationCallbackHandler handler : AbstractJaasAuthenticationProvider.this.callbackHandlers) {
for (Callback callback : callbacks) {
handler.handle(callback, this.authentication);
}
}
}
}
}
|
InternalCallbackHandler
|
java
|
spring-projects__spring-framework
|
spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AnnotationBindingTests.java
|
{
"start": 986,
"end": 1642
}
|
class ____ {
private ClassPathXmlApplicationContext ctx;
private AnnotatedTestBean testBean;
@BeforeEach
void setup() {
this.ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());
testBean = (AnnotatedTestBean) ctx.getBean("testBean");
}
@AfterEach
void tearDown() {
this.ctx.close();
}
@Test
void annotationBindingInAroundAdvice() {
assertThat(testBean.doThis()).isEqualTo("this value");
assertThat(testBean.doThat()).isEqualTo("that value");
}
@Test
void noMatchingWithoutAnnotationPresent() {
assertThat(testBean.doTheOther()).isEqualTo("doTheOther");
}
}
|
AnnotationBindingTests
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/streams/tests/StreamsUpgradeTest.java
|
{
"start": 17777,
"end": 19697
}
|
class ____ extends AssignmentInfo {
private final boolean bumpUsedVersion;
private final boolean bumpSupportedVersion;
final ByteBuffer originalUserMetadata;
private FutureAssignmentInfo(final boolean bumpUsedVersion,
final boolean bumpSupportedVersion,
final ByteBuffer bytes) {
super(LATEST_SUPPORTED_VERSION, LATEST_SUPPORTED_VERSION);
this.bumpUsedVersion = bumpUsedVersion;
this.bumpSupportedVersion = bumpSupportedVersion;
originalUserMetadata = bytes;
}
@Override
public ByteBuffer encode() {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
originalUserMetadata.rewind();
try (final DataOutputStream out = new DataOutputStream(baos)) {
if (bumpUsedVersion) {
originalUserMetadata.getInt(); // discard original used version
out.writeInt(LATEST_SUPPORTED_VERSION + 1);
} else {
out.writeInt(originalUserMetadata.getInt());
}
if (bumpSupportedVersion) {
originalUserMetadata.getInt(); // discard original supported version
out.writeInt(LATEST_SUPPORTED_VERSION + 1);
}
try {
while (true) {
out.write(originalUserMetadata.get());
}
} catch (final BufferUnderflowException expectedWhenAllDataCopied) { }
out.flush();
out.close();
return ByteBuffer.wrap(baos.toByteArray());
} catch (final IOException ex) {
throw new TaskAssignmentException("Failed to encode AssignmentInfo", ex);
}
}
}
}
|
FutureAssignmentInfo
|
java
|
alibaba__nacos
|
api/src/main/java/com/alibaba/nacos/api/ai/model/a2a/AgentProvider.java
|
{
"start": 749,
"end": 1564
}
|
class ____ {
private String organization;
private String url;
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
AgentProvider that = (AgentProvider) o;
return Objects.equals(organization, that.organization) && Objects.equals(url, that.url);
}
@Override
public int hashCode() {
return Objects.hash(organization, url);
}
}
|
AgentProvider
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/schedulers/ExecutorScheduler.java
|
{
"start": 11013,
"end": 11674
}
|
class ____ implements Runnable {
private final SequentialDisposable mar;
private final Runnable decoratedRun;
SequentialDispose(SequentialDisposable mar, Runnable decoratedRun) {
this.mar = mar;
this.decoratedRun = decoratedRun;
}
@Override
public void run() {
mar.replace(schedule(decoratedRun));
}
}
/**
* Wrapper for a {@link Runnable} with additional logic for handling interruption on
* a shared thread, similar to how Java Executors do it.
*/
static final
|
SequentialDispose
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/kryo/KryoSerializerUpgradeTest.java
|
{
"start": 12449,
"end": 12487
}
|
class ____ {}
/** Dummy
|
DummyClassOne
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/ApiKeyAggregationsBuilder.java
|
{
"start": 1778,
"end": 9764
}
|
class ____ {
public static AggregatorFactories.Builder process(
@Nullable AggregatorFactories.Builder aggsBuilder,
@Nullable Consumer<String> fieldNameVisitor
) {
if (aggsBuilder == null) {
return null;
}
// Most of these can be supported without much hassle, but they're not useful for the identified use cases so far
for (PipelineAggregationBuilder pipelineAggregator : aggsBuilder.getPipelineAggregatorFactories()) {
throw new IllegalArgumentException("Unsupported aggregation of type [" + pipelineAggregator.getType() + "]");
}
AggregatorFactories.Builder copiedAggsBuilder = AggregatorFactories.builder();
for (AggregationBuilder aggregationBuilder : aggsBuilder.getAggregatorFactories()) {
copiedAggsBuilder.addAggregator(
translateAggsFields(aggregationBuilder, fieldNameVisitor != null ? fieldNameVisitor : ignored -> {})
);
}
return copiedAggsBuilder;
}
private static AggregationBuilder translateAggsFields(AggregationBuilder aggsBuilder, Consumer<String> fieldNameVisitor) {
return AggregationBuilder.deepCopy(aggsBuilder, copiedAggsBuilder -> {
// Most of these can be supported without much hassle, but they're not useful for the identified use cases so far
for (PipelineAggregationBuilder pipelineAggregator : copiedAggsBuilder.getPipelineAggregations()) {
throw new IllegalArgumentException("Unsupported aggregation of type [" + pipelineAggregator.getType() + "]");
}
if (copiedAggsBuilder instanceof ValuesSourceAggregationBuilder<?> valuesSourceAggregationBuilder) {
if (valuesSourceAggregationBuilder instanceof TermsAggregationBuilder == false
&& valuesSourceAggregationBuilder instanceof RangeAggregationBuilder == false
&& valuesSourceAggregationBuilder instanceof DateRangeAggregationBuilder == false
&& valuesSourceAggregationBuilder instanceof MissingAggregationBuilder == false
&& valuesSourceAggregationBuilder instanceof CardinalityAggregationBuilder == false
&& valuesSourceAggregationBuilder instanceof ValueCountAggregationBuilder == false) {
throw new IllegalArgumentException(
"Unsupported API Keys agg [" + copiedAggsBuilder.getName() + "] of type [" + copiedAggsBuilder.getType() + "]"
);
}
// scripts are not currently supported because it's harder to restrict and rename the doc fields the script has access to
if (valuesSourceAggregationBuilder.script() != null) {
throw new IllegalArgumentException("Unsupported script value source for [" + copiedAggsBuilder.getName() + "] agg");
}
// the user-facing field names are different from the index mapping field names of API Key docs
String translatedFieldName = API_KEY_FIELD_NAME_TRANSLATORS.translate(valuesSourceAggregationBuilder.field());
valuesSourceAggregationBuilder.field(translatedFieldName);
fieldNameVisitor.accept(translatedFieldName);
return valuesSourceAggregationBuilder;
} else if (copiedAggsBuilder instanceof CompositeAggregationBuilder compositeAggregationBuilder) {
for (CompositeValuesSourceBuilder<?> valueSource : compositeAggregationBuilder.sources()) {
if (valueSource.script() != null) {
throw new IllegalArgumentException(
"Unsupported script value source for ["
+ valueSource.name()
+ "] of composite agg ["
+ compositeAggregationBuilder.getName()
+ "]"
);
}
String translatedFieldName = API_KEY_FIELD_NAME_TRANSLATORS.translate(valueSource.field());
valueSource.field(translatedFieldName);
fieldNameVisitor.accept(translatedFieldName);
}
return compositeAggregationBuilder;
} else if (copiedAggsBuilder instanceof FilterAggregationBuilder filterAggregationBuilder) {
// filters the aggregation query to user's allowed API Keys only
FilterAggregationBuilder newFilterAggregationBuilder = new FilterAggregationBuilder(
filterAggregationBuilder.getName(),
API_KEY_FIELD_NAME_TRANSLATORS.translateQueryBuilderFields(filterAggregationBuilder.getFilter(), fieldNameVisitor)
);
if (filterAggregationBuilder.getMetadata() != null) {
newFilterAggregationBuilder.setMetadata(filterAggregationBuilder.getMetadata());
}
for (AggregationBuilder subAgg : filterAggregationBuilder.getSubAggregations()) {
newFilterAggregationBuilder.subAggregation(subAgg);
}
return newFilterAggregationBuilder;
} else if (copiedAggsBuilder instanceof FiltersAggregationBuilder filtersAggregationBuilder) {
// filters the aggregation's bucket queries to user's allowed API Keys only
QueryBuilder[] filterQueryBuilders = new QueryBuilder[filtersAggregationBuilder.filters().size()];
for (int i = 0; i < filtersAggregationBuilder.filters().size(); i++) {
filterQueryBuilders[i] = API_KEY_FIELD_NAME_TRANSLATORS.translateQueryBuilderFields(
filtersAggregationBuilder.filters().get(i).filter(),
fieldNameVisitor
);
}
final FiltersAggregationBuilder newFiltersAggregationBuilder;
if (filtersAggregationBuilder.isKeyed()) {
FiltersAggregator.KeyedFilter[] keyedFilters = new FiltersAggregator.KeyedFilter[filterQueryBuilders.length];
for (int i = 0; i < keyedFilters.length; i++) {
keyedFilters[i] = new FiltersAggregator.KeyedFilter(
filtersAggregationBuilder.filters().get(i).key(),
filterQueryBuilders[i]
);
}
newFiltersAggregationBuilder = new FiltersAggregationBuilder(filtersAggregationBuilder.getName(), keyedFilters);
} else {
newFiltersAggregationBuilder = new FiltersAggregationBuilder(filtersAggregationBuilder.getName(), filterQueryBuilders);
}
assert newFiltersAggregationBuilder.isKeyed() == filtersAggregationBuilder.isKeyed();
newFiltersAggregationBuilder.otherBucket(filtersAggregationBuilder.otherBucket())
.otherBucketKey(filtersAggregationBuilder.otherBucketKey())
.keyedBucket(filtersAggregationBuilder.keyedBucket());
for (AggregationBuilder subAgg : filtersAggregationBuilder.getSubAggregations()) {
newFiltersAggregationBuilder.subAggregation(subAgg);
}
return newFiltersAggregationBuilder;
} else {
// BEWARE: global agg type must NOT be supported!
// This is because "global" breaks out of the search execution context and will expose disallowed API Keys
// (e.g. keys with different owners), as well as other .security docs
throw new IllegalArgumentException(
"Unsupported API Keys agg [" + copiedAggsBuilder.getName() + "] of type [" + copiedAggsBuilder.getType() + "]"
);
}
});
}
}
|
ApiKeyAggregationsBuilder
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/support/GenericXmlContextLoaderResourceLocationsTests.java
|
{
"start": 5075,
"end": 5176
}
|
class ____ {
}
@ContextConfiguration("https://example.com/context.xml")
|
ExplicitFileLocationsTestCase
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/type/AbstractMethodMetadataTests.java
|
{
"start": 8174,
"end": 8265
}
|
interface ____ {
}
@DirectAnnotation
@Retention(RetentionPolicy.RUNTIME)
@
|
DirectAnnotation
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/filecache/DistributedCache.java
|
{
"start": 5353,
"end": 5901
}
|
class ____ methods that should be used by users
* (specifically those mentioned in the example above, as well
* as {@link DistributedCache#addArchiveToClassPath(Path, Configuration)}),
* as well as methods intended for use by the MapReduce framework
* (e.g., {@link org.apache.hadoop.mapred.JobClient}).
*
* @see org.apache.hadoop.mapred.JobConf
* @see org.apache.hadoop.mapred.JobClient
* @see org.apache.hadoop.mapreduce.Job
*/
@SuppressWarnings("deprecation")
@InterfaceAudience.Public
@InterfaceStability.Stable
@Deprecated
public
|
includes
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/ContainerManagementProtocolPB.java
|
{
"start": 1560,
"end": 1801
}
|
interface ____ extends ContainerManagementProtocolService.BlockingInterface {
SignalContainerResponseProto signalToContainer(RpcController arg0,
SignalContainerRequestProto proto) throws ServiceException;
}
|
ContainerManagementProtocolPB
|
java
|
square__retrofit
|
retrofit/src/main/java/retrofit2/RequestFactory.java
|
{
"start": 1997,
"end": 4562
}
|
class ____ {
static RequestFactory parseAnnotations(Retrofit retrofit, Class<?> service, Method method) {
return new Builder(retrofit, service, method).build();
}
private final Class<?> service;
private final Method method;
private final HttpUrl baseUrl;
final String httpMethod;
private final @Nullable String relativeUrl;
private final @Nullable Headers headers;
private final @Nullable MediaType contentType;
private final boolean hasBody;
private final boolean isFormEncoded;
private final boolean isMultipart;
private final ParameterHandler<?>[] parameterHandlers;
final boolean isKotlinSuspendFunction;
RequestFactory(Builder builder) {
service = builder.service;
method = builder.method;
baseUrl = builder.retrofit.baseUrl;
httpMethod = builder.httpMethod;
relativeUrl = builder.relativeUrl;
headers = builder.headers;
contentType = builder.contentType;
hasBody = builder.hasBody;
isFormEncoded = builder.isFormEncoded;
isMultipart = builder.isMultipart;
parameterHandlers = builder.parameterHandlers;
isKotlinSuspendFunction = builder.isKotlinSuspendFunction;
}
okhttp3.Request create(@Nullable Object instance, Object[] args) throws IOException {
@SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;
int argumentCount = args.length;
if (argumentCount != handlers.length) {
throw new IllegalArgumentException(
"Argument count ("
+ argumentCount
+ ") doesn't match expected count ("
+ handlers.length
+ ")");
}
RequestBuilder requestBuilder =
new RequestBuilder(
httpMethod,
baseUrl,
relativeUrl,
headers,
contentType,
hasBody,
isFormEncoded,
isMultipart);
if (isKotlinSuspendFunction) {
// The Continuation is the last parameter and the handlers array contains null at that index.
argumentCount--;
}
List<Object> argumentList = new ArrayList<>(argumentCount);
for (int p = 0; p < argumentCount; p++) {
argumentList.add(args[p]);
handlers[p].apply(requestBuilder, args[p]);
}
return requestBuilder
.get()
.tag(Invocation.class, new Invocation(service, instance, method, argumentList, relativeUrl))
.build();
}
/**
* Inspects the annotations on an
|
RequestFactory
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/ResourceRequestPreMappings.java
|
{
"start": 9121,
"end": 19497
}
|
class ____ {
private final Map<ResourceProfile, Integer> unfulfilledRequired;
private final Map<ResourceProfile, Integer> availableResources;
// The variable to maintain the base mappings result related information, which can
// assure that the allocation for all requests could be run successfully at least.
private final Map<ResourceProfile, Map<ResourceProfile, Integer>>
baseRequiredResourcePreMappings;
private ResourceRequestPreMappingsBuilder(
Collection<PendingRequest> pendingRequests,
Collection<? extends PhysicalSlot> slots) {
this.unfulfilledRequired =
pendingRequests.stream()
.collect(
Collectors.groupingBy(
PendingRequest::getResourceProfile,
Collectors.summingInt(ignored -> 1)));
this.unfulfilledRequired
.keySet()
.forEach(
rp ->
Preconditions.checkState(
!rp.equals(ResourceProfile.ZERO)
&& !rp.equals(ResourceProfile.ANY),
"The required resource must not be ResourceProfile.ZERO and ResourceProfile.ANY."));
this.availableResources =
slots.stream()
.collect(
Collectors.groupingBy(
PhysicalSlot::getResourceProfile,
Collectors.summingInt(ignored -> 1)));
this.availableResources
.keySet()
.forEach(
rp ->
Preconditions.checkState(
!rp.equals(ResourceProfile.UNKNOWN)
&& !rp.equals(ResourceProfile.ZERO),
"The resource profile of a slot must not be ResourceProfile.UNKNOWN and ResourceProfile.ZERO."));
this.baseRequiredResourcePreMappings =
CollectionUtil.newHashMapWithExpectedSize(slots.size());
}
private ResourceRequestPreMappings build() {
if (unfulfilledRequired.isEmpty()
|| availableResources.isEmpty()
|| !canFulfillDesiredResources()) {
return currentPreMappings(false);
}
buildFineGrainedRequestFulfilledExactMapping();
if (isMatchingFulfilled()) {
return currentPreMappings(true);
}
buildRemainingFineGrainedRequestFulfilledAnyMapping();
if (isMatchingFulfilled()) {
return currentPreMappings(true);
}
buildUnknownRequestFulfilledMapping();
return currentPreMappings(isMatchingFulfilled());
}
private void buildFineGrainedRequestFulfilledExactMapping() {
for (Map.Entry<ResourceProfile, Integer> unfulfilledEntry :
new HashMap<>(unfulfilledRequired).entrySet()) {
ResourceProfile requiredFineGrainedResourceProfile = unfulfilledEntry.getKey();
if (ResourceProfile.UNKNOWN.equals(requiredFineGrainedResourceProfile)) {
continue;
}
// checking fine-grained
int unfulfilledFineGrainedRequiredCnt = unfulfilledEntry.getValue();
int availableFineGrainedResourceCnt =
availableResources.getOrDefault(requiredFineGrainedResourceProfile, 0);
if (unfulfilledFineGrainedRequiredCnt <= 0
|| availableFineGrainedResourceCnt <= 0) {
continue;
}
int diff = unfulfilledFineGrainedRequiredCnt - availableFineGrainedResourceCnt;
Map<ResourceProfile, Integer> fulfilledProfileCount =
baseRequiredResourcePreMappings.computeIfAbsent(
requiredFineGrainedResourceProfile, ignored -> new HashMap<>());
fulfilledProfileCount.put(
requiredFineGrainedResourceProfile,
diff > 0
? availableFineGrainedResourceCnt
: unfulfilledFineGrainedRequiredCnt);
int newUnfulfilledFineGrainedRequiredCnt = Math.max(diff, 0);
int unAvailableFineGrainedResourceCnt = Math.max(-diff, 0);
availableResources.put(
requiredFineGrainedResourceProfile, unAvailableFineGrainedResourceCnt);
unfulfilledRequired.put(
requiredFineGrainedResourceProfile, newUnfulfilledFineGrainedRequiredCnt);
}
}
private void buildRemainingFineGrainedRequestFulfilledAnyMapping() {
Integer availableResourceProfileANYCount =
availableResources.getOrDefault(ResourceProfile.ANY, 0);
if (availableResourceProfileANYCount <= 0) {
return;
}
for (Map.Entry<ResourceProfile, Integer> unfulfilledEntry :
new HashMap<>(unfulfilledRequired).entrySet()) {
availableResourceProfileANYCount =
availableResources.getOrDefault(ResourceProfile.ANY, 0);
if (availableResourceProfileANYCount <= 0) {
return;
}
ResourceProfile fineGrainedRequestResourceProfile = unfulfilledEntry.getKey();
if (ResourceProfile.UNKNOWN.equals(fineGrainedRequestResourceProfile)) {
continue;
}
// checking fine-grained
int unfulfilledFineGrainedRequiredCnt =
unfulfilledRequired.getOrDefault(fineGrainedRequestResourceProfile, 0);
if (unfulfilledFineGrainedRequiredCnt <= 0) {
continue;
}
int diff = unfulfilledFineGrainedRequiredCnt - availableResourceProfileANYCount;
Map<ResourceProfile, Integer> fulfilledProfileCount =
baseRequiredResourcePreMappings.computeIfAbsent(
fineGrainedRequestResourceProfile, ignored -> new HashMap<>());
fulfilledProfileCount.put(
ResourceProfile.ANY,
diff > 0
? availableResourceProfileANYCount
: unfulfilledFineGrainedRequiredCnt);
int newUnfulfilledFineGrainedRequiredCnt = Math.max(diff, 0);
int newAvailableResourceProfileANYCount = Math.max(-diff, 0);
availableResources.put(ResourceProfile.ANY, newAvailableResourceProfileANYCount);
unfulfilledRequired.put(
fineGrainedRequestResourceProfile, newUnfulfilledFineGrainedRequiredCnt);
}
}
private void buildUnknownRequestFulfilledMapping() {
if (unfulfilledRequired.getOrDefault(ResourceProfile.UNKNOWN, 0) <= 0) {
return;
}
for (Map.Entry<ResourceProfile, Integer> availableResourceEntry :
new HashMap<>(availableResources).entrySet()) {
Integer unfulfilledUnknownRequiredCnt =
unfulfilledRequired.getOrDefault(ResourceProfile.UNKNOWN, 0);
ResourceProfile availableResourceProfile = availableResourceEntry.getKey();
int availableResourceCnt =
availableResources.getOrDefault(availableResourceProfile, 0);
if (availableResourceCnt <= 0) {
continue;
}
if (unfulfilledUnknownRequiredCnt <= 0) {
return;
}
int diff = unfulfilledUnknownRequiredCnt - availableResourceCnt;
Map<ResourceProfile, Integer> fulfilledProfileCount =
baseRequiredResourcePreMappings.computeIfAbsent(
ResourceProfile.UNKNOWN, ignored -> new HashMap<>());
fulfilledProfileCount.put(
availableResourceProfile,
diff > 0 ? availableResourceCnt : unfulfilledUnknownRequiredCnt);
int newUnfulfilledUnknownRequiredCnt = Math.max(diff, 0);
int newAvailableResourceCnt = Math.max(-diff, 0);
availableResources.put(availableResourceProfile, newAvailableResourceCnt);
unfulfilledRequired.put(ResourceProfile.UNKNOWN, newUnfulfilledUnknownRequiredCnt);
}
}
private ResourceRequestPreMappings currentPreMappings(boolean matchingFulfilled) {
if (!matchingFulfilled) {
return new ResourceRequestPreMappings(false, new HashMap<>(), new HashMap<>());
}
return new ResourceRequestPreMappings(
true,
Collections.unmodifiableMap(baseRequiredResourcePreMappings),
Collections.unmodifiableMap(availableResources));
}
private boolean isMatchingFulfilled() {
for (ResourceProfile unfulfilledProfile : unfulfilledRequired.keySet()) {
Integer unfulfilled = unfulfilledRequired.getOrDefault(unfulfilledProfile, 0);
if (unfulfilled > 0) {
return false;
}
}
return true;
}
private boolean canFulfillDesiredResources() {
Integer totalUnfulfilledCnt =
unfulfilledRequired.values().stream().reduce(0, Integer::sum);
Integer totalAvailableCnt =
availableResources.values().stream().reduce(0, Integer::sum);
return totalAvailableCnt >= totalUnfulfilledCnt;
}
}
}
|
ResourceRequestPreMappingsBuilder
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson/OAuth2AuthorizationRequestDeserializer.java
|
{
"start": 1448,
"end": 3333
}
|
class ____ extends ValueDeserializer<OAuth2AuthorizationRequest> {
private static final StdConverter<JsonNode, AuthorizationGrantType> AUTHORIZATION_GRANT_TYPE_CONVERTER = new StdConverters.AuthorizationGrantTypeConverter();
@Override
public OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context) {
JsonNode root = context.readTree(parser);
return deserialize(parser, context, root);
}
private OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context, JsonNode root) {
AuthorizationGrantType authorizationGrantType = AUTHORIZATION_GRANT_TYPE_CONVERTER
.convert(JsonNodeUtils.findObjectNode(root, "authorizationGrantType"));
Builder builder = getBuilder(parser, authorizationGrantType);
builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri"));
builder.clientId(JsonNodeUtils.findStringValue(root, "clientId"));
builder.redirectUri(JsonNodeUtils.findStringValue(root, "redirectUri"));
builder.scopes(JsonNodeUtils.findValue(root, "scopes", JsonNodeUtils.STRING_SET, context));
builder.state(JsonNodeUtils.findStringValue(root, "state"));
builder.additionalParameters(
JsonNodeUtils.findValue(root, "additionalParameters", JsonNodeUtils.STRING_OBJECT_MAP, context));
builder.authorizationRequestUri(JsonNodeUtils.findStringValue(root, "authorizationRequestUri"));
builder.attributes(JsonNodeUtils.findValue(root, "attributes", JsonNodeUtils.STRING_OBJECT_MAP, context));
return builder.build();
}
private Builder getBuilder(JsonParser parser, AuthorizationGrantType authorizationGrantType) {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) {
return OAuth2AuthorizationRequest.authorizationCode();
}
throw new StreamReadException(parser, "Invalid authorizationGrantType");
}
}
|
OAuth2AuthorizationRequestDeserializer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.