language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
google__dagger
javatests/dagger/hilt/processor/internal/root/RootFileFormatterTest.java
{ "start": 6087, "end": 6681 }
class ____ {}"), entryPoint("SingletonComponent", "EntryPoint1")) .withProcessorOptions( ImmutableMap.of("dagger.hilt.shareTestComponents", Boolean.toString(true))) .compile( subject -> { subject.hasErrorCount(0); StringSubject stringSubject = subject.generatedSourceFileWithPath( "dagger/hilt/android/internal/testing/root/Default_HiltComponents.java"); stringSubject.contains( JOINER.join( " public abstract static
MyTest
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/SockJsWebSocketHandler.java
{ "start": 1680, "end": 2172 }
class ____ exceptions from the wrapped {@link WebSocketHandler} to * propagate. However, any exceptions resulting from SockJS message handling (for example, while * sending SockJS frames or heartbeat messages) are caught and treated as transport * errors, i.e. routed to the * {@link WebSocketHandler#handleTransportError(WebSocketSession, Throwable) * handleTransportError} method of the wrapped handler and the session closed. * * @author Rossen Stoyanchev * @since 4.0 */ public
allow
java
spring-projects__spring-boot
module/spring-boot-data-jdbc-test/src/test/java/org/springframework/boot/data/jdbc/test/autoconfigure/DataJdbcTestPropertiesIntegrationTests.java
{ "start": 1370, "end": 1724 }
class ____ { @Autowired private Environment innerEnvironment; @Test void propertiesFromEnclosingClassAffectNestedTests() { assertThat(DataJdbcTestPropertiesIntegrationTests.this.environment.getActiveProfiles()) .containsExactly("test"); assertThat(this.innerEnvironment.getActiveProfiles()).containsExactly("test"); } } }
NestedTests
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/Archiveable.java
{ "start": 937, "end": 1004 }
interface ____<T extends Serializable> { T archive(); }
Archiveable
java
netty__netty
common/src/test/java/io/netty/util/internal/TypeParameterMatcherTest.java
{ "start": 4620, "end": 4672 }
class ____<E> { E e; } private static
W
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/config/JmsListenerEndpointRegistrar.java
{ "start": 1422, "end": 7212 }
class ____ implements BeanFactoryAware, InitializingBean { private @Nullable JmsListenerEndpointRegistry endpointRegistry; private @Nullable MessageHandlerMethodFactory messageHandlerMethodFactory; private @Nullable JmsListenerContainerFactory<?> containerFactory; private @Nullable String containerFactoryBeanName; private @Nullable BeanFactory beanFactory; private final List<JmsListenerEndpointDescriptor> endpointDescriptors = new ArrayList<>(); private boolean startImmediately; /** * Set the {@link JmsListenerEndpointRegistry} instance to use. */ public void setEndpointRegistry(@Nullable JmsListenerEndpointRegistry endpointRegistry) { this.endpointRegistry = endpointRegistry; } /** * Return the {@link JmsListenerEndpointRegistry} instance for this * registrar, may be {@code null}. */ public @Nullable JmsListenerEndpointRegistry getEndpointRegistry() { return this.endpointRegistry; } /** * Set the {@link MessageHandlerMethodFactory} to use to configure the message * listener responsible to serve an endpoint detected by this processor. * <p>By default, {@link DefaultMessageHandlerMethodFactory} is used and it * can be configured further to support additional method arguments * or to customize conversion and validation support. See * {@link DefaultMessageHandlerMethodFactory} javadoc for more details. */ public void setMessageHandlerMethodFactory(@Nullable MessageHandlerMethodFactory messageHandlerMethodFactory) { this.messageHandlerMethodFactory = messageHandlerMethodFactory; } /** * Return the custom {@link MessageHandlerMethodFactory} to use, if any. */ public @Nullable MessageHandlerMethodFactory getMessageHandlerMethodFactory() { return this.messageHandlerMethodFactory; } /** * Set the {@link JmsListenerContainerFactory} to use in case a {@link JmsListenerEndpoint} * is registered with a {@code null} container factory. * <p>Alternatively, the bean name of the {@link JmsListenerContainerFactory} to use * can be specified for a lazy lookup, see {@link #setContainerFactoryBeanName}. */ public void setContainerFactory(JmsListenerContainerFactory<?> containerFactory) { this.containerFactory = containerFactory; } /** * Set the bean name of the {@link JmsListenerContainerFactory} to use in case * a {@link JmsListenerEndpoint} is registered with a {@code null} container factory. * Alternatively, the container factory instance can be registered directly: * see {@link #setContainerFactory(JmsListenerContainerFactory)}. * @see #setBeanFactory */ public void setContainerFactoryBeanName(String containerFactoryBeanName) { this.containerFactoryBeanName = containerFactoryBeanName; } /** * A {@link BeanFactory} only needs to be available in conjunction with * {@link #setContainerFactoryBeanName}. */ @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public void afterPropertiesSet() { registerAllEndpoints(); } protected void registerAllEndpoints() { Assert.state(this.endpointRegistry != null, "No JmsListenerEndpointRegistry set"); for (JmsListenerEndpointDescriptor descriptor : this.endpointDescriptors) { this.endpointRegistry.registerListenerContainer( descriptor.endpoint, resolveContainerFactory(descriptor)); } this.startImmediately = true; // trigger immediate startup } private JmsListenerContainerFactory<?> resolveContainerFactory(JmsListenerEndpointDescriptor descriptor) { if (descriptor.containerFactory != null) { return descriptor.containerFactory; } else if (this.containerFactory != null) { return this.containerFactory; } else if (this.containerFactoryBeanName != null) { Assert.state(this.beanFactory != null, "BeanFactory must be set to obtain container factory by bean name"); // Consider changing this if live change of the factory is required... this.containerFactory = this.beanFactory.getBean( this.containerFactoryBeanName, JmsListenerContainerFactory.class); return this.containerFactory; } else { throw new IllegalStateException("Could not resolve the " + JmsListenerContainerFactory.class.getSimpleName() + " to use for [" + descriptor.endpoint + "] no factory was given and no default is set."); } } /** * Register a new {@link JmsListenerEndpoint} alongside the * {@link JmsListenerContainerFactory} to use to create the underlying container. * <p>The {@code factory} may be {@code null} if the default factory should be * used for the supplied endpoint. */ public void registerEndpoint(JmsListenerEndpoint endpoint, @Nullable JmsListenerContainerFactory<?> factory) { Assert.notNull(endpoint, "Endpoint must not be null"); Assert.hasText(endpoint.getId(), "Endpoint id must be set"); // Factory may be null, we defer the resolution right before actually creating the container JmsListenerEndpointDescriptor descriptor = new JmsListenerEndpointDescriptor(endpoint, factory); if (this.startImmediately) { // register and start immediately Assert.state(this.endpointRegistry != null, "No JmsListenerEndpointRegistry set"); this.endpointRegistry.registerListenerContainer(descriptor.endpoint, resolveContainerFactory(descriptor), true); } else { this.endpointDescriptors.add(descriptor); } } /** * Register a new {@link JmsListenerEndpoint} using the default * {@link JmsListenerContainerFactory} to create the underlying container. * @see #setContainerFactory(JmsListenerContainerFactory) * @see #registerEndpoint(JmsListenerEndpoint, JmsListenerContainerFactory) */ public void registerEndpoint(JmsListenerEndpoint endpoint) { registerEndpoint(endpoint, null); } private static
JmsListenerEndpointRegistrar
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/DeferredLogTests.java
{ "start": 1073, "end": 4867 }
class ____ { private final DeferredLog deferredLog = new DeferredLog(); private final Object message = "Message"; private final Throwable throwable = new IllegalStateException(); private final Log log = mock(Log.class); @Test void isTraceEnabled() { assertThat(this.deferredLog.isTraceEnabled()).isTrue(); } @Test void isDebugEnabled() { assertThat(this.deferredLog.isDebugEnabled()).isTrue(); } @Test void isInfoEnabled() { assertThat(this.deferredLog.isInfoEnabled()).isTrue(); } @Test void isWarnEnabled() { assertThat(this.deferredLog.isWarnEnabled()).isTrue(); } @Test void isErrorEnabled() { assertThat(this.deferredLog.isErrorEnabled()).isTrue(); } @Test void isFatalEnabled() { assertThat(this.deferredLog.isFatalEnabled()).isTrue(); } @Test void trace() { this.deferredLog.trace(this.message); this.deferredLog.replayTo(this.log); then(this.log).should().trace(this.message, null); } @Test void traceWithThrowable() { this.deferredLog.trace(this.message, this.throwable); this.deferredLog.replayTo(this.log); then(this.log).should().trace(this.message, this.throwable); } @Test void debug() { this.deferredLog.debug(this.message); this.deferredLog.replayTo(this.log); then(this.log).should().debug(this.message, null); } @Test void debugWithThrowable() { this.deferredLog.debug(this.message, this.throwable); this.deferredLog.replayTo(this.log); then(this.log).should().debug(this.message, this.throwable); } @Test void info() { this.deferredLog.info(this.message); this.deferredLog.replayTo(this.log); then(this.log).should().info(this.message, null); } @Test void infoWithThrowable() { this.deferredLog.info(this.message, this.throwable); this.deferredLog.replayTo(this.log); then(this.log).should().info(this.message, this.throwable); } @Test void warn() { this.deferredLog.warn(this.message); this.deferredLog.replayTo(this.log); then(this.log).should().warn(this.message, null); } @Test void warnWithThrowable() { this.deferredLog.warn(this.message, this.throwable); this.deferredLog.replayTo(this.log); then(this.log).should().warn(this.message, this.throwable); } @Test void error() { this.deferredLog.error(this.message); this.deferredLog.replayTo(this.log); then(this.log).should().error(this.message, null); } @Test void errorWithThrowable() { this.deferredLog.error(this.message, this.throwable); this.deferredLog.replayTo(this.log); then(this.log).should().error(this.message, this.throwable); } @Test void fatal() { this.deferredLog.fatal(this.message); this.deferredLog.replayTo(this.log); then(this.log).should().fatal(this.message, null); } @Test void fatalWithThrowable() { this.deferredLog.fatal(this.message, this.throwable); this.deferredLog.replayTo(this.log); then(this.log).should().fatal(this.message, this.throwable); } @Test void clearsOnReplayTo() { this.deferredLog.info("1"); this.deferredLog.fatal("2"); Log log2 = mock(Log.class); this.deferredLog.replayTo(this.log); this.deferredLog.replayTo(log2); then(this.log).should().info("1", null); then(this.log).should().fatal("2", null); then(this.log).shouldHaveNoMoreInteractions(); then(log2).shouldHaveNoInteractions(); } @Test void switchTo() { Lines lines = (Lines) ReflectionTestUtils.getField(this.deferredLog, "lines"); assertThat(lines).isEmpty(); this.deferredLog.error(this.message, this.throwable); assertThat(lines).hasSize(1); this.deferredLog.switchTo(this.log); assertThat(lines).isEmpty(); this.deferredLog.info("Message2"); assertThat(lines).isEmpty(); then(this.log).should().error(this.message, this.throwable); then(this.log).should().info("Message2", null); } }
DeferredLogTests
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/ThreadCache.java
{ "start": 11332, "end": 13089 }
class ____ implements PeekingKeyValueIterator<Bytes, LRUCacheEntry> { private final Iterator<Bytes> keys; private final NamedCache cache; private KeyValue<Bytes, LRUCacheEntry> nextEntry; MemoryLRUCacheBytesIterator(final Iterator<Bytes> keys, final NamedCache cache) { this.keys = keys; this.cache = cache; } public Bytes peekNextKey() { if (!hasNext()) { throw new NoSuchElementException(); } return nextEntry.key; } public KeyValue<Bytes, LRUCacheEntry> peekNext() { if (!hasNext()) { throw new NoSuchElementException(); } return nextEntry; } @Override public boolean hasNext() { if (nextEntry != null) { return true; } while (keys.hasNext() && nextEntry == null) { internalNext(); } return nextEntry != null; } @Override public KeyValue<Bytes, LRUCacheEntry> next() { if (!hasNext()) { throw new NoSuchElementException(); } final KeyValue<Bytes, LRUCacheEntry> result = nextEntry; nextEntry = null; return result; } private void internalNext() { final Bytes cacheKey = keys.next(); final LRUCacheEntry entry = cache.get(cacheKey); if (entry == null) { return; } nextEntry = new KeyValue<>(cacheKey, entry); } @Override public void close() { // do nothing } } static
MemoryLRUCacheBytesIterator
java
quarkusio__quarkus
integration-tests/logging-min-level-set/src/main/java/io/quarkus/it/logging/minlevel/set/below/LoggingMinLevelBelow.java
{ "start": 293, "end": 594 }
class ____ { static final Logger LOG = Logger.getLogger(LoggingMinLevelBelow.class); @GET @Path("/trace") @Produces(MediaType.TEXT_PLAIN) public boolean isTrace() { return LOG.isTraceEnabled() && LoggingWitness.loggedTrace("trace-message", LOG); } }
LoggingMinLevelBelow
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFlatMapNotification.java
{ "start": 2179, "end": 5359 }
class ____<T, R> extends AtomicReference<Disposable> implements MaybeObserver<T>, Disposable { private static final long serialVersionUID = 4375739915521278546L; final MaybeObserver<? super R> downstream; final Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper; final Function<? super Throwable, ? extends MaybeSource<? extends R>> onErrorMapper; final Supplier<? extends MaybeSource<? extends R>> onCompleteSupplier; Disposable upstream; FlatMapMaybeObserver(MaybeObserver<? super R> actual, Function<? super T, ? extends MaybeSource<? extends R>> onSuccessMapper, Function<? super Throwable, ? extends MaybeSource<? extends R>> onErrorMapper, Supplier<? extends MaybeSource<? extends R>> onCompleteSupplier) { this.downstream = actual; this.onSuccessMapper = onSuccessMapper; this.onErrorMapper = onErrorMapper; this.onCompleteSupplier = onCompleteSupplier; } @Override public void dispose() { DisposableHelper.dispose(this); upstream.dispose(); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); } } @Override public void onSuccess(T value) { MaybeSource<? extends R> source; try { source = Objects.requireNonNull(onSuccessMapper.apply(value), "The onSuccessMapper returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); downstream.onError(ex); return; } if (!isDisposed()) { source.subscribe(new InnerObserver()); } } @Override public void onError(Throwable e) { MaybeSource<? extends R> source; try { source = Objects.requireNonNull(onErrorMapper.apply(e), "The onErrorMapper returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); downstream.onError(new CompositeException(e, ex)); return; } if (!isDisposed()) { source.subscribe(new InnerObserver()); } } @Override public void onComplete() { MaybeSource<? extends R> source; try { source = Objects.requireNonNull(onCompleteSupplier.get(), "The onCompleteSupplier returned a null MaybeSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); downstream.onError(ex); return; } if (!isDisposed()) { source.subscribe(new InnerObserver()); } } final
FlatMapMaybeObserver
java
grpc__grpc-java
testing-proto/src/generated/main/grpc/io/grpc/testing/protobuf/SimpleServiceGrpc.java
{ "start": 23560, "end": 24159 }
class ____ implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { SimpleServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return io.grpc.testing.protobuf.SimpleServiceProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("SimpleService"); } } private static final
SimpleServiceBaseDescriptorSupplier
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/sps/ExternalSPSContext.java
{ "start": 7303, "end": 8004 }
class ____ implements BlockMovementListener { private List<Block> actualBlockMovements = new ArrayList<>(); @Override public void notifyMovementTriedBlocks(Block[] moveAttemptFinishedBlks) { for (Block block : moveAttemptFinishedBlks) { actualBlockMovements.add(block); } LOG.info("Movement attempted blocks", actualBlockMovements); } } public void initMetrics(StoragePolicySatisfier sps) { spsBeanMetrics = new ExternalSPSBeanMetrics(sps); } public void closeMetrics() { spsBeanMetrics.close(); } @VisibleForTesting public ExternalSPSBeanMetrics getSpsBeanMetrics() { return spsBeanMetrics; } }
ExternalBlockMovementListener
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TruthContainsExactlyElementsInUsageTest.java
{ "start": 12825, "end": 13197 }
class ____ { void test() { assertThat(ImmutableList.of(1, 2, 3)).containsExactlyElementsIn(new Integer[] {1, 2, 3}); } } """) .addOutputLines( "ExampleClassTest.java", """ import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; public
ExampleClassTest
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/autoconfigure/error/ErrorViewResolver.java
{ "start": 1051, "end": 1471 }
interface ____ { /** * Resolve an error view for the specified details. * @param request the source request * @param status the http status of the error * @param model the suggested model to be used with the view * @return a resolved {@link ModelAndView} or {@code null} */ @Nullable ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model); }
ErrorViewResolver
java
grpc__grpc-java
services/src/generated/test/grpc/io/grpc/reflection/testing/AnotherReflectableServiceGrpc.java
{ "start": 11975, "end": 12178 }
class ____ extends AnotherReflectableServiceBaseDescriptorSupplier { AnotherReflectableServiceFileDescriptorSupplier() {} } private static final
AnotherReflectableServiceFileDescriptorSupplier
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_895/MultiArrayMapper.java
{ "start": 442, "end": 678 }
class ____ { private byte[][] bytes; public byte[][] getBytes() { return bytes; } public void setBytes(byte[][] bytes) { this.bytes = bytes; } }
WithArrayOfByteArray
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine2.java
{ "start": 26487, "end": 27610 }
class ____ extends RpcWritable.Buffer { private volatile RequestHeaderProto requestHeader; private Message payload; RpcProtobufRequest() { } RpcProtobufRequest(RequestHeaderProto header, Message payload) { this.requestHeader = header; this.payload = payload; } RequestHeaderProto getRequestHeader() throws IOException { if (getByteBuffer() != null && requestHeader == null) { requestHeader = getValue(RequestHeaderProto.getDefaultInstance()); } return requestHeader; } @Override public void writeTo(ResponseBuffer out) throws IOException { requestHeader.writeDelimitedTo(out); if (payload != null) { payload.writeDelimitedTo(out); } } // this is used by htrace to name the span. @Override public String toString() { try { RequestHeaderProto header = getRequestHeader(); return header.getDeclaringClassProtocolName() + "." + header.getMethodName(); } catch (IOException e) { throw new IllegalArgumentException(e); } } } }
RpcProtobufRequest
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ext/DOMSerializer.java
{ "start": 501, "end": 2807 }
class ____ extends StdSerializer<Node> { protected final TransformerFactory transformerFactory; public DOMSerializer() { super(Node.class); try { transformerFactory = TransformerFactory.newInstance(); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // 22-Mar-2023, tatu: [databind#3837] add these 2 settings further setTransformerFactoryAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_DTD, ""); setTransformerFactoryAttribute(transformerFactory, XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); } catch (Exception e) { throw new IllegalStateException("Could not instantiate `TransformerFactory`: "+e.getMessage(), e); } } @Override public void serialize(Node value, JsonGenerator g, SerializationContext provider) throws JacksonException { try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(new DOMSource(value), result); g.writeString(result.getWriter().toString()); } catch (TransformerConfigurationException e) { throw new IllegalStateException("Could not create XML Transformer for writing DOM `Node` value: "+e.getMessage(), e); } catch (TransformerException e) { provider.reportMappingProblem(e, "DOM `Node` value serialization failed: %s", e.getMessage()); } } @Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) { if (visitor != null) visitor.expectAnyFormat(typeHint); } private static void setTransformerFactoryAttribute(final TransformerFactory transformerFactory, final String name, final Object value) { try { transformerFactory.setAttribute(name, value); } catch (Exception e) { System.err.println("[DOMSerializer] Failed to set TransformerFactory attribute: " + name); } } }
DOMSerializer
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/converter/ObjectConverterTest.java
{ "start": 1391, "end": 9448 }
class ____ { @Test public void testIterator() { Iterator<?> it = ObjectConverter.iterator("Claus,Jonathan"); assertEquals("Claus", it.next()); assertEquals("Jonathan", it.next()); assertFalse(it.hasNext()); } @Test public void testStreamIterator() { Iterator<?> it = ObjectConverter.iterator(Stream.of("Claus", "Jonathan", "Andrea")); assertEquals("Claus", it.next()); assertEquals("Jonathan", it.next()); assertEquals("Andrea", it.next()); assertFalse(it.hasNext()); } @SuppressWarnings("unchecked") @Test public void testIterable() { for (final String name : (Iterable<String>) ObjectConverter.iterable("Claus,Jonathan")) { switch (name) { case "Claus": case "Jonathan": break; default: fail(); } } } @Test public void testToByte() { assertEquals(Byte.valueOf("4"), ObjectConverter.toByte(Byte.valueOf("4"))); assertEquals(Byte.valueOf("4"), ObjectConverter.toByte(Integer.valueOf("4"))); assertEquals(Byte.valueOf("4"), ObjectConverter.toByte("4")); assertEquals(Byte.valueOf("4"), ObjectConverter.toByte("4".getBytes(StandardCharsets.UTF_8), null)); } @Test public void testToClass() { assertEquals(String.class, ObjectConverter.toClass("java.lang.String", null)); assertNull(ObjectConverter.toClass("foo.Bar", null)); } @Test public void testToShort() { assertEquals(Short.valueOf("4"), ObjectConverter.toShort(Short.valueOf("4"))); assertEquals(Short.valueOf("4"), ObjectConverter.toShort(Integer.valueOf("4"))); assertEquals(Short.valueOf("4"), ObjectConverter.toShort("4")); assertEquals(Short.valueOf("4"), ObjectConverter.toShort("4".getBytes(StandardCharsets.UTF_8), null)); assertNull(ObjectConverter.toShort(Double.NaN)); assertNull(ObjectConverter.toShort(Float.NaN)); assertEquals(Short.valueOf("4"), ObjectConverter.toShort(Short.valueOf("4"))); } @Test public void testToInteger() { assertEquals(Integer.valueOf("4"), ObjectConverter.toInteger(Integer.valueOf("4"))); assertEquals(Integer.valueOf("4"), ObjectConverter.toInteger(Long.valueOf("4"))); assertEquals(Integer.valueOf("4"), ObjectConverter.toInteger("4")); assertEquals(Integer.valueOf("4"), ObjectConverter.toInteger("4".getBytes(StandardCharsets.UTF_8), null)); assertNull(ObjectConverter.toInteger(Double.NaN)); assertNull(ObjectConverter.toInteger(Float.NaN)); assertEquals(Integer.valueOf("4"), ObjectConverter.toInteger(Integer.valueOf("4"))); assertEquals(Integer.valueOf("1234"), ObjectConverter.toInteger(new byte[] { 49, 50, 51, 52 }, null)); } @Test public void testToLong() { assertEquals(Long.valueOf("4"), ObjectConverter.toLong(Long.valueOf("4"))); assertEquals(Long.valueOf("4"), ObjectConverter.toLong(Integer.valueOf("4"))); assertEquals(Long.valueOf("4"), ObjectConverter.toLong("4")); assertEquals(Long.valueOf("4"), ObjectConverter.toLong("4".getBytes(StandardCharsets.UTF_8), null)); assertNull(ObjectConverter.toLong(Double.NaN)); assertNull(ObjectConverter.toLong(Float.NaN)); assertEquals(Long.valueOf("4"), ObjectConverter.toLong(Long.valueOf("4"))); assertEquals(Long.valueOf("1234"), ObjectConverter.toLong(new byte[] { 49, 50, 51, 52 }, null)); } @Test public void testToFloat() { assertEquals(Float.valueOf("4"), ObjectConverter.toFloat(Float.valueOf("4"))); assertEquals(Float.valueOf("4"), ObjectConverter.toFloat(Integer.valueOf("4"))); assertEquals(Float.valueOf("4"), ObjectConverter.toFloat("4")); assertEquals(Float.valueOf("4"), ObjectConverter.toFloat("4".getBytes(StandardCharsets.UTF_8), null)); assertEquals((Float) Float.NaN, ObjectConverter.toFloat(Double.NaN)); assertEquals((Float) Float.NaN, ObjectConverter.toFloat(Float.NaN)); assertEquals(Float.valueOf("4"), ObjectConverter.toFloat(Float.valueOf("4"))); } @Test public void testToDouble() { assertEquals(Double.valueOf("4"), ObjectConverter.toDouble(Double.valueOf("4"))); assertEquals(Double.valueOf("4"), ObjectConverter.toDouble(Integer.valueOf("4"))); assertEquals(Double.valueOf("4"), ObjectConverter.toDouble("4")); assertEquals(Double.valueOf("4"), ObjectConverter.toDouble("4".getBytes(StandardCharsets.UTF_8), null)); assertEquals((Double) Double.NaN, ObjectConverter.toDouble(Double.NaN)); assertEquals((Double) Double.NaN, ObjectConverter.toDouble(Float.NaN)); assertEquals(Double.valueOf("4"), ObjectConverter.toDouble(Double.valueOf("4"))); } @Test public void testToBigInteger() { assertEquals(BigInteger.valueOf(4), ObjectConverter.toBigInteger(Long.valueOf("4"))); assertEquals(BigInteger.valueOf(4), ObjectConverter.toBigInteger(Integer.valueOf("4"))); assertEquals(BigInteger.valueOf(4), ObjectConverter.toBigInteger("4")); assertEquals(BigInteger.valueOf(123456789L), ObjectConverter.toBigInteger("123456789")); assertNull(ObjectConverter.toBigInteger(new Date())); assertNull(ObjectConverter.toBigInteger(Double.NaN)); assertNull(ObjectConverter.toBigInteger(Float.NaN)); assertEquals(BigInteger.valueOf(4), ObjectConverter.toBigInteger(Long.valueOf("4"))); assertEquals(new BigInteger("14350442579497085228"), ObjectConverter.toBigInteger("14350442579497085228")); } @Test public void testToString() { assertEquals("ABC", ObjectConverter.toString(new StringBuffer("ABC"))); assertEquals("ABC", ObjectConverter.toString(new StringBuilder("ABC"))); assertEquals("", ObjectConverter.toString(new StringBuffer())); assertEquals("", ObjectConverter.toString(new StringBuilder())); } @Test public void testToChar() { assertEquals('A', ObjectConverter.toChar("A")); assertEquals('A', ObjectConverter.toChar("A".getBytes(StandardCharsets.UTF_8))); assertEquals(Character.valueOf('A'), ObjectConverter.toCharacter("A")); assertEquals(Character.valueOf('A'), ObjectConverter.toCharacter("A".getBytes(StandardCharsets.UTF_8))); } @Test public void testNaN() { assertEquals((Double) Double.NaN, ObjectConverter.toDouble(Double.NaN)); assertEquals((Double) Double.NaN, ObjectConverter.toDouble(Float.NaN)); assertEquals((Float) Float.NaN, ObjectConverter.toFloat(Double.NaN)); assertEquals((Float) Float.NaN, ObjectConverter.toFloat(Float.NaN)); } @Test public void testToBoolean() { assertTrue(ObjectConverter.toBoolean("true")); assertTrue(ObjectConverter.toBoolean("true".getBytes(StandardCharsets.UTF_8))); assertTrue(ObjectConverter.toBoolean("TRUE")); assertFalse(ObjectConverter.toBoolean("false")); assertFalse(ObjectConverter.toBoolean("FALSE")); assertNull(ObjectConverter.toBoolean("1")); assertNull(ObjectConverter.toBoolean("")); assertNull(ObjectConverter.toBoolean("yes")); assertTrue(ObjectConverter.toBool("true")); assertTrue(ObjectConverter.toBool("true".getBytes(StandardCharsets.UTF_8))); assertTrue(ObjectConverter.toBool("TRUE")); assertFalse(ObjectConverter.toBool("false")); assertFalse(ObjectConverter.toBool("FALSE")); // primitive boolean is stricter assertThrows(IllegalArgumentException.class, () -> ObjectConverter.toBool("1"), "Should throw exception"); assertThrows(IllegalArgumentException.class, () -> ObjectConverter.toBool(""), "Should throw exception"); assertThrows(IllegalArgumentException.class, () -> ObjectConverter.toBool("yes"), "Should throw exception"); } }
ObjectConverterTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 65326, "end": 65552 }
class ____ { @Bean @Lazy @Scope(proxyMode = ScopedProxyMode.INTERFACES) public ITestBean scopedClass() { return new TestBean(); } } @Configuration(proxyBeanMethods = false) public static
ScopedProxyConfigurationClass
java
apache__spark
examples/src/main/java/org/apache/spark/examples/sql/streaming/JavaStructuredComplexSessionization.java
{ "start": 11748, "end": 12496 }
class ____ { private List<SessionAcc> sessions; public List<SessionAcc> getSessions() { return sessions; } public void setSessions(List<SessionAcc> sessions) { // `sessions` should not be empty, and be sorted by start time if (sessions.isEmpty()) { throw new IllegalArgumentException("events should not be empty!"); } List<SessionAcc> sorted = new ArrayList<>(sessions); sorted.sort(Comparator.comparingLong(session -> session.startTime().getTime())); this.sessions = sorted; } public static Sessions newInstance(List<SessionAcc> sessions) { Sessions instance = new Sessions(); instance.setSessions(sessions); return instance; } } public
Sessions
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/aot/hint/OAuth2AuthorizationServerBeanRegistrationAotProcessor.java
{ "start": 5302, "end": 16493 }
class ____ implements BeanRegistrationAotContribution { private final BindingReflectionHintsRegistrar reflectionHintsRegistrar = new BindingReflectionHintsRegistrar(); @Override public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { registerHints(generationContext.getRuntimeHints()); } private void registerHints(RuntimeHints hints) { // Collections -> UnmodifiableSet, UnmodifiableList, UnmodifiableMap, // UnmodifiableRandomAccessList, etc. hints.reflection().registerType(Collections.class, MemberCategory.DECLARED_CLASSES); // HashSet hints.reflection() .registerType(HashSet.class, MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS); hints.reflection() .registerTypes(Arrays.asList(TypeReference.of(AbstractAuthenticationToken.class), TypeReference.of(DefaultSavedRequest.Builder.class), TypeReference.of(WebAuthenticationDetails.class), TypeReference.of(UsernamePasswordAuthenticationToken.class), TypeReference.of(User.class), TypeReference.of(DefaultOidcUser.class), TypeReference.of(DefaultOAuth2User.class), TypeReference.of(OidcUserAuthority.class), TypeReference.of(OAuth2UserAuthority.class), TypeReference.of(SimpleGrantedAuthority.class), TypeReference.of(OidcIdToken.class), TypeReference.of(AbstractOAuth2Token.class), TypeReference.of(OidcUserInfo.class), TypeReference.of(OAuth2TokenExchangeActor.class), TypeReference.of(OAuth2AuthorizationRequest.class), TypeReference.of(OAuth2TokenExchangeCompositeAuthenticationToken.class), TypeReference.of(AuthorizationGrantType.class), TypeReference.of(OAuth2AuthorizationResponseType.class), TypeReference.of(OAuth2TokenFormat.class)), (builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS)); // Jackson Modules if (jackson2Present) { hints.reflection() .registerTypes( Arrays.asList(TypeReference.of(CoreJackson2Module.class), TypeReference.of(WebServletJackson2Module.class), TypeReference.of(OAuth2AuthorizationServerJackson2Module.class)), (builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS)); } if (jackson3Present) { hints.reflection() .registerTypes( Arrays.asList(TypeReference.of(CoreJacksonModule.class), TypeReference.of(WebServletJacksonModule.class), TypeReference.of(OAuth2AuthorizationServerJacksonModule.class)), (builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS)); } // Jackson Mixins if (jackson2Present) { this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson2.UnmodifiableSetMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson2.UnmodifiableListMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson2.UnmodifiableMapMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson2.UnmodifiableMapMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.server.authorization.jackson2.HashSetMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.web.jackson2.DefaultSavedRequestMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.web.jackson2.WebAuthenticationDetailsMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson2.UserMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson2.SimpleGrantedAuthorityMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson2.OAuth2TokenExchangeActorMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationRequestMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson2.OAuth2TokenExchangeCompositeAuthenticationTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson2.OAuth2TokenFormatMixin")); } if (jackson3Present) { this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.web.jackson.DefaultSavedRequestMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.web.jackson.WebAuthenticationDetailsMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson.UsernamePasswordAuthenticationTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson.UserMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.jackson.SimpleGrantedAuthorityMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson.OAuth2TokenExchangeActorMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson.OAuth2AuthorizationRequestMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson.OAuth2TokenExchangeCompositeAuthenticationTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.server.authorization.jackson.OAuth2TokenFormatMixin")); } // Check if OAuth2 Client is on classpath if (ClassUtils.isPresent("org.springframework.security.oauth2.client.registration.ClientRegistration", ClassUtils.getDefaultClassLoader())) { hints.reflection() .registerType(TypeReference .of("org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken"), (builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS)); // Jackson Module if (jackson2Present) { hints.reflection() .registerType(TypeReference .of("org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module"), (builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS)); } if (jackson3Present) { hints.reflection() .registerType( TypeReference .of("org.springframework.security.oauth2.client.jackson.OAuth2ClientJacksonModule"), (builder) -> builder.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_METHODS)); } // Jackson Mixins if (jackson2Present) { this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.client.jackson2.OAuth2AuthenticationTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson2.DefaultOidcUserMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson2.DefaultOAuth2UserMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson2.OidcUserAuthorityMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson2.OAuth2UserAuthorityMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson2.OidcIdTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson2.OidcUserInfoMixin")); } if (jackson3Present) { this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass( "org.springframework.security.oauth2.client.jackson.OAuth2AuthenticationTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson.DefaultOidcUserMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson.DefaultOAuth2UserMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson.OidcUserAuthorityMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson.OAuth2UserAuthorityMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson.OidcIdTokenMixin")); this.reflectionHintsRegistrar.registerReflectionHints(hints.reflection(), loadClass("org.springframework.security.oauth2.client.jackson.OidcUserInfoMixin")); } } } private static Class<?> loadClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } } }
JacksonConfigurationBeanRegistrationAotContribution
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/scheduling/annotation/EnableSchedulingTests.java
{ "start": 15505, "end": 16344 }
class ____ { String threadName; @Bean @Qualifier("myScheduler") public TaskScheduler taskScheduler1() { SimpleAsyncTaskScheduler scheduler = new SimpleAsyncTaskScheduler(); scheduler.setThreadNamePrefix("explicitScheduler1-"); return scheduler; } @Bean public TaskScheduler taskScheduler2() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadNamePrefix("explicitScheduler2-"); return scheduler; } @Bean public AtomicInteger counter() { return new AtomicInteger(); } @Scheduled(fixedRate = 10, scheduler = "myScheduler") public void task() throws InterruptedException { threadName = Thread.currentThread().getName(); counter().incrementAndGet(); Thread.sleep(10); } } @Configuration @EnableScheduling static
QualifiedExplicitSchedulerConfig
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/joda/JodaTest_2_LocalDateTimeTest3_private.java
{ "start": 223, "end": 838 }
class ____ extends TestCase { public void test_for_issue() throws Exception { String text = "{\"date\":\"20111203\"}"; VO vo = JSON.parseObject(text, VO.class); assertEquals(2011, vo.date.getYear()); assertEquals(12, vo.date.getMonthOfYear()); assertEquals(03, vo.date.getDayOfMonth()); assertEquals(0, vo.date.getHourOfDay()); assertEquals(0, vo.date.getMinuteOfHour()); assertEquals(0, vo.date.getSecondOfMinute()); assertEquals(text, JSON.toJSONString(vo)); } private static
JodaTest_2_LocalDateTimeTest3_private
java
apache__spark
common/unsafe/src/main/java/org/apache/spark/sql/catalyst/util/CollationAwareUTF8String.java
{ "start": 19611, "end": 20344 }
class ____ // convert the string to lowercase, which only accepts a Java strings as input. return UTF8String.fromString(UCharacter.toLowerCase(target.toValidString())); } /** * Convert the input string to lowercase using the specified ICU collation rules. * * @param target the input string * @return the lowercase string */ public static UTF8String toLowerCase(final UTF8String target, final int collationId) { if (target.isFullAscii()) return target.toLowerCaseAscii(); return toLowerCaseSlow(target, collationId); } private static UTF8String toLowerCaseSlow(final UTF8String target, final int collationId) { // Note: In order to achieve the desired behavior, we use the ICU UCharacter
to
java
apache__spark
common/variant/src/main/java/org/apache/spark/types/variant/VariantSchema.java
{ "start": 2938, "end": 5300 }
class ____ extends ScalarType { } // The index of the typed_value, value, and metadata fields in the schema, respectively. If a // given field is not in the schema, its value must be set to -1 to indicate that it is invalid. // The indices of valid fields should be contiguous and start from 0. public final int typedIdx; public final int variantIdx; // topLevelMetadataIdx must be non-negative in the top-level schema, and -1 at all other nesting // levels. public final int topLevelMetadataIdx; // The number of fields in the schema. I.e. a value between 1 and 3, depending on which of value, // typed_value and metadata are present. public final int numFields; public final ScalarType scalarSchema; public final ObjectField[] objectSchema; // Map for fast lookup of object fields by name. The values are an index into `objectSchema`. public final Map<String, Integer> objectSchemaMap; public final VariantSchema arraySchema; public VariantSchema(int typedIdx, int variantIdx, int topLevelMetadataIdx, int numFields, ScalarType scalarSchema, ObjectField[] objectSchema, VariantSchema arraySchema) { this.typedIdx = typedIdx; this.numFields = numFields; this.variantIdx = variantIdx; this.topLevelMetadataIdx = topLevelMetadataIdx; this.scalarSchema = scalarSchema; this.objectSchema = objectSchema; if (objectSchema != null) { objectSchemaMap = new HashMap<>(); for (int i = 0; i < objectSchema.length; i++) { objectSchemaMap.put(objectSchema[i].fieldName, i); } } else { objectSchemaMap = null; } this.arraySchema = arraySchema; } // Return whether the variant column is unshrededed. The user is not required to do anything // special, but can have certain optimizations for unshrededed variant. public boolean isUnshredded() { return topLevelMetadataIdx >= 0 && variantIdx >= 0 && typedIdx < 0; } @Override public String toString() { return "VariantSchema{" + "typedIdx=" + typedIdx + ", variantIdx=" + variantIdx + ", topLevelMetadataIdx=" + topLevelMetadataIdx + ", numFields=" + numFields + ", scalarSchema=" + scalarSchema + ", objectSchema=" + objectSchema + ", arraySchema=" + arraySchema + '}'; } }
UuidType
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/aop/around/AroundSpec.java
{ "start": 848, "end": 1302 }
class ____ { @Test void testNotNull() { try (ApplicationContext applicationContext = ApplicationContext.run()) { var ex = assertThrows(IllegalArgumentException.class, () -> { var exampleBean = applicationContext.getBean(NotNullExample.class); exampleBean.doWork(null); }); assertEquals(ex.getMessage(), "Null parameter [taskName] not allowed"); } } }
AroundSpec
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/repositories/VerifyNodeRepositoryCoordinationAction.java
{ "start": 2064, "end": 2404 }
class ____ extends ActionResponse { final List<DiscoveryNode> nodes; public Response(List<DiscoveryNode> nodes) { this.nodes = nodes; } @Override public void writeTo(StreamOutput out) throws IOException { TransportAction.localOnly(); } } public static
Response
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentSet.java
{ "start": 438, "end": 633 }
interface ____ this implementation is incompatible * with the set contract. While iterating over a set's entries, any value that has not passed iteration is referenced non-weakly. */ public
because
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/alter/OracleAlterTableTest19.java
{ "start": 1061, "end": 3038 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "ALTER TABLE warehouses" + " ADD CONSTRAINT wh_unq UNIQUE (warehouse_id, warehouse_name)"// + " USING INDEX PCTFREE 5"// + " EXCEPTIONS INTO wrong_id;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals("ALTER TABLE warehouses\n" + "\tADD CONSTRAINT wh_unq UNIQUE (warehouse_id, warehouse_name)\n" + "\t\tUSING INDEX\n" + "\t\tPCTFREE 5\n" + "\t\tEXCEPTIONS INTO wrong_id;", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("warehouses"))); assertEquals(2, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("PRODUCT_IDS_ZZJ_TBD0209", // "discount_amount"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("ws_affiliate_tran_product", // "commission_amount"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleAlterTableTest19
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/TestExecutionListenersNestedTests.java
{ "start": 2964, "end": 3185 }
class ____ { @Test void test() { assertThat(listeners).containsExactly(BAR); } } @Nested @NestedTestConfiguration(INHERIT) @TestExecutionListeners(BarTestExecutionListener.class)
ConfigOverriddenByDefaultTests
java
apache__camel
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalProcessor.java
{ "start": 35043, "end": 36212 }
class ____ implements CamelInternalProcessorAdvice<StopWatch> { private final Debugger debugger; private final Processor target; private final NamedNode definition; public DebuggerAdvice(Debugger debugger, Processor target, NamedNode definition) { this.debugger = debugger; this.target = target; this.definition = definition; } @Override public StopWatch before(Exchange exchange) throws Exception { if (definition.acceptDebugger(exchange)) { debugger.beforeProcess(exchange, target, definition); return new StopWatch(); } return null; } @Override public void after(Exchange exchange, StopWatch stopWatch) throws Exception { if (stopWatch != null) { debugger.afterProcess(exchange, target, definition, stopWatch.taken()); } } } /** * Advice to inject new {@link UnitOfWork} to the {@link Exchange} if needed, and as well to ensure the * {@link UnitOfWork} is done and stopped. */ public static
DebuggerAdvice
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/contextual/ContextualSerializationTest.java
{ "start": 874, "end": 1203 }
class ____ { // NOTE: important; MUST be considered a 'Jackson' annotation to be seen // (or recognized otherwise via AnnotationIntrospect.isHandled()) @Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @JacksonAnnotation public @
ContextualSerializationTest
java
quarkusio__quarkus
integration-tests/jackson/src/main/java/io/quarkus/it/jackson/model/ModelWithJsonTypeIdResolver.java
{ "start": 499, "end": 710 }
class ____ extends ModelWithJsonTypeIdResolver { public SubclassOne() { } @Override public String getType() { return "ONE"; } } public static
SubclassOne
java
elastic__elasticsearch
x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/SqlTranslateResponse.java
{ "start": 768, "end": 1897 }
class ____ extends ActionResponse implements ToXContentObject { private final SearchSourceBuilder source; public SqlTranslateResponse(StreamInput in) throws IOException { source = new SearchSourceBuilder(in); } public SqlTranslateResponse(SearchSourceBuilder source) { this.source = source; } public SearchSourceBuilder source() { return source; } @Override public void writeTo(StreamOutput out) throws IOException { source.writeTo(out); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } SqlTranslateResponse other = (SqlTranslateResponse) obj; return Objects.equals(source, other.source); } @Override public int hashCode() { return Objects.hash(source); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return source.toXContent(builder, params); } }
SqlTranslateResponse
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/JKSKeyStoreWithAliasCredentialsProviderTest.java
{ "start": 1145, "end": 2506 }
class ____ { private static final String configuration = """ quarkus.tls.key-store.jks.path=target/certs/test-credentials-provider-alias-keystore.jks quarkus.tls.key-store.jks.alias=my-alias quarkus.tls.key-store.credentials-provider.name=tls """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClass(MyCredentialProvider.class) .add(new StringAsset(configuration), "application.properties")); @Inject TlsConfigurationRegistry certificates; @Test void test() throws KeyStoreException, CertificateParsingException { TlsConfiguration def = certificates.getDefault().orElseThrow(); assertThat(def.getKeyStoreOptions()).isNotNull(); assertThat(def.getKeyStore()).isNotNull(); X509Certificate certificate = (X509Certificate) def.getKeyStore().getCertificate("my-alias"); assertThat(certificate).isNotNull(); assertThat(certificate.getSubjectAlternativeNames()).anySatisfy(l -> { assertThat(l.get(0)).isEqualTo(2); assertThat(l.get(1)).isEqualTo("dns:acme.org"); }); } @ApplicationScoped public static
JKSKeyStoreWithAliasCredentialsProviderTest
java
quarkusio__quarkus
integration-tests/main/src/main/java/io/quarkus/it/websocket/ServerDtoEncoder.java
{ "start": 231, "end": 743 }
class ____ implements Encoder.TextStream<Dto> { @Override public void encode(Dto object, Writer writer) { JsonObject jsonObject = Json.createObjectBuilder() .add("content", object.getContent()) .build(); try (JsonWriter jsonWriter = Json.createWriter(writer)) { jsonWriter.writeObject(jsonObject); } } @Override public void init(EndpointConfig config) { } @Override public void destroy() { } }
ServerDtoEncoder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyOneToOneRemoveFlushAccessTest.java
{ "start": 3892, "end": 4784 }
class ____ { @Id private Integer id; @OneToOne( fetch = FetchType.LAZY ) private ContainingEntity parent; @OneToOne( mappedBy = "parent", fetch = FetchType.LAZY ) private ContainingEntity child; @OneToOne( mappedBy = "containing" ) private ContainedEntity contained; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public ContainingEntity getParent() { return parent; } public void setParent(ContainingEntity parent) { this.parent = parent; } public ContainingEntity getChild() { return child; } public void setChild(ContainingEntity child) { this.child = child; } public ContainedEntity getContained() { return contained; } public void setContained(ContainedEntity contained) { this.contained = contained; } } @Entity( name = "ContainedEntity" ) static
ContainingEntity
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/ClientNamenodeProtocolServerSideTranslatorPB.java
{ "start": 27087, "end": 27214 }
class ____ used on the server side. Calls come across the wire for the * for protocol {@link ClientNamenodeProtocolPB}. * This
is
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/GenericMappedSuperclassNestedJoinTest.java
{ "start": 6081, "end": 6294 }
class ____<T extends SeqOrderLinkObjectWithUserContext<?>> extends SimpleObject { @ManyToOne protected T parent; } @Entity( name = "SelectionProductRuleProductLink" ) public static
AbsProductRuleProductLink
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/subclassmapping/fixture/SubSourceSeparate.java
{ "start": 211, "end": 524 }
class ____ extends ImplementedParentSource implements InterfaceParentSource { private final String separateValue; public SubSourceSeparate(String separateValue) { this.separateValue = separateValue; } public String getSeparateValue() { return separateValue; } }
SubSourceSeparate
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedTypeConverterRegistryMBean.java
{ "start": 973, "end": 2379 }
interface ____ extends ManagedServiceMBean { @ManagedAttribute(description = "Number of noop attempts (no type conversion was needed)") long getNoopCounter(); @ManagedAttribute(description = "Number of type conversion attempts") long getAttemptCounter(); @ManagedAttribute(description = "Number of type conversion hits (successful conversions)") long getHitCounter(); @ManagedAttribute(description = "Number of type conversion misses (no suitable type converter)") long getMissCounter(); @ManagedAttribute(description = "Number of type conversion failures (failed conversions)") long getFailedCounter(); @ManagedOperation(description = "Resets the type conversion counters") void resetTypeConversionCounters(); @ManagedAttribute(description = "Number of type converters in the registry") int getNumberOfTypeConverters(); @ManagedAttribute(description = "Logging level to use if attempting to add a duplicate type converter") String getTypeConverterExistsLoggingLevel(); @ManagedAttribute(description = "What to do if attempting to add a duplicate type converter (Override, Ignore or Fail)") String getTypeConverterExists(); @ManagedOperation(description = "Checks whether a type converter exists for converting (from -> to)") boolean hasTypeConverter(String fromType, String toType); }
ManagedTypeConverterRegistryMBean
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/exceptions/stacktrace/StackTraceFilter.java
{ "start": 2592, "end": 5387 }
class ____ a method to fast-path into {@link * Throwable#getStackTrace()} and retrieve a single {@link StackTraceElement}. This prevents the * JVM from having to generate a full stacktrace, which could potentially be expensive if * stacktraces become very large. * * @param target The throwable target to find the first {@link StackTraceElement} that should * not be filtered out per {@link StackTraceFilter#CLEANER}. * @return The first {@link StackTraceElement} outside of the {@link StackTraceFilter#CLEANER} */ public StackTraceElement filterFirst(Throwable target, boolean isInline) { boolean shouldSkip = isInline; if (GET_STACK_TRACE_ELEMENT != null) { int i = 0; // The assumption here is that the CLEANER filter will not filter out every single // element. However, since we don't want to compute the full length of the stacktrace, // we don't know the upper boundary. Therefore, simply increment the counter and go as // far as we have to go, assuming that we get there. If, in the rare occasion, we // don't, we fall back to the old slow path. while (true) { try { StackTraceElement stackTraceElement = (StackTraceElement) GET_STACK_TRACE_ELEMENT.invoke(JAVA_LANG_ACCESS, target, i); if (CLEANER.isIn(stackTraceElement)) { if (shouldSkip) { shouldSkip = false; } else { return stackTraceElement; } } } catch (Exception e) { // Fall back to slow path break; } i++; } } // If we can't use the fast path of retrieving stackTraceElements, use the slow path by // iterating over the actual stacktrace for (StackTraceElement stackTraceElement : target.getStackTrace()) { if (CLEANER.isIn(stackTraceElement)) { if (shouldSkip) { shouldSkip = false; } else { return stackTraceElement; } } } return null; } /** * Finds the source file of the target stack trace. * Returns the default value if source file cannot be found. */ public String findSourceFile(StackTraceElement[] target, String defaultValue) { for (StackTraceElement e : target) { if (CLEANER.isIn(e)) { return e.getFileName(); } } return defaultValue; } }
has
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/tracker/DirtyTracker.java
{ "start": 273, "end": 446 }
interface ____ { void add(String name); boolean contains(String name); void clear(); boolean isEmpty(); String[] get(); void suspend(boolean suspend); }
DirtyTracker
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeFinalTest.java
{ "start": 6059, "end": 6436 }
class ____ { private int x; Test() { this.x = 42; } void incr() { x += 1; } } """) .doTest(); } @Test public void unaryAssignment() { compilationHelper .addSourceLines( "Test.java", """
Test
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/security/HttpUpgradeRolesAllowedAnnotationTest.java
{ "start": 3447, "end": 4064 }
class ____ { @Inject CurrentIdentityAssociation currentIdentity; @OnOpen String open() { return "ready"; } @RolesAllowed("admin") @OnTextMessage String echo(String message) { if (!currentIdentity.getIdentity().hasRole("admin")) { throw new IllegalStateException(); } return message; } @OnError String error(ForbiddenException t) { return "forbidden:" + currentIdentity.getIdentity().getPrincipal().getName(); } } public static
Endpoint
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/search/aggregations/bucket/AbstractSignificanceHeuristicTestCase.java
{ "start": 3321, "end": 11805 }
class ____ extends ESTestCase { /** * @return A random instance of the heuristic to test */ protected abstract SignificanceHeuristic getHeuristic(); protected TransportVersion randomVersion() { return TransportVersionUtils.randomVersion(random()); } // test that stream output can actually be read - does not replace bwc test public void testStreamResponse() throws Exception { TransportVersion version = randomVersion(); InternalMappedSignificantTerms<?, ?> sigTerms = getRandomSignificantTerms(getHeuristic()); // write ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer); out.setTransportVersion(version); out.writeNamedWriteable(sigTerms); // read ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); StreamInput in = new InputStreamStreamInput(inBuffer); // populates the registry through side effects in = new NamedWriteableAwareStreamInput(in, writableRegistry()); in.setTransportVersion(version); InternalMappedSignificantTerms<?, ?> read = (InternalMappedSignificantTerms<?, ?>) in.readNamedWriteable(InternalAggregation.class); assertEquals(sigTerms.getSignificanceHeuristic(), read.getSignificanceHeuristic()); assertThat(read.getSubsetSize(), equalTo(10L)); assertThat(read.getSupersetSize(), equalTo(20L)); SignificantTerms.Bucket originalBucket = sigTerms.getBuckets().get(0); SignificantTerms.Bucket streamedBucket = read.getBuckets().get(0); assertThat(originalBucket.getKeyAsString(), equalTo(streamedBucket.getKeyAsString())); assertThat(originalBucket.getSupersetDf(), equalTo(streamedBucket.getSupersetDf())); assertThat(originalBucket.getSubsetDf(), equalTo(streamedBucket.getSubsetDf())); } InternalMappedSignificantTerms<?, ?> getRandomSignificantTerms(SignificanceHeuristic heuristic) { if (randomBoolean()) { SignificantLongTerms.Bucket bucket = new SignificantLongTerms.Bucket( 1, 3, 123, InternalAggregations.EMPTY, DocValueFormat.RAW, randomDoubleBetween(0, 100, true) ); return new SignificantLongTerms("some_name", 1, 1, null, DocValueFormat.RAW, 10, 20, heuristic, singletonList(bucket)); } else { SignificantStringTerms.Bucket bucket = new SignificantStringTerms.Bucket( new BytesRef("someterm"), 1, 3, InternalAggregations.EMPTY, DocValueFormat.RAW, randomDoubleBetween(0, 100, true) ); return new SignificantStringTerms("some_name", 1, 1, null, DocValueFormat.RAW, 10, 20, heuristic, singletonList(bucket)); } } public void testReduce() { List<InternalAggregation> aggs = createInternalAggregations(); AggregationReduceContext context = InternalAggregationTestCase.emptyReduceContextBuilder().forFinalReduction(); SignificantTerms reducedAgg = (SignificantTerms) InternalAggregationTestCase.reduce(aggs, context); assertThat(reducedAgg.getSubsetSize(), equalTo(16L)); assertThat(reducedAgg.getSupersetSize(), equalTo(30L)); assertThat(reducedAgg.getBuckets().size(), equalTo(2)); assertThat(reducedAgg.getBuckets().get(0).getSubsetDf(), equalTo(8L)); assertThat(reducedAgg.getBuckets().get(0).getSupersetDf(), equalTo(10L)); assertThat(reducedAgg.getBuckets().get(1).getSubsetDf(), equalTo(8L)); assertThat(reducedAgg.getBuckets().get(1).getSupersetDf(), equalTo(10L)); } public void testBasicScoreProperties() { testBasicScoreProperties(getHeuristic(), true); } protected void testBasicScoreProperties(SignificanceHeuristic heuristic, boolean testZeroScore) { assertThat(heuristic.getScore(1, 1, 1, 3), greaterThan(0.0)); assertThat(heuristic.getScore(1, 1, 2, 3), lessThan(heuristic.getScore(1, 1, 1, 3))); assertThat(heuristic.getScore(1, 1, 3, 4), lessThan(heuristic.getScore(1, 1, 2, 4))); if (testZeroScore) { assertThat(heuristic.getScore(0, 1, 2, 3), equalTo(0.0)); } double score = 0.0; try { long a = randomLong(); long b = randomLong(); long c = randomLong(); long d = randomLong(); score = heuristic.getScore(a, b, c, d); } catch (IllegalArgumentException e) {} assertThat(score, greaterThanOrEqualTo(0.0)); } /** * Testing heuristic specific assertions * Typically, this method would call either * {@link AbstractSignificanceHeuristicTestCase#testBackgroundAssertions(SignificanceHeuristic, SignificanceHeuristic)} * or {@link AbstractSignificanceHeuristicTestCase#testAssertions(SignificanceHeuristic)} * depending on which was appropriate */ public abstract void testAssertions(); public void testParseFromString() throws IOException { SignificanceHeuristic significanceHeuristic = getHeuristic(); try (XContentBuilder builder = JsonXContent.contentBuilder()) { builder.startObject().field("field", "text").field("min_doc_count", "200"); significanceHeuristic.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); try (XContentParser stParser = createParser(builder)) { SignificanceHeuristic parsedHeuristic = parseSignificanceHeuristic(stParser); assertThat(significanceHeuristic, equalTo(parsedHeuristic)); } } } public void testParseFromAggBuilder() throws IOException { SignificanceHeuristic significanceHeuristic = getHeuristic(); SignificantTermsAggregationBuilder stBuilder = significantTerms("testagg"); stBuilder.significanceHeuristic(significanceHeuristic).field("text").minDocCount(200); XContentBuilder stXContentBuilder = XContentFactory.jsonBuilder(); stBuilder.internalXContent(stXContentBuilder, null); SignificanceHeuristic parsedHeuristic; try (XContentParser stParser = createParser(JsonXContent.jsonXContent, Strings.toString(stXContentBuilder))) { parsedHeuristic = parseSignificanceHeuristic(stParser); } assertThat(significanceHeuristic, equalTo(parsedHeuristic)); } public void testParseFailure() throws IOException { SignificanceHeuristic significanceHeuristic = getHeuristic(); try (XContentBuilder builder = JsonXContent.contentBuilder()) { builder.startObject() .field("field", "text") .startObject(significanceHeuristic.getWriteableName()) .field("unknown_field", false) .endObject() .field("min_doc_count", "200") .endObject(); try (XContentParser stParser = createParser(builder)) { try { parseSignificanceHeuristic(stParser); fail("parsing the heurstic should have failed"); } catch (XContentParseException e) { assertThat(e.getMessage(), containsString("unknown field [unknown_field]")); } } } } // Create aggregations as they might come from three different shards and return as list. private List<InternalAggregation> createInternalAggregations() { SignificanceHeuristic significanceHeuristic = getHeuristic(); AbstractSignificanceHeuristicTestCase.TestAggFactory<?, ?> factory = randomBoolean() ? new AbstractSignificanceHeuristicTestCase.StringTestAggFactory() : new AbstractSignificanceHeuristicTestCase.LongTestAggFactory(); List<InternalAggregation> aggs = new ArrayList<>(); aggs.add(factory.createAggregation(significanceHeuristic, 4, 10, 1, (f, i) -> f.createBucket(4, 5, 0))); aggs.add(factory.createAggregation(significanceHeuristic, 4, 10, 1, (f, i) -> f.createBucket(4, 5, 1))); aggs.add(factory.createAggregation(significanceHeuristic, 8, 10, 2, (f, i) -> f.createBucket(4, 5, i))); return aggs; } private abstract
AbstractSignificanceHeuristicTestCase
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/support/caching/DefaultRedisCache.java
{ "start": 350, "end": 1370 }
class ____<K, V> implements RedisCache<K, V> { private final StatefulRedisConnection<K, V> connection; private final RedisCodec<K, V> codec; public DefaultRedisCache(StatefulRedisConnection<K, V> connection, RedisCodec<K, V> codec) { this.connection = connection; this.codec = codec; } @Override public V get(K key) { return connection.sync().get(key); } @Override public void put(K key, V value) { connection.sync().set(key, value); } @Override public void addInvalidationListener(java.util.function.Consumer<? super K> listener) { connection.addListener(message -> { if (message.getType().equals("invalidate")) { List<Object> content = message.getContent(codec::decodeKey); List<K> keys = (List<K>) content.get(1); keys.forEach(listener); } }); } @Override public void close() { connection.close(); } }
DefaultRedisCache
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java
{ "start": 16723, "end": 16821 }
class ____ { public void test() { } } @Rollback(false) static
EmptyClassLevelRollbackTestCase
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/transport/TestProfiles.java
{ "start": 572, "end": 1664 }
class ____ { private TestProfiles() {} /** * A pre-built light connection profile that shares a single connection across all * types. */ public static final ConnectionProfile LIGHT_PROFILE; static { ConnectionProfile source = ConnectionProfile.buildDefaultConnectionProfile(Settings.EMPTY); ConnectionProfile.Builder builder = new ConnectionProfile.Builder(); builder.setConnectTimeout(source.getConnectTimeout()); builder.setHandshakeTimeout(source.getHandshakeTimeout()); builder.setCompressionEnabled(source.getCompressionEnabled()); builder.setCompressionScheme(source.getCompressionScheme()); builder.setPingInterval(source.getPingInterval()); builder.addConnections( 1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE ); LIGHT_PROFILE = builder.build(); } }
TestProfiles
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/graph/GraphSemantic.java
{ "start": 631, "end": 3028 }
enum ____ { /** * Indicates that an {@link jakarta.persistence.EntityGraph} should be interpreted as a JPA "fetch graph". * <ul> * <li>Attributes explicitly specified using an {@link org.hibernate.graph.AttributeNode}s are treated as * {@link jakarta.persistence.FetchType#EAGER} and fetched via a join or subsequent select. * <li>Attributes not explicitly specified are treated as {@link jakarta.persistence.FetchType#LAZY} and * are not fetched. * </ul> */ FETCH, /** * Indicates that an {@link jakarta.persistence.EntityGraph} should be interpreted as a JPA "load graph". * <ul> * <li>Attributes explicitly specified using an {@link org.hibernate.graph.AttributeNode}s are treated as * {@link jakarta.persistence.FetchType#EAGER} and fetched via a join or subsequent select. * <li>Attributes not explicitly specified are treated as {@code FetchType.LAZY} or {@code FetchType.EAGER} * depending on the mapping of the attribute, instead of forcing {@code FetchType.LAZY}. * </ul> */ LOAD; /** * The corresponding Jakarta Persistence hint name. * * @see org.hibernate.jpa.SpecHints#HINT_SPEC_FETCH_GRAPH * @see org.hibernate.jpa.SpecHints#HINT_SPEC_LOAD_GRAPH */ public String getJakartaHintName() { return switch ( this ) { case FETCH -> HINT_SPEC_FETCH_GRAPH; case LOAD -> HINT_SPEC_LOAD_GRAPH; }; } /** * The hint name that should be used with Java Persistence. * * @see org.hibernate.jpa.LegacySpecHints#HINT_JAVAEE_FETCH_GRAPH * @see org.hibernate.jpa.LegacySpecHints#HINT_JAVAEE_LOAD_GRAPH * * @deprecated Use {@link #getJakartaHintName} instead */ @Deprecated(since = "6.0") public String getJpaHintName() { return switch ( this ) { case FETCH -> HINT_JAVAEE_FETCH_GRAPH; case LOAD -> HINT_JAVAEE_LOAD_GRAPH; }; } public static GraphSemantic fromHintName(String hintName) { return switch ( hintName ) { case HINT_SPEC_FETCH_GRAPH, HINT_JAVAEE_FETCH_GRAPH -> FETCH; case HINT_SPEC_LOAD_GRAPH, HINT_JAVAEE_LOAD_GRAPH -> LOAD; default -> throw new IllegalArgumentException( String.format( Locale.ROOT, "Unknown EntityGraph hint name - `%s`. " + "Expecting `%s` or `%s` (or `%s` and `%s`).", hintName, HINT_SPEC_FETCH_GRAPH, HINT_SPEC_LOAD_GRAPH, HINT_JAVAEE_FETCH_GRAPH, HINT_JAVAEE_LOAD_GRAPH ) ); }; } }
GraphSemantic
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
{ "start": 6909, "end": 7768 }
class ____ {@code null}. * @throws IllegalArgumentException if the field name is blank or empty or is matched at multiple places * in the inheritance hierarchy. * @throws SecurityException if an underlying accessible object's method denies the request. * @see SecurityManager#checkPermission */ public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) { Objects.requireNonNull(cls, "cls"); Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty"); // FIXME is this workaround still needed? lang requires Java 6 // Sun Java 1.3 has a bugged implementation of getField hence we write the // code ourselves // getField() will return the Field object with the declaring class // set correctly to the
is
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/test/java/org/apache/hadoop/mapreduce/v2/hs/TestJobHistoryParsing.java
{ "start": 29094, "end": 29790 }
class ____ extends MRAppWithHistory { public MRAppWithHistoryWithFailedTask(int maps, int reduces, boolean autoComplete, String testName, boolean cleanOnStart) { super(maps, reduces, autoComplete, testName, cleanOnStart); } @SuppressWarnings("unchecked") @Override protected void attemptLaunched(TaskAttemptId attemptID) { if (attemptID.getTaskId().getId() == 0) { getContext().getEventHandler().handle( new TaskAttemptFailEvent(attemptID)); } else { getContext().getEventHandler().handle( new TaskAttemptEvent(attemptID, TaskAttemptEventType.TA_DONE)); } } } static
MRAppWithHistoryWithFailedTask
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/FallbackRefCursorSupport.java
{ "start": 394, "end": 2073 }
class ____ implements RefCursorSupport { private final JdbcServices jdbcServices; public FallbackRefCursorSupport(JdbcServices jdbcServices) { this.jdbcServices = jdbcServices; } @Override public void registerRefCursorParameter(CallableStatement statement, int position) { try { jdbcServices.getDialect().registerResultSetOutParameter( statement, position ); } catch (SQLException e) { throw jdbcServices.getSqlExceptionHelper() .convert( e, "Error asking dialect to register ref cursor parameter [" + position + "]" ); } } @Override public void registerRefCursorParameter(CallableStatement statement, String name) { try { jdbcServices.getDialect().registerResultSetOutParameter( statement, name ); } catch (SQLException e) { throw jdbcServices.getSqlExceptionHelper() .convert( e, "Error asking dialect to register ref cursor parameter [" + name + "]" ); } } @Override public ResultSet getResultSet(CallableStatement statement, int position) { try { return jdbcServices.getDialect().getResultSet( statement, position ); } catch (SQLException e) { throw jdbcServices.getSqlExceptionHelper().convert( e, "Error asking dialect to extract ResultSet from CallableStatement parameter [" + position + "]" ); } } @Override public ResultSet getResultSet(CallableStatement statement, String name) { try { return jdbcServices.getDialect().getResultSet( statement, name ); } catch (SQLException e) { throw jdbcServices.getSqlExceptionHelper().convert( e, "Error asking dialect to extract ResultSet from CallableStatement parameter [" + name + "]" ); } } }
FallbackRefCursorSupport
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/MoreThanOneQualifierTest.java
{ "start": 5500, "end": 5676 }
class ____ { @Bar private int n; @Bar public TestClass3() {} @Bar public void setN(@Bar int n) {} } @Qualifier @Retention(RUNTIME) public @
TestClass3
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
{ "start": 10632, "end": 11020 }
class ____ { private final double actual = 1.0; @Test void should_run_test_when_assumption_passes() { thenCode(() -> given(actual).isOne()).doesNotThrowAnyException(); } @Test void should_ignore_test_when_assumption_fails() { expectAssumptionNotMetException(() -> given(actual).isZero()); } } @Nested
BDDAssumptions_given_double_primitive_Test
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DebeziumDb2EndpointBuilderFactory.java
{ "start": 86247, "end": 88485 }
class ____ should be used to * determine the topic name for data change, schema change, transaction, * heartbeat event etc. * * The option is a: <code>java.lang.String</code> type. * * Default: io.debezium.schema.SchemaTopicNamingStrategy * Group: db2 * * @param topicNamingStrategy the value to set * @return the dsl builder */ default DebeziumDb2EndpointBuilder topicNamingStrategy(String topicNamingStrategy) { doSetProperty("topicNamingStrategy", topicNamingStrategy); return this; } /** * Topic prefix that identifies and provides a namespace for the * particular database server/cluster is capturing changes. The topic * prefix should be unique across all other connectors, since it is used * as a prefix for all Kafka topic names that receive events emitted by * this connector. Only alphanumeric characters, hyphens, dots and * underscores must be accepted. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: db2 * * @param topicPrefix the value to set * @return the dsl builder */ default DebeziumDb2EndpointBuilder topicPrefix(String topicPrefix) { doSetProperty("topicPrefix", topicPrefix); return this; } /** * Class to make transaction context &amp; transaction struct/schemas. * * The option is a: <code>java.lang.String</code> type. * * Default: * io.debezium.pipeline.txmetadata.DefaultTransactionMetadataFactory * Group: db2 * * @param transactionMetadataFactory the value to set * @return the dsl builder */ default DebeziumDb2EndpointBuilder transactionMetadataFactory(String transactionMetadataFactory) { doSetProperty("transactionMetadataFactory", transactionMetadataFactory); return this; } } /** * Advanced builder for endpoint for the Debezium DB2 Connector component. */ public
that
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/legacy/W.java
{ "start": 163, "end": 514 }
class ____ { private long id; private Set zeds; /** * */ public W() { } /** * @return */ public long getId() { return id; } /** * @return */ public Set getZeds() { return zeds; } /** * @param l */ public void setId(long l) { id = l; } /** * @param set */ public void setZeds(Set set) { zeds = set; } }
W
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/transaction/ejb/dao/RequiredEjbTxTestEntityDao.java
{ "start": 1223, "end": 1546 }
class ____ extends AbstractEjbTxTestEntityDao { @Override public int getCount(String name) { return super.getCountInternal(name); } @TransactionAttribute(TransactionAttributeType.REQUIRED) @Override public int incrementCount(String name) { return super.incrementCountInternal(name); } }
RequiredEjbTxTestEntityDao
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/saml/IdpConfiguration.java
{ "start": 528, "end": 1230 }
class ____ { private final String entityId; private final Supplier<List<Credential>> signingCredentials; IdpConfiguration(String entityId, Supplier<List<Credential>> signingCredentials) { this.entityId = entityId; this.signingCredentials = signingCredentials; } /** * The SAML identifier (as a URI) for the IDP */ String getEntityId() { return entityId; } /** * A list of credentials that the IDP uses for signing messages. * A trusted message should be signed with any one (or more) of these credentials. */ List<Credential> getSigningCredentials() { return signingCredentials.get(); } }
IdpConfiguration
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/recursive/comparison/RecursiveComparisonDifferenceCalculator.java
{ "start": 4967, "end": 26917 }
class ____ { // Not using a Set as we want to precisely track visited values, a set would remove duplicates VisitedDualValues visitedDualValues; List<ComparisonDifference> differences = new ArrayList<>(); DualValueDeque dualValuesToCompare; RecursiveComparisonConfiguration recursiveComparisonConfiguration; public ComparisonState(VisitedDualValues visitedDualValues, RecursiveComparisonConfiguration recursiveComparisonConfiguration) { this.visitedDualValues = visitedDualValues; this.dualValuesToCompare = new DualValueDeque(recursiveComparisonConfiguration); this.recursiveComparisonConfiguration = recursiveComparisonConfiguration; } void addDifference(ComparisonDifference comparisonDifference) { differences.add(comparisonDifference); } void addDifference(DualValue dualValue) { addDifference(dualValue, null); } void addDifference(DualValue dualValue, String description) { // to evaluate differences on fields of compared types, we have to traverse the whole graph of objects to compare // and decide afterward if differences were relevant, for example if we compare only the Employee type, and we // come across a Company having a list of Employee, we should evaluate the Company but ignore any of its // differences unless the ones on Employees. if (recursiveComparisonConfiguration.hasComparedTypes()) { // the comparison includes the union of fields of compared types and compared fields, if the difference is // reported on a field whose type is not in the compared types, we should ignore the difference unless it was // on a field from the set of compared fields. if (recursiveComparisonConfiguration.isNotAComparedField(dualValue) // TODO check if there compared fields ? && !recursiveComparisonConfiguration.matchesOrIsChildOfFieldMatchingAnyComparedTypes(dualValue)) // was not a field we had to compared return; // check if the value was meant to be ignored, if it is the case simply skip the difference if (recursiveComparisonConfiguration.shouldIgnore(dualValue)) return; } String customErrorMessage = getCustomErrorMessage(dualValue); ComparisonDifference comparisonDifference = new ComparisonDifference(dualValue, description, customErrorMessage); differences.add(comparisonDifference); // track the difference for the given dual values, in case we visit the same dual values again visitedDualValues.registerComparisonDifference(dualValue, comparisonDifference); } void addKeyDifference(DualValue parentDualValue, Object actualKey, Object expectedKey) { differences.add(new ComparisonKeyDifference(parentDualValue, actualKey, expectedKey)); } public List<ComparisonDifference> getDifferences() { Collections.sort(differences); return differences; } public boolean hasDualValuesToCompare() { return !dualValuesToCompare.isEmpty(); } public DualValue pickDualValueToCompare() { return dualValuesToCompare.removeFirst(); } private void registerForComparison(DualValue dualValue) { dualValuesToCompare.addFirst(dualValue); } private void initDualValuesToCompare(DualValue dualValue) { // We must check compared fields existence only once and at the root level, if we don't as we use the recursive // comparison to compare unordered collection elements, we would check the compared fields at the wrong level. if (dualValue.fieldLocation.isRoot() && recursiveComparisonConfiguration.someComparedFieldsWereSpecified()) { recursiveComparisonConfiguration.checkComparedFieldsExist(dualValue.actual); } if (recursiveComparisonConfiguration.shouldNotEvaluate(dualValue)) return; registerForComparison(dualValue); } private String getCustomErrorMessage(DualValue dualValue) { String fieldName = dualValue.getConcatenatedPath(); // field custom messages take precedence over type messages if (recursiveComparisonConfiguration.hasCustomMessageForField(fieldName)) { return recursiveComparisonConfiguration.getMessageForField(fieldName); } Class<?> fieldType = null; if (dualValue.actual != null) { fieldType = dualValue.actual.getClass(); } else if (dualValue.expected != null) { fieldType = dualValue.expected.getClass(); } if (fieldType != null && recursiveComparisonConfiguration.hasCustomMessageForType(fieldType)) { return recursiveComparisonConfiguration.getMessageForType(fieldType); } return null; } String toStringOf(Object value) { return recursiveComparisonConfiguration.getRepresentation().toStringOf(value); } } /** * Compare two objects for differences by doing a 'deep' comparison. This will traverse the * Object graph and perform either a field-by-field comparison on each * object (if not .equals() method has been overridden from Object), or it * will call the customized .equals() method if it exists. * <p> * This method handles cycles correctly, for example A-&gt;B-&gt;C-&gt;A. * Suppose a1 and a2 are two separate instances of the A with the same values * for all fields on A, B, and C. Then a1.deepEquals(a2) will return an empty list. It * uses cycle detection storing visited objects in a Set to prevent endless * loops. * * @param actual Object one to compare * @param expected Object two to compare * @param recursiveComparisonConfiguration the recursive comparison configuration * @return the list of differences found or an empty list if objects are equivalent. * Equivalent means that all field values of both sub-graphs are the same, * either at the field level or via the respectively encountered overridden * .equals() methods during traversal. */ public List<ComparisonDifference> determineDifferences(Object actual, Object expected, RecursiveComparisonConfiguration recursiveComparisonConfiguration) { DualValue rootDualValue = rootDualValue(actual, expected); if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && typesDiffer(rootDualValue)) { return list(typeDifference(rootDualValue)); } return determineDifferences(rootDualValue, new VisitedDualValues(), recursiveComparisonConfiguration); } private static ComparisonDifference typeDifference(DualValue dualValue) { String detail = STRICT_TYPE_ERROR.formatted(dualValue.getActualTypeDescription(), dualValue.getExpectedTypeDescription()); return new ComparisonDifference(dualValue, detail); } // TODO keep track of ignored fields in an RecursiveComparisonExecution class ? private static List<ComparisonDifference> determineDifferences(DualValue dualValue, VisitedDualValues visitedDualValues, RecursiveComparisonConfiguration recursiveComparisonConfiguration) { ComparisonState comparisonState = new ComparisonState(visitedDualValues, recursiveComparisonConfiguration); comparisonState.initDualValuesToCompare(dualValue); while (comparisonState.hasDualValuesToCompare()) { dualValue = comparisonState.pickDualValueToCompare(); if (recursiveComparisonConfiguration.hierarchyMatchesAnyComparedTypes(dualValue)) { // keep track of field locations of type to compare, needed to compare child nodes, for example if we want to // only compare the Person type, we must compare the Person fields too even though they are not of type Person recursiveComparisonConfiguration.registerFieldLocationToCompareBecauseOfTypesToCompare(dualValue.fieldLocation); } // if we have already visited the dual value, no need to compute the comparison differences again, this also avoid cycles Optional<List<ComparisonDifference>> comparisonDifferences = comparisonState.visitedDualValues.registeredComparisonDifferencesOf(dualValue); if (comparisonDifferences.isPresent()) { if (!comparisonDifferences.get().isEmpty()) { comparisonState.addDifference(dualValue, "already visited node but now location is: " + dualValue.fieldLocation); } continue; } // first time we evaluate this dual value, perform the usual recursive comparison from there // visited dual values are tracked to avoid cycle if (recursiveComparisonConfiguration.someComparedFieldsWereSpecified()) { // only track dual values if their field location is a compared field or a child of one that could have cycles, // before we get to a compared field, tracking dual values is wrong, ex: given a person root object with a // neighbour.neighbour field that cycles back to itself, and we compare neighbour.neighbour.name, if we track // visited all dual values, we would not introspect neighbour.neighbour as it was already visited as root. if (recursiveComparisonConfiguration.isOrIsChildOfAnyComparedFields(dualValue.fieldLocation) && dualValue.hasPotentialCyclingValues()) { comparisonState.visitedDualValues.registerVisitedDualValue(dualValue); } } else if (dualValue.hasPotentialCyclingValues()) { comparisonState.visitedDualValues.registerVisitedDualValue(dualValue); } // Custom comparators take precedence over all other types of comparison if (recursiveComparisonConfiguration.hasCustomComparator(dualValue)) { if (!areDualValueEqual(dualValue, recursiveComparisonConfiguration)) comparisonState.addDifference(dualValue); // since we used a custom comparator we don't need to inspect the nested fields any further continue; } if (dualValue.actual == dualValue.expected) continue; if (recursiveComparisonConfiguration.isTreatingNullAndEmptyIterablesAsEqualEnabled() && (dualValue.actual == null || dualValue.isActualAnIterable()) && (dualValue.expected == null || dualValue.isExpectedAnIterable()) && isNullOrEmpty((Iterable<?>) dualValue.actual) && isNullOrEmpty((Iterable<?>) dualValue.expected)) { // we know one of the value is not null since actualFieldValue != expectedFieldValue and is an iterable // if the other value is null, we can't know if it was an iterable, we just assume so, this is true if actual // and expected root values had the same type, but could be false if the types are different and both have a // field with the same name but the field type is not an iterable in one of them. // TODO add type to introspection strategy ? continue; } if (dualValue.actual == null || dualValue.expected == null) { // one of the value is null while the other is not as we already know that actualFieldValue != expectedFieldValue comparisonState.addDifference(dualValue); continue; } if (dualValue.isActualAnEnum() || dualValue.isExpectedAnEnum()) { compareAsEnums(dualValue, comparisonState, recursiveComparisonConfiguration); continue; } if (dualValue.isExpectedAThrowable()) { compareAsThrowables(dualValue, comparisonState); continue; } // TODO move hasFieldTypesDifference check into each compareXXX if (dualValue.isExpectedAnArray()) { if (!dualValue.isActualAnArray()) { // at the moment we only allow comparing arrays with arrays, but we might allow comparing to collections later on // but only if we are not in strict type mode. comparisonState.addDifference(dualValue, differentTypeErrorMessage(dualValue, "an array")); continue; } if (recursiveComparisonConfiguration.shouldIgnoreArrayOrder()) { compareUnorderedArrays(dualValue, comparisonState); } else { compareArrays(dualValue, comparisonState); } continue; } // we compare ordered collections specifically as to be matching, each pair of elements at a given index must match. // concretely we compare: (col1[0] vs col2[0]), (col1[1] vs col2[1])...(col1[n] vs col2[n]) if (dualValue.isExpectedAnOrderedCollection() && !recursiveComparisonConfiguration.shouldIgnoreCollectionOrder(dualValue.fieldLocation)) { compareOrderedCollections(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnIterable()) { compareUnorderedIterables(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnOptional()) { compareOptional(dualValue, comparisonState); continue; } // Compare two SortedMaps taking advantage of the fact that these Maps can be compared in O(N) time due to their ordering if (dualValue.isExpectedASortedMap()) { compareSortedMap(dualValue, comparisonState); continue; } // Compare two Unordered Maps. This is a slightly more expensive comparison because order cannot be assumed, therefore a // temporary Map must be created, however the comparison still runs in O(N) time. if (dualValue.isExpectedAMap()) { compareUnorderedMap(dualValue, comparisonState); continue; } // compare Atomic types by value manually as they are container type, and we can't use introspection in java 17+ if (dualValue.isExpectedAnAtomicBoolean()) { compareAtomicBoolean(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnAtomicInteger()) { compareAtomicInteger(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnAtomicIntegerArray()) { compareAtomicIntegerArray(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnAtomicLong()) { compareAtomicLong(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnAtomicLongArray()) { compareAtomicLongArray(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnAtomicReference()) { compareAtomicReference(dualValue, comparisonState); continue; } if (dualValue.isExpectedAnAtomicReferenceArray()) { compareAtomicReferenceArray(dualValue, comparisonState); continue; } // Taking expected as the reference, we have checked all java special cases (containers, enum, ...) // If both actual and expected are java types, we compare them with equals because we need to compare values // at some point (and we can't introspect java types anymore since Java 17). boolean javaTypesOnly = dualValue.isActualJavaType() && dualValue.isExpectedJavaType(); if (javaTypesOnly) { if (!deepEquals(dualValue.actual, dualValue.expected)) { String description = dualValue.getActualTypeDescription().equals(dualValue.getExpectedTypeDescription()) ? "Actual and expected value are both java types (%s) and thus were compared to with equals".formatted(dualValue.getActualTypeDescription()) : "Actual and expected value are both java types (%s and %s) and thus were compared to with actual equals method".formatted(dualValue.getActualTypeDescription(), dualValue.getExpectedTypeDescription()); comparisonState.addDifference(dualValue, description); } continue; } // If either actual or expected is a java types and the other is not, we compare them with equals since we // can't introspect java types (it's the best we can at this point). boolean oneJavaType = dualValue.isActualJavaType() || dualValue.isExpectedJavaType(); if (oneJavaType && !dualValue.actual.equals(dualValue.expected)) { String description = dualValue.isActualJavaType() ? "Actual was compared to expected with equals because it is a java type (%s) and expected is not (%s)".formatted(dualValue.getActualTypeDescription(), dualValue.getExpectedTypeDescription()) : "Actual was compared to expected with equals because expected is a java type (%s) and actual is not (%s)".formatted(dualValue.getExpectedTypeDescription(), dualValue.getActualTypeDescription()); comparisonState.addDifference(dualValue, description); continue; } // both actual and expected are not java types, we compare them recursively unless we were told to use equals boolean shouldHonorOverriddenEquals = recursiveComparisonConfiguration.shouldHonorOverriddenEquals(dualValue); if (shouldHonorOverriddenEquals && hasOverriddenEquals(dualValue.actual.getClass())) { if (!dualValue.actual.equals(dualValue.expected)) { comparisonState.addDifference(dualValue, "Actual was compared to expected with equals as the recursive comparison was configured to do so."); } continue; } if (recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && typesDiffer(dualValue)) { comparisonState.addDifference(typeDifference(dualValue)); continue; } Set<String> actualChildrenNodeNamesToCompare = recursiveComparisonConfiguration.getActualChildrenNodeNamesToCompare(dualValue); if (reportActualHasMissingOrExtraFields(dualValue, actualChildrenNodeNamesToCompare, comparisonState)) { continue; } // compare actual and expected nodes for (String nodeNameToCompare : actualChildrenNodeNamesToCompare) { var nodeDualValue = new DualValue(dualValue.fieldLocation.field(nodeNameToCompare), recursiveComparisonConfiguration.getValue(nodeNameToCompare, dualValue.actual), recursiveComparisonConfiguration.getValue(nodeNameToCompare, dualValue.expected)); comparisonState.registerForComparison(nodeDualValue); } } return comparisonState.getDifferences(); } private static boolean reportActualHasMissingOrExtraFields(DualValue dualValue, Set<String> actualChildrenNodeNamesToCompare, ComparisonState comparisonState) { RecursiveComparisonConfiguration recursiveComparisonConfiguration = comparisonState.recursiveComparisonConfiguration; if (typesDiffer(dualValue)) { // check missing or extra actual fields, to do so, we get actual ignored fields, remove them from expected // fields and see if there are any differences. Set<String> actualChildrenNodesNames = recursiveComparisonConfiguration.getChildrenNodeNamesOf(dualValue.actual); Set<String> actualIgnoredChildrenNodesNames = removeAll(actualChildrenNodesNames, actualChildrenNodeNamesToCompare); Set<String> expectedChildrenNodesNames = recursiveComparisonConfiguration.getChildrenNodeNamesOf(dualValue.expected); Set<String> expectedChildrenNodesNamesToCompare = removeAll(expectedChildrenNodesNames, actualIgnoredChildrenNodesNames); // if we have compared fields, we should only check they are in expected and ignore extra expected fields if (recursiveComparisonConfiguration.hasComparedFields()) { if (!expectedChildrenNodesNamesToCompare.containsAll(actualChildrenNodeNamesToCompare)) { Set<String> actualNodesNamesNotInExpected = removeAll(actualChildrenNodeNamesToCompare, expectedChildrenNodesNamesToCompare); comparisonState.addDifference(dualValue, EXTRA_ACTUAL_FIELDS.formatted(actualNodesNamesNotInExpected)); return true; } // all good, we ignore extra expected fields, which means we only check actual compared fields expectedChildrenNodesNamesToCompare = actualChildrenNodeNamesToCompare; } if (!expectedChildrenNodesNamesToCompare.equals(actualChildrenNodeNamesToCompare)) { // report expected nodes not in actual Set<String> expectedNodesNamesNotInActual = newHashSet(expectedChildrenNodesNamesToCompare); expectedNodesNamesNotInActual.removeAll(actualChildrenNodeNamesToCompare); // report extra nodes in actual Set<String> actualNodesNamesNotInExpected = newHashSet(actualChildrenNodeNamesToCompare); actualNodesNamesNotInExpected.removeAll(expectedChildrenNodesNamesToCompare); if (!expectedNodesNamesNotInActual.isEmpty() && !actualNodesNamesNotInExpected.isEmpty()) { comparisonState.addDifference(dualValue, MISSING_AND_EXTRA_ACTUAL_FIELDS.formatted(expectedNodesNamesNotInActual, actualNodesNamesNotInExpected)); } else if (!expectedNodesNamesNotInActual.isEmpty()) { comparisonState.addDifference(dualValue, MISSING_ACTUAL_FIELDS.formatted(expectedNodesNamesNotInActual)); return true; } else if (!actualNodesNamesNotInExpected.isEmpty()) { comparisonState.addDifference(dualValue, EXTRA_ACTUAL_FIELDS.formatted(actualNodesNamesNotInExpected)); } return true; } } return false; } // avoid comparing
ComparisonState
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/dataview/StateListView.java
{ "start": 4396, "end": 5347 }
class ____<N, T> extends StateListView<N, T> { private final InternalListState<?, N, T> listState; private N namespace; public NamespacedStateListView(InternalListState<?, N, T> listState) { this.listState = listState; } @Override public void setCurrentNamespace(N namespace) { this.namespace = namespace; } @Override protected ListState<T> getListState() { listState.setCurrentNamespace(namespace); return listState; } } private static void checkValue(Object value) { if (value == null) { throw new TableRuntimeException("List views don't support null values."); } } private static void checkList(List<?> list) { if (list.contains(null)) { throw new TableRuntimeException("List views don't support null values."); } } }
NamespacedStateListView