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
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/writer/DispatchWriter.java
{ "start": 24858, "end": 26947 }
class ____ extends AbstractDispatchTarget { final ClassElement declaringType; final MethodElement methodElement; private final boolean useOneDispatch; private MethodDispatchTarget(ClassElement targetType, MethodElement methodElement, boolean useOneDispatch) { this.declaringType = targetType; this.methodElement = methodElement; this.useOneDispatch = useOneDispatch; } @Override public boolean supportsDispatchOne() { return useOneDispatch; } @Override public boolean supportsDispatchMulti() { return !useOneDispatch; } @Override public ClassElement getDeclaringType() { return declaringType; } @Override public MethodElement getMethodElement() { return methodElement; } @Override public ExpressionDef dispatchMultiExpression(ExpressionDef target, List<? extends ExpressionDef> values) { ClassTypeDef targetType = ClassTypeDef.of(declaringType); if (methodElement.isStatic()) { return targetType.invokeStatic(methodElement, values); } return target.cast(targetType).invoke(methodElement, values); } @Override public ExpressionDef dispatchOneExpression(ExpressionDef target, ExpressionDef value) { ClassTypeDef targetType = ClassTypeDef.of(declaringType); if (methodElement.isStatic()) { return targetType.invokeStatic(methodElement, TypeDef.OBJECT.array().instantiate(value)); } if (methodElement.getSuspendParameters().length > 0) { return target.cast(targetType).invoke(methodElement, value); } return target.cast(targetType).invoke(methodElement); } } /** * Method invocation dispatch target. */ @Internal public static final
MethodDispatchTarget
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/UnidirectionalSetTest.java
{ "start": 1687, "end": 2138 }
class ____ { @Id private Long id; @OneToMany(cascade = CascadeType.ALL) private Set<Phone> phones = new HashSet<>(); //Getters and setters are omitted for brevity //end::collections-unidirectional-set-example[] public Person() { } public Person(Long id) { this.id = id; } public Set<Phone> getPhones() { return phones; } //tag::collections-unidirectional-set-example[] } @Entity(name = "Phone") public static
Person
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/AuthorizeHttpRequestsConfigurerTests.java
{ "start": 53667, "end": 53991 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off return http .authorizeHttpRequests((authorize) -> authorize .anyRequest().hasRole("USER") ) .build(); // @formatter:on } } @Configuration @EnableWebSecurity static
RoleUserConfig
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/RegistryExtensionResolver.java
{ "start": 933, "end": 12402 }
class ____ { public static final int VERSION_NOT_RECOGNIZED = -1; public static final int VERSION_NOT_CONFIGURED = 0; public static final int VERSION_RECOGNIZED = 1; public static final int VERSION_EXCLUSIVE_PROVIDER = 2; private static final String DASH_SUPPORT = "-support"; /** * Returns an extra config option value with an expected type. * If an option was not configured, the returned value will be null. * If the configured value cannot be cast to an expected type, the method will throw an error. * * @param config registry configuration * @param name option name * @param type expected value type * @return configured value or null * @param <T> expected value type */ private static <T> T getExtraConfigOption(RegistryConfig config, String name, Class<T> type) { Object o = config.getExtra().get(name); if (o == null) { return null; } if (type.isInstance(o)) { return (T) o; } throw new IllegalArgumentException( "Expected a value of type " + type.getName() + " for option " + name + " but got " + o + " of type " + o.getClass().getName()); } /** * Returns offering configured by the user in the registry configuration or null, in case * no offering was configured. * * An offering would be the name part of the {@code <name>-support} in the extension metadata. * * @param config registry configuration * @return user configured offering or null */ private static String getConfiguredOfferingOrNull(RegistryConfig config) { var offering = getExtraConfigOption(config, OFFERING, String.class); return offering == null || offering.isBlank() ? null : offering; } /** * Returns the lowest boundaries for recommended streams, if configured. * The returned map will have platform keys as the map keys and stream IDs split using dot as a separator. * If the lowest boundaries have not been configured, this method will return an empty map. * * @param config registry configuration * @return lowest boundaries for recommended streams per platform key or an empty map, if not configured */ private static Map<String, String[]> getRecommendStreamsFromOrNull(RegistryConfig config) { final Map<String, String> recommendStreamsStarting = getExtraConfigOption(config, RECOMMEND_STREAMS_FROM, Map.class); if (recommendStreamsStarting == null) { return Map.of(); } final Map<String, String[]> result = new HashMap<>(recommendStreamsStarting.size()); for (Map.Entry<String, String> e : recommendStreamsStarting.entrySet()) { result.put(e.getKey(), e.getValue().split("\\.")); } return result; } /** * Compares two streams as versions. * * @param streamParts1 stream one * @param streamParts2 stream two * @return 1 if stream one is newer than stream two, -1 if stream two is newer than stream 1, otherwise 0 */ private static int compareStreams(String[] streamParts1, String[] streamParts2) { int partI = 0; while (true) { if (partI == streamParts1.length) { return partI == streamParts2.length ? 0 : -1; } if (partI == streamParts2.length) { return 1; } final int result = streamParts1[partI].compareTo(streamParts2[partI]); if (result != 0) { return result; } ++partI; } } private final RegistryConfig config; private final RegistryClient registry; private final Pattern recognizedQuarkusVersions; private final Collection<String> recognizedGroupIds; /** * {@code -support} extension metadata key that corresponds to the user selected offering, can be null */ private final String offeringSupportKey; /** * If configured, this will be the lowest boundary for stream recommendations. * IOW, streams before this value will be ignored. */ private final Map<String, String[]> recommendStreamsFrom; RegistryExtensionResolver(RegistryClient registryClient, MessageWriter log) throws RegistryResolutionException { this.registry = Objects.requireNonNull(registryClient, "Registry extension resolver is null"); this.config = registryClient.resolveRegistryConfig(); final String versionExpr = config.getQuarkusVersions() == null ? null : config.getQuarkusVersions().getRecognizedVersionsExpression(); recognizedQuarkusVersions = versionExpr == null ? null : Pattern.compile(GlobUtil.toRegexPattern(versionExpr)); this.recognizedGroupIds = config.getQuarkusVersions() == null ? Collections.emptyList() : config.getQuarkusVersions().getRecognizedGroupIds(); final String offering = getConfiguredOfferingOrNull(config); if (offering != null) { log.debug("Registry %s is limited to offerings %s", config.getId(), offering); this.offeringSupportKey = offering + DASH_SUPPORT; } else { offeringSupportKey = null; } recommendStreamsFrom = getRecommendStreamsFromOrNull(config); if (!recommendStreamsFrom.isEmpty()) { log.debug("Streams before %s recommended by %s will be ignored", recommendStreamsFrom, config.getId()); } } String getId() { return config.getId(); } int checkQuarkusVersion(String quarkusVersion) { if (recognizedQuarkusVersions == null) { return VERSION_NOT_CONFIGURED; } if (quarkusVersion == null) { throw new IllegalArgumentException(); } if (!recognizedQuarkusVersions.matcher(quarkusVersion).matches()) { return VERSION_NOT_RECOGNIZED; } return config.getQuarkusVersions().isExclusiveProvider() ? VERSION_EXCLUSIVE_PROVIDER : VERSION_RECOGNIZED; } boolean isExclusiveProviderOf(String quarkusVersion) { return checkQuarkusVersion(quarkusVersion) == VERSION_EXCLUSIVE_PROVIDER; } boolean isAcceptsQuarkusVersionQueries(String quarkusVersion) { return checkQuarkusVersion(quarkusVersion) >= 0; } int checkPlatform(ArtifactCoords platform) { if (!recognizedGroupIds.isEmpty() && !recognizedGroupIds.contains(platform.getGroupId())) { return VERSION_NOT_RECOGNIZED; } return checkQuarkusVersion(platform.getVersion()); } PlatformCatalog.Mutable resolvePlatformCatalog() throws RegistryResolutionException { return resolvePlatformCatalog(null); } PlatformCatalog.Mutable resolvePlatformCatalog(String quarkusCoreVersion) throws RegistryResolutionException { PlatformCatalog.Mutable platformCatalog = registry.resolvePlatforms(quarkusCoreVersion); if (!recommendStreamsFrom.isEmpty()) { final Iterator<Platform> platformI = platformCatalog.getPlatforms().iterator(); boolean allPlatformsIgnored = true; while (platformI.hasNext()) { var platform = platformI.next(); final String[] fromStream = recommendStreamsFrom.get(platform.getPlatformKey()); if (fromStream != null) { final Iterator<PlatformStream> streamI = platform.getStreams().iterator(); boolean allStreamsIgnored = true; while (streamI.hasNext()) { var stream = streamI.next(); if (compareStreams(fromStream, stream.getId().split("\\.")) > 0) { streamI.remove(); break; } else { allStreamsIgnored = false; } } while (streamI.hasNext()) { streamI.next(); streamI.remove(); } if (allStreamsIgnored) { platformI.remove(); } else { allPlatformsIgnored = false; } } else { allPlatformsIgnored = false; } } if (allPlatformsIgnored) { return null; } } return platformCatalog; } Platform resolveRecommendedPlatform() throws RegistryResolutionException { return resolvePlatformCatalog().getRecommendedPlatform(); } ExtensionCatalog.Mutable resolveNonPlatformExtensions(String quarkusCoreVersion) throws RegistryResolutionException { return applyOfferingFilter(registry.resolveNonPlatformExtensions(quarkusCoreVersion)); } /** * Resolves a platform extension catalog using a given JSON artifact. * <p> * If a user did not configure an offering the original catalog is returned. * <p> * If an offering was configured, we filter out extensions that are not part of the selected offering * {@link Constants#DEFAULT_REGISTRY_ARTIFACT_VERSION} to the metadata with the corresponding {@code <name>-support} * as its value that will be used by the extension list commands later to display the relevant support scope. * * @param platform either a BOM or a JSON descriptor coordinates * @return extension catalog * @throws RegistryResolutionException in case of a failure */ ExtensionCatalog.Mutable resolvePlatformExtensions(ArtifactCoords platform) throws RegistryResolutionException { return applyOfferingFilter(registry.resolvePlatformExtensions(platform)); } private ExtensionCatalog.Mutable applyOfferingFilter(ExtensionCatalog.Mutable catalog) { if (catalog == null) { return null; } final Collection<Extension> originalCollection = catalog.getExtensions(); final List<Extension> offeringCollection = offeringSupportKey == null ? null : new ArrayList<>(originalCollection.size()); final Map<ArtifactKey, ArtifactCoords> allCatalogExtensions = new HashMap<>(originalCollection.size()); for (Extension ext : originalCollection) { allCatalogExtensions.put(ext.getArtifact().getKey(), ext.getArtifact()); if (offeringCollection != null) { if (ext.getMetadata().containsKey(offeringSupportKey)) { ext.getMetadata().put(Constants.REGISTRY_CLIENT_USER_SELECTED_SUPPORT_KEY, offeringSupportKey); offeringCollection.add(ext); } else if (ext.getArtifact().getArtifactId().equals("quarkus-core")) { // we need quarkus-core for proper quarkus-bom to become the primary platform when creating projects offeringCollection.add(ext); } } } catalog.getMetadata().put(Constants.REGISTRY_CLIENT_ALL_CATALOG_EXTENSIONS, allCatalogExtensions); if (offeringCollection != null) { catalog.setExtensions(offeringCollection); } return catalog; } void clearCache() throws RegistryResolutionException { registry.clearCache(); } }
RegistryExtensionResolver
java
apache__flink
flink-state-backends/flink-statebackend-changelog/src/test/java/org/apache/flink/state/changelog/ChangelogKeyedStateBackendTest.java
{ "start": 2917, "end": 8085 }
class ____ { @Parameterized.Parameters(name = "checkpointID={0}, materializationId={1}") public static Object[][] parameters() { return new Object[][] { {0L, 200L}, {200L, 0L}, }; } @Parameter(0) public long checkpointId; @Parameter(1) public long materializationId; @Test public void testCheckpointConfirmation() throws Exception { MockKeyedStateBackend<Integer> mock = createMock(); ChangelogKeyedStateBackend<Integer> changelog = createChangelog(mock); try { changelog.handleMaterializationResult( SnapshotResult.empty(), materializationId, SequenceNumber.of(Long.MAX_VALUE)); checkpoint(changelog, checkpointId).get().discardState(); changelog.notifyCheckpointComplete(checkpointId); assertEquals(materializationId, mock.getLastCompletedCheckpointID()); } finally { changelog.close(); changelog.dispose(); } } @Test public void testInitMaterialization() throws Exception { MockKeyedStateBackend<Integer> delegatedBackend = createMock(); ChangelogKeyedStateBackend<Integer> backend = createChangelog(delegatedBackend); try { Optional<MaterializationRunnable> runnable; appendMockStateChange(backend); // ensure there is non-materialized changelog runnable = backend.initMaterialization(); // 1. should trigger first materialization assertTrue("first materialization should be trigger.", runnable.isPresent()); appendMockStateChange(backend); // ensure there is non-materialized changelog // 2. should not trigger new one until the previous one has been confirmed or failed assertFalse(backend.initMaterialization().isPresent()); backend.handleMaterializationFailureOrCancellation( runnable.get().getMaterializationID(), runnable.get().getMaterializedTo(), null); runnable = backend.initMaterialization(); // 3. should trigger new one after previous one failed assertTrue(runnable.isPresent()); appendMockStateChange(backend); // ensure there is non-materialized changelog // 4. should not trigger new one until the previous one has been confirmed or failed assertFalse(backend.initMaterialization().isPresent()); backend.handleMaterializationResult( SnapshotResult.empty(), runnable.get().getMaterializationID(), runnable.get().getMaterializedTo()); checkpoint(backend, checkpointId).get().discardState(); backend.notifyCheckpointComplete(checkpointId); // 5. should trigger new one after previous one has been confirmed assertTrue(backend.initMaterialization().isPresent()); } finally { backend.close(); backend.dispose(); } } private void appendMockStateChange(ChangelogKeyedStateBackend changelogKeyedBackend) throws IOException { changelogKeyedBackend.getChangelogWriter().append(0, new byte[] {'s'}); } private MockKeyedStateBackend<Integer> createMock() { return new MockKeyedStateBackendBuilder<>( new KvStateRegistry().createTaskRegistry(new JobID(), new JobVertexID()), IntSerializer.INSTANCE, getClass().getClassLoader(), 1, KeyGroupRange.of(0, 0), new ExecutionConfig(), TtlTimeProvider.DEFAULT, LatencyTrackingStateConfig.disabled(), SizeTrackingStateConfig.disabled(), emptyList(), UncompressedStreamCompressionDecorator.INSTANCE, new CloseableRegistry(), MockSnapshotSupplier.EMPTY) .build(); } private ChangelogKeyedStateBackend<Integer> createChangelog( MockKeyedStateBackend<Integer> mock) { return new ChangelogKeyedStateBackend<>( mock, "test", new ExecutionConfig(), TtlTimeProvider.DEFAULT, UnregisteredMetricGroups.createUnregisteredOperatorMetricGroup(), new InMemoryStateChangelogStorage() .createWriter("test", KeyGroupRange.EMPTY_KEY_GROUP_RANGE, null), emptyList(), new DummyCheckpointingStorageAccess()); } private RunnableFuture<SnapshotResult<KeyedStateHandle>> checkpoint( ChangelogKeyedStateBackend<Integer> backend, long checkpointId) throws Exception { return backend.snapshot( checkpointId, 0L, new MemCheckpointStreamFactory(1000), CheckpointOptions.forCheckpointWithDefaultLocation()); } }
ChangelogKeyedStateBackendTest
java
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/visitor/JavaBeanDefinitionBuilder.java
{ "start": 2152, "end": 9765 }
class ____ extends AbstractBeanDefinitionBuilder { private final JavaAnnotationMetadataBuilder annotationMetadataBuilder; /** * Default constructor. * * @param originatingElement The originating element * @param beanType The bean type * @param elementAnnotationMetadataFactory The element annotation metadata factory * @param visitorContext the visitor context */ JavaBeanDefinitionBuilder(Element originatingElement, ClassElement beanType, ElementAnnotationMetadataFactory elementAnnotationMetadataFactory, JavaVisitorContext visitorContext) { super(originatingElement, beanType, visitorContext, elementAnnotationMetadataFactory); if (visitorContext.getVisitorKind() == TypeElementVisitor.VisitorKind.ISOLATING) { if (getClass() == JavaBeanDefinitionBuilder.class) { visitorContext.addBeanDefinitionBuilder(this); } } else { visitorContext.fail("Cannot add bean definition using addAssociatedBean(..) from a AGGREGATING TypeElementVisitor, consider overriding getVisitorKind()", originatingElement); } this.annotationMetadataBuilder = visitorContext.getAnnotationMetadataBuilder(); } @NonNull @Override protected AbstractBeanDefinitionBuilder createChildBean(FieldElement producerField) { final ClassElement parentType = getBeanType(); return new JavaBeanDefinitionBuilder( JavaBeanDefinitionBuilder.this.getOriginatingElement(), producerField.getGenericField().getType(), elementAnnotationMetadataFactory, (JavaVisitorContext) JavaBeanDefinitionBuilder.this.visitorContext ) { @Override public @NonNull Element getProducingElement() { return producerField; } @Override public @NonNull ClassElement getDeclaringElement() { return producerField.getDeclaringType(); } @Override protected BeanDefinitionVisitor createBeanDefinitionWriter() { final BeanDefinitionVisitor writer = super.createBeanDefinitionWriter(); ClassElement newParent = parentType.withAnnotationMetadata(parentType.copyAnnotationMetadata()); // Just a copy writer.visitBeanFactoryField( newParent, producerField.withAnnotationMetadata( new AnnotationMetadataHierarchy(newParent.getDeclaredMetadata(), producerField.getDeclaredMetadata()) ) ); return writer; } }; } @NonNull @Override protected BeanDefinitionVisitor createAopWriter(BeanDefinitionWriter beanDefinitionWriter, AnnotationMetadata annotationMetadata) { AnnotationValue<?>[] interceptorTypes = InterceptedMethodUtil.resolveInterceptorBinding(annotationMetadata, InterceptorKind.AROUND); return new AopProxyWriter( getBeanType(), beanDefinitionWriter, annotationMetadata.getValues(Around.class, Boolean.class), visitorContext, interceptorTypes ); } @NonNull @Override protected BiConsumer<TypedElement, MethodElement> createAroundMethodVisitor(BeanDefinitionVisitor aopWriter) { AopProxyWriter aopProxyWriter = (AopProxyWriter) aopWriter; return (bean, method) -> { AnnotationValue<?>[] newTypes = InterceptedMethodUtil.resolveInterceptorBinding(method.getAnnotationMetadata(), InterceptorKind.AROUND); aopProxyWriter.visitInterceptorBinding(newTypes); aopProxyWriter.visitAroundMethod( bean, method ); }; } @NonNull @Override protected AbstractBeanDefinitionBuilder createChildBean(MethodElement producerMethod) { final ClassElement parentType = getBeanType(); return new JavaBeanDefinitionBuilder( JavaBeanDefinitionBuilder.this.getOriginatingElement(), producerMethod.getGenericReturnType(), elementAnnotationMetadataFactory, (JavaVisitorContext) JavaBeanDefinitionBuilder.this.visitorContext ) { BeanParameterElement[] parameters; @NonNull @Override public Element getProducingElement() { return producerMethod; } @NonNull @Override public ClassElement getDeclaringElement() { return producerMethod.getDeclaringType(); } @Override protected BeanParameterElement[] getParameters() { if (parameters == null) { parameters = initBeanParameters(producerMethod.getParameters()); } return parameters; } @Override protected BeanDefinitionVisitor createBeanDefinitionWriter() { final BeanDefinitionVisitor writer = super.createBeanDefinitionWriter(); ClassElement newParent = parentType.withAnnotationMetadata(parentType.copyAnnotationMetadata()); // Just a copy writer.visitBeanFactoryMethod( newParent, producerMethod.withAnnotationMetadata( new AnnotationMetadataHierarchy(newParent.getDeclaredMetadata(), producerMethod.getDeclaredMetadata()) ), getParameters() ); return writer; } }; } @Override protected <T extends Annotation> void annotate(@NonNull AnnotationMetadata annotationMetadata, @NonNull AnnotationValue<T> annotationValue) { ArgumentUtils.requireNonNull("annotationMetadata", annotationMetadata); ArgumentUtils.requireNonNull("annotationValue", annotationValue); annotationMetadataBuilder.annotate(annotationMetadata, annotationValue); } @Override protected <T extends Annotation> void annotate(AnnotationMetadata annotationMetadata, String annotationType, Consumer<AnnotationValueBuilder<T>> consumer) { ArgumentUtils.requireNonNull("annotationType", annotationType); ArgumentUtils.requireNonNull("consumer", consumer); final AnnotationValueBuilder<T> builder = AnnotationValue.builder(annotationType); consumer.accept(builder); final AnnotationValue<T> av = builder.build(); annotationMetadataBuilder.annotate(annotationMetadata, av); } @Override protected void removeStereotype(AnnotationMetadata annotationMetadata, String annotationType) { ArgumentUtils.requireNonNull("annotationType", annotationType); annotationMetadataBuilder.removeStereotype(annotationMetadata, annotationType); } @Override protected <T extends Annotation> void removeAnnotationIf(AnnotationMetadata annotationMetadata, Predicate<AnnotationValue<T>> predicate) { ArgumentUtils.requireNonNull("predicate", predicate); annotationMetadataBuilder.removeAnnotationIf(annotationMetadata, predicate); } @Override protected void removeAnnotation(AnnotationMetadata annotationMetadata, String annotationType) { ArgumentUtils.requireNonNull("annotationType", annotationType); annotationMetadataBuilder.removeAnnotation(annotationMetadata, annotationType); } }
JavaBeanDefinitionBuilder
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogstashStructuredLogFormatterTests.java
{ "start": 1367, "end": 4127 }
class ____ extends AbstractStructuredLoggingTests { private LogstashStructuredLogFormatter formatter; @Override @BeforeEach void setUp() { super.setUp(); this.formatter = new LogstashStructuredLogFormatter(null, TestContextPairs.include(), getThrowableProxyConverter(), this.customizer); } @Test void callsCustomizer() { then(this.customizer).should().customize(any()); } @Test void shouldFormat() { LoggingEvent event = createEvent(); event.setMDCPropertyMap(Map.of("mdc-1", "mdc-v-1")); event.setKeyValuePairs(keyValuePairs("kv-1", "kv-v-1")); Marker marker1 = getMarker("marker-1"); marker1.add(getMarker("marker-2")); event.addMarker(marker1); String json = this.formatter.format(event); assertThat(json).endsWith("\n"); Map<String, Object> deserialized = deserialize(json); String timestamp = DateTimeFormatter.ISO_OFFSET_DATE_TIME .format(OffsetDateTime.ofInstant(EVENT_TIME, ZoneId.systemDefault())); assertThat(deserialized).containsExactlyInAnyOrderEntriesOf(map("@timestamp", timestamp, "@version", "1", "message", "message", "logger_name", "org.example.Test", "thread_name", "main", "level", "INFO", "level_value", 20000, "mdc-1", "mdc-v-1", "kv-1", "kv-v-1", "tags", List.of("marker-1", "marker-2"))); } @Test void shouldFormatException() { LoggingEvent event = createEvent(); event.setThrowableProxy(new ThrowableProxy(new RuntimeException("Boom"))); event.setMDCPropertyMap(Collections.emptyMap()); String json = this.formatter.format(event); Map<String, Object> deserialized = deserialize(json); String stackTrace = (String) deserialized.get("stack_trace"); assertThat(stackTrace).startsWith( "java.lang.RuntimeException: Boom%n\tat org.springframework.boot.logging.logback.LogstashStructuredLogFormatterTests.shouldFormatException" .formatted()); assertThat(json).contains( "java.lang.RuntimeException: Boom%n\\tat org.springframework.boot.logging.logback.LogstashStructuredLogFormatterTests.shouldFormatException" .formatted() .replace("\n", "\\n") .replace("\r", "\\r")); } @Test void shouldFormatExceptionWithStackTracePrinter() { this.formatter = new LogstashStructuredLogFormatter(new SimpleStackTracePrinter(), TestContextPairs.include(), getThrowableProxyConverter(), this.customizer); LoggingEvent event = createEvent(); event.setThrowableProxy(new ThrowableProxy(new RuntimeException("Boom"))); event.setMDCPropertyMap(Collections.emptyMap()); String json = this.formatter.format(event); Map<String, Object> deserialized = deserialize(json); String stackTrace = (String) deserialized.get("stack_trace"); assertThat(stackTrace).isEqualTo("stacktrace:RuntimeException"); } }
LogstashStructuredLogFormatterTests
java
apache__camel
components/camel-infinispan/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/remote/InfinispanRemoteConsumer.java
{ "start": 3124, "end": 4457 }
class ____ extends ServiceSupport implements ContinuousQueryListener<Object, Object> { private ContinuousQuery<Object, Object> continuousQuery; @Override public void resultJoining(Object key, Object value) { processEvent(InfinispanConstants.CACHE_ENTRY_JOINING, cacheName, key, value, null); } @Override public void resultUpdated(Object key, Object value) { processEvent(InfinispanConstants.CACHE_ENTRY_UPDATED, cacheName, key, value, null); } @Override public void resultLeaving(Object key) { processEvent(InfinispanConstants.CACHE_ENTRY_LEAVING, cacheName, key, null, null); } @SuppressWarnings("unchecked") @Override public void doStart() { RemoteCache<Object, Object> remoteCache = getCache(RemoteCache.class); Query<?> query = InfinispanRemoteUtil.buildQuery(getConfiguration().getQueryBuilder(), remoteCache); continuousQuery = remoteCache.continuousQuery(); continuousQuery.addContinuousQueryListener(query, this); } @Override public void doStop() { if (continuousQuery != null) { continuousQuery.removeAllListeners(); } } } private
ContinuousQueryHandler
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanConfigurationErrorTests.java
{ "start": 5072, "end": 5149 }
class ____ { @MockitoSpyBean String example; } static
ByTypeSingleLookup
java
grpc__grpc-java
services/src/generated/main/grpc/io/grpc/channelz/v1/ChannelzGrpc.java
{ "start": 23183, "end": 26700 }
class ____ extends io.grpc.stub.AbstractBlockingStub<ChannelzBlockingV2Stub> { private ChannelzBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ChannelzBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ChannelzBlockingV2Stub(channel, callOptions); } /** * <pre> * Gets all root channels (i.e. channels the application has directly * created). This does not include subchannels nor non-top level channels. * </pre> */ public io.grpc.channelz.v1.GetTopChannelsResponse getTopChannels(io.grpc.channelz.v1.GetTopChannelsRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetTopChannelsMethod(), getCallOptions(), request); } /** * <pre> * Gets all servers that exist in the process. * </pre> */ public io.grpc.channelz.v1.GetServersResponse getServers(io.grpc.channelz.v1.GetServersRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetServersMethod(), getCallOptions(), request); } /** * <pre> * Returns a single Server, or else a NOT_FOUND code. * </pre> */ public io.grpc.channelz.v1.GetServerResponse getServer(io.grpc.channelz.v1.GetServerRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetServerMethod(), getCallOptions(), request); } /** * <pre> * Gets all server sockets that exist in the process. * </pre> */ public io.grpc.channelz.v1.GetServerSocketsResponse getServerSockets(io.grpc.channelz.v1.GetServerSocketsRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetServerSocketsMethod(), getCallOptions(), request); } /** * <pre> * Returns a single Channel, or else a NOT_FOUND code. * </pre> */ public io.grpc.channelz.v1.GetChannelResponse getChannel(io.grpc.channelz.v1.GetChannelRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetChannelMethod(), getCallOptions(), request); } /** * <pre> * Returns a single Subchannel, or else a NOT_FOUND code. * </pre> */ public io.grpc.channelz.v1.GetSubchannelResponse getSubchannel(io.grpc.channelz.v1.GetSubchannelRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetSubchannelMethod(), getCallOptions(), request); } /** * <pre> * Returns a single Socket or else a NOT_FOUND code. * </pre> */ public io.grpc.channelz.v1.GetSocketResponse getSocket(io.grpc.channelz.v1.GetSocketRequest request) throws io.grpc.StatusException { return io.grpc.stub.ClientCalls.blockingV2UnaryCall( getChannel(), getGetSocketMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service Channelz. * <pre> * Channelz is a service exposed by gRPC servers that provides detailed debug * information. * </pre> */ public static final
ChannelzBlockingV2Stub
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/streaming/StreamingWrite.java
{ "start": 1099, "end": 2285 }
interface ____ defines how to write the data to data source in streaming queries. * * The writing procedure is: * <ol> * <li>Create a writer factory by {@link #createStreamingWriterFactory(PhysicalWriteInfo)}, * serialize and send it to all the partitions of the input data(RDD).</li> * <li>For each epoch in each partition, create the data writer, and write the data of the * epoch in the partition with this writer. If all the data are written successfully, call * {@link DataWriter#commit()}. If exception happens during the writing, call * {@link DataWriter#abort()}.</li> * <li>If writers in all partitions of one epoch are successfully committed, call * {@link #commit(long, WriterCommitMessage[])}. If some writers are aborted, or the job failed * with an unknown reason, call {@link #abort(long, WriterCommitMessage[])}.</li> * </ol> * <p> * While Spark will retry failed writing tasks, Spark won't retry failed writing jobs. Users should * do it manually in their Spark applications if they want to retry. * <p> * Please refer to the documentation of commit/abort methods for detailed specifications. * * @since 3.0.0 */ @Evolving public
that
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/id/enhanced/InitialValueAwareOptimizer.java
{ "start": 144, "end": 396 }
interface ____ optimizer which wishes to know the user-specified initial value. * <p> * Used instead of constructor injection since that is already a public understanding and * because not all optimizers care. * * @author Steve Ebersole */ public
for
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/ConsoleAppenderAnsiStyleJira272Main.java
{ "start": 1509, "end": 2593 }
class ____ { private static final Logger LOG = LogManager.getLogger(ConsoleAppenderAnsiStyleJira272Main.class); public static void main(final String[] args) { final String config = args.length == 0 ? "target/test-classes/log4j2-272.xml" : args[0]; try (final LoggerContext ignored = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (final Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?"); LOG.info("Information message."); } } }
ConsoleAppenderAnsiStyleJira272Main
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conditional/propertyname/sourcepropertyname/ErroneousNonStringSourcePropertyNameParameter.java
{ "start": 503, "end": 886 }
interface ____ { @Mapping(target = "country", source = "originCountry") @Mapping(target = "addresses", source = "originAddresses") Employee map(EmployeeDto employee); @Condition default boolean isNotBlank(String value, @SourcePropertyName int propName) { return value != null && !value.trim().isEmpty(); } }
ErroneousNonStringSourcePropertyNameParameter
java
elastic__elasticsearch
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramGenerator.java
{ "start": 1370, "end": 1705 }
class ____ accumulating raw values into an {@link ExponentialHistogram} with a given maximum number of buckets. * * If the number of values is less than or equal to the bucket capacity, the resulting histogram is guaranteed * to represent the exact raw values with a relative error less than {@code 2^(2^-MAX_SCALE) - 1}. */ public
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/notfound/RequiredLazyNotFoundTest.java
{ "start": 8346, "end": 8897 }
class ____ extends Person { @Id private Long id; @OneToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) @MapsId @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) private City city; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public City getCity() { return city; } @Override public void setCity(City city) { this.city = city; } } @Entity @Table(name = "PersonMapsIdSelectException") public static
PersonMapsIdJoinException
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/typeutils/AbstractMapSerializer.java
{ "start": 1657, "end": 6225 }
class ____<K, V, M extends Map<K, V>> extends TypeSerializer<M> { private static final long serialVersionUID = 1L; /** The serializer for the keys in the map. */ final TypeSerializer<K> keySerializer; /** The serializer for the values in the map. */ final TypeSerializer<V> valueSerializer; /** * Creates a map serializer that uses the given serializers to serialize the key-value pairs in * the map. * * @param keySerializer The serializer for the keys in the map * @param valueSerializer The serializer for the values in the map */ AbstractMapSerializer(TypeSerializer<K> keySerializer, TypeSerializer<V> valueSerializer) { Preconditions.checkNotNull(keySerializer, "The key serializer must not be null"); Preconditions.checkNotNull(valueSerializer, "The value serializer must not be null."); this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; } // ------------------------------------------------------------------------ /** * Returns the serializer for the keys in the map. * * @return The serializer for the keys in the map. */ public TypeSerializer<K> getKeySerializer() { return keySerializer; } /** * Returns the serializer for the values in the map. * * @return The serializer for the values in the map. */ public TypeSerializer<V> getValueSerializer() { return valueSerializer; } // ------------------------------------------------------------------------ // Type Serializer implementation // ------------------------------------------------------------------------ @Override public boolean isImmutableType() { return false; } @Override public M copy(M from) { M newMap = createInstance(); for (Map.Entry<K, V> entry : from.entrySet()) { K newKey = entry.getKey() == null ? null : keySerializer.copy(entry.getKey()); V newValue = entry.getValue() == null ? null : valueSerializer.copy(entry.getValue()); newMap.put(newKey, newValue); } return newMap; } @Override public M copy(M from, M reuse) { return copy(from); } @Override public int getLength() { return -1; // var length } @Override public void serialize(M map, DataOutputView target) throws IOException { final int size = map.size(); target.writeInt(size); for (Map.Entry<K, V> entry : map.entrySet()) { keySerializer.serialize(entry.getKey(), target); if (entry.getValue() == null) { target.writeBoolean(true); } else { target.writeBoolean(false); valueSerializer.serialize(entry.getValue(), target); } } } @Override public M deserialize(DataInputView source) throws IOException { final int size = source.readInt(); final M map = createInstance(); for (int i = 0; i < size; ++i) { K key = keySerializer.deserialize(source); boolean isNull = source.readBoolean(); V value = isNull ? null : valueSerializer.deserialize(source); map.put(key, value); } return map; } @Override public M deserialize(M reuse, DataInputView source) throws IOException { return deserialize(source); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { final int size = source.readInt(); target.writeInt(size); for (int i = 0; i < size; ++i) { keySerializer.copy(source, target); boolean isNull = source.readBoolean(); target.writeBoolean(isNull); if (!isNull) { valueSerializer.copy(source, target); } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractMapSerializer<?, ?, ?> that = (AbstractMapSerializer<?, ?, ?>) o; return keySerializer.equals(that.keySerializer) && valueSerializer.equals(that.valueSerializer); } @Override public int hashCode() { int result = keySerializer.hashCode(); result = 31 * result + valueSerializer.hashCode(); return result; } }
AbstractMapSerializer
java
quarkusio__quarkus
independent-projects/resteasy-reactive/client/processor/src/main/java/org/jboss/resteasy/reactive/client/processor/beanparam/ItemType.java
{ "start": 72, "end": 203 }
enum ____ { BEAN_PARAM, QUERY_PARAM, COOKIE, HEADER_PARAM, PATH_PARAM, FORM_PARAM, // TODO: more }
ItemType
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/function/json/JsonArrayUnnestTest.java
{ "start": 7632, "end": 8076 }
class ____ { @Id private Long id; private String title; @JdbcTypeCode(SqlTypes.JSON_ARRAY) private Publisher[] publishers; @JdbcTypeCode(SqlTypes.JSON_ARRAY) private List<Label> labels; public Book() { } public Book(Long id, String title, Publisher[] publishers, List<Label> labels) { this.id = id; this.title = title; this.publishers = publishers; this.labels = labels; } } @Embeddable public static
Book
java
apache__camel
components/camel-xslt/src/main/java/org/apache/camel/component/xslt/XsltUriResolverFactory.java
{ "start": 1574, "end": 1936 }
interface ____ { /** * Method is called during the creation of a xslt endpoint. * * @param camelContext camel context * @param resourceUri resource URI specified in the endpoint URI * @return URI resolver */ URIResolver createUriResolver(CamelContext camelContext, String resourceUri); }
XsltUriResolverFactory
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/data/ExponentialHistogramBlock.java
{ "start": 716, "end": 867 }
enum ____ the components * that can be directly accessed, potentially avoiding loading the entire histogram from disk. * <br> * This
defines
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/runtime/src/main/java/io/quarkus/rest/client/reactive/QuarkusRestClientBuilder.java
{ "start": 10556, "end": 13155 }
class ____ use. * @return the current builder */ QuarkusRestClientBuilder clientHeadersFactory(Class<? extends ClientHeadersFactory> clientHeadersFactoryClass); /** * Specifies the client headers factory to use. * * @param clientHeadersFactory the client headers factory to use. * @return the current builder */ QuarkusRestClientBuilder clientHeadersFactory(ClientHeadersFactory clientHeadersFactory); /** * Specifies the HTTP client options to use. * * @param httpClientOptionsClass the HTTP client options to use. * @return the current builder */ QuarkusRestClientBuilder httpClientOptions(Class<? extends HttpClientOptions> httpClientOptionsClass); /** * Specifies the HTTP client options to use. * * @param httpClientOptions the HTTP client options to use. * @return the current builder */ QuarkusRestClientBuilder httpClientOptions(HttpClientOptions httpClientOptions); /** * Specifies the client logger to use. * * @param clientLogger the client logger to use. * @return the current builder */ QuarkusRestClientBuilder clientLogger(ClientLogger clientLogger); /** * Specifies the client logger to use. * * @param loggingScope to use * @return the current builder */ QuarkusRestClientBuilder loggingScope(LoggingScope loggingScope); /** * How many characters of the body should be logged. Message body can be large and can easily pollute the logs. * */ QuarkusRestClientBuilder loggingBodyLimit(Integer limit); /** * Enable trusting all certificates. Disable by default. */ QuarkusRestClientBuilder trustAll(boolean trustAll); /** * Set the User-Agent header to be used */ QuarkusRestClientBuilder userAgent(String userAgent); /** * If set to {@code true}, then this REST Client will not the default exception mapper which * always throws an exception if HTTP response code >= 400 */ QuarkusRestClientBuilder disableDefaultMapper(Boolean disable); /** * Supports receiving compressed messages using GZIP. * When this feature is enabled and a server returns a response that includes the header {@code Content-Encoding: gzip}, * REST Client will automatically decode the content and proceed with the message handling. */ QuarkusRestClientBuilder enableCompression(boolean enableCompression); /** * Based on the configured QuarkusRestClientBuilder, creates a new instance of the given REST
to
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest93.java
{ "start": 942, "end": 8566 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE TABLE \"GXYY\".\"EMR_MED_REC\" \n" + " ( \"PK_REC\" CHAR(32), \n" + " \"PK_PATREC\" CHAR(32), \n" + " \"NAME\" VARCHAR2(64), \n" + " \"SEQ_NO\" NUMBER(18,0), \n" + " \"REC_DATE\" TIMESTAMP (3), \n" + " \"DESCRIBE\" VARCHAR2(64), \n" + " \"PK_PI\" CHAR(32), \n" + " \"TIMES\" NUMBER(5,0), \n" + " \"PK_PV\" CHAR(32), \n" + " \"PK_DEPT\" CHAR(32), \n" + " \"PK_WARD\" CHAR(32), \n" + " \"TYPE_CODE\" VARCHAR2(20), \n" + " \"PK_TMP\" CHAR(32), \n" + " \"PK_DOC\" CHAR(32), \n" + " \"FLAG_AUDIT\" CHAR(1), \n" + " \"EU_AUDIT_LEVEL\" NUMBER(2,0), \n" + " \"EU_DOC_STATUS\" CHAR(1), \n" + " \"EU_AUDIT_STATUS\" CHAR(1), \n" + " \"PK_EMP_REFER\" CHAR(32), \n" + " \"REFER_SIGN_DATE\" TIMESTAMP (3), \n" + " \"PK_EMP_CONSULT_ACT\" CHAR(32), \n" + " \"PK_EMP_CONSULT\" CHAR(32), \n" + " \"CONSULT_AUDIT_DATE\" TIMESTAMP (3), \n" + " \"CONSULT_SIGN_DATE\" TIMESTAMP (3), \n" + " \"PK_EMP_DIRECTOR_ACT\" CHAR(32), \n" + " \"PK_EMP_DIRECTOR\" CHAR(32), \n" + " \"DIRECTOR_AUDIT_DATE\" TIMESTAMP (3), \n" + " \"DIRECTOR_SIGN_DATE\" TIMESTAMP (3), \n" + " \"DOC_DATA\" LONG RAW, \n" + " \"DOC_XML\" \"SYS\".\"XMLTYPE\" , \n" + " \"DEL_FLAG\" CHAR(1), \n" + " \"REMARK\" VARCHAR2(64), \n" + " \"CREATOR\" VARCHAR2(32), \n" + " \"CREATE_TIME\" TIMESTAMP (3), \n" + " \"TS\" TIMESTAMP (3), \n" + " \"FLAG_AUDIT_FINISH\" CHAR(1), \n" + " \"AUDIT_LEVEL_SET\" VARCHAR2(32), \n" + " \"PK_EMP_INTERN\" VARCHAR2(32), \n" + " \"INTERN_SIGN_DATE\" DATE, \n" + " \"PK_EMP_REFER_ACT\" VARCHAR2(32), \n" + " \"REFER_AUDIT_DATE\" DATE\n" + " ) SEGMENT CREATION IMMEDIATE \n" + " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" + " NOCOMPRESS LOGGING\n" + " STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" + " TABLESPACE \"GXDATA\" \n" + " XMLTYPE COLUMN \"DOC_XML\" STORE AS SECUREFILE BINARY XML (\n" + " TABLESPACE \"GXDATA\" ENABLE STORAGE IN ROW CHUNK 8192\n" + " NOCACHE LOGGING NOCOMPRESS KEEP_DUPLICATES \n" + " STORAGE(INITIAL 106496 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)) ALLOW NONSCHEMA DISALLOW ANYSCHEMA;"; 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(1, visitor.getTables().size()); assertEquals("CREATE TABLE \"GXYY\".\"EMR_MED_REC\" (\n" + "\t\"PK_REC\" CHAR(32),\n" + "\t\"PK_PATREC\" CHAR(32),\n" + "\t\"NAME\" VARCHAR2(64),\n" + "\t\"SEQ_NO\" NUMBER(18, 0),\n" + "\t\"REC_DATE\" TIMESTAMP(3),\n" + "\t\"DESCRIBE\" VARCHAR2(64),\n" + "\t\"PK_PI\" CHAR(32),\n" + "\t\"TIMES\" NUMBER(5, 0),\n" + "\t\"PK_PV\" CHAR(32),\n" + "\t\"PK_DEPT\" CHAR(32),\n" + "\t\"PK_WARD\" CHAR(32),\n" + "\t\"TYPE_CODE\" VARCHAR2(20),\n" + "\t\"PK_TMP\" CHAR(32),\n" + "\t\"PK_DOC\" CHAR(32),\n" + "\t\"FLAG_AUDIT\" CHAR(1),\n" + "\t\"EU_AUDIT_LEVEL\" NUMBER(2, 0),\n" + "\t\"EU_DOC_STATUS\" CHAR(1),\n" + "\t\"EU_AUDIT_STATUS\" CHAR(1),\n" + "\t\"PK_EMP_REFER\" CHAR(32),\n" + "\t\"REFER_SIGN_DATE\" TIMESTAMP(3),\n" + "\t\"PK_EMP_CONSULT_ACT\" CHAR(32),\n" + "\t\"PK_EMP_CONSULT\" CHAR(32),\n" + "\t\"CONSULT_AUDIT_DATE\" TIMESTAMP(3),\n" + "\t\"CONSULT_SIGN_DATE\" TIMESTAMP(3),\n" + "\t\"PK_EMP_DIRECTOR_ACT\" CHAR(32),\n" + "\t\"PK_EMP_DIRECTOR\" CHAR(32),\n" + "\t\"DIRECTOR_AUDIT_DATE\" TIMESTAMP(3),\n" + "\t\"DIRECTOR_SIGN_DATE\" TIMESTAMP(3),\n" + "\t\"DOC_DATA\" LONG RAW,\n" + "\t\"DOC_XML\" \"SYS\".\"XMLTYPE\",\n" + "\t\"DEL_FLAG\" CHAR(1),\n" + "\t\"REMARK\" VARCHAR2(64),\n" + "\t\"CREATOR\" VARCHAR2(32),\n" + "\t\"CREATE_TIME\" TIMESTAMP(3),\n" + "\t\"TS\" TIMESTAMP(3),\n" + "\t\"FLAG_AUDIT_FINISH\" CHAR(1),\n" + "\t\"AUDIT_LEVEL_SET\" VARCHAR2(32),\n" + "\t\"PK_EMP_INTERN\" VARCHAR2(32),\n" + "\t\"INTERN_SIGN_DATE\" DATE,\n" + "\t\"PK_EMP_REFER_ACT\" VARCHAR2(32),\n" + "\t\"REFER_AUDIT_DATE\" DATE\n" + ")\n" + "PCTFREE 10\n" + "PCTUSED 40\n" + "INITRANS 1\n" + "MAXTRANS 255\n" + "NOCOMPRESS\n" + "LOGGING\n" + "TABLESPACE \"GXDATA\"\n" + "STORAGE (\n" + "\tINITIAL 65536\n" + "\tNEXT 1048576\n" + "\tMINEXTENTS 1\n" + "\tMAXEXTENTS 2147483645\n" + "\tPCTINCREASE 0\n" + "\tFREELISTS 1\n" + "\tFREELIST GROUPS 1\n" + "\tBUFFER_POOL DEFAULT\n" + "\tFLASH_CACHE DEFAULT\n" + "\tCELL_FLASH_CACHE DEFAULT\n" + ")\n" + "XMLTYPE \"DOC_XML\" ALLOW NONSCHEMA DISALLOW ANYSCHEMA;", stmt.toString()); } }
OracleCreateTableTest93
java
elastic__elasticsearch
x-pack/plugin/esql/src/internalClusterTest/java/org/elasticsearch/xpack/esql/spatial/StGeohexLicenseIT.java
{ "start": 718, "end": 1378 }
class ____ extends SpatialGridLicenseTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return List.of(SpatialPlugin.class, EsqlPluginWithEnterpriseOrTrialLicense.class); } @Override protected String gridFunction() { return "ST_GEOHEX"; } @Override protected DataType gridType() { return DataType.GEOHEX; } @Override protected long pointToGridId(Point point) { return StGeohex.unboundedGrid.calculateGridId(point, precision()); } public void testGeoGridWithShapes() { assertGeoGridFromIndex("index_geo_shape"); } }
StGeohexLicenseIT
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTests.java
{ "start": 16917, "end": 17707 }
class ____ { @Bean SecurityWebFilterChain filterChain(ServerHttpSecurity http) { // @formatter:off http .authorizeExchange((authorize) -> authorize.anyExchange().authenticated()) .httpBasic(Customizer.withDefaults()); // @formatter:on return http.build(); } @Bean ReactiveUserDetailsService userDetailsService() { return new MapReactiveUserDetailsService( User.withUsername("user").password("password").authorities("app").build()); } @Bean TestController testController() { return new TestController(); } @Bean AnnotationTemplateExpressionDefaults templateExpressionDefaults() { return new AnnotationTemplateExpressionDefaults(); } } @Configuration @EnableWebFlux @EnableWebFluxSecurity static
MetaAnnotationPlaceholderConfig
java
google__guice
extensions/throwingproviders/src/com/google/inject/throwingproviders/CheckedProvides.java
{ "start": 1510, "end": 1549 }
interface ____ { /** The
CheckedProvides
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/SecondaryRow.java
{ "start": 620, "end": 1423 }
interface ____ { /** * The name of the secondary table, as specified by * {@link jakarta.persistence.SecondaryTable#name()}. */ String table() default ""; /** * If disabled, Hibernate will never insert or update the columns of the secondary table. * <p> * This setting is useful if data in the secondary table belongs to some other entity, * or if it is maintained externally to Hibernate. */ boolean owned() default true; /** * Unless disabled, specifies that no row should be inserted in the secondary table if * all the columns of the secondary table would be null. Furthermore, an outer join will * always be used to read the row. Thus, by default, Hibernate avoids creating a row * containing only null column values. */ boolean optional() default true; }
SecondaryRow
java
spring-projects__spring-boot
module/spring-boot-cassandra/src/main/java/org/springframework/boot/cassandra/autoconfigure/CassandraProperties.java
{ "start": 8467, "end": 10293 }
class ____ { /** * Request throttling type. */ private @Nullable ThrottlerType type; /** * Maximum number of requests that can be enqueued when the throttling threshold * is exceeded. */ private @Nullable Integer maxQueueSize; /** * Maximum number of requests that are allowed to execute in parallel. */ private @Nullable Integer maxConcurrentRequests; /** * Maximum allowed request rate. */ private @Nullable Integer maxRequestsPerSecond; /** * How often the throttler attempts to dequeue requests. Set this high enough that * each attempt will process multiple entries in the queue, but not delay requests * too much. */ private @Nullable Duration drainInterval; public @Nullable ThrottlerType getType() { return this.type; } public void setType(@Nullable ThrottlerType type) { this.type = type; } public @Nullable Integer getMaxQueueSize() { return this.maxQueueSize; } public void setMaxQueueSize(@Nullable Integer maxQueueSize) { this.maxQueueSize = maxQueueSize; } public @Nullable Integer getMaxConcurrentRequests() { return this.maxConcurrentRequests; } public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) { this.maxConcurrentRequests = maxConcurrentRequests; } public @Nullable Integer getMaxRequestsPerSecond() { return this.maxRequestsPerSecond; } public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) { this.maxRequestsPerSecond = maxRequestsPerSecond; } public @Nullable Duration getDrainInterval() { return this.drainInterval; } public void setDrainInterval(@Nullable Duration drainInterval) { this.drainInterval = drainInterval; } } /** * Name of the algorithm used to compress protocol frames. */ public
Throttler
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/BeanNotOfRequiredTypeFailureAnalyzerTests.java
{ "start": 3252, "end": 3371 }
class ____ implements SomeInterface { @Async void foo() { } @Override public void bar() { } }
AsyncBean
java
resilience4j__resilience4j
resilience4j-ratelimiter/src/main/java/io/github/resilience4j/ratelimiter/event/RateLimiterOnSuccessEvent.java
{ "start": 699, "end": 1107 }
class ____ extends AbstractRateLimiterEvent { public RateLimiterOnSuccessEvent(String rateLimiterName) { super(rateLimiterName, 1); } public RateLimiterOnSuccessEvent(String rateLimiterName, int numberOfPermits) { super(rateLimiterName, numberOfPermits); } @Override public Type getEventType() { return Type.SUCCESSFUL_ACQUIRE; } }
RateLimiterOnSuccessEvent
java
apache__flink
flink-clients/src/test/java/org/apache/flink/client/program/ClientTest.java
{ "start": 17795, "end": 18265 }
class ____ { public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromData(1, 2).sinkTo(new DiscardingSink<>()); JobExecutionResult result = env.execute(); result.getAccumulatorResult("dummy"); } } /** Test job with multiple execute() calls. */ public static final
TestEager
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/model/dataformat/DummyDataformat.java
{ "start": 1087, "end": 1805 }
class ____ extends ServiceSupport implements DataFormat, DataFormatName { private String name; private String version; @Override public void marshal(Exchange exchange, Object graph, OutputStream stream) { } @Override public Object unmarshal(Exchange exchange, InputStream stream) { return null; } @Override public String getDataFormatName() { return "dummy"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
DummyDataformat
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/MixinsWithBundlesTest.java
{ "start": 735, "end": 1259 }
class ____ { private String stuff; Foo(String stuff) { this.stuff = stuff; } public String getStuff() { return stuff; } } @Test public void testMixinWithBundles() throws Exception { ObjectMapper mapper = jsonMapperBuilder() .addMixIn(Foo.class, FooMixin.class) .build(); String result = mapper.writeValueAsString(new Foo("result")); assertEquals("{\"bar\":\"result\"}", result); } }
Foo
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/support/CallbackPreferringPlatformTransactionManager.java
{ "start": 1116, "end": 1344 }
interface ____ express a preference for * callbacks over programmatic {@code getTransaction}, {@code commit} * and {@code rollback} calls. Calling code may check whether a given * transaction manager implements this
automatically
java
elastic__elasticsearch
modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java
{ "start": 11566, "end": 12802 }
class ____ extends DefaultMustache { private static final String CODE = "url"; private final Encoder encoder; UrlEncoderCode(TemplateContext tc, DefaultMustacheFactory df, Mustache mustache, String variable) { super(tc, df, mustache.getCodes(), variable); this.encoder = new UrlEncoder(); } @Override public Writer run(Writer writer, List<Object> scopes) { if (getCodes() != null) { for (Code code : getCodes()) { try (StringWriter capture = new StringWriter()) { code.execute(capture, scopes); String s = capture.toString(); if (s != null) { encoder.encode(s, writer); } } catch (IOException e) { throw new MustacheException("Exception while parsing mustache function at line " + tc.line(), e); } } } return writer; } static boolean match(String variable) { return CODE.equalsIgnoreCase(variable); } } @FunctionalInterface
UrlEncoderCode
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ValidRepresentation.java
{ "start": 152, "end": 392 }
class ____ { @NotEmpty private String name = ""; @JsonProperty public String getName() { return name; } @JsonProperty public void setName(String name) { this.name = name; } }
ValidRepresentation
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/config/TimeoutConfigTest.java
{ "start": 607, "end": 2461 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(jar -> jar.addClasses(TimeoutConfigBean.class)) .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.TimeoutConfigBean/value\".timeout.value", "1000") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.TimeoutConfigBean/unit\".timeout.unit", "millis") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.TimeoutConfigBean/both\".timeout.value", "1000") .overrideConfigKey( "quarkus.fault-tolerance.\"io.quarkus.smallrye.faulttolerance.test.config.TimeoutConfigBean/both\".timeout.unit", "millis"); @Inject private TimeoutConfigBean bean; @Test public void value() { doTest(() -> bean.value()); } @Test public void unit() { doTest(() -> bean.unit()); } @Test public void both() { doTest(() -> { try { bean.both().toCompletableFuture().get(1, TimeUnit.MINUTES); } catch (ExecutionException e) { throw e.getCause(); } }); } private void doTest(ThrowingCallable action) { long start = System.nanoTime(); assertThatThrownBy(action).isExactlyInstanceOf(TimeoutException.class); long end = System.nanoTime(); long durationInMillis = Duration.ofNanos(end - start).toMillis(); assertThat(durationInMillis).isGreaterThan(800); assertThat(durationInMillis).isLessThan(2000); } }
TimeoutConfigTest
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/remote/client/RpcTlsConfigFactory.java
{ "start": 827, "end": 2062 }
interface ____ { /** * Create a TlsConfig for SDK connections based on the provided properties. * * @param properties Properties containing configuration * @return TlsConfig instance for SDK connections */ TlsConfig createSdkConfig(Properties properties); /** * Create a TlsConfig for cluster connections based on the provided properties. * * @param properties Properties containing configuration * @return TlsConfig instance for cluster connections */ TlsConfig createClusterConfig(Properties properties); /** * Get boolean property from properties. * * @param properties Properties containing configuration * @param key Key of the property * @param defaultValue Default value to return if the property is not found or is invalid * @return Boolean value of the property, or the provided defaultValue if not found or invalid */ default Boolean getBooleanProperty(Properties properties, String key, Boolean defaultValue) { String value = properties.getProperty(key); if (value != null) { return Boolean.parseBoolean(value); } return defaultValue; } }
RpcTlsConfigFactory
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/analysis/AnalyzerRules.java
{ "start": 1526, "end": 2212 }
class ____<SubPlan extends LogicalPlan, P> extends ParameterizedRule< SubPlan, LogicalPlan, P> { // transformUp (post-order) - that is first children and then the node // but with a twist; only if the tree is not resolved or analyzed public final LogicalPlan apply(LogicalPlan plan, P context) { return plan.transformUp(typeToken(), t -> t.analyzed() || skipResolved() && t.resolved() ? t : rule(t, context)); } protected abstract LogicalPlan rule(SubPlan plan, P context); protected boolean skipResolved() { return true; } } public abstract static
ParameterizedAnalyzerRule
java
google__guava
android/guava/src/com/google/common/base/Equivalence.java
{ "start": 7997, "end": 11811 }
class ____<T extends @Nullable Object> implements Serializable { /* * Equivalence's type argument is always non-nullable: Equivalence<Number>, never * Equivalence<@Nullable Number>. That can still produce wrappers of various types -- * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just * Equivalence<? super T> below, no type could satisfy both that bound and T's own * bound. With this type, they have some overlap: in our example, Equivalence<Number> * and Equivalence<Object>. */ private final Equivalence<? super @NonNull T> equivalence; @ParametricNullness private final T reference; private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) { this.equivalence = checkNotNull(equivalence); this.reference = reference; } /** Returns the (possibly null) reference wrapped by this instance. */ @ParametricNullness public T get() { return reference; } /** * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} * equivalence. */ @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof Wrapper) { Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> if (this.equivalence.equals(that.equivalence)) { /* * We'll accept that as sufficient "proof" that either equivalence should be able to * handle either reference, so it's safe to circumvent compile-time type checking. */ @SuppressWarnings("unchecked") Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; return equivalence.equivalent(this.reference, that.reference); } } return false; } /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */ @Override public int hashCode() { return equivalence.hash(reference); } /** * Returns a string representation for this equivalence wrapper. The form of this string * representation is not specified. */ @Override public String toString() { return equivalence + ".wrap(" + reference + ")"; } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Returns an equivalence over iterables based on the equivalence of their elements. More * specifically, two iterables are considered equivalent if they both contain the same number of * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null * iterables are equivalent to one another. * * <p>Note that this method performs a similar function for equivalences as {@link * com.google.common.collect.Ordering#lexicographical} does for orderings. * * <p>The returned object is serializable if this object is serializable. * * @since 10.0 */ public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() { // Ideally, the returned equivalence would support Iterable<? extends T>. However, // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. return new PairwiseEquivalence<>(this); } /** * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code * target} according to this equivalence relation. * * @since 10.0 */ public final Predicate<@Nullable T> equivalentTo(@Nullable T target) { return new EquivalentToPredicate<>(this, target); } private static final
Wrapper
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/filters/NameFilterClassLevelTest.java
{ "start": 316, "end": 1212 }
class ____ extends TestCase { public void test_0() throws Exception { Object[] array = { new ModelA(), new ModelB() }; SerializeConfig config = new SerializeConfig(); config.addFilter(ModelA.class, // new PascalNameFilter()); config.addFilter(ModelB.class, // new NameFilter() { @Override public String process(Object object, String name, Object value) { return name; } }); String text2 = JSON.toJSONString(array, config); Assert.assertEquals("[{\"Id\":1001},{\"id\":1002}]", text2); String text = JSON.toJSONString(array); Assert.assertEquals("[{\"id\":1001},{\"id\":1002}]", text); } public static
NameFilterClassLevelTest
java
apache__spark
sql/hive/src/test/java/org/apache/spark/sql/hive/execution/UDFCatchException.java
{ "start": 1139, "end": 1778 }
class ____ extends GenericUDF { @Override public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException { if (args.length != 1) { throw new UDFArgumentException("Exactly one argument is expected."); } return PrimitiveObjectInspectorFactory.javaStringObjectInspector; } @Override public Object evaluate(GenericUDF.DeferredObject[] args) { if (args == null) { return null; } try { return args[0].get(); } catch (Exception e) { return null; } } @Override public String getDisplayString(String[] children) { return null; } }
UDFCatchException
java
netty__netty
handler/src/main/java/io/netty/handler/traffic/package-info.java
{ "start": 1077, "end": 1385 }
class ____ the counters needed by the * handlers. It can be accessed to get some extra information like the read or write bytes since last check, * the read and write bandwidth from last check...</li> * * <li> <tt>{@link io.netty.handler.traffic.AbstractTrafficShapingHandler}</tt>: this abstract
implements
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SmbEndpointBuilderFactory.java
{ "start": 145227, "end": 150116 }
interface ____ extends AdvancedSmbEndpointConsumerBuilder, AdvancedSmbEndpointProducerBuilder { default SmbEndpointBuilder basic() { return (SmbEndpointBuilder) this; } /** * Automatically create missing directories in the file's pathname. For * the file consumer, that means creating the starting directory. For * the file producer, it means the directory the files should be written * to. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param autoCreate the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder autoCreate(boolean autoCreate) { doSetProperty("autoCreate", autoCreate); return this; } /** * Automatically create missing directories in the file's pathname. For * the file consumer, that means creating the starting directory. For * the file producer, it means the directory the files should be written * to. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param autoCreate the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder autoCreate(String autoCreate) { doSetProperty("autoCreate", autoCreate); return this; } /** * Maximum number of messages to keep in memory available for browsing. * Use 0 for unlimited. * * The option is a: <code>int</code> type. * * Default: 100 * Group: advanced * * @param browseLimit the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder browseLimit(int browseLimit) { doSetProperty("browseLimit", browseLimit); return this; } /** * Maximum number of messages to keep in memory available for browsing. * Use 0 for unlimited. * * The option will be converted to a <code>int</code> type. * * Default: 100 * Group: advanced * * @param browseLimit the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder browseLimit(String browseLimit) { doSetProperty("browseLimit", browseLimit); return this; } /** * Buffer size in bytes used for writing files (or in case of FTP for * downloading and uploading files). * * The option is a: <code>int</code> type. * * Default: 131072 * Group: advanced * * @param bufferSize the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder bufferSize(int bufferSize) { doSetProperty("bufferSize", bufferSize); return this; } /** * Buffer size in bytes used for writing files (or in case of FTP for * downloading and uploading files). * * The option will be converted to a <code>int</code> type. * * Default: 131072 * Group: advanced * * @param bufferSize the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder bufferSize(String bufferSize) { doSetProperty("bufferSize", bufferSize); return this; } /** * An optional SMB client configuration, can be used to configure client * specific configurations, like timeouts. * * The option is a: <code>com.hierynomus.smbj.SmbConfig</code> type. * * Group: advanced * * @param smbConfig the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder smbConfig(com.hierynomus.smbj.SmbConfig smbConfig) { doSetProperty("smbConfig", smbConfig); return this; } /** * An optional SMB client configuration, can be used to configure client * specific configurations, like timeouts. * * The option will be converted to a * <code>com.hierynomus.smbj.SmbConfig</code> type. * * Group: advanced * * @param smbConfig the value to set * @return the dsl builder */ default AdvancedSmbEndpointBuilder smbConfig(String smbConfig) { doSetProperty("smbConfig", smbConfig); return this; } } public
AdvancedSmbEndpointBuilder
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/webapp/TestRMWithXFSFilter.java
{ "start": 1671, "end": 4278 }
class ____ { private static MockRM rm; private void createMockRm(final Boolean xfsEnabled, final String xfsHeaderValue) { Configuration conf = new Configuration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class); conf.setBoolean("mockrm.webapp.enabled", true); if (xfsEnabled != null) { conf.setBoolean(YarnConfiguration.YARN_XFS_ENABLED, xfsEnabled); } if (xfsHeaderValue != null) { conf.setStrings(YarnConfiguration.RM_XFS_OPTIONS, xfsHeaderValue); } rm = new MockRM(conf); rm.start(); } @Test public void testXFrameOptionsDefaultBehaviour() throws Exception { createMockRm(null, null); URL url = new URL("http://localhost:8088/ws/v1/cluster/info"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String xfoHeader = conn.getHeaderField("X-FRAME-OPTIONS"); assertTrue(xfoHeader.endsWith(HttpServer2.XFrameOption .SAMEORIGIN.toString())); } @Test public void testXFrameOptionsExplicitlyEnabled() throws Exception { createMockRm(true, HttpServer2.XFrameOption .SAMEORIGIN.toString()); URL url = new URL("http://localhost:8088/ws/v1/cluster/info"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String xfoHeader = conn.getHeaderField("X-FRAME-OPTIONS"); assertTrue(xfoHeader.endsWith(HttpServer2.XFrameOption .SAMEORIGIN.toString())); } @Test public void testXFrameOptionsEnabledDefaultApps() throws Exception { createMockRm(true, HttpServer2.XFrameOption .SAMEORIGIN.toString()); URL url = new URL("http://localhost:8088/logs"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String xfoHeader = conn.getHeaderField("X-FRAME-OPTIONS"); assertTrue(xfoHeader.endsWith(HttpServer2.XFrameOption .SAMEORIGIN.toString())); } @Test public void testXFrameOptionsDisabled() throws Exception { createMockRm(false, null); URL url = new URL("http://localhost:8088/ws/v1/cluster/info"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String xfoHeader = conn.getHeaderField("X-FRAME-OPTIONS"); assertNull(xfoHeader, "Unexpected X-FRAME-OPTION in header"); } @Test public void testXFrameOptionsIllegalOption() { IllegalArgumentException e = assertThrows( IllegalArgumentException.class, () -> createMockRm(true, "otherValue")); } @AfterEach public void tearDown() throws IOException { rm.close(); } }
TestRMWithXFSFilter
java
reactor__reactor-core
benchmarks/src/main/java/reactor/core/publisher/FluxPublishBenchmark.java
{ "start": 2093, "end": 2941 }
class ____<T> extends CountDownLatch implements CoreSubscriber<T> { Blackhole blackhole; Subscription s; public JmhSubscriber() { super(1); } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.s, s)) { this.s = s; s.request(Long.MAX_VALUE); } } @Override public void onNext(T t) { blackhole.consume(t); } @Override public void onError(Throwable t) { blackhole.consume(t); countDown(); } @Override public void onComplete() { countDown(); } } @SuppressWarnings("unused") @Benchmark @Threads(Threads.MAX) public Object measureThroughput(Blackhole blackhole, JmhSubscriber<Integer> subscriber) throws InterruptedException { subscriber.blackhole = blackhole; source.subscribe(subscriber); subscriber.await(); return subscriber; } }
JmhSubscriber
java
spring-projects__spring-framework
spring-context-support/src/main/java/org/springframework/cache/jcache/interceptor/AbstractJCacheOperation.java
{ "start": 1446, "end": 5001 }
class ____<A extends Annotation> implements JCacheOperation<A> { private final CacheMethodDetails<A> methodDetails; private final CacheResolver cacheResolver; protected final List<CacheParameterDetail> allParameterDetails; /** * Construct a new {@code AbstractJCacheOperation}. * @param methodDetails the {@link CacheMethodDetails} related to the cached method * @param cacheResolver the cache resolver to resolve regular caches */ protected AbstractJCacheOperation(CacheMethodDetails<A> methodDetails, CacheResolver cacheResolver) { Assert.notNull(methodDetails, "CacheMethodDetails must not be null"); Assert.notNull(cacheResolver, "CacheResolver must not be null"); this.methodDetails = methodDetails; this.cacheResolver = cacheResolver; this.allParameterDetails = initializeAllParameterDetails(methodDetails.getMethod()); } private static List<CacheParameterDetail> initializeAllParameterDetails(Method method) { int parameterCount = method.getParameterCount(); List<CacheParameterDetail> result = new ArrayList<>(parameterCount); for (int i = 0; i < parameterCount; i++) { CacheParameterDetail detail = new CacheParameterDetail(method, i); result.add(detail); } return result; } @Override public Method getMethod() { return this.methodDetails.getMethod(); } @Override public Set<Annotation> getAnnotations() { return this.methodDetails.getAnnotations(); } @Override public A getCacheAnnotation() { return this.methodDetails.getCacheAnnotation(); } @Override public String getCacheName() { return this.methodDetails.getCacheName(); } @Override public Set<String> getCacheNames() { return Collections.singleton(getCacheName()); } @Override public CacheResolver getCacheResolver() { return this.cacheResolver; } @Override public CacheInvocationParameter[] getAllParameters(@Nullable Object... values) { if (this.allParameterDetails.size() != values.length) { throw new IllegalStateException("Values mismatch, operation has " + this.allParameterDetails.size() + " parameter(s) but got " + values.length + " value(s)"); } List<CacheInvocationParameter> result = new ArrayList<>(); for (int i = 0; i < this.allParameterDetails.size(); i++) { result.add(this.allParameterDetails.get(i).toCacheInvocationParameter(values[i])); } return result.toArray(new CacheInvocationParameter[0]); } /** * Return the {@link ExceptionTypeFilter} to use to filter exceptions thrown while * invoking the method. * @see #createExceptionTypeFilter */ public abstract ExceptionTypeFilter getExceptionTypeFilter(); /** * Convenience method for subclasses to create a specific {@code ExceptionTypeFilter}. * @see #getExceptionTypeFilter() */ protected ExceptionTypeFilter createExceptionTypeFilter( Class<? extends Throwable>[] includes, Class<? extends Throwable>[] excludes) { return new ExceptionTypeFilter(Arrays.asList(includes), Arrays.asList(excludes)); } @Override public String toString() { return getOperationDescription().append(']').toString(); } /** * Return an identifying description for this caching operation. * <p>Available to subclasses, for inclusion in their {@code toString()} result. */ protected StringBuilder getOperationDescription() { StringBuilder result = new StringBuilder(); result.append(getClass().getSimpleName()); result.append('['); result.append(this.methodDetails); return result; } /** * Details for a single cache parameter. */ protected static
AbstractJCacheOperation
java
apache__maven
compat/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/AndArtifactFilterTest.java
{ "start": 1150, "end": 1905 }
class ____ { private ArtifactFilter newSubFilter() { return artifact -> false; } @Test void testEquals() { AndArtifactFilter filter1 = new AndArtifactFilter(); AndArtifactFilter filter2 = new AndArtifactFilter(Arrays.asList(newSubFilter())); assertFalse(filter1.equals(null), "Expected " + filter1 + " to not equal " + null); assertTrue(filter1.equals(filter1), "Expected " + filter1 + " to equal " + filter1); assertEquals(filter1.hashCode(), filter1.hashCode()); assertFalse(filter1.equals(filter2), "Expected " + filter1 + " to not equal " + filter2); assertFalse(filter2.equals(filter1), "Expected " + filter2 + " to not equal " + filter1); } }
AndArtifactFilterTest
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/assignment/AssignorConfiguration.java
{ "start": 7924, "end": 8020 }
interface ____ { void onAssignmentComplete(final boolean stable); } }
AssignmentListener
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/MaterializedBlobEntity.java
{ "start": 397, "end": 1044 }
class ____ { @Id() @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String name; @Lob private byte[] theBytes; public MaterializedBlobEntity() { } public MaterializedBlobEntity(String name, byte[] theBytes) { this.name = name; this.theBytes = theBytes; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getTheBytes() { return theBytes; } public void setTheBytes(byte[] theBytes) { this.theBytes = theBytes; } }
MaterializedBlobEntity
java
spring-projects__spring-security
rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java
{ "start": 2105, "end": 7041 }
class ____ { private PayloadSocketAcceptor acceptor; private List<PayloadInterceptor> interceptors; @Mock private SocketAcceptor delegate; @Mock private PayloadInterceptor interceptor; @Mock private ConnectionSetupPayload setupPayload; @Mock private RSocket rSocket; @Mock private Payload payload; @BeforeEach public void setup() { this.interceptors = Arrays.asList(this.interceptor); this.acceptor = new PayloadSocketAcceptor(this.delegate, this.interceptors); } @Test public void constructorWhenNullDelegateThenException() { this.delegate = null; assertThatIllegalArgumentException() .isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); } @Test public void constructorWhenNullInterceptorsThenException() { this.interceptors = null; assertThatIllegalArgumentException() .isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); } @Test public void constructorWhenEmptyInterceptorsThenException() { this.interceptors = Collections.emptyList(); assertThatIllegalArgumentException() .isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); } @Test public void acceptWhenDataMimeTypeNullThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.acceptor.accept(this.setupPayload, this.rSocket).block()); } @Test public void acceptWhenDefaultMetadataMimeTypeThenDefaulted() { given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); assertThat(exchange.getMetadataMimeType().toString()) .isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() { this.acceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON); given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON); assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test public void acceptWhenDefaultDataMimeTypeThenDefaulted() { this.acceptor.setDefaultDataMimeType(MediaType.APPLICATION_JSON); PayloadExchange exchange = captureExchange(); assertThat(exchange.getMetadataMimeType().toString()) .isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test public void acceptWhenExplicitMimeTypeThenThenOverrideDefault() { given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE); given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test // gh-8654 public void acceptWhenDelegateAcceptRequiresReactiveSecurityContext() { given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE); given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); SecurityContext expectedSecurityContext = new SecurityContextImpl( new TestingAuthenticationToken("user", "password", "ROLE_USER")); CaptureSecurityContextSocketAcceptor captureSecurityContext = new CaptureSecurityContextSocketAcceptor( this.rSocket); PayloadInterceptor authenticateInterceptor = (exchange, chain) -> { Context withSecurityContext = ReactiveSecurityContextHolder .withSecurityContext(Mono.just(expectedSecurityContext)); return chain.next(exchange).contextWrite(withSecurityContext); }; List<PayloadInterceptor> interceptors = Arrays.asList(authenticateInterceptor); this.acceptor = new PayloadSocketAcceptor(captureSecurityContext, interceptors); this.acceptor.accept(this.setupPayload, this.rSocket).block(); assertThat(captureSecurityContext.getSecurityContext()).isEqualTo(expectedSecurityContext); } private PayloadExchange captureExchange() { given(this.delegate.accept(any(), any())).willReturn(Mono.just(this.rSocket)); given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); RSocket result = this.acceptor.accept(this.setupPayload, this.rSocket).block(); assertThat(result).isInstanceOf(PayloadInterceptorRSocket.class); given(this.rSocket.fireAndForget(any())).willReturn(Mono.empty()); result.fireAndForget(this.payload).block(); ArgumentCaptor<PayloadExchange> exchangeArg = ArgumentCaptor.forClass(PayloadExchange.class); verify(this.interceptor, times(2)).intercept(exchangeArg.capture(), any()); return exchangeArg.getValue(); } }
PayloadSocketAcceptorTests
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionBwcSetupPlugin.java
{ "start": 17939, "end": 19954 }
class ____ { final String name; final File checkoutDir; final String projectPath; /** * can be removed once we don't build 7.10 anymore * from source for bwc tests. */ @Deprecated final boolean expandedDistDirSupport; final DistributionProjectArtifact expectedBuildArtifact; private final boolean extractedAssembleSupported; DistributionProject(String name, String baseDir, Version version, String classifier, String extension, File checkoutDir) { this.name = name; this.checkoutDir = checkoutDir; this.projectPath = baseDir + "/" + name; this.expandedDistDirSupport = version.onOrAfter("7.10.0") && (name.endsWith("zip") || name.endsWith("tar")); this.extractedAssembleSupported = version.onOrAfter("7.11.0") && (name.endsWith("zip") || name.endsWith("tar")); this.expectedBuildArtifact = new DistributionProjectArtifact( new File( checkoutDir, baseDir + "/" + name + "/build/distributions/elasticsearch-" + (name.startsWith("oss") ? "oss-" : "") + version + "-SNAPSHOT" + classifier + "." + extension ), expandedDistDirSupport ? new File(checkoutDir, baseDir + "/" + name + "/build/install") : null ); } /** * Newer elasticsearch branches allow building extracted bwc elasticsearch versions * from source without the overhead of creating an archive by using assembleExtracted instead of assemble. */ public String getAssembleTaskName() { return extractedAssembleSupported ? "extractedAssemble" : "assemble"; } } private static
DistributionProject
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/NestedTestClassesTests.java
{ "start": 12924, "end": 14714 }
class ____ between %s and %s".formatted( from.getName(), to.getName()); results.containerEvents().assertThatEvents() // .haveExactly(1, finishedWithFailure(message(it -> it.contains(expectedMessage)))); } @Test void discoversButWarnsAboutTopLevelNestedTestClasses() { var results = discoverTestsForClass(TopLevelNestedTestCase.class); var engineDescriptor = results.getEngineDescriptor(); assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors"); var discoveryIssues = results.getDiscoveryIssues(); assertThat(discoveryIssues).hasSize(1); assertThat(discoveryIssues.getFirst().message()) // .isEqualTo( "Top-level class '%s' must not be annotated with @Nested. " + "It will be executed anyway for backward compatibility. " + "You should remove the @Nested annotation to resolve this warning.", TopLevelNestedTestCase.class.getName()); } @Test void discoversButWarnsAboutStaticNestedTestClasses() { var results = discoverTestsForClass(StaticNestedTestCase.TestCase.class); var engineDescriptor = results.getEngineDescriptor(); assertEquals(2, engineDescriptor.getDescendants().size(), "# resolved test descriptors"); var discoveryIssues = results.getDiscoveryIssues(); assertThat(discoveryIssues).hasSize(1); assertThat(discoveryIssues.getFirst().message()) // .isEqualTo( "@Nested class '%s' must not be static. " + "It will only be executed if discovered as a standalone test class. " + "You should remove the annotation or make it non-static to resolve this warning.", StaticNestedTestCase.TestCase.class.getName()); } // ------------------------------------------------------------------- @SuppressWarnings("JUnitMalformedDeclaration") static
hierarchy
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/HqlSubselectParameterTest.java
{ "start": 1691, "end": 2023 }
class ____ { @Id @Column(name = "id", nullable = false, unique = true, updatable = false) private Long key; private String name; public Bookmark() { } public Bookmark(Long key, String name) { this.key = key; this.name = name; } } @Entity(name = "resource") @Table(name = "o_resource") public static
Bookmark
java
google__dagger
javatests/dagger/internal/codegen/SubcomponentValidationTest.java
{ "start": 19241, "end": 19535 }
interface ____ {", " Sub newSubcomponent();", "}"); Source sub = CompilerTests.javaSource( "test.Sub", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent
ParentComponent
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/sql/BaseSqmToSqlAstConverter.java
{ "start": 358423, "end": 358856 }
class ____ { @ManyToOne Sample parent; String name; } TypedQuery<Sample> query = entityManager.createQuery( "select s from Sample s", Sample.class ); query.setHint( SpecHints.HINT_SPEC_LOAD_GRAPH, entityGraph ); */ return creationContext.getMaximumFetchDepth() == null && ( entityGraphTraversalState != null || getLoadQueryInfluencers().hasEnabledFetchProfiles() ); } }
Sample
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/UnionResultSubpartitionView.java
{ "start": 1476, "end": 1976 }
class ____ * the following guarantees to the output buffers. * * <ul> * <li>Each output buffer corresponds to a buffer in one of the subpartitions. * <li>Buffers in the same subpartition are output without their order changed. * <li>If a record is split and placed into multiple adjacent buffers due to the capacity limit of * the buffer, these buffers will be output consecutively without the entry of buffers from * other subpartitions in between. * </ul> */ public
provides
java
apache__flink
flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/windowing/GroupedProcessingTimeWindowExample.java
{ "start": 4183, "end": 4728 }
class ____ implements WindowFunction<Tuple2<Long, Long>, Tuple2<Long, Long>, Long, Window> { @Override public void apply( Long key, Window window, Iterable<Tuple2<Long, Long>> values, Collector<Tuple2<Long, Long>> out) { long sum = 0L; for (Tuple2<Long, Long> value : values) { sum += value.f1; } out.collect(new Tuple2<>(key, sum)); } } private static
SummingWindowFunction
java
netty__netty
codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicStreamChannelCloseTest.java
{ "start": 11288, "end": 12539 }
class ____ extends QuicChannelValidationHandler { private final QuicStreamType type; private final boolean halfClose; private final Promise<Channel> streamPromise; StreamCreationHandler(QuicStreamType type, boolean halfClose, Promise<Channel> streamPromise) { this.type = type; this.halfClose = halfClose; this.streamPromise = streamPromise; } @Override public void channelActive(ChannelHandlerContext ctx) { super.channelActive(ctx); QuicChannel channel = (QuicChannel) ctx.channel(); channel.createStream(type, new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) { streamPromise.trySuccess(ctx.channel()); // Do the write and close the channel ctx.writeAndFlush(Unpooled.buffer().writeZero(8)) .addListener(halfClose ? QuicStreamChannel.SHUTDOWN_OUTPUT : ChannelFutureListener.CLOSE); } }); } } private static final
StreamCreationHandler
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/Products.java
{ "start": 385, "end": 753 }
class ____ { @Id @GeneratedValue private Integer id; @ElementCollection @OrderBy("name ASC") private Set<Widgets> widgets; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Set<Widgets> getWidgets() { return widgets; } public void setWidgets(Set<Widgets> widgets) { this.widgets = widgets; } }
Products
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/referencedcolumnname/ZItemCost.java
{ "start": 365, "end": 956 }
class ____ extends GenericObject { Item item; Vendor vendor; BigDecimal cost; @ManyToOne( fetch = FetchType.LAZY ) @JoinColumn(name="item_id", nullable=false) public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } @ManyToOne( fetch = FetchType.LAZY ) @JoinColumn(name="vendor_id", nullable=false) public Vendor getVendor() { return vendor; } public void setVendor(Vendor vendor) { this.vendor = vendor; } public BigDecimal getCost() { return cost; } public void setCost(BigDecimal cost) { this.cost = cost; } }
ZItemCost
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/H2ArrayRemoveIndexFunction.java
{ "start": 716, "end": 1836 }
class ____ extends ArrayRemoveIndexUnnestFunction { private final int maximumArraySize; public H2ArrayRemoveIndexFunction(int maximumArraySize) { super( false ); this.maximumArraySize = maximumArraySize; } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { final Expression arrayExpression = (Expression) sqlAstArguments.get( 0 ); final Expression indexExpression = (Expression) sqlAstArguments.get( 1 ); sqlAppender.append( "case when "); arrayExpression.accept( walker ); sqlAppender.append( " is not null then coalesce((select array_agg(array_get("); arrayExpression.accept( walker ); sqlAppender.append(",i.idx)) from system_range(1," ); sqlAppender.append( Integer.toString( maximumArraySize ) ); sqlAppender.append( ") i(idx) where i.idx<=coalesce(cardinality("); arrayExpression.accept( walker ); sqlAppender.append("),0) and i.idx is distinct from " ); indexExpression.accept( walker ); sqlAppender.append( "),array[]) end" ); } }
H2ArrayRemoveIndexFunction
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AInstrumentation.java
{ "start": 63510, "end": 63634 }
class ____'t collect any local statistics. * Instead it directly updates the S3A Instrumentation. */ private final
doesn
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationReplacements.java
{ "start": 2787, "end": 2876 }
class ____ as the value. * @param annotation annotation to load * @param classLoader
name
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/retry/RetryBean.java
{ "start": 242, "end": 517 }
class ____ { private AtomicInteger counter = new AtomicInteger(); @Retry public int hello() { int inc = counter.incrementAndGet(); if (inc <= 3) { throw new RuntimeException("should retry"); } return inc; } }
RetryBean
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/beans/factory/annotation/BridgeMethodAutowiringTests.java
{ "start": 1252, "end": 1347 }
class ____<D> { public abstract void setObject(D object); } public static
GenericServiceImpl
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2781/Issue2781Mapper.java
{ "start": 836, "end": 1202 }
class ____ { private String field1; private String field2; public Source(String field1, String field2) { this.field1 = field1; this.field2 = field2; } public String getField1() { return field1; } public String getField2() { return field2; } } }
Source
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3248/Issue3248Mapper.java
{ "start": 431, "end": 624 }
interface ____ { @BeanMapping(ignoreUnmappedSourceProperties = "otherValue") Target map(Source source); @InheritConfiguration Target secondMap(Source source);
Issue3248Mapper
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest67.java
{ "start": 893, "end": 2039 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); provider.getConfig().setSchemaCheck(true); assertTrue(provider.checkValid(// "SELECT c.table_name, column_name, column_type, is_nullable, column_key" + " , column_default, extra, collation_name, character_set_name, column_comment " + "FROM information_schema.columns c " + "INNER JOIN (" + " SELECT table_schema, table_name " + " FROM information_schema.tables " + " WHERE LOWER(table_schema) = LOWER('sp5035d3d0b2d4a')" + ") t ON t.table_name COLLATE utf8_bin = c.table_name COLLATE utf8_bin " + "WHERE LOWER(c.table_schema) = LOWER('sp5035d3d0b2d4a') " + " AND ('Y' = '' OR LOWER(c.table_name) IN ('leader01_weibo')) " + "ORDER BY t.table_name")); assertEquals(2, provider.getTableStats().size()); } }
MySqlWallTest67
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/handler/predicate/WeightRoutePredicateFactoryYaml404Tests.java
{ "start": 2333, "end": 2496 }
class ____ { TestConfig(WeightCalculatorWebFilter filter) { Supplier<Double> random = getRandom(0.4); filter.setRandomSupplier(random); } } }
TestConfig
java
square__okhttp
regression-test/src/androidTest/java/okhttp/regression/LetsEncryptTest.java
{ "start": 1519, "end": 6210 }
class ____ { @Test public void getFailsWithoutAdditionalCert() throws IOException { OkHttpClient client = new OkHttpClient(); boolean androidMorEarlier = Build.VERSION.SDK_INT <= 23; try { sendRequest(client, "https://valid-isrgrootx1.letsencrypt.org/robots.txt"); if (androidMorEarlier) { fail(); } } catch (SSLHandshakeException sslhe) { assertTrue(androidMorEarlier); } } @Test public void getPassesAdditionalCert() throws IOException, CertificateException { boolean androidMorEarlier = Build.VERSION.SDK_INT <= 23; OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (androidMorEarlier) { String isgCert = "-----BEGIN CERTIFICATE-----\n" + "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n" + "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n" + "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n" + "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n" + "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n" + "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n" + "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n" + "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n" + "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n" + "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n" + "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n" + "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n" + "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n" + "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n" + "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n" + "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n" + "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n" + "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n" + "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n" + "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n" + "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n" + "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n" + "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n" + "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n" + "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n" + "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n" + "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n" + "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n" + "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n" + "-----END CERTIFICATE-----"; CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate isgCertificate = cf.generateCertificate(new ByteArrayInputStream(isgCert.getBytes("UTF-8"))); HandshakeCertificates certificates = new HandshakeCertificates.Builder() .addTrustedCertificate((X509Certificate) isgCertificate) // Uncomment to allow connection to any site generally, but will cause // noticeable memory pressure in Android apps. // .addPlatformTrustedCertificates() .build(); builder.sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager()); } OkHttpClient client = builder.build(); sendRequest(client, "https://valid-isrgrootx1.letsencrypt.org/robots.txt"); try { sendRequest(client, "https://google.com/robots.txt"); if (androidMorEarlier) { // will pass with default CAs on N or later fail(); } } catch (SSLHandshakeException sslhe) { assertTrue(androidMorEarlier); } } private void sendRequest(OkHttpClient client, String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { assertTrue(response.code() == 200 || response.code() == 404); assertEquals(Protocol.HTTP_2, response.protocol()); } } }
LetsEncryptTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/validation/beanvalidation/MethodValidationExcludeFilterTests.java
{ "start": 2184, "end": 2258 }
class ____ { } @Inherited @Retention(RetentionPolicy.RUNTIME) @
Annotated
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/FieldMissingNullableTest.java
{ "start": 3885, "end": 4414 }
class ____ { // BUG: Diagnostic contains: @Nullable public static final String MESSAGE = null; } """) .doTest(); } @Test public void maybeNullAssignmentInLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public
NullableParameterTest
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/NamespaceTemplateExtensionTest.java
{ "start": 3098, "end": 3256 }
enum ____ { OPEN, CLOSED; public String getFoo() { return toString().toLowerCase(); } } public static
State
java
apache__camel
components/camel-mvel/src/test/java/org/apache/camel/language/mvel/MvelComponentTest.java
{ "start": 1129, "end": 3059 }
class ____ extends CamelTestSupport { @Test public void testMvel() { Exchange exchange = template.request("direct:a", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setBody(7); } }); assertEquals("\n{ \"text\": \"The result is 14\" }", exchange.getMessage().getBody()); } @Test public void testMvelTemplate() { Exchange exchange = template.request("direct:b", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setBody(7); exchange.getIn().setHeader(MvelConstants.MVEL_TEMPLATE, "{ \"text\": \"@{\"The result is \" + request.body * 3}\" }"); } }); assertEquals("{ \"text\": \"The result is 21\" }", exchange.getMessage().getBody()); } @Test public void testMvelUri() { Exchange exchange = template.request("direct:b", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setBody(7); exchange.getIn().setHeader(MvelConstants.MVEL_RESOURCE_URI, getClass().getClassLoader().getResource("template2.mvel").toURI().toString()); } }); assertEquals("\n{ \"text\": \"The result is 28\" }", exchange.getMessage().getBody()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: example from("direct:a").to("mvel:template.mvel"); from("direct:b").to("mvel:template.mvel?allowTemplateFromHeader=true&allowContextMapAll=true"); // END SNIPPET: example } }; } }
MvelComponentTest
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/connection/ServiceConnectionScopeTest.java
{ "start": 1890, "end": 2784 }
class ____ { @Inject WebSocketConnection connection; @OnTextMessage public String onMessage(String message) { assertNotNull(Arc.container().getActiveContext(SessionScoped.class)); // By default, the request context is only activated if needed assertNull(Arc.container().getActiveContext(RequestScoped.class)); assertNotNull(connection.id()); return message.toUpperCase(); } @ActivateRequestContext void testConnectionNotAccessibleOutsideOfWsMethods() { assertNull(Arc.container().getActiveContext(SessionScoped.class)); assertNotNull(Arc.container().getActiveContext(RequestScoped.class)); // WebSocketConnection is @SessionScoped assertThrows(ContextNotActiveException.class, () -> connection.id()); } } }
MyEndpoint
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/concurrent/BasicThreadFactory.java
{ "start": 4397, "end": 4501 }
class ____ creating instances of {@code * BasicThreadFactory}. * <p> * Using this builder
for
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ArrayCollectionInitializor.java
{ "start": 611, "end": 2156 }
class ____ extends AbstractCollectionInitializor<Object[]> { private final MiddleComponentData elementComponentData; private final MiddleComponentData indexComponentData; public ArrayCollectionInitializor( EnversService enversService, AuditReaderImplementor versionsReader, RelationQueryGenerator queryGenerator, Object primaryKey, Number revision, boolean removed, MiddleComponentData elementComponentData, MiddleComponentData indexComponentData) { super( enversService, versionsReader, queryGenerator, primaryKey, revision, removed ); this.elementComponentData = elementComponentData; this.indexComponentData = indexComponentData; } @Override protected Object[] initializeCollection(int size) { return new Object[size]; } @Override @SuppressWarnings("unchecked") protected void addToCollection(Object[] collection, Object collectionRow) { final Object elementData = ( (List) collectionRow ).get( elementComponentData.getComponentIndex() ); final Object element = elementComponentData.getComponentMapper().mapToObjectFromFullMap( entityInstantiator, (Map<String, Object>) elementData, null, revision ); final Object indexData = ( (List) collectionRow ).get( indexComponentData.getComponentIndex() ); final Object indexObj = indexComponentData.getComponentMapper().mapToObjectFromFullMap( entityInstantiator, (Map<String, Object>) indexData, element, revision ); final int index = ( (Number) indexObj ).intValue(); collection[index] = element; } }
ArrayCollectionInitializor
java
google__gson
gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java
{ "start": 17436, "end": 17751 }
class ____ { @JsonAdapter(DelegatingAdapterFactory.class) Integer f; @JsonAdapter(DelegatingAdapterFactory.class) JsonElement f2; // Also have non-delegating adapter to make tests handle both cases @JsonAdapter(JsonElementAdapter.class) JsonElement f3; static
DelegatingAndOverwriting
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest34.java
{ "start": 837, "end": 1027 }
class ____ extends TestCase { public void test_true() throws Exception { assertTrue(WallUtils.isValidateMySql(// "SELECT @@sql_big_selects")); } }
MySqlWallTest34
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/mutiny/UniRouteTest.java
{ "start": 1905, "end": 4210 }
class ____ { @Route(path = "hello") Uni<String> hello(RoutingContext context) { return Uni.createFrom().item("Hello world!"); } @Route(path = "hello-buffer") Uni<Buffer> helloWithBuffer(RoutingContext context) { return Uni.createFrom().item(Buffer.buffer("Buffer")); } @Route(path = "hello-mutiny-buffer") Uni<io.vertx.mutiny.core.buffer.Buffer> helloWithMutinyBuffer(RoutingContext context) { return Uni.createFrom().item(io.vertx.mutiny.core.buffer.Buffer.buffer("Mutiny Buffer")); } @Route(path = "hello-on-pool") Uni<String> helloOnPool() { return Uni.createFrom().item("Pool") .emitOn(Infrastructure.getDefaultExecutor()); } @Route(path = "failure") Uni<String> fail(RoutingContext context) { return Uni.createFrom().<String> failure(new IOException("boom")) .emitOn(Infrastructure.getDefaultExecutor()); } @Route(path = "sync-failure") Uni<String> failUniSync(RoutingContext context) { throw new IllegalStateException("boom"); } @Route(path = "null") Uni<String> uniNull(RoutingContext context) { return null; } @Route(path = "void") Uni<Void> uniOfVoid() { return Uni.createFrom().nullItem(); } @Route(path = "uni-null") Uni<String> produceNull(RoutingContext context) { return Uni.createFrom().nullItem(); } @Route(path = "person", produces = "application/json") Uni<Person> getPersonAsUni(RoutingContext context) { return Uni.createFrom().item(() -> new Person("neo", 12345)).emitOn(Infrastructure.getDefaultExecutor()); } @Route(path = "person-content-type-set", produces = "application/json") Uni<Person> getPersonAsUniUtf8(RoutingContext context) { return Uni.createFrom().item(() -> new Person("neo", 12345)) .onItem() .invoke(x -> context.response().putHeader("content-type", "application/json;charset=utf-8")) .emitOn(Infrastructure.getDefaultExecutor()); } } static
SimpleBean
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/merge/ArrayNode3338MergeTest.java
{ "start": 363, "end": 4639 }
class ____ { @Test public void testEnabledArrayNodeMerge() throws Exception { final ObjectMapper mapperWithMerge = sharedMapper(); JsonNode merged = _updateTreeWithArray(mapperWithMerge); ObjectNode expected = mapperWithMerge.createObjectNode(); expected.put("number", 888); // default behavior is to enable merge, so we get all elements ArrayNode array = expected.putArray("array"); array.add("Mr."); array.add("Ms."); array.add("Mister"); array.add("Miss"); assertEquals(expected, merged); } @Test public void testDisabledArrayNodeMerge() throws Exception { ObjectMapper mapperNoArrayMerge = jsonMapperBuilder() .withConfigOverride(ArrayNode.class, cfg -> cfg.setMergeable(false)) .build(); JsonNode merged = _updateTreeWithArray(mapperNoArrayMerge); ObjectNode expected = mapperNoArrayMerge.createObjectNode(); ArrayNode array = expected.putArray("array"); array.add("Mister"); array.add("Miss"); expected.put("number", 888); assertEquals(expected, merged); // Also should work via JsonNode ObjectMapper mapperNoJsonNodeMerge = jsonMapperBuilder() .withConfigOverride(JsonNode.class, cfg -> cfg.setMergeable(false)) .build(); JsonNode merged2 = _updateTreeWithArray(mapperNoJsonNodeMerge); assertEquals(expected, merged2); } private JsonNode _updateTreeWithArray(ObjectMapper mapper) throws Exception { JsonNode mergeTarget = mapper.readTree(a2q("{" + "'array': ['Mr.', 'Ms.' ]," + "'number': 888" + "}")); JsonNode updateNode = mapper.readTree(a2q("{" + "'array': ['Mister', 'Miss' ]" + "}")); return mapper.readerForUpdating(mergeTarget).readValue(updateNode); } @Test public void testEnabledObjectNodeMerge() throws Exception { final ObjectMapper mapperWithMerge = sharedMapper(); JsonNode merged = _updateTreeWithObject(mapperWithMerge); // default behavior is to enable merge: ObjectNode expected = mapperWithMerge.createObjectNode(); ObjectNode obj = expected.putObject("object"); obj.put("a", "1"); obj.put("b", "xyz"); expected.put("number", 42); ArrayNode array = expected.putArray("array"); array.add(1); array.add(2); array.add(3); assertEquals(expected, merged); } @Test public void testDisabledObjectNodeMerge() throws Exception { ObjectMapper mapperNoObjectMerge = jsonMapperBuilder() .withConfigOverride(ObjectNode.class, cfg -> cfg.setMergeable(false)) .build(); JsonNode merged = _updateTreeWithObject(mapperNoObjectMerge); // but that can be disabled ObjectNode expected = mapperNoObjectMerge.createObjectNode(); ObjectNode obj = expected.putObject("object"); obj.put("b", "xyz"); expected.put("number", 42); ArrayNode array = expected.putArray("array"); array.add(1); array.add(2); array.add(3); assertEquals(expected, merged); // Also: verify that `JsonNode` target also works: ObjectMapper mapperNoJsonNodeMerge = jsonMapperBuilder() .withConfigOverride(JsonNode.class, cfg -> cfg.setMergeable(false)) .build(); JsonNode merged2 = _updateTreeWithObject(mapperNoJsonNodeMerge); assertEquals(expected, merged2); } private JsonNode _updateTreeWithObject(ObjectMapper mapper) throws Exception { JsonNode mergeTarget = mapper.readTree(a2q("{" + "'object': {'a':'1', 'b':'2' }," + "'array': [1, 2, 3]," + "'number': 42" + "}")); JsonNode updateNode = mapper.readTree(a2q("{" + "'object': {'b':'xyz'}" + "}")); return mapper.readerForUpdating(mergeTarget).readValue(updateNode); } }
ArrayNode3338MergeTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsStatus.java
{ "start": 1087, "end": 1242 }
class ____ used to represent the capacity, free and used space on a * {@link FileSystem}. */ @InterfaceAudience.Public @InterfaceStability.Stable public
is
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClass.java
{ "start": 3016, "end": 3087 }
class ____ that must be present. */ String[] name() default {}; }
names
java
apache__camel
components/camel-cyberark-vault/src/generated/java/org/apache/camel/component/cyberark/vault/CyberArkVaultEndpointConfigurer.java
{ "start": 741, "end": 5547 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { CyberArkVaultEndpoint target = (CyberArkVaultEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "account": target.getConfiguration().setAccount(property(camelContext, java.lang.String.class, value)); return true; case "apikey": case "apiKey": target.getConfiguration().setApiKey(property(camelContext, java.lang.String.class, value)); return true; case "authtoken": case "authToken": target.getConfiguration().setAuthToken(property(camelContext, java.lang.String.class, value)); return true; case "certificatepath": case "certificatePath": target.getConfiguration().setCertificatePath(property(camelContext, java.lang.String.class, value)); return true; case "conjurclient": case "conjurClient": target.getConfiguration().setConjurClient(property(camelContext, org.apache.camel.component.cyberark.vault.client.ConjurClient.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.cyberark.vault.CyberArkVaultOperations.class, value)); return true; case "password": target.getConfiguration().setPassword(property(camelContext, java.lang.String.class, value)); return true; case "secretid": case "secretId": target.getConfiguration().setSecretId(property(camelContext, java.lang.String.class, value)); return true; case "url": target.getConfiguration().setUrl(property(camelContext, java.lang.String.class, value)); return true; case "username": target.getConfiguration().setUsername(property(camelContext, java.lang.String.class, value)); return true; case "verifyssl": case "verifySsl": target.getConfiguration().setVerifySsl(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "account": return java.lang.String.class; case "apikey": case "apiKey": return java.lang.String.class; case "authtoken": case "authToken": return java.lang.String.class; case "certificatepath": case "certificatePath": return java.lang.String.class; case "conjurclient": case "conjurClient": return org.apache.camel.component.cyberark.vault.client.ConjurClient.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "operation": return org.apache.camel.component.cyberark.vault.CyberArkVaultOperations.class; case "password": return java.lang.String.class; case "secretid": case "secretId": return java.lang.String.class; case "url": return java.lang.String.class; case "username": return java.lang.String.class; case "verifyssl": case "verifySsl": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { CyberArkVaultEndpoint target = (CyberArkVaultEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "account": return target.getConfiguration().getAccount(); case "apikey": case "apiKey": return target.getConfiguration().getApiKey(); case "authtoken": case "authToken": return target.getConfiguration().getAuthToken(); case "certificatepath": case "certificatePath": return target.getConfiguration().getCertificatePath(); case "conjurclient": case "conjurClient": return target.getConfiguration().getConjurClient(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "operation": return target.getConfiguration().getOperation(); case "password": return target.getConfiguration().getPassword(); case "secretid": case "secretId": return target.getConfiguration().getSecretId(); case "url": return target.getConfiguration().getUrl(); case "username": return target.getConfiguration().getUsername(); case "verifyssl": case "verifySsl": return target.getConfiguration().isVerifySsl(); default: return null; } } }
CyberArkVaultEndpointConfigurer
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/filter/UrlHandlerFilter.java
{ "start": 7283, "end": 7677 }
interface ____ { /** * Whether the handler handles the given request. */ boolean supports(HttpServletRequest request, RequestPath path); /** * Handle the request, possibly delegating to the rest of the filter chain. */ void handle(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException; } /** * Base
Handler
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/server/adapter/HttpWebHandlerAdapterObservabilityTests.java
{ "start": 5221, "end": 5769 }
class ____ implements WebHandler { Observation currentObservation; boolean observationStarted; @Override public Mono<Void> handle(ServerWebExchange exchange) { exchange.getResponse().setStatusCode(HttpStatus.OK); return Mono.deferContextual(contextView -> { this.currentObservation = contextView.get(ObservationThreadLocalAccessor.KEY); this.observationStarted = this.currentObservation.getContext().getLowCardinalityKeyValue("outcome") != null; return Mono.empty(); }); } } private static
ReactorContextWebHandler
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ResourceSizingPBImpl.java
{ "start": 1411, "end": 3707 }
class ____ extends ResourceSizing { ResourceSizingProto proto = ResourceSizingProto.getDefaultInstance(); ResourceSizingProto.Builder builder = null; boolean viaProto = false; private Resource resources = null; public ResourceSizingPBImpl() { builder = ResourceSizingProto.newBuilder(); } public ResourceSizingPBImpl(ResourceSizingProto proto) { this.proto = proto; viaProto = true; } public ResourceSizingProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void mergeLocalToBuilder() { if (this.resources != null) { builder.setResources(convertToProtoFormat(this.resources)); } } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = ResourceSizingProto.newBuilder(proto); } viaProto = false; } @Override public int getNumAllocations() { ResourceSizingProtoOrBuilder p = viaProto ? proto : builder; return (p.getNumAllocations()); } @Override public void setNumAllocations(int numAllocations) { maybeInitBuilder(); builder.setNumAllocations(numAllocations); } @Override public Resource getResources() { ResourceSizingProtoOrBuilder p = viaProto ? proto : builder; if (this.resources != null) { return this.resources; } if (!p.hasResources()) { return null; } this.resources = convertFromProtoFormat(p.getResources()); return this.resources; } @Override public void setResources(Resource resources) { maybeInitBuilder(); if (resources == null) { builder.clearResources(); } this.resources = resources; } private ResourcePBImpl convertFromProtoFormat(ResourceProto r) { return new ResourcePBImpl(r); } private ResourceProto convertToProtoFormat(Resource r) { return ProtoUtils.convertToProtoFormat(r); } @Override public String toString() { return "ResourceSizingPBImpl{" + "numAllocations=" + getNumAllocations() + ", resources=" + getResources() + '}'; } }
ResourceSizingPBImpl
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/SlotSelectionStrategy.java
{ "start": 1158, "end": 1885 }
interface ____ { /** * Selects the best {@link SlotInfo} w.r.t. a certain selection criterion from the provided list * of available slots and considering the given {@link SlotProfile} that describes the * requirements. * * @param freeSlotTracker a list of the available slots together with their remaining resources * to select from. * @param slotProfile a slot profile, describing requirements for the slot selection. * @return the selected slot info with the corresponding locality hint. */ Optional<SlotInfoAndLocality> selectBestSlotForProfile( @Nonnull FreeSlotTracker freeSlotTracker, @Nonnull SlotProfile slotProfile); /** This
SlotSelectionStrategy
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/compare/ObjectToStringComparatorTest.java
{ "start": 1302, "end": 3319 }
class ____ { final String string; Thing(final String string) { this.string = string; } @Override public String toString() { return string; } } @Test void testNullLeft() { final Thing thing = new Thing("y"); final List<Thing> things = Arrays.asList(null, thing); things.sort(ObjectToStringComparator.INSTANCE); assertEquals("y", things.get(0).string); assertEquals(2, things.size()); assertSame(thing, things.get(0)); assertNull(things.get(1)); } @Test void testNullRight() { final Thing thing = new Thing("y"); final List<Thing> things = Arrays.asList(thing, null); things.sort(ObjectToStringComparator.INSTANCE); assertEquals(2, things.size()); assertSame(thing, things.get(0)); assertNull(things.get(1)); } @Test void testNulls() { final Thing thing = new Thing("y"); final List<Thing> things = Arrays.asList(null, thing, null); things.sort(ObjectToStringComparator.INSTANCE); assertEquals("y", things.get(0).string); assertEquals(3, things.size()); assertSame(thing, things.get(0)); assertNull(things.get(1)); assertNull(things.get(2)); } @Test void testNullToString() { final List<Thing> things = Arrays.asList(new Thing(null), new Thing("y"), new Thing(null)); things.sort(ObjectToStringComparator.INSTANCE); assertEquals("y", things.get(0).string); assertNull(things.get(1).string); assertNull(things.get(2).string); } @Test void testSortCollection() { final List<Thing> things = Arrays.asList(new Thing("z"), new Thing("y"), new Thing("x")); things.sort(ObjectToStringComparator.INSTANCE); assertEquals("x", things.get(0).string); assertEquals("y", things.get(1).string); assertEquals("z", things.get(2).string); } }
Thing
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java
{ "start": 68636, "end": 69210 }
class ____ extends ServerWebExchangeDecorator { private final Mono<WebSession> sessionMono; private SessionRegistryWebExchange(ServerWebExchange delegate) { super(delegate); this.sessionMono = delegate.getSession() .flatMap((session) -> SessionRegistryWebFilter.this.sessionRegistry .updateLastAccessTime(session.getId()) .thenReturn(session)) .map(SessionRegistryWebSession::new); } @Override public Mono<WebSession> getSession() { return this.sessionMono; } } private final
SessionRegistryWebExchange
java
elastic__elasticsearch
x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/ExplainDataFrameAnalyticsIT.java
{ "start": 1989, "end": 12391 }
class ____ extends MlNativeDataFrameAnalyticsIntegTestCase { public void testExplain_GivenMissingSourceIndex() { DataFrameAnalyticsConfig config = new DataFrameAnalyticsConfig.Builder().setSource( new DataFrameAnalyticsSource(new String[] { "missing_index" }, null, null, Collections.emptyMap()) ).setAnalysis(new OutlierDetection.Builder().build()).buildForExplain(); ResourceNotFoundException e = expectThrows(ResourceNotFoundException.class, () -> explainDataFrame(config)); assertThat(e.getMessage(), equalTo("cannot retrieve data because index [missing_index] does not exist")); } public void testSourceQueryIsApplied() throws IOException { // To test the source query is applied when we extract data, // we set up a job where we have a query which excludes all but one document. // We then assert the memory estimation is low enough. String sourceIndex = "test-source-query-is-applied"; indicesAdmin().prepareCreate(sourceIndex) .setMapping( "numeric_1", "type=double", "numeric_2", "type=unsigned_long", "categorical", "type=keyword", "filtered_field", "type=keyword" ) .get(); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 30; i++) { IndexRequest indexRequest = new IndexRequest(sourceIndex); indexRequest.source( "numeric_1", 1.0, "numeric_2", 2, "categorical", i % 2 == 0 ? "class_1" : "class_2", "filtered_field", i < 2 ? "bingo" : "rest" ); // We tag bingo on the first two docs to ensure we have 2 classes bulkRequestBuilder.add(indexRequest); } BulkResponse bulkResponse = bulkRequestBuilder.get(); if (bulkResponse.hasFailures()) { fail("Failed to index data: " + bulkResponse.buildFailureMessage()); } String id = "test_source_query_is_applied"; DataFrameAnalyticsConfig config = new DataFrameAnalyticsConfig.Builder().setId(id) .setSource( new DataFrameAnalyticsSource( new String[] { sourceIndex }, QueryProvider.fromParsedQuery(QueryBuilders.termQuery("filtered_field", "bingo")), null, Collections.emptyMap() ) ) .setAnalysis(new Classification("categorical")) .buildForExplain(); ExplainDataFrameAnalyticsAction.Response explainResponse = explainDataFrame(config); assertThat(explainResponse.getMemoryEstimation().getExpectedMemoryWithoutDisk().getKb(), lessThanOrEqualTo(1024L)); } public void testTrainingPercentageIsApplied() throws IOException { String sourceIndex = "test-training-percentage-applied"; RegressionIT.indexData(sourceIndex, 100, 0); DataFrameAnalyticsConfig config = new DataFrameAnalyticsConfig.Builder().setId("dfa-training-100-" + sourceIndex) .setSource( new DataFrameAnalyticsSource( new String[] { sourceIndex }, QueryProvider.fromParsedQuery(QueryBuilders.matchAllQuery()), null, Collections.emptyMap() ) ) .setAnalysis( new Regression( RegressionIT.DEPENDENT_VARIABLE_FIELD, BoostedTreeParams.builder().build(), null, 100.0, null, null, null, null, null ) ) .buildForExplain(); ExplainDataFrameAnalyticsAction.Response explainResponse = explainDataFrame(config); ByteSizeValue allDataUsedForTraining = explainResponse.getMemoryEstimation().getExpectedMemoryWithoutDisk(); config = new DataFrameAnalyticsConfig.Builder().setId("dfa-training-50-" + sourceIndex) .setSource( new DataFrameAnalyticsSource( new String[] { sourceIndex }, QueryProvider.fromParsedQuery(QueryBuilders.matchAllQuery()), null, Collections.emptyMap() ) ) .setAnalysis( new Regression( RegressionIT.DEPENDENT_VARIABLE_FIELD, BoostedTreeParams.builder().build(), null, 50.0, null, null, null, null, null ) ) .buildForExplain(); explainResponse = explainDataFrame(config); assertThat(explainResponse.getMemoryEstimation().getExpectedMemoryWithoutDisk(), lessThanOrEqualTo(allDataUsedForTraining)); } public void testSimultaneousExplainSameConfig() throws IOException { final int simultaneousInvocationCount = 10; String sourceIndex = "test-simultaneous-explain"; RegressionIT.indexData(sourceIndex, 100, 0); DataFrameAnalyticsConfig config = new DataFrameAnalyticsConfig.Builder().setId("dfa-simultaneous-explain-" + sourceIndex) .setSource( new DataFrameAnalyticsSource( new String[] { sourceIndex }, QueryProvider.fromParsedQuery(QueryBuilders.matchAllQuery()), null, Collections.emptyMap() ) ) .setAnalysis( new Regression( RegressionIT.DEPENDENT_VARIABLE_FIELD, BoostedTreeParams.builder().build(), null, 100.0, null, null, null, null, null ) ) .buildForExplain(); safeAwait(SubscribableListener.<Void>newForked(testListener -> { try (var listeners = new RefCountingListener(testListener)) { final var firstResponseRef = new AtomicReference<ExplainDataFrameAnalyticsAction.Response>(); for (int i = 0; i < simultaneousInvocationCount; ++i) { client().execute( ExplainDataFrameAnalyticsAction.INSTANCE, new ExplainDataFrameAnalyticsAction.Request(config), // The main purpose of this test is that the action will complete its listener exceptionally if any of the // simultaneous calls returns an error due to interaction between the many estimation processes that get run. listeners.acquire(response -> { // A secondary check the test can perform is that the multiple invocations return the same result // (but it was failures due to unwanted interactions that caused this test to be written) assertNotNull(response); firstResponseRef.compareAndSet(null, response); assertEquals(firstResponseRef.get(), response); }) ); } } })); } public void testRuntimeFields() { String sourceIndex = "test-explain-runtime-fields"; String mapping = """ { "properties": { "mapped_field": { "type": "double" } }, "runtime": { "mapped_runtime_field": { "type": "double", "script": "emit(doc['mapped_field'].value + 10.0)" } } }"""; client().admin().indices().prepareCreate(sourceIndex).setMapping(mapping).get(); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10; i++) { Object[] source = new Object[] { "mapped_field", i }; IndexRequest indexRequest = new IndexRequest(sourceIndex).source(source).opType(DocWriteRequest.OpType.CREATE); bulkRequestBuilder.add(indexRequest); } BulkResponse bulkResponse = bulkRequestBuilder.get(); if (bulkResponse.hasFailures()) { fail("Failed to index data: " + bulkResponse.buildFailureMessage()); } Map<String, Object> configRuntimeField = new HashMap<>(); configRuntimeField.put("type", "double"); configRuntimeField.put("script", "emit(doc['mapped_field'].value + 20.0)"); Map<String, Object> configRuntimeFields = Collections.singletonMap("config_runtime_field", configRuntimeField); DataFrameAnalyticsConfig config = new DataFrameAnalyticsConfig.Builder().setId(sourceIndex + "-job") .setSource(new DataFrameAnalyticsSource(new String[] { sourceIndex }, null, null, configRuntimeFields)) .setDest(new DataFrameAnalyticsDest(sourceIndex + "-results", null)) .setAnalysis(new OutlierDetection.Builder().build()) .build(); ExplainDataFrameAnalyticsAction.Response explainResponse = explainDataFrame(config); List<FieldSelection> fieldSelection = explainResponse.getFieldSelection(); assertThat(fieldSelection.size(), equalTo(3)); assertThat( fieldSelection.stream().map(FieldSelection::getName).collect(Collectors.toList()), contains("config_runtime_field", "mapped_field", "mapped_runtime_field") ); assertThat(fieldSelection.stream().map(FieldSelection::isIncluded).allMatch(isIncluded -> isIncluded), is(true)); } @Override boolean supportsInference() { return false; } }
ExplainDataFrameAnalyticsIT
java
apache__avro
lang/java/tools/src/main/java/org/apache/avro/tool/InduceSchemaTool.java
{ "start": 1078, "end": 1128 }
class ____ a protocol from an interface. */ public
or
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/logging/Log4jImpl.java
{ "start": 731, "end": 2913 }
class ____ implements Log { private static final String callerFQCN = Log4jImpl.class.getName(); private Logger log; private int errorCount; private int warnCount; private int infoCount; private int debugCount; /** * @param log the Log instance to be used for logging * @since 0.2.21 */ public Log4jImpl(Logger log) { this.log = log; } public Log4jImpl(String loggerName) { log = Logger.getLogger(loggerName); } public Logger getLog() { return log; } public boolean isDebugEnabled() { return log.isDebugEnabled(); } public void error(String s, Throwable e) { errorCount++; log.log(callerFQCN, Level.ERROR, s, e); } public void error(String s) { errorCount++; log.log(callerFQCN, Level.ERROR, s, null); } public void debug(String s) { debugCount++; log.log(callerFQCN, Level.DEBUG, s, null); } public void debug(String s, Throwable e) { debugCount++; log.log(callerFQCN, Level.DEBUG, s, e); } public void warn(String s) { log.log(callerFQCN, Level.WARN, s, null); warnCount++; } public void warn(String s, Throwable e) { log.log(callerFQCN, Level.WARN, s, e); warnCount++; } public int getWarnCount() { return warnCount; } public int getErrorCount() { return errorCount; } public void resetStat() { errorCount = 0; warnCount = 0; infoCount = 0; debugCount = 0; } public int getDebugCount() { return debugCount; } public boolean isInfoEnabled() { return log.isInfoEnabled(); } public void info(String msg) { infoCount++; log.log(callerFQCN, Level.INFO, msg, null); } public boolean isWarnEnabled() { return log.isEnabledFor(Level.WARN); } public boolean isErrorEnabled() { return log.isEnabledFor(Level.ERROR); } public int getInfoCount() { return infoCount; } public String toString() { return log.toString(); } }
Log4jImpl
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/co/IntervalJoinOperator.java
{ "start": 4084, "end": 15302 }
class ____<K, T1, T2, OUT> extends AbstractUdfStreamOperator<OUT, ProcessJoinFunction<T1, T2, OUT>> implements TwoInputStreamOperator<T1, T2, OUT>, Triggerable<K, String> { private static final long serialVersionUID = -5380774605111543454L; private static final Logger logger = LoggerFactory.getLogger(IntervalJoinOperator.class); private static final String LEFT_BUFFER = "LEFT_BUFFER"; private static final String RIGHT_BUFFER = "RIGHT_BUFFER"; private static final String CLEANUP_TIMER_NAME = "CLEANUP_TIMER"; private static final String CLEANUP_NAMESPACE_LEFT = "CLEANUP_LEFT"; private static final String CLEANUP_NAMESPACE_RIGHT = "CLEANUP_RIGHT"; private final long lowerBound; private final long upperBound; private final OutputTag<T1> leftLateDataOutputTag; private final OutputTag<T2> rightLateDataOutputTag; private final TypeSerializer<T1> leftTypeSerializer; private final TypeSerializer<T2> rightTypeSerializer; private transient MapState<Long, List<BufferEntry<T1>>> leftBuffer; private transient MapState<Long, List<BufferEntry<T2>>> rightBuffer; private transient TimestampedCollector<OUT> collector; private transient ContextImpl context; private transient InternalTimerService<String> internalTimerService; /** * Creates a new IntervalJoinOperator. * * @param lowerBound The lower bound for evaluating if elements should be joined * @param upperBound The upper bound for evaluating if elements should be joined * @param lowerBoundInclusive Whether or not to include elements where the timestamp matches the * lower bound * @param upperBoundInclusive Whether or not to include elements where the timestamp matches the * upper bound * @param udf A user-defined {@link ProcessJoinFunction} that gets called whenever two elements * of T1 and T2 are joined */ public IntervalJoinOperator( long lowerBound, long upperBound, boolean lowerBoundInclusive, boolean upperBoundInclusive, OutputTag<T1> leftLateDataOutputTag, OutputTag<T2> rightLateDataOutputTag, TypeSerializer<T1> leftTypeSerializer, TypeSerializer<T2> rightTypeSerializer, ProcessJoinFunction<T1, T2, OUT> udf) { super(Preconditions.checkNotNull(udf)); Preconditions.checkArgument( lowerBound <= upperBound, "lowerBound <= upperBound must be fulfilled"); // Move buffer by +1 / -1 depending on inclusiveness in order not needing // to check for inclusiveness later on this.lowerBound = (lowerBoundInclusive) ? lowerBound : lowerBound + 1L; this.upperBound = (upperBoundInclusive) ? upperBound : upperBound - 1L; this.leftLateDataOutputTag = leftLateDataOutputTag; this.rightLateDataOutputTag = rightLateDataOutputTag; this.leftTypeSerializer = Preconditions.checkNotNull(leftTypeSerializer); this.rightTypeSerializer = Preconditions.checkNotNull(rightTypeSerializer); } @Override public void open() throws Exception { super.open(); collector = new TimestampedCollector<>(output); context = new ContextImpl(userFunction); internalTimerService = getInternalTimerService(CLEANUP_TIMER_NAME, StringSerializer.INSTANCE, this); } @Override public void initializeState(StateInitializationContext context) throws Exception { super.initializeState(context); this.leftBuffer = context.getKeyedStateStore() .getMapState( new MapStateDescriptor<>( LEFT_BUFFER, LongSerializer.INSTANCE, new ListSerializer<>( new BufferEntrySerializer<>(leftTypeSerializer)))); this.rightBuffer = context.getKeyedStateStore() .getMapState( new MapStateDescriptor<>( RIGHT_BUFFER, LongSerializer.INSTANCE, new ListSerializer<>( new BufferEntrySerializer<>(rightTypeSerializer)))); } /** * Process a {@link StreamRecord} from the left stream. Whenever an {@link StreamRecord} arrives * at the left stream, it will get added to the left buffer. Possible join candidates for that * element will be looked up from the right buffer and if the pair lies within the user defined * boundaries, it gets passed to the {@link ProcessJoinFunction}. * * @param record An incoming record to be joined * @throws Exception Can throw an Exception during state access */ @Override public void processElement1(StreamRecord<T1> record) throws Exception { processElement(record, leftBuffer, rightBuffer, lowerBound, upperBound, true); } /** * Process a {@link StreamRecord} from the right stream. Whenever a {@link StreamRecord} arrives * at the right stream, it will get added to the right buffer. Possible join candidates for that * element will be looked up from the left buffer and if the pair lies within the user defined * boundaries, it gets passed to the {@link ProcessJoinFunction}. * * @param record An incoming record to be joined * @throws Exception Can throw an exception during state access */ @Override public void processElement2(StreamRecord<T2> record) throws Exception { processElement(record, rightBuffer, leftBuffer, -upperBound, -lowerBound, false); } @SuppressWarnings("unchecked") private <THIS, OTHER> void processElement( final StreamRecord<THIS> record, final MapState<Long, List<IntervalJoinOperator.BufferEntry<THIS>>> ourBuffer, final MapState<Long, List<IntervalJoinOperator.BufferEntry<OTHER>>> otherBuffer, final long relativeLowerBound, final long relativeUpperBound, final boolean isLeft) throws Exception { final THIS ourValue = record.getValue(); final long ourTimestamp = record.getTimestamp(); if (ourTimestamp == Long.MIN_VALUE) { throw new FlinkException( "Long.MIN_VALUE timestamp: Elements used in " + "interval stream joins need to have timestamps meaningful timestamps."); } if (isLate(ourTimestamp)) { sideOutput(ourValue, ourTimestamp, isLeft); return; } addToBuffer(ourBuffer, ourValue, ourTimestamp); for (Map.Entry<Long, List<BufferEntry<OTHER>>> bucket : otherBuffer.entries()) { final long timestamp = bucket.getKey(); if (timestamp < ourTimestamp + relativeLowerBound || timestamp > ourTimestamp + relativeUpperBound) { continue; } for (BufferEntry<OTHER> entry : bucket.getValue()) { if (isLeft) { collect((T1) ourValue, (T2) entry.element, ourTimestamp, timestamp); } else { collect((T1) entry.element, (T2) ourValue, timestamp, ourTimestamp); } } } long cleanupTime = (relativeUpperBound > 0L) ? ourTimestamp + relativeUpperBound : ourTimestamp; if (isLeft) { internalTimerService.registerEventTimeTimer(CLEANUP_NAMESPACE_LEFT, cleanupTime); } else { internalTimerService.registerEventTimeTimer(CLEANUP_NAMESPACE_RIGHT, cleanupTime); } } private boolean isLate(long timestamp) { long currentWatermark = internalTimerService.currentWatermark(); return timestamp < currentWatermark; } /** Write skipped late arriving element to SideOutput. */ protected <T> void sideOutput(T value, long timestamp, boolean isLeft) { if (isLeft) { if (leftLateDataOutputTag != null) { output.collect(leftLateDataOutputTag, new StreamRecord<>((T1) value, timestamp)); } } else { if (rightLateDataOutputTag != null) { output.collect(rightLateDataOutputTag, new StreamRecord<>((T2) value, timestamp)); } } } private void collect(T1 left, T2 right, long leftTimestamp, long rightTimestamp) throws Exception { final long resultTimestamp = Math.max(leftTimestamp, rightTimestamp); collector.setAbsoluteTimestamp(resultTimestamp); context.updateTimestamps(leftTimestamp, rightTimestamp, resultTimestamp); userFunction.processElement(left, right, context, collector); } private static <T> void addToBuffer( final MapState<Long, List<IntervalJoinOperator.BufferEntry<T>>> buffer, final T value, final long timestamp) throws Exception { List<BufferEntry<T>> elemsInBucket = buffer.get(timestamp); if (elemsInBucket == null) { elemsInBucket = new ArrayList<>(); } elemsInBucket.add(new BufferEntry<>(value, false)); buffer.put(timestamp, elemsInBucket); } @Override public void onEventTime(InternalTimer<K, String> timer) throws Exception { long timerTimestamp = timer.getTimestamp(); String namespace = timer.getNamespace(); logger.trace("onEventTime @ {}", timerTimestamp); switch (namespace) { case CLEANUP_NAMESPACE_LEFT: { long timestamp = (upperBound <= 0L) ? timerTimestamp : timerTimestamp - upperBound; logger.trace("Removing from left buffer @ {}", timestamp); leftBuffer.remove(timestamp); break; } case CLEANUP_NAMESPACE_RIGHT: { long timestamp = (lowerBound <= 0L) ? timerTimestamp + lowerBound : timerTimestamp; logger.trace("Removing from right buffer @ {}", timestamp); rightBuffer.remove(timestamp); break; } default: throw new RuntimeException("Invalid namespace " + namespace); } } @Override public void onProcessingTime(InternalTimer<K, String> timer) throws Exception { // do nothing. } /** * The context that is available during an invocation of {@link * ProcessJoinFunction#processElement(Object, Object, ProcessJoinFunction.Context, Collector)}. * * <p>It gives access to the timestamps of the left element in the joined pair, the right one, * and that of the joined pair. In addition, this context allows to emit elements on a side * output. */ private final
IntervalJoinOperator
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/model/InteractiveMessageRequest.java
{ "start": 862, "end": 1239 }
class ____ extends BaseMessage { private InteractiveMessage interactive; public InteractiveMessageRequest() { setType("interactive"); } public InteractiveMessage getInteractive() { return interactive; } public void setInteractive(InteractiveMessage interactive) { this.interactive = interactive; } }
InteractiveMessageRequest
java
mockito__mockito
mockito-core/src/testFixtures/java/org/mockitoutil/ClassLoadersTest.java
{ "start": 14014, "end": 14103 }
class ____ implements Interface1 {} @SuppressWarnings("unused")
ClassUsingInterface1
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2ClientRegistrationHttpMessageConverter.java
{ "start": 2364, "end": 5910 }
class ____ extends AbstractHttpMessageConverter<OAuth2ClientRegistration> { private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<>() { }; private final GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters .getJsonMessageConverter(); private Converter<Map<String, Object>, OAuth2ClientRegistration> clientRegistrationConverter = new MapOAuth2ClientRegistrationConverter(); private Converter<OAuth2ClientRegistration, Map<String, Object>> clientRegistrationParametersConverter = new OAuth2ClientRegistrationMapConverter(); public OAuth2ClientRegistrationHttpMessageConverter() { super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json")); } @Override protected boolean supports(Class<?> clazz) { return OAuth2ClientRegistration.class.isAssignableFrom(clazz); } @Override @SuppressWarnings("unchecked") protected OAuth2ClientRegistration readInternal(Class<? extends OAuth2ClientRegistration> clazz, HttpInputMessage inputMessage) throws HttpMessageNotReadableException { try { Map<String, Object> clientRegistrationParameters = (Map<String, Object>) this.jsonMessageConverter .read(STRING_OBJECT_MAP.getType(), null, inputMessage); return this.clientRegistrationConverter.convert(clientRegistrationParameters); } catch (Exception ex) { throw new HttpMessageNotReadableException( "An error occurred reading the OAuth 2.0 Client Registration: " + ex.getMessage(), ex, inputMessage); } } @Override protected void writeInternal(OAuth2ClientRegistration clientRegistration, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException { try { Map<String, Object> clientRegistrationParameters = this.clientRegistrationParametersConverter .convert(clientRegistration); this.jsonMessageConverter.write(clientRegistrationParameters, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, outputMessage); } catch (Exception ex) { throw new HttpMessageNotWritableException( "An error occurred writing the OAuth 2.0 Client Registration: " + ex.getMessage(), ex); } } /** * Sets the {@link Converter} used for converting the OAuth 2.0 Client Registration * parameters to an {@link OAuth2ClientRegistration}. * @param clientRegistrationConverter the {@link Converter} used for converting to an * {@link OAuth2ClientRegistration} */ public final void setClientRegistrationConverter( Converter<Map<String, Object>, OAuth2ClientRegistration> clientRegistrationConverter) { Assert.notNull(clientRegistrationConverter, "clientRegistrationConverter cannot be null"); this.clientRegistrationConverter = clientRegistrationConverter; } /** * Sets the {@link Converter} used for converting the {@link OAuth2ClientRegistration} * to a {@code Map} representation of the OAuth 2.0 Client Registration parameters. * @param clientRegistrationParametersConverter the {@link Converter} used for * converting to a {@code Map} representation of the OAuth 2.0 Client Registration * parameters */ public final void setClientRegistrationParametersConverter( Converter<OAuth2ClientRegistration, Map<String, Object>> clientRegistrationParametersConverter) { Assert.notNull(clientRegistrationParametersConverter, "clientRegistrationParametersConverter cannot be null"); this.clientRegistrationParametersConverter = clientRegistrationParametersConverter; } private static final
OAuth2ClientRegistrationHttpMessageConverter
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/reflection/property/PropertyTokenizer.java
{ "start": 766, "end": 1970 }
class ____ implements Iterator<PropertyTokenizer> { private String name; private final String indexedName; private String index; private final String children; public PropertyTokenizer(String fullname) { int delim = fullname.indexOf('.'); if (delim > -1) { name = fullname.substring(0, delim); children = fullname.substring(delim + 1); } else { name = fullname; children = null; } indexedName = name; delim = name.indexOf('['); if (delim > -1) { index = name.substring(delim + 1, name.length() - 1); name = name.substring(0, delim); } } public String getName() { return name; } public String getIndex() { return index; } public String getIndexedName() { return indexedName; } public String getChildren() { return children; } @Override public boolean hasNext() { return children != null; } @Override public PropertyTokenizer next() { return new PropertyTokenizer(children); } @Override public void remove() { throw new UnsupportedOperationException( "Remove is not supported, as it has no meaning in the context of properties."); } }
PropertyTokenizer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/module/TestTypeModifiers.java
{ "start": 7211, "end": 7906 }
class ____ extends ValueDeserializer<MyCollectionLikeType> { @Override public MyCollectionLikeType deserialize(JsonParser p, DeserializationContext ctxt) { if (p.currentToken() != JsonToken.START_ARRAY) throw new StreamReadException(p, "Wrong token: "+p.currentToken()); if (p.nextToken() != JsonToken.VALUE_NUMBER_INT) throw new StreamReadException(p, "Wrong token: "+p.currentToken()); int value = p.getIntValue(); if (p.nextToken() != JsonToken.END_ARRAY) throw new StreamReadException(p, "Wrong token: "+p.currentToken()); return new MyCollectionLikeType(value); } } static
MyCollectionDeserializer