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
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/client/ResponseExtractor.java
{ "start": 1430, "end": 1740 }
interface ____<T> { /** * Extract data from the given {@code ClientHttpResponse} and return it. * @param response the HTTP response * @return the extracted data * @throws IOException in case of I/O errors */ @Nullable T extractData(ClientHttpResponse response) throws IOException; }
ResponseExtractor
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/ConnectableFluxHide.java
{ "start": 1023, "end": 1746 }
class ____<T> extends InternalConnectableFluxOperator<T, T> implements Scannable { ConnectableFluxHide(ConnectableFlux<T> source) { super(source); } @Override public int getPrefetch() { return source.getPrefetch(); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return source; if (key == Attr.PREFETCH) return getPrefetch(); if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { return actual; } @Override public void connect(Consumer<? super Disposable> cancelSupport) { source.connect(cancelSupport); } }
ConnectableFluxHide
java
quarkusio__quarkus
devtools/cli/src/main/java/io/quarkus/cli/deploy/Kind.java
{ "start": 808, "end": 1179 }
class ____ extends BaseKubernetesDeployCommand { private static final String KIND = "kind"; private static final String KIND_EXTENSION = "io.quarkus:quarkus-kind"; private static final String CONTAINER_IMAGE_EXTENSION = "io.quarkus:quarkus-container-image"; private static final String DEPLOYMENT_KIND = "quarkus.kubernetes.deployment-kind"; public
Kind
java
google__guava
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/SortedMultiset.java
{ "start": 933, "end": 1713 }
interface ____<E extends @Nullable Object> extends Multiset<E>, SortedIterable<E> { Comparator<? super E> comparator(); @Nullable Entry<E> firstEntry(); @Nullable Entry<E> lastEntry(); @Nullable Entry<E> pollFirstEntry(); @Nullable Entry<E> pollLastEntry(); /** * Returns a {@link SortedSet} view of the distinct elements in this multiset. (Outside GWT, this * returns a {@code NavigableSet}.) */ @Override SortedSet<E> elementSet(); SortedMultiset<E> descendingMultiset(); SortedMultiset<E> headMultiset(E upperBound, BoundType boundType); SortedMultiset<E> subMultiset( E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType); SortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType); }
SortedMultiset
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java
{ "start": 1460, "end": 3620 }
class ____ { private static final Log logger = LogFactory.getLog(ConcurrencyThrottleInterceptorTests.class); private static final int NR_OF_THREADS = 100; private static final int NR_OF_ITERATIONS = 1000; @Test void interceptorMustBeSerializable() throws Exception { DerivedTestBean tb = new DerivedTestBean(); ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setInterfaces(ITestBean.class); ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor(); proxyFactory.addAdvice(cti); proxyFactory.setTarget(tb); ITestBean proxy = (ITestBean) proxyFactory.getProxy(); proxy.getAge(); ITestBean serializedProxy = SerializationTestUtils.serializeAndDeserialize(proxy); Advised advised = (Advised) serializedProxy; ConcurrencyThrottleInterceptor serializedCti = (ConcurrencyThrottleInterceptor) advised.getAdvisors()[0].getAdvice(); assertThat(serializedCti.getConcurrencyLimit()).isEqualTo(cti.getConcurrencyLimit()); serializedProxy.getAge(); } @ParameterizedTest @ValueSource(ints = {1, 10}) void multipleThreadsWithLimit(int concurrencyLimit) { TestBean tb = new TestBean(); ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setInterfaces(ITestBean.class); ConcurrencyThrottleInterceptor cti = new ConcurrencyThrottleInterceptor(); cti.setConcurrencyLimit(concurrencyLimit); proxyFactory.addAdvice(cti); proxyFactory.setTarget(tb); ITestBean proxy = (ITestBean) proxyFactory.getProxy(); Thread[] threads = new Thread[NR_OF_THREADS]; for (int i = 0; i < NR_OF_THREADS; i++) { threads[i] = new ConcurrencyThread(proxy, null); threads[i].start(); } for (int i = 0; i < NR_OF_THREADS / 10; i++) { try { Thread.sleep(5); } catch (InterruptedException ex) { ex.printStackTrace(); } threads[i] = new ConcurrencyThread(proxy, (i % 2 == 0 ? new OutOfMemoryError() : new IllegalStateException())); threads[i].start(); } for (int i = 0; i < NR_OF_THREADS; i++) { try { threads[i].join(); } catch (InterruptedException ex) { ex.printStackTrace(); } } } private static
ConcurrencyThrottleInterceptorTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassCanBeStaticTest.java
{ "start": 5616, "end": 5744 }
class ____ { int nonStaticVar = outerVar; // BUG: Diagnostic contains: public static
NonStaticOuter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ConvertedEmbeddableCollectionTest.java
{ "start": 2333, "end": 2658 }
class ____ implements AttributeConverter<TestEmbeddable, String> { @Override public String convertToDatabaseColumn(TestEmbeddable attribute) { return attribute.getData(); } @Override public TestEmbeddable convertToEntityAttribute(String dbData) { return new TestEmbeddable( dbData ); } } }
EmbeddableConverter
java
google__dagger
javatests/dagger/functional/assisted/subpackage/Dep.java
{ "start": 743, "end": 778 }
class ____ { @Inject Dep() {} }
Dep
java
quarkusio__quarkus
integration-tests/gradle/src/test/java/io/quarkus/gradle/BasicCompositeBuildExtensionQuarkusBuildTest.java
{ "start": 276, "end": 2866 }
class ____ extends QuarkusGradleWrapperTestBase { @Test public void testBasicMultiModuleBuild() throws Exception { final File projectDir = getProjectDir("basic-composite-build-extension-project"); final File appProperties = new File(projectDir, "application/gradle.properties"); final File libsProperties = new File(projectDir, "libraries/gradle.properties"); final File extensionProperties = new File(projectDir, "extensions/example-extension/gradle.properties"); final Path projectProperties = projectDir.toPath().resolve("gradle.properties"); try { Files.copy(projectProperties, appProperties.toPath(), StandardCopyOption.REPLACE_EXISTING); Files.copy(projectProperties, libsProperties.toPath(), StandardCopyOption.REPLACE_EXISTING); Files.copy(projectProperties, extensionProperties.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new IllegalStateException("Unable to copy gradle.properties file", e); } runGradleWrapper(projectDir, ":application:quarkusBuild"); final Path extension = projectDir.toPath().resolve("extensions").resolve("example-extension").resolve("runtime") .resolve("build") .resolve("libs"); assertThat(extension).exists(); assertThat(extension.resolve("example-extension-1.0-SNAPSHOT.jar")).exists(); final Path libA = projectDir.toPath().resolve("libraries").resolve("libraryA").resolve("build").resolve("libs"); assertThat(libA).exists(); assertThat(libA.resolve("libraryA-1.0-SNAPSHOT.jar")).exists(); final Path libB = projectDir.toPath().resolve("libraries").resolve("libraryB").resolve("build").resolve("libs"); assertThat(libB).exists(); assertThat(libB.resolve("libraryB-1.0-SNAPSHOT.jar")).exists(); final Path applicationLib = projectDir.toPath().resolve("application").resolve("build").resolve("quarkus-app"); assertThat(applicationLib.resolve("lib").resolve("main").resolve("org.acme.libs.libraryA-1.0-SNAPSHOT.jar")).exists(); assertThat(applicationLib.resolve("lib").resolve("main").resolve("org.acme.libs.libraryB-1.0-SNAPSHOT.jar")).exists(); assertThat(applicationLib.resolve("lib").resolve("main") .resolve("org.acme.extensions.example-extension-1.0-SNAPSHOT.jar")).exists(); assertThat(applicationLib.resolve("app").resolve("application-1.0-SNAPSHOT.jar")).exists(); } }
BasicCompositeBuildExtensionQuarkusBuildTest
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/manytomany/unidirectional/M2MTargetNotAuditedEntity.java
{ "start": 709, "end": 2568 }
class ____ { @Id private Integer id; @Audited private String data; @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) @ManyToMany(fetch = FetchType.LAZY) private List<UnversionedStrTestEntity> references; public M2MTargetNotAuditedEntity() { } public M2MTargetNotAuditedEntity(Integer id, String data, List<UnversionedStrTestEntity> references) { this.id = id; this.data = data; this.references = references; } public M2MTargetNotAuditedEntity(String data, List<UnversionedStrTestEntity> references) { this.data = data; this.references = references; } public M2MTargetNotAuditedEntity(Integer id, String data) { this.id = id; this.data = data; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public List<UnversionedStrTestEntity> getReferences() { return references; } public void setReferences(List<UnversionedStrTestEntity> references) { this.references = references; } public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof M2MTargetNotAuditedEntity) ) { return false; } M2MTargetNotAuditedEntity that = (M2MTargetNotAuditedEntity) o; if ( data != null ? !data.equals( that.getData() ) : that.getData() != null ) { return false; } //noinspection RedundantIfStatement if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) { return false; } return true; } public int hashCode() { int result; result = (id != null ? id.hashCode() : 0); result = 31 * result + (data != null ? data.hashCode() : 0); return result; } public String toString() { return "M2MTargetNotAuditedEntity(id = " + id + ", data = " + data + ")"; } }
M2MTargetNotAuditedEntity
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/complex/source/Person.java
{ "start": 202, "end": 470 }
class ____ { private String name; public Person() { } public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Person
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/converter/GenericMessageConverterTests.java
{ "start": 1210, "end": 2172 }
class ____ { private final ConversionService conversionService = new DefaultConversionService(); private final GenericMessageConverter converter = new GenericMessageConverter(conversionService); @Test void fromMessageWithConversion() { Message<String> content = MessageBuilder.withPayload("33").build(); assertThat(converter.fromMessage(content, Integer.class)).isEqualTo(33); } @Test void fromMessageNoConverter() { Message<Integer> content = MessageBuilder.withPayload(1234).build(); assertThat(converter.fromMessage(content, Locale.class)).as("No converter from integer to locale").isNull(); } @Test void fromMessageWithFailedConversion() { Message<String> content = MessageBuilder.withPayload("test not a number").build(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> converter.fromMessage(content, Integer.class)) .withCauseInstanceOf(ConversionException.class); } }
GenericMessageConverterTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentTypeTest.java
{ "start": 6025, "end": 6357 }
interface ____<K, V> { boolean containsKey(@CompatibleWith("K") Object key); boolean containsValue(@CompatibleWith("V") Object value); boolean containsEntry(@CompatibleWith("K") Object key, @CompatibleWith("V") Object value); boolean containsAllKeys(@CompatibleWith("K") Object key, Object... others); }
Multimap
java
apache__maven
src/mdo/java/InputSource.java
{ "start": 1483, "end": 1588 }
class ____ factory methods for convenient creation of instances. * * @since 4.0.0 */ public final
provides
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/DescribeConfigsOptions.java
{ "start": 944, "end": 2349 }
class ____ extends AbstractOptions<DescribeConfigsOptions> { private boolean includeSynonyms = false; private boolean includeDocumentation = false; /** * Set the timeout in milliseconds for this operation or {@code null} if the default api timeout for the * AdminClient should be used. * */ // This method is retained to keep binary compatibility with 0.11 public DescribeConfigsOptions timeoutMs(Integer timeoutMs) { this.timeoutMs = timeoutMs; return this; } /** * Return true if synonym configs should be returned in the response. */ public boolean includeSynonyms() { return includeSynonyms; } /** * Return true if config documentation should be returned in the response. */ public boolean includeDocumentation() { return includeDocumentation; } /** * Set to true if synonym configs should be returned in the response. */ public DescribeConfigsOptions includeSynonyms(boolean includeSynonyms) { this.includeSynonyms = includeSynonyms; return this; } /** * Set to true if config documentation should be returned in the response. */ public DescribeConfigsOptions includeDocumentation(boolean includeDocumentation) { this.includeDocumentation = includeDocumentation; return this; } }
DescribeConfigsOptions
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/ClusterResolverLoadBalancerProvider.java
{ "start": 2773, "end": 4331 }
class ____ { // Cluster to be resolved. final DiscoveryMechanism discoveryMechanism; // GracefulSwitch configuration final Object lbConfig; private final boolean isHttp11ProxyAvailable; ClusterResolverConfig(DiscoveryMechanism discoveryMechanism, Object lbConfig, boolean isHttp11ProxyAvailable) { this.discoveryMechanism = checkNotNull(discoveryMechanism, "discoveryMechanism"); this.lbConfig = checkNotNull(lbConfig, "lbConfig"); this.isHttp11ProxyAvailable = isHttp11ProxyAvailable; } boolean isHttp11ProxyAvailable() { return isHttp11ProxyAvailable; } @Override public int hashCode() { return Objects.hash(discoveryMechanism, lbConfig, isHttp11ProxyAvailable); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterResolverConfig that = (ClusterResolverConfig) o; return discoveryMechanism.equals(that.discoveryMechanism) && lbConfig.equals(that.lbConfig) && isHttp11ProxyAvailable == that.isHttp11ProxyAvailable; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("discoveryMechanism", discoveryMechanism) .add("lbConfig", lbConfig) .add("isHttp11ProxyAvailable", isHttp11ProxyAvailable) .toString(); } // Describes the mechanism for a specific cluster. static final
ClusterResolverConfig
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/timer/TimerSuspendCamelContextTest.java
{ "start": 1130, "end": 1942 }
class ____ extends ContextTestSupport { @Test public void testTimerSuspendResume() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(1); assertMockEndpointsSatisfied(); mock.reset(); mock.expectedMessageCount(0); context.suspend(); assertMockEndpointsSatisfied(); mock.reset(); mock.expectedMinimumMessageCount(1); context.resume(); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("timer://foo?fixedRate=true&delay=0&period=10").to("mock:result"); } }; } }
TimerSuspendCamelContextTest
java
elastic__elasticsearch
x-pack/plugin/text-structure/src/main/java/org/elasticsearch/xpack/textstructure/structurefinder/TimeoutChecker.java
{ "start": 5725, "end": 6033 }
class ____ interrupt * matching operations that take too long. Rather than have a timeout per match operation * like the {@link MatcherWatchdog.Default} implementation, the interruption is governed by * a {@link TimeoutChecker} associated with the thread doing the matching. */ static
to
java
micronaut-projects__micronaut-core
context/src/main/java/io/micronaut/runtime/beans/MapperIntroduction.java
{ "start": 22317, "end": 29576 }
class ____ implements MapInvocation { private final Map<String, Function<Object, BiConsumer<Object, MappingBuilder<Object>>>> customMapperSuppliers; private final List<Function<Object, BiConsumer<Object, MappingBuilder<Object>>>> rootMapperSuppliers; private final boolean isMap; private final boolean needsCustom; private final BeanIntrospection<Object> fromIntrospection; private final BeanIntrospection<Object> toIntrospection; private final int argIndex; private final ConflictStrategy conflictStrategy; public DefaultMapInvocation( AnnotationMetadata annotationMetadata, Argument<Object> fromArgument, BeanIntrospection<Object> toIntrospection, int argIndex, ConflictStrategy conflictStrategy ) { Class<Object> fromClass = fromArgument.getType(); this.isMap = Map.class.isAssignableFrom(fromClass); this.fromIntrospection = isMap ? null : BeanIntrospection.getIntrospection(fromClass); this.toIntrospection = toIntrospection; if (annotationMetadata.isPresent(Mapper.class, AnnotationMetadata.VALUE_MEMBER)) { List<AnnotationValue<Mapper.Mapping>> annotations = annotationMetadata.getAnnotationValuesByType(Mapper.Mapping.class); customMapperSuppliers = buildCustomMappers(fromArgument, fromIntrospection, toIntrospection, conflictStrategy, annotations, isMap); rootMapperSuppliers = buildRootMappers(fromIntrospection, conflictStrategy, annotations, isMap); } else { customMapperSuppliers = null; rootMapperSuppliers = null; } this.needsCustom = (customMapperSuppliers != null && !customMapperSuppliers.isEmpty()) || (rootMapperSuppliers != null && !rootMapperSuppliers.isEmpty()); this.argIndex = argIndex; this.conflictStrategy = conflictStrategy; } public void map(MethodInvocationContext<Object, Object> callContext, MappingBuilder<Object> builder) { if (needsCustom) { MapStrategy mapStrategy = buildMapStrategy(conflictStrategy, customMapperSuppliers, rootMapperSuppliers, callContext); if (isMap) { mapMap((Map<String, Object>) callContext.getParameterValues()[argIndex], mapStrategy, builder); } else { mapBean(callContext.getParameterValues()[argIndex], mapStrategy, fromIntrospection, builder); } } else if (isMap) { mapMap((Map<String, Object>) callContext.getParameterValues()[argIndex], MapStrategy.DEFAULT, builder ); } else { mapBean( callContext.getParameterValues()[argIndex], MapStrategy.DEFAULT, fromIntrospection, builder ); } } @Override public Object map(MethodInvocationContext<Object, Object> invocationContext) { MappingBuilder<Object> builder = new DefaultMappingBuilder<>(toIntrospection.builder()); map(invocationContext, builder); return builder.build(); } private <I, O> void mapBean(I input, MapStrategy mapStrategy, BeanIntrospection<I> inputIntrospection, MappingBuilder<O> builder) { boolean isDefault = mapStrategy == MapStrategy.DEFAULT; Mapper.ConflictStrategy conflictStrategy = mapStrategy.conflictStrategy(); @SuppressWarnings("unchecked") @NonNull Argument<Object>[] arguments = (Argument<Object>[]) builder.getBuilderArguments(); if (!isDefault) { processCustomMappers(input, mapStrategy, builder); } for (BeanProperty<I, Object> beanProperty : inputIntrospection.getBeanProperties()) { if (!beanProperty.isWriteOnly()) { String propertyName = beanProperty.getName(); if (!isDefault && mapStrategy.customMappers().containsKey(propertyName)) { continue; } int i = builder.indexOf(propertyName); if (i > -1) { Argument<Object> argument = arguments[i]; Object value = beanProperty.get(input); if (value == null || argument.isInstance(value)) { builder.with(i, argument, value, propertyName, input); } else if (conflictStrategy == Mapper.ConflictStrategy.CONVERT) { ArgumentConversionContext<Object> conversionContext = ConversionContext.of(argument); builder.convert(i, conversionContext, value, conversionService, propertyName, input); } else { builder.with(i, argument, value, propertyName, input); } } } } } private <O> void mapMap(Map<String, Object> input, MapStrategy mapStrategy, MappingBuilder<O> builder) { @NonNull Argument<Object>[] arguments = (Argument<Object>[]) builder.getBuilderArguments(); Mapper.ConflictStrategy conflictStrategy = mapStrategy.conflictStrategy(); boolean isDefault = mapStrategy == MapStrategy.DEFAULT; if (!isDefault) { processCustomMappers(input, mapStrategy, builder); } input.forEach((key, value) -> { int i = builder.indexOf(key); if (!isDefault && mapStrategy.customMappers().containsKey(key)) { return; } if (i > -1) { Argument<Object> argument = arguments[i]; if (conflictStrategy == Mapper.ConflictStrategy.CONVERT) { builder.convert(i, ConversionContext.of(argument), value, conversionService, key, input); } else { builder.with(i, argument, value, key, input); } } }); } } private record MapStrategy( Mapper.ConflictStrategy conflictStrategy, Map<String, BiConsumer<Object, MappingBuilder<Object>>> customMappers, List<BiConsumer<Object, MappingBuilder<Object>>> rootMappers ) { static final MapStrategy DEFAULT = new MapStrategy(Mapper.ConflictStrategy.CONVERT, Collections.emptyMap(), List.of()); private MapStrategy { if (conflictStrategy == null) { conflictStrategy = Mapper.ConflictStrategy.CONVERT; } if (customMappers == null) { customMappers = new HashMap<>(10); } if (rootMappers == null) { rootMappers = new ArrayList<>(3); } } public MapStrategy(Mapper.ConflictStrategy conflictStrategy) { this(conflictStrategy, new HashMap<>(10), new ArrayList<>(3)); } } private sealed
DefaultMapInvocation
java
spring-projects__spring-boot
module/spring-boot-jackson2/src/test/java/org/springframework/boot/jackson2/autoconfigure/Jackson2AutoConfigurationTests.java
{ "start": 26022, "end": 26203 }
class ____ extends JsonObjectSerializer<Baz> { @Override protected void serializeObject(Baz value, JsonGenerator jgen, SerializerProvider provider) { } } static
BazSerializer
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/remoting/activity/AckMessageActivity.java
{ "start": 1186, "end": 1667 }
class ____ extends AbstractRemotingActivity { public AckMessageActivity(RequestPipeline requestPipeline, MessagingProcessor messagingProcessor) { super(requestPipeline, messagingProcessor); } @Override protected RemotingCommand processRequest0(ChannelHandlerContext ctx, RemotingCommand request, ProxyContext context) throws Exception { return request(ctx, request, context, Duration.ofSeconds(3).toMillis()); } }
AckMessageActivity
java
spring-projects__spring-boot
module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/autoconfigure/servlet/ServletWebServerFactoryCustomizerTests.java
{ "start": 2153, "end": 8559 }
class ____ { private final ServerProperties properties = new ServerProperties(); private ServletWebServerFactoryCustomizer customizer; @BeforeEach void setup() { this.customizer = new ServletWebServerFactoryCustomizer(this.properties); } @Test void testDefaultDisplayName() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should().setDisplayName("application"); } @Test void testCustomizeDisplayName() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.properties.getServlet().setApplicationDisplayName("TestName"); this.customizer.customize(factory); then(factory).should().setDisplayName("TestName"); } @Test void withNoCustomMimeMappingsThenEmptyMimeMappingsIsAdded() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); ArgumentCaptor<MimeMappings> mimeMappingsCaptor = ArgumentCaptor.forClass(MimeMappings.class); then(factory).should().addMimeMappings(mimeMappingsCaptor.capture()); MimeMappings mimeMappings = mimeMappingsCaptor.getValue(); assertThat(mimeMappings.getAll()).isEmpty(); } @Test void withCustomMimeMappingsThenPopulatedMimeMappingsIsAdded() { this.properties.getMimeMappings().add("a", "alpha"); this.properties.getMimeMappings().add("b", "bravo"); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); ArgumentCaptor<MimeMappings> mimeMappingsCaptor = ArgumentCaptor.forClass(MimeMappings.class); then(factory).should().addMimeMappings(mimeMappingsCaptor.capture()); MimeMappings mimeMappings = mimeMappingsCaptor.getValue(); assertThat(mimeMappings.getAll()).hasSize(2); } @Test void testCustomizeDefaultServlet() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.properties.getServlet().setRegisterDefaultServlet(false); this.customizer.customize(factory); then(factory).should().setRegisterDefaultServlet(false); } @Test void testCustomizeSsl() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); Ssl ssl = mock(Ssl.class); this.properties.setSsl(ssl); this.customizer.customize(factory); then(factory).should().setSsl(ssl); } @Test void testCustomizeJsp() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should().setJsp(any(Jsp.class)); } @Test void customizeSessionProperties() { Map<String, String> map = new HashMap<>(); map.put("server.servlet.session.timeout", "123"); map.put("server.servlet.session.tracking-modes", "cookie,url"); map.put("server.servlet.session.cookie.name", "testname"); map.put("server.servlet.session.cookie.domain", "testdomain"); map.put("server.servlet.session.cookie.path", "/testpath"); map.put("server.servlet.session.cookie.http-only", "true"); map.put("server.servlet.session.cookie.secure", "true"); map.put("server.servlet.session.cookie.max-age", "60"); bindProperties(map); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should().setSession(assertArg((session) -> { assertThat(session.getTimeout()).hasSeconds(123); Cookie cookie = session.getCookie(); assertThat(cookie.getName()).isEqualTo("testname"); assertThat(cookie.getDomain()).isEqualTo("testdomain"); assertThat(cookie.getPath()).isEqualTo("/testpath"); assertThat(cookie.getHttpOnly()).isTrue(); assertThat(cookie.getMaxAge()).hasSeconds(60); })); } @Test void testCustomizeTomcatPort() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.properties.setPort(8080); this.customizer.customize(factory); then(factory).should().setPort(8080); } @Test void customizeServletDisplayName() { Map<String, String> map = new HashMap<>(); map.put("server.servlet.application-display-name", "MyBootApp"); bindProperties(map); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should().setDisplayName("MyBootApp"); } @Test void sessionStoreDir() { Map<String, String> map = new HashMap<>(); map.put("server.servlet.session.store-dir", "mydirectory"); bindProperties(map); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should() .setSession(assertArg((session) -> assertThat(session.getStoreDir()).isEqualTo(new File("mydirectory")))); } @Test void whenShutdownPropertyIsSetThenShutdownIsCustomized() { Map<String, String> map = new HashMap<>(); map.put("server.shutdown", "immediate"); bindProperties(map); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should().setShutdown(assertArg((shutdown) -> assertThat(shutdown).isEqualTo(Shutdown.IMMEDIATE))); } @Test void noLocaleCharsetMapping() { ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should(never()).setLocaleCharsetMappings(anyMap()); } @Test void customLocaleCharsetMappings() { Map<String, String> map = Map.of("server.servlet.encoding.mapping.en", "UTF-8", "server.servlet.encoding.mapping.fr_FR", "UTF-8"); bindProperties(map); ConfigurableServletWebServerFactory factory = mock(ConfigurableServletWebServerFactory.class); this.customizer.customize(factory); then(factory).should() .setLocaleCharsetMappings((assertArg((mappings) -> assertThat(mappings).hasSize(2) .containsEntry(Locale.ENGLISH, StandardCharsets.UTF_8) .containsEntry(Locale.FRANCE, StandardCharsets.UTF_8)))); } private void bindProperties(Map<String, String> map) { ConfigurationPropertySource source = new MapConfigurationPropertySource(map); new Binder(source).bind("server", Bindable.ofInstance(this.properties)); } }
ServletWebServerFactoryCustomizerTests
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/issues/PrivateClasses.java
{ "start": 1354, "end": 1552 }
class ____ implements HelloCamel { @Override public String sayHello(String input) { return EXPECTED_OUTPUT; } } private static final
PackagePrivateHelloCamel
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleRegistry.java
{ "start": 990, "end": 1246 }
interface ____ extends ExtensibleEnumRegistry<Lifecycle>, Iterable<Lifecycle> { default Stream<Lifecycle> stream() { return StreamSupport.stream(spliterator(), false); } List<String> computePhases(Lifecycle lifecycle); }
LifecycleRegistry
java
apache__camel
components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorWaitForTaskCompleteOnCompletionTest.java
{ "start": 1410, "end": 3514 }
class ____ extends CamelTestSupport { private static String done = ""; @Test void testAlways() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(0); try { template.sendBody("direct:start", "Hello World"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertEquals("Forced", e.getCause().getMessage()); } MockEndpoint.assertIsSatisfied(context); // 3 + 1 C and A should be last assertEquals("CCCCA", done); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { errorHandler(defaultErrorHandler().maximumRedeliveries(3).redeliveryDelay(0)); from("direct:start").process(new Processor() { @Override public void process(final Exchange exchange) { exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() { @Override public void onDone(final Exchange exchange) { done += "A"; } }); } }).to("disruptor:foo?waitForTaskToComplete=Always").process(new Processor() { @Override public void process(final Exchange exchange) { done += "B"; } }).to("mock:result"); from("disruptor:foo").errorHandler(noErrorHandler()).process(new Processor() { @Override public void process(final Exchange exchange) { done = done + "C"; } }).throwException(new IllegalArgumentException("Forced")); } }; } }
DisruptorWaitForTaskCompleteOnCompletionTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/aot/TestAotProcessorTests.java
{ "start": 2029, "end": 4343 }
class ____ extends AbstractAotTests { @Test void process(@TempDir(cleanup = CleanupMode.ON_SUCCESS) Path tempDir) throws Exception { // Limit the scope of this test by creating a new classpath root on the fly. Path classpathRoot = Files.createDirectories(tempDir.resolve("build/classes")); Stream.of( BasicSpringJupiterImportedConfigTests.class, BasicSpringJupiterParameterizedClassTests.class, BasicSpringJupiterSharedConfigTests.class, BasicSpringJupiterTests.class, BasicSpringTestNGTests.class, BasicSpringVintageTests.class, DisabledInAotProcessingTests.class, DisabledInAotRuntimeClassLevelTests.class, DisabledInAotRuntimeMethodLevelTests.class ).forEach(testClass -> copy(testClass, classpathRoot)); Set<Path> classpathRoots = Set.of(classpathRoot); Path sourceOutput = tempDir.resolve("generated/sources"); Path resourceOutput = tempDir.resolve("generated/resources"); Path classOutput = tempDir.resolve("generated/classes"); String groupId = "org.example"; String artifactId = "app-tests"; TestAotProcessor processor = new DemoTestAotProcessor(classpathRoots, sourceOutput, resourceOutput, classOutput, groupId, artifactId); processor.process(); assertThat(findFiles(sourceOutput)).containsExactlyInAnyOrderElementsOf(expectedSourceFiles()); assertThat(findFiles(resourceOutput.resolve("META-INF/native-image"))).contains( Path.of(groupId, artifactId, "reachability-metadata.json")); } private void copy(Class<?> testClass, Path destination) { String classFilename = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".class"; Path source = classpathRoot(testClass).resolve(classFilename); Path target = destination.resolve(classFilename); try { Files.createDirectories(target.getParent()); Files.copy(source, target); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static Stream<Path> findFiles(Path directory) throws IOException { return Files.walk(directory).filter(Files::isRegularFile) .map(path -> path.subpath(directory.getNameCount(), path.getNameCount())); } private static List<Path> expectedSourceFiles() { return Arrays.stream(expectedSourceFilesForBasicSpringTests).map(Path::of).toList(); } private static
TestAotProcessorTests
java
apache__camel
components/camel-fhir/camel-fhir-component/src/generated/java/org/apache/camel/component/fhir/internal/FhirOperationApiMethod.java
{ "start": 664, "end": 3619 }
enum ____ implements ApiMethod { ON_INSTANCE( org.hl7.fhir.instance.model.api.IBaseResource.class, "onInstance", arg("id", org.hl7.fhir.instance.model.api.IIdType.class), arg("name", String.class), arg("parameters", org.hl7.fhir.instance.model.api.IBaseParameters.class), arg("outputParameterType", Class.class), arg("useHttpGet", boolean.class), arg("returnType", Class.class), arg("extraParameters", java.util.Map.class)), ON_INSTANCE_VERSION( org.hl7.fhir.instance.model.api.IBaseResource.class, "onInstanceVersion", arg("id", org.hl7.fhir.instance.model.api.IIdType.class), arg("name", String.class), arg("parameters", org.hl7.fhir.instance.model.api.IBaseParameters.class), arg("outputParameterType", Class.class), arg("useHttpGet", boolean.class), arg("returnType", Class.class), arg("extraParameters", java.util.Map.class)), ON_SERVER( org.hl7.fhir.instance.model.api.IBaseResource.class, "onServer", arg("name", String.class), arg("parameters", org.hl7.fhir.instance.model.api.IBaseParameters.class), arg("outputParameterType", Class.class), arg("useHttpGet", boolean.class), arg("returnType", Class.class), arg("extraParameters", java.util.Map.class)), ON_TYPE( org.hl7.fhir.instance.model.api.IBaseResource.class, "onType", arg("resourceType", Class.class), arg("name", String.class), arg("parameters", org.hl7.fhir.instance.model.api.IBaseParameters.class), arg("outputParameterType", Class.class), arg("useHttpGet", boolean.class), arg("returnType", Class.class), arg("extraParameters", java.util.Map.class)), PROCESS_MESSAGE( org.hl7.fhir.instance.model.api.IBaseBundle.class, "processMessage", arg("respondToUri", String.class), arg("msgBundle", org.hl7.fhir.instance.model.api.IBaseBundle.class), arg("asynchronous", boolean.class), arg("responseClass", Class.class), arg("extraParameters", java.util.Map.class)); private final ApiMethod apiMethod; FhirOperationApiMethod(Class<?> resultType, String name, ApiMethodArg... args) { this.apiMethod = new ApiMethodImpl(FhirOperation.class, resultType, name, args); } @Override public String getName() { return apiMethod.getName(); } @Override public Class<?> getResultType() { return apiMethod.getResultType(); } @Override public List<String> getArgNames() { return apiMethod.getArgNames(); } @Override public List<String> getSetterArgNames() { return apiMethod.getSetterArgNames(); } @Override public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); } @Override public Method getMethod() { return apiMethod.getMethod(); } }
FhirOperationApiMethod
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/batch/sql/TruncateTableITCase.java
{ "start": 1630, "end": 4532 }
class ____ extends BatchTestBase { private static final int ROW_NUM = 2; @Test void testTruncateTable() { String dataId = registerData(); tEnv().executeSql( String.format( "CREATE TABLE t (a int) WITH" + " ('connector' = 'test-update-delete'," + " 'data-id' = '%s'," + " 'only-accept-equal-predicate' = 'true'" + ")", dataId)); List<Row> rows = toRows(tEnv().executeSql("SELECT * FROM t")); assertThat(rows.toString()).isEqualTo("[+I[0], +I[1]]"); tEnv().executeSql("TRUNCATE TABLE t"); rows = toRows(tEnv().executeSql("SELECT * FROM t")); assertThat(rows).isEmpty(); } @Test void testTruncateTableWithoutImplementation() { tEnv().executeSql("CREATE TABLE t (a int) WITH" + " ('connector' = 'values')"); assertThatThrownBy(() -> tEnv().executeSql("TRUNCATE TABLE t")) .isInstanceOf(TableException.class) .hasMessage( "TRUNCATE TABLE statement is not supported for the table default_catalog.default_database.t" + " since the table hasn't implemented the interface" + " org.apache.flink.table.connector.sink.abilities.SupportsTruncate."); } @Test void testTruncateLegacyTable() { tEnv().executeSql( "CREATE TABLE t (a int, b string, c double) WITH" + " ('connector' = 'COLLECTION')"); assertThatThrownBy(() -> tEnv().executeSql("TRUNCATE TABLE t")) .isInstanceOf(TableException.class) .hasMessage( String.format( "Can't perform truncate table operation of the table %s " + "because the corresponding table sink is the legacy " + "TableSink." + " Please implement %s for it.", "`default_catalog`.`default_database`.`t`", DynamicTableSink.class.getName())); } private String registerData() { List<RowData> values = createValue(); return TestUpdateDeleteTableFactory.registerRowData(values); } private List<RowData> createValue() { List<RowData> values = new ArrayList<>(); for (int i = 0; i < ROW_NUM; i++) { values.add(GenericRowData.of(i)); } return values; } private List<Row> toRows(TableResult result) { return CollectionUtil.iteratorToList(result.collect()); } }
TruncateTableITCase
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/redshift/stmt/RedshiftCreateTableStatement.java
{ "start": 331, "end": 2325 }
class ____ extends SQLCreateTableStatement implements RedshiftObject { private SQLExpr distStyle; private SQLExpr distKey; private SQLExpr backup; private RedshiftSortKey sortKey; private boolean encodeAuto; public RedshiftCreateTableStatement() { super(DbType.redshift); encodeAuto = false; } public SQLExpr getDistStyle() { return distStyle; } public void setDistStyle(SQLExpr distStyle) { if (distStyle != null) { distStyle.setParent(this); } this.distStyle = distStyle; } public SQLExpr getDistKey() { return distKey; } public void setDistKey(SQLExpr distKey) { if (distKey != null) { distKey.setParent(this); } this.distKey = distKey; } public RedshiftSortKey getSortKey() { return sortKey; } public void setSortKey(RedshiftSortKey sortKey) { if (sortKey != null) { sortKey.setParent(this); } this.sortKey = sortKey; } public boolean isEncodeAuto() { return encodeAuto; } public void setEncodeAuto(boolean encodeAuto) { this.encodeAuto = encodeAuto; } public SQLExpr getBackup() { return backup; } public void setBackup(SQLExpr backup) { if (backup != null) { backup.setParent(this); } this.backup = backup; } @Override public void accept0(SQLASTVisitor v) { if (v instanceof RedshiftASTVisitor) { accept0((RedshiftASTVisitor) v); } else { super.accept0(v); } } @Override public void accept0(RedshiftASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, this.backup); acceptChild(visitor, this.distStyle); acceptChild(visitor, this.distKey); acceptChild(visitor, this.sortKey); } } }
RedshiftCreateTableStatement
java
dropwizard__dropwizard
dropwizard-health/src/main/java/io/dropwizard/health/response/HealthResponseProviderFactory.java
{ "start": 587, "end": 809 }
interface ____ extends Discoverable { /** * Configures a health responder for responding to health check requests (e.g. from load balancer). * * @param healthStatusChecker an
HealthResponseProviderFactory
java
apache__camel
core/camel-util/src/main/java/org/apache/camel/util/URISupport.java
{ "start": 1841, "end": 38583 }
class ____ { public static final String RAW_TOKEN_PREFIX = "RAW"; public static final char[] RAW_TOKEN_START = { '(', '{' }; public static final char[] RAW_TOKEN_END = { ')', '}' }; @SuppressWarnings("RegExpUnnecessaryNonCapturingGroup") private static final String PRE_SECRETS_FORMAT = "([?&][^=]*(?:%s)[^=]*)=(RAW(([{][^}]*[}])|([(][^)]*[)]))|[^&]*)"; // Match any key-value pair in the URI query string whose key contains // "passphrase" or "password" or secret key (case-insensitive). // First capture group is the key, second is the value. private static final Pattern ALL_SECRETS = Pattern.compile(PRE_SECRETS_FORMAT.formatted(SensitiveUtils.getSensitivePattern()), Pattern.CASE_INSENSITIVE); // Match the user password in the URI as second capture group // (applies to URI with authority component and userinfo token in the form // "user:password"). private static final Pattern USERINFO_PASSWORD = Pattern.compile("(.*://.*?:)(.*)(@)"); // Match the user password in the URI path as second capture group // (applies to URI path with authority component and userinfo token in the // form "user:password"). private static final Pattern PATH_USERINFO_PASSWORD = Pattern.compile("(.*?:)(.*)(@)"); private static final Charset CHARSET = StandardCharsets.UTF_8; private static final String EMPTY_QUERY_STRING = ""; private static Pattern EXTRA_SECRETS; private URISupport() { // Helper class } /** * Adds custom keywords for sanitizing sensitive information (such as passwords) from URIs. Notice that when a key * has been added it cannot be removed. * * @param keywords keywords separated by comma */ public static synchronized void addSanitizeKeywords(String keywords) { StringJoiner pattern = new StringJoiner("|"); for (String key : keywords.split(",")) { // skip existing keys key = key.toLowerCase(Locale.ROOT).trim(); if (!SensitiveUtils.containsSensitive(key)) { pattern.add("\\Q" + key.toLowerCase(Locale.ROOT) + "\\E"); } } EXTRA_SECRETS = Pattern.compile(PRE_SECRETS_FORMAT.formatted(pattern), Pattern.CASE_INSENSITIVE); } /** * Removes detected sensitive information (such as passwords) from the URI and returns the result. * * @param uri The uri to sanitize. * @return Returns null if the uri is null, otherwise the URI with the passphrase, password or secretKey * sanitized. * @see #ALL_SECRETS and #USERINFO_PASSWORD for the matched pattern */ public static String sanitizeUri(String uri) { // use xxxxx as replacement as that works well with JMX also String sanitized = uri; if (uri != null) { sanitized = ALL_SECRETS.matcher(sanitized).replaceAll("$1=xxxxxx"); if (EXTRA_SECRETS != null) { sanitized = EXTRA_SECRETS.matcher(sanitized).replaceFirst("$1=xxxxxx"); } sanitized = USERINFO_PASSWORD.matcher(sanitized).replaceFirst("$1xxxxxx$3"); } return sanitized; } public static String textBlockToSingleLine(String uri) { // Java 17 text blocks have new lines with optional white space if (uri != null) { // we want text blocks to be as-is before query parameters // as this allows some Camel components to provide code or SQL // to be provided in the context-path. // query parameters are key=value pairs in Camel endpoints and therefore // the lines should be trimmed (after we detect the first ? sign). final AtomicBoolean query = new AtomicBoolean(); StringJoiner sj = new StringJoiner(""); // use lines() to support splitting in any OS platform (also Windows) uri.lines().forEach(l -> { l = l.trim(); if (!query.get()) { l = l + " "; if (l.indexOf('?') != -1) { query.set(true); l = l.trim(); } } sj.add(l); }); uri = sj.toString(); uri = uri.trim(); } return uri; } /** * Removes detected sensitive information (such as passwords) from the <em>path part</em> of an URI (that is, the * part without the query parameters or component prefix) and returns the result. * * @param path the URI path to sanitize * @return null if the path is null, otherwise the sanitized path */ public static String sanitizePath(String path) { String sanitized = path; if (path != null) { sanitized = PATH_USERINFO_PASSWORD.matcher(sanitized).replaceFirst("$1xxxxxx$3"); } return sanitized; } /** * Extracts the scheme specific path from the URI that is used as the remainder option when creating endpoints. * * @param u the URI * @param useRaw whether to force using raw values * @return the remainder path */ public static String extractRemainderPath(URI u, boolean useRaw) { String path = useRaw ? u.getRawSchemeSpecificPart() : u.getSchemeSpecificPart(); // lets trim off any query arguments if (path.startsWith("//")) { path = path.substring(2); } return StringHelper.before(path, "?", path); } /** * Extracts the query part of the given uri * * @param uri the uri * @return the query parameters or <tt>null</tt> if the uri has no query */ public static String extractQuery(String uri) { if (uri == null) { return null; } return StringHelper.after(uri, "?"); } /** * Strips the query parameters from the uri * * @param uri the uri * @return the uri without the query parameter */ public static String stripQuery(String uri) { return StringHelper.before(uri, "?", uri); } /** * Parses the query part of the uri (eg the parameters). * <p/> * The URI parameters will by default be URI encoded. However you can define a parameter values with the syntax: * <tt>key=RAW(value)</tt> which tells Camel to not encode the value, and use the value as is (eg key=value) and the * value has <b>not</b> been encoded. * * @param uri the uri * @return the parameters, or an empty map if no parameters (eg never null) * @throws URISyntaxException is thrown if uri has invalid syntax. * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static Map<String, Object> parseQuery(String uri) throws URISyntaxException { return parseQuery(uri, false); } /** * Parses the query part of the uri (eg the parameters). * <p/> * The URI parameters will by default be URI encoded. However you can define a parameter values with the syntax: * <tt>key=RAW(value)</tt> which tells Camel to not encode the value, and use the value as is (eg key=value) and the * value has <b>not</b> been encoded. * * @param uri the uri * @param useRaw whether to force using raw values * @return the parameters, or an empty map if no parameters (eg never null) * @throws URISyntaxException is thrown if uri has invalid syntax. * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static Map<String, Object> parseQuery(String uri, boolean useRaw) throws URISyntaxException { return parseQuery(uri, useRaw, false); } /** * Parses the query part of the uri (eg the parameters). * <p/> * The URI parameters will by default be URI encoded. However you can define a parameter values with the syntax: * <tt>key=RAW(value)</tt> which tells Camel to not encode the value, and use the value as is (eg key=value) and the * value has <b>not</b> been encoded. * * @param uri the uri * @param useRaw whether to force using raw values * @param lenient whether to parse lenient and ignore trailing & markers which has no key or value which * can happen when using HTTP components * @return the parameters, or an empty map if no parameters (eg never null) * @throws URISyntaxException is thrown if uri has invalid syntax. * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static Map<String, Object> parseQuery(String uri, boolean useRaw, boolean lenient) throws URISyntaxException { if (uri == null || uri.isEmpty()) { // return an empty map return Collections.emptyMap(); } // must check for trailing & as the uri.split("&") will ignore those if (!lenient && uri.endsWith("&")) { throw new URISyntaxException( uri, "Invalid uri syntax: Trailing & marker found. " + "Check the uri and remove the trailing & marker."); } URIScanner scanner = new URIScanner(); return scanner.parseQuery(uri, useRaw); } /** * Scans RAW tokens in the string and returns the list of pair indexes which tell where a RAW token starts and ends * in the string. * <p/> * This is a companion method with {@link #isRaw(int, List)} and the returned value is supposed to be used as the * parameter of that method. * * @param str the string to scan RAW tokens * @return the list of pair indexes which represent the start and end positions of a RAW token * @see #isRaw(int, List) * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static List<Pair<Integer>> scanRaw(String str) { return URIScanner.scanRaw(str); } /** * Tests if the index is within any pair of the start and end indexes which represent the start and end positions of * a RAW token. * <p/> * This is a companion method with {@link #scanRaw(String)} and is supposed to consume the returned value of that * method as the second parameter <tt>pairs</tt>. * * @param index the index to be tested * @param pairs the list of pair indexes which represent the start and end positions of a RAW token * @return <tt>true</tt> if the index is within any pair of the indexes, <tt>false</tt> otherwise * @see #scanRaw(String) * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static boolean isRaw(int index, List<Pair<Integer>> pairs) { if (pairs == null || pairs.isEmpty()) { return false; } for (Pair<Integer> pair : pairs) { if (index < pair.getLeft()) { return false; } if (index <= pair.getRight()) { return true; } } return false; } /** * Parses the query parameters of the uri (eg the query part). * * @param uri the uri * @return the parameters, or an empty map if no parameters (eg never null) * @throws URISyntaxException is thrown if uri has invalid syntax. */ public static Map<String, Object> parseParameters(URI uri) throws URISyntaxException { String query = prepareQuery(uri); if (query == null) { // empty an empty map return new LinkedHashMap<>(0); } return parseQuery(query); } public static String prepareQuery(URI uri) { String query = uri.getQuery(); if (query == null) { String schemeSpecificPart = uri.getSchemeSpecificPart(); query = StringHelper.after(schemeSpecificPart, "?"); } else if (query.indexOf('?') == 0) { // skip leading query query = query.substring(1); } return query; } /** * Traverses the given parameters, and resolve any parameter values which uses the RAW token syntax: * <tt>key=RAW(value)</tt>. This method will then remove the RAW tokens, and replace the content of the value, with * just the value. * * @param parameters the uri parameters * @see #parseQuery(String) * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static void resolveRawParameterValues(Map<String, Object> parameters) { resolveRawParameterValues(parameters, null); } /** * Traverses the given parameters, and resolve any parameter values which uses the RAW token syntax: * <tt>key=RAW(value)</tt>. This method will then remove the RAW tokens, and replace the content of the value, with * just the value. * * @param parameters the uri parameters * @param onReplace optional function executed when replace the raw value * @see #parseQuery(String) * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static void resolveRawParameterValues(Map<String, Object> parameters, Function<String, String> onReplace) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { if (entry.getValue() == null) { continue; } // if the value is a list then we need to iterate Object value = entry.getValue(); if (value instanceof List list) { for (int i = 0; i < list.size(); i++) { Object obj = list.get(i); if (obj == null) { continue; } String str = obj.toString(); String raw = URIScanner.resolveRaw(str); if (raw != null) { // update the string in the list // do not encode RAW parameters unless it has % // need to reverse: replace % with %25 to avoid losing "%" when decoding String s = raw.replace("%25", "%"); if (onReplace != null) { s = onReplace.apply(s); } list.set(i, s); } } } else { String str = entry.getValue().toString(); String raw = URIScanner.resolveRaw(str); if (raw != null) { // do not encode RAW parameters unless it has % // need to reverse: replace % with %25 to avoid losing "%" when decoding String s = raw.replace("%25", "%"); if (onReplace != null) { s = onReplace.apply(s); } entry.setValue(s); } } } } /** * Creates a URI with the given query * * @param uri the uri * @param query the query to append to the uri * @return uri with the query appended * @throws URISyntaxException is thrown if uri has invalid syntax. */ public static URI createURIWithQuery(URI uri, String query) throws URISyntaxException { ObjectHelper.notNull(uri, "uri"); // assemble string as new uri and replace parameters with the query // instead String s = uri.toString(); String before = StringHelper.before(s, "?"); if (before == null) { before = StringHelper.before(s, "#"); } if (before != null) { s = before; } if (query != null) { s = s + "?" + query; } if (!s.contains("#") && uri.getFragment() != null) { s = s + "#" + uri.getFragment(); } return new URI(s); } /** * Strips the prefix from the value. * <p/> * Returns the value as-is if not starting with the prefix. * * @param value the value * @param prefix the prefix to remove from value * @return the value without the prefix */ public static String stripPrefix(String value, String prefix) { if (value == null || prefix == null) { return value; } if (value.startsWith(prefix)) { return value.substring(prefix.length()); } return value; } /** * Strips the suffix from the value. * <p/> * Returns the value as-is if not ending with the prefix. * * @param value the value * @param suffix the suffix to remove from value * @return the value without the suffix */ public static String stripSuffix(final String value, final String suffix) { if (value == null || suffix == null) { return value; } if (value.endsWith(suffix)) { return value.substring(0, value.length() - suffix.length()); } return value; } /** * Assembles a query from the given map. * * @param options the map with the options (eg key/value pairs) * @return a query string with <tt>key1=value&key2=value2&...</tt>, or an empty string if there is no * options. */ public static String createQueryString(Map<String, Object> options) { final Set<String> keySet = options.keySet(); return createQueryString(keySet.toArray(new String[0]), options, true); } /** * Assembles a query from the given map. * * @param options the map with the options (eg key/value pairs) * @param encode whether to URL encode the query string * @return a query string with <tt>key1=value&key2=value2&...</tt>, or an empty string if there is no * options. */ public static String createQueryString(Map<String, Object> options, boolean encode) { return createQueryString(options.keySet(), options, encode); } private static String createQueryString(String[] sortedKeys, Map<String, Object> options, boolean encode) { if (options.isEmpty()) { return EMPTY_QUERY_STRING; } StringBuilder rc = new StringBuilder(128); boolean first = true; for (String key : sortedKeys) { if (first) { first = false; } else { rc.append("&"); } Object value = options.get(key); // the value may be a list since the same key has multiple // values if (value instanceof List) { List<String> list = (List<String>) value; for (Iterator<String> it = list.iterator(); it.hasNext();) { String s = it.next(); appendQueryStringParameter(key, s, rc, encode); // append & separator if there is more in the list // to append if (it.hasNext()) { rc.append("&"); } } } else { // use the value as a String String s = value != null ? value.toString() : null; appendQueryStringParameter(key, s, rc, encode); } } return rc.toString(); } /** * Assembles a query from the given map. * * @param options the map with the options (eg key/value pairs) * @param ampersand to use & for Java code, and &amp; for XML * @return a query string with <tt>key1=value&key2=value2&...</tt>, or an empty string if there * is no options. * @throws URISyntaxException is thrown if uri has invalid syntax. */ @Deprecated(since = "4.1.0") public static String createQueryString(Map<String, String> options, String ampersand, boolean encode) { if (!options.isEmpty()) { StringBuilder rc = new StringBuilder(); boolean first = true; for (String key : options.keySet()) { if (first) { first = false; } else { rc.append(ampersand); } Object value = options.get(key); // use the value as a String String s = value != null ? value.toString() : null; appendQueryStringParameter(key, s, rc, encode); } return rc.toString(); } else { return ""; } } @Deprecated(since = "4.0.0") public static String createQueryString(Collection<String> sortedKeys, Map<String, Object> options, boolean encode) { return createQueryString(sortedKeys.toArray(new String[0]), options, encode); } private static void appendQueryStringParameter(String key, String value, StringBuilder rc, boolean encode) { if (encode) { String encoded = URLEncoder.encode(key, CHARSET); rc.append(encoded); } else { rc.append(key); } if (value == null) { return; } // only append if value is not null rc.append("="); String raw = URIScanner.resolveRaw(value); if (raw != null) { // do not encode RAW parameters unless it has % // need to replace % with %25 to avoid losing "%" when decoding final String s = URIScanner.replacePercent(value); rc.append(s); } else { if (encode) { String encoded = URLEncoder.encode(value, CHARSET); rc.append(encoded); } else { rc.append(value); } } } /** * Creates a URI from the original URI and the remaining parameters * <p/> * Used by various Camel components */ public static URI createRemainingURI(URI originalURI, Map<String, Object> params) throws URISyntaxException { String s = createQueryString(params); if (s.isEmpty()) { s = null; } return createURIWithQuery(originalURI, s); } /** * Appends the given parameters to the given URI. * <p/> * It keeps the original parameters and if a new parameter is already defined in {@code originalURI}, it will be * replaced by its value in {@code newParameters}. * * @param originalURI the original URI * @param newParameters the parameters to add * @return the URI with all the parameters * @throws URISyntaxException is thrown if the uri syntax is invalid * @throws UnsupportedEncodingException is thrown if encoding error */ public static String appendParametersToURI(String originalURI, Map<String, Object> newParameters) throws URISyntaxException { URI uri = new URI(normalizeUri(originalURI)); Map<String, Object> parameters = parseParameters(uri); parameters.putAll(newParameters); return createRemainingURI(uri, parameters).toString(); } /** * Normalizes the uri by reordering the parameters so they are sorted and thus we can use the uris for endpoint * matching. * <p/> * The URI parameters will by default be URI encoded. However you can define a parameter values with the syntax: * <tt>key=RAW(value)</tt> which tells Camel to not encode the value, and use the value as is (eg key=value) and the * value has <b>not</b> been encoded. * * @param uri the uri * @return the normalized uri * @throws URISyntaxException in thrown if the uri syntax is invalid * * @see #RAW_TOKEN_PREFIX * @see #RAW_TOKEN_START * @see #RAW_TOKEN_END */ public static String normalizeUri(String uri) throws URISyntaxException { // try to parse using the simpler and faster Camel URI parser String[] parts = CamelURIParser.fastParseUri(uri); if (parts != null) { // we optimized specially if an empty array is returned if (parts == URI_ALREADY_NORMALIZED) { return uri; } // use the faster and more simple normalizer return doFastNormalizeUri(parts); } else { // use the legacy normalizer as the uri is complex and may have unsafe URL characters return doComplexNormalizeUri(uri); } } /** * Normalizes the URI so unsafe characters are encoded * * @param uri the input uri * @return as URI instance * @throws URISyntaxException is thrown if syntax error in the input uri */ public static URI normalizeUriAsURI(String uri) throws URISyntaxException { // java 17 text blocks to single line uri uri = URISupport.textBlockToSingleLine(uri); return new URI(UnsafeUriCharactersEncoder.encode(uri, true)); } /** * The complex (and Camel 2.x) compatible URI normalizer when the URI is more complex such as having percent encoded * values, or other unsafe URL characters, or have authority user/password, etc. */ private static String doComplexNormalizeUri(String uri) throws URISyntaxException { // java 17 text blocks to single line uri uri = URISupport.textBlockToSingleLine(uri); URI u = new URI(UnsafeUriCharactersEncoder.encode(uri, true)); String scheme = u.getScheme(); String path = u.getSchemeSpecificPart(); // not possible to normalize if (scheme == null || path == null) { return uri; } // find start and end position in path as we only check the context-path and not the query parameters int start = path.startsWith("//") ? 2 : 0; int end = path.indexOf('?'); if (start == 0 && end == 0 || start == 2 && end == 2) { // special when there is no context path path = ""; } else { if (start != 0 && end == -1) { path = path.substring(start); } else if (end != -1) { path = path.substring(start, end); } if (scheme.startsWith("http")) { path = UnsafeUriCharactersEncoder.encodeHttpURI(path); } else { path = UnsafeUriCharactersEncoder.encode(path); } } // okay if we have user info in the path and they use @ in username or password, // then we need to encode them (but leave the last @ sign before the hostname) // this is needed as Camel end users may not encode their user info properly, // but expect this to work out of the box with Camel, and hence we need to // fix it for them int idxPath = path.indexOf('/'); if (StringHelper.countChar(path, '@', idxPath) > 1) { String userInfoPath = idxPath > 0 ? path.substring(0, idxPath) : path; int max = userInfoPath.lastIndexOf('@'); String before = userInfoPath.substring(0, max); // after must be from original path String after = path.substring(max); // replace the @ with %40 before = before.replace("@", "%40"); path = before + after; } // in case there are parameters we should reorder them String query = prepareQuery(u); if (query == null) { // no parameters then just return return buildUri(scheme, path, null); } else { Map<String, Object> parameters = URISupport.parseQuery(query, false, false); if (parameters.size() == 1) { // only 1 parameter need to create new query string query = URISupport.createQueryString(parameters); } else { // reorder parameters a..z final Set<String> keySet = parameters.keySet(); final String[] parametersArray = keySet.toArray(new String[0]); Arrays.sort(parametersArray); // build uri object with sorted parameters query = URISupport.createQueryString(parametersArray, parameters, true); } return buildUri(scheme, path, query); } } /** * The fast parser for normalizing Camel endpoint URIs when the URI is not complex and can be parsed in a much more * efficient way. */ private static String doFastNormalizeUri(String[] parts) throws URISyntaxException { String scheme = parts[0]; String path = parts[1]; String query = parts[2]; // in case there are parameters we should reorder them if (query == null) { // no parameters then just return return buildUri(scheme, path, null); } else { return buildReorderingParameters(scheme, path, query); } } private static String buildReorderingParameters(String scheme, String path, String query) throws URISyntaxException { Map<String, Object> parameters = null; if (query.indexOf('&') != -1) { // only parse if there are parameters parameters = URISupport.parseQuery(query, false, false); } if (parameters != null && parameters.size() != 1) { final Set<String> entries = parameters.keySet(); // reorder parameters a..z // optimize and only build new query if the keys was resorted boolean sort = false; String prev = null; for (String key : entries) { if (prev != null) { int comp = key.compareTo(prev); if (comp < 0) { sort = true; break; } } prev = key; } if (sort) { final String[] array = entries.toArray(new String[0]); Arrays.sort(array); query = URISupport.createQueryString(array, parameters, true); } } return buildUri(scheme, path, query); } private static String buildUri(String scheme, String path, String query) { // must include :// to do a correct URI all components can work with int len = scheme.length() + 3 + path.length(); if (query != null) { len += 1 + query.length(); StringBuilder sb = new StringBuilder(len); sb.append(scheme).append("://").append(path).append('?').append(query); return sb.toString(); } else { StringBuilder sb = new StringBuilder(len); sb.append(scheme).append("://").append(path); return sb.toString(); } } public static Map<String, Object> extractProperties(Map<String, Object> properties, String optionPrefix) { Map<String, Object> rc = new LinkedHashMap<>(properties.size()); for (Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = it.next(); String name = entry.getKey(); if (name.startsWith(optionPrefix)) { Object value = properties.get(name); name = name.substring(optionPrefix.length()); rc.put(name, value); it.remove(); } } return rc; } private static String makeUri(String uriWithoutQuery, String query) { int len = uriWithoutQuery.length(); if (query != null) { len += 1 + query.length(); StringBuilder sb = new StringBuilder(len); sb.append(uriWithoutQuery).append('?').append(query); return sb.toString(); } else { StringBuilder sb = new StringBuilder(len); sb.append(uriWithoutQuery); return sb.toString(); } } public static String getDecodeQuery(final String uri) { try { URI u = new URI(uri); String query = URISupport.prepareQuery(u); String uriWithoutQuery = URISupport.stripQuery(uri); if (query == null) { return uriWithoutQuery; } else { Map<String, Object> parameters = URISupport.parseQuery(query, false, false); if (parameters.size() == 1) { // only 1 parameter need to create new query string query = URISupport.createQueryString(parameters); } else { // reorder parameters a..z final Set<String> keySet = parameters.keySet(); final String[] parametersArray = keySet.toArray(new String[0]); Arrays.sort(parametersArray); // build uri object with sorted parameters query = URISupport.createQueryString(parametersArray, parameters, true); } return makeUri(uriWithoutQuery, query); } } catch (URISyntaxException ex) { return null; } } public static String pathAndQueryOf(final URI uri) { final String path = uri.getPath(); String pathAndQuery = path; if (ObjectHelper.isEmpty(path)) { pathAndQuery = "/"; } final String query = uri.getQuery(); if (ObjectHelper.isNotEmpty(query)) { pathAndQuery += "?" + query; } return pathAndQuery; } public static String joinPaths(final String... paths) { if (paths == null || paths.length == 0) { return ""; } final StringBuilder joined = new StringBuilder(paths.length * 64); boolean addedLast = false; for (int i = paths.length - 1; i >= 0; i--) { String path = paths[i]; if (ObjectHelper.isNotEmpty(path)) { if (addedLast) { path = stripSuffix(path, "/"); } addedLast = true; if (path.charAt(0) == '/') { joined.insert(0, path); } else { if (i > 0) { joined.insert(0, '/').insert(1, path); } else { joined.insert(0, path); } } } } return joined.toString(); } public static String buildMultiValueQuery(String key, Iterable<Object> values) { StringBuilder sb = new StringBuilder(256); for (Object v : values) { if (!sb.isEmpty()) { sb.append("&"); } sb.append(key); sb.append("="); sb.append(v); } return sb.toString(); } /** * Remove white-space noise from uri, xxxUri attributes, eg new lines, and tabs etc, which allows end users to * format their Camel routes in more human-readable format, but at runtime those attributes must be trimmed. The * parser removes most of the noise, but keeps spaces in the attribute values */ public static String removeNoiseFromUri(String uri) { String before = StringHelper.before(uri, "?"); String after = StringHelper.after(uri, "?"); if (before != null && after != null) { String changed = after.replaceAll("&\\s+", "&").trim(); if (!after.equals(changed)) { return before.trim() + "?" + changed; } } return uri; } }
URISupport
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/lucene/LuceneTopNSourceOperatorScoringTests.java
{ "start": 2052, "end": 6550 }
class ____ extends LuceneTopNSourceOperatorTests { private static final MappedFieldType S_FIELD = new NumberFieldMapper.NumberFieldType("s", NumberFieldMapper.NumberType.LONG); private Directory directory = newDirectory(); private IndexReader reader; @After public void closeScoringIndex() throws IOException { IOUtils.close(reader, directory); } @Override protected LuceneTopNSourceOperator.Factory simple(SimpleOptions options) { return simple(DataPartitioning.SHARD, 10_000, 100); } private LuceneTopNSourceOperator.Factory simple(DataPartitioning dataPartitioning, int size, int limit) { int commitEvery = Math.max(1, size / 10); try ( RandomIndexWriter writer = new RandomIndexWriter( random(), directory, newIndexWriterConfig().setMergePolicy(NoMergePolicy.INSTANCE) ) ) { for (int d = 0; d < size; d++) { List<IndexableField> doc = new ArrayList<>(); doc.add(new SortedNumericDocValuesField("s", d)); writer.addDocument(doc); if (d % commitEvery == 0) { writer.commit(); } } reader = writer.getReader(); } catch (IOException e) { throw new RuntimeException(e); } ShardContext ctx = new LuceneSourceOperatorTests.MockShardContext(reader, 0) { @Override public Optional<SortAndFormats> buildSort(List<SortBuilder<?>> sorts) { SortField field = new SortedNumericSortField("s", SortField.Type.LONG, false, SortedNumericSelector.Type.MIN); return Optional.of(new SortAndFormats(new Sort(field), new DocValueFormat[] { null })); } }; Function<ShardContext, List<LuceneSliceQueue.QueryAndTags>> queryFunction = c -> List.of( new LuceneSliceQueue.QueryAndTags(new MatchAllDocsQuery(), List.of()) ); int taskConcurrency = 0; int maxPageSize = between(10, Math.max(10, size)); List<SortBuilder<?>> sorts = List.of(new FieldSortBuilder("s")); long estimatedPerRowSortSize = 16; return new LuceneTopNSourceOperator.Factory( new IndexedByShardIdFromSingleton<>(ctx), queryFunction, dataPartitioning, taskConcurrency, maxPageSize, limit, sorts, estimatedPerRowSortSize, true // scoring ); } @Override protected Matcher<String> expectedToStringOfSimple() { return matchesRegex( "LuceneTopNSourceOperator\\[shards = \\[test], " + "maxPageSize = \\d+, limit = 100, needsScore = true, sorts = \\[\\{.+}]]" ); } @Override protected Matcher<String> expectedDescriptionOfSimple() { return matchesRegex( "LuceneTopNSourceOperator\\[dataPartitioning = (DOC|SHARD|SEGMENT), " + "maxPageSize = \\d+, limit = 100, needsScore = true, sorts = \\[\\{.+}]]" ); } @Override protected void testSimple(DriverContext ctx, int size, int limit) { LuceneTopNSourceOperator.Factory factory = simple(DataPartitioning.SHARD, size, limit); Operator.OperatorFactory readS = ValuesSourceReaderOperatorTests.factory(reader, S_FIELD, ElementType.LONG); List<Page> results = new ArrayList<>(); OperatorTestCase.runDriver( TestDriverFactory.create(ctx, factory.get(ctx), List.of(readS.get(ctx)), new TestResultPageSinkOperator(results::add)) ); OperatorTestCase.assertDriverContext(ctx); long expectedS = 0; int maxPageSize = factory.maxPageSize(); for (Page page : results) { if (limit - expectedS < maxPageSize) { assertThat(page.getPositionCount(), equalTo((int) (limit - expectedS))); } else { assertThat(page.getPositionCount(), equalTo(maxPageSize)); } DoubleBlock sBlock = page.getBlock(1); for (int p = 0; p < page.getPositionCount(); p++) { assertThat(sBlock.getDouble(sBlock.getFirstValueIndex(p)), equalTo(1.0d)); expectedS++; } } int pages = (int) Math.ceil((float) Math.min(size, limit) / maxPageSize); assertThat(results, hasSize(pages)); } }
LuceneTopNSourceOperatorScoringTests
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/annotation/EvaluatedAnnotationValue.java
{ "start": 1314, "end": 4078 }
class ____<A extends Annotation> extends AnnotationValue<A> { private final ConfigurableExpressionEvaluationContext evaluationContext; private final AnnotationValue<A> annotationValue; EvaluatedAnnotationValue(AnnotationValue<A> annotationValue, ConfigurableExpressionEvaluationContext evaluationContext) { super( annotationValue, annotationValue.getDefaultValues(), new EvaluatedConvertibleValuesMap<>(evaluationContext, annotationValue.getConvertibleValues()), value -> { if (value instanceof EvaluatedExpression expression) { return expression.evaluate(evaluationContext); } else if (annotationValue instanceof EnvironmentAnnotationValue<A> eav) { Function<Object, Object> valueMapper = eav.getValueMapper(); if (valueMapper != null) { return valueMapper.apply(value); } } return value; } ); this.evaluationContext = evaluationContext; this.annotationValue = annotationValue; } @Override public <T extends Annotation> List<AnnotationValue<T>> getAnnotations(String member, Class<T> type) { return super.getAnnotations(member, type).stream().map(av -> new EvaluatedAnnotationValue<>(av, evaluationContext)).collect(Collectors.toList()); } @Override public <T extends Annotation> List<AnnotationValue<T>> getAnnotations(String member) { return super.<T>getAnnotations(member) .stream() .map(av -> new EvaluatedAnnotationValue<>(av, evaluationContext)) .collect(Collectors.toList()); } @Override public <T extends Annotation> Optional<AnnotationValue<T>> getAnnotation(String member, Class<T> type) { return super.getAnnotation(member, type).map(av -> new EvaluatedAnnotationValue<>(av, evaluationContext)); } @Override public <T extends Annotation> Optional<AnnotationValue<T>> getAnnotation(@NonNull String member) { return super.<T>getAnnotation(member).map(av -> new EvaluatedAnnotationValue<>(av, evaluationContext)); } /** * Provide a copy of this annotation metadata with passed method arguments. * * @param thisObject The object that represents this in a non-static context. * @param args arguments passed to method * @return copy of annotation metadata */ public EvaluatedAnnotationValue<A> withArguments(@Nullable Object thisObject, Object[] args) { return new EvaluatedAnnotationValue<>( annotationValue, evaluationContext.withArguments(thisObject, args)); } }
EvaluatedAnnotationValue
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java
{ "start": 14130, "end": 14459 }
class ____ extends AbstractInvocable { @BeforeTransaction public void beforeTransaction() { invoked(true); } @MetaTxWithOverride(propagation = NOT_SUPPORTED) public void transactionalTest() { } public void nonTransactionalTest() { } } static
TransactionalDeclaredOnMethodViaMetaAnnotationWithOverrideTestCase
java
apache__logging-log4j2
log4j-appserver/src/main/java/org/apache/logging/log4j/appserver/tomcat/TomcatLogger.java
{ "start": 1353, "end": 1419 }
interface ____ Tomcat 8.5 and greater. * * In order to use this
from
java
micronaut-projects__micronaut-core
router/src/main/java/io/micronaut/web/router/version/resolution/HeaderVersionResolver.java
{ "start": 1205, "end": 1906 }
class ____ implements RequestVersionResolver { private final List<String> headerNames; /** * Creates a {@link RequestVersionResolver} to extract version from request header. * * @param configuration A configuration to pick correct request header names. */ public HeaderVersionResolver(HeaderVersionResolverConfiguration configuration) { this.headerNames = configuration.getNames(); } @Override public Optional<String> resolve(HttpRequest<?> request) { return headerNames.stream() .map(name -> request.getHeaders().get(name)) .filter(Objects::nonNull) .findFirst(); } }
HeaderVersionResolver
java
google__guice
extensions/grapher/src/com/google/inject/grapher/AbstractInjectorGrapher.java
{ "start": 1239, "end": 1598 }
class ____ implements InjectorGrapher { private final RootKeySetCreator rootKeySetCreator; private final AliasCreator aliasCreator; private final NodeCreator nodeCreator; private final EdgeCreator edgeCreator; /** * Parameters used to override default settings of the grapher. * * @since 4.0 */ public static final
AbstractInjectorGrapher
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/FileSystemTestHelper.java
{ "start": 7568, "end": 8251 }
enum ____ {isDir, isFile, isSymlink}; public static void checkFileStatus(FileSystem aFs, String path, fileType expectedType) throws IOException { FileStatus s = aFs.getFileStatus(new Path(path)); assertNotNull(s); if (expectedType == fileType.isDir) { assertTrue(s.isDirectory()); } else if (expectedType == fileType.isFile) { assertTrue(s.isFile()); } else if (expectedType == fileType.isSymlink) { assertTrue(s.isSymlink()); } assertEquals(aFs.makeQualified(new Path(path)), s.getPath()); } /** * Class to enable easier mocking of a FileSystem * Use getRawFileSystem to retrieve the mock */ public static
fileType
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/ResourceAllocationStrategy.java
{ "start": 1196, "end": 3038 }
interface ____ { /** * Try to make an allocation decision to fulfill the resource requirements. The strategy * generates a series of actions to take, based on the current status. * * <p>Notice: For performance considerations, modifications might be performed directly on the * input arguments. If the arguments are reused elsewhere, please make a deep copy in advance. * * @param missingResources resource requirements that are not yet fulfilled, indexed by jobId * @param taskManagerResourceInfoProvider provide the registered/pending resources of the * current cluster * @param blockedTaskManagerChecker blocked task manager checker * @return a {@link ResourceAllocationResult} based on the current status, which contains * whether the requirements can be fulfilled and the actions to take */ ResourceAllocationResult tryFulfillRequirements( Map<JobID, Collection<ResourceRequirement>> missingResources, TaskManagerResourceInfoProvider taskManagerResourceInfoProvider, BlockedTaskManagerChecker blockedTaskManagerChecker); /** * Try to make a decision to reconcile the cluster resources. This is more light weighted than * {@link #tryFulfillRequirements}, only consider empty registered / pending workers and assume * all requirements are fulfilled by registered / pending workers. * * @param taskManagerResourceInfoProvider provide the registered/pending resources of the * current cluster * @return a {@link ResourceReconcileResult} based on the current status, which contains the * actions to take */ ResourceReconcileResult tryReconcileClusterResources( TaskManagerResourceInfoProvider taskManagerResourceInfoProvider); }
ResourceAllocationStrategy
java
quarkusio__quarkus
extensions/smallrye-metrics/deployment/src/test/java/io/quarkus/smallrye/metrics/stereotype/StereotypeCountedClassTest.java
{ "start": 516, "end": 1307 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(CountedClass.class, CountMe.class)); @Inject MetricRegistry metricRegistry; @Inject CountedClass bean; @Test public void test() { MetricID id_constructor = new MetricID(CountedClass.class.getName() + ".CountedClass"); assertTrue(metricRegistry.getCounters().containsKey(id_constructor)); MetricID id_method = new MetricID(CountedClass.class.getName() + ".foo"); assertTrue(metricRegistry.getCounters().containsKey(id_method)); bean.foo(); assertEquals(1, metricRegistry.getCounters().get(id_method).getCount()); } }
StereotypeCountedClassTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/SimpleNaturalIdLoadAccess.java
{ "start": 917, "end": 6151 }
interface ____<T> { /** * Specify the {@linkplain LockMode lock mode} to use when * querying the database. * * @param lockMode The lock mode to apply * @return {@code this}, for method chaining */ default SimpleNaturalIdLoadAccess<T> with(LockMode lockMode) { return with( lockMode, PessimisticLockScope.NORMAL ); } /** * Specify the {@linkplain LockMode lock mode} to use when * querying the database. * * @param lockMode The lock mode to apply * * @return {@code this}, for method chaining */ SimpleNaturalIdLoadAccess<T> with(LockMode lockMode, PessimisticLockScope lockScope); /** * Specify the {@linkplain Timeout timeout} to use when * querying the database. * * @param timeout The timeout to apply to the database operation * * @return {@code this}, for method chaining */ SimpleNaturalIdLoadAccess<T> with(Timeout timeout); /** * Specify the {@linkplain LockOptions lock options} to use when * querying the database. * * @param lockOptions The lock options to use * * @return {@code this}, for method chaining * * @deprecated Use one of {@linkplain #with(LockMode)}, * {@linkplain #with(LockMode, PessimisticLockScope)} * and/or {@linkplain #with(Timeout)} instead. */ @Deprecated(since = "7.0", forRemoval = true) SimpleNaturalIdLoadAccess<T> with(LockOptions lockOptions); /** * Override the associations fetched by default by specifying * the complete list of associations to be fetched as an * {@linkplain jakarta.persistence.EntityGraph entity graph}. * * @since 6.3 */ default SimpleNaturalIdLoadAccess<T> withFetchGraph(EntityGraph<T> graph) { return with( graph, GraphSemantic.FETCH ); } /** * Augment the associations fetched by default by specifying a * list of additional associations to be fetched as an * {@linkplain jakarta.persistence.EntityGraph entity graph}. * * @since 6.3 */ default SimpleNaturalIdLoadAccess<T> withLoadGraph(EntityGraph<T> graph) { return with( graph, GraphSemantic.LOAD ); } /** * Customize the associations fetched by specifying an * {@linkplain jakarta.persistence.EntityGraph entity graph}, * and how it should be {@linkplain GraphSemantic interpreted}. * * @since 6.3 */ SimpleNaturalIdLoadAccess<T> with(EntityGraph<T> graph, GraphSemantic semantic); /** * Customize the associations fetched by specifying a * {@linkplain org.hibernate.annotations.FetchProfile fetch profile} * that should be enabled during this operation. * <p> * This allows the {@linkplain Session#isFetchProfileEnabled(String) * session-level fetch profiles} to be temporarily overridden. * * @since 6.3 */ SimpleNaturalIdLoadAccess<T> enableFetchProfile(String profileName); /** * Customize the associations fetched by specifying a * {@linkplain org.hibernate.annotations.FetchProfile fetch profile} * that should be disabled during this operation. * <p> * This allows the {@linkplain Session#isFetchProfileEnabled(String) * session-level fetch profiles} to be temporarily overridden. * * @since 6.3 */ SimpleNaturalIdLoadAccess<T> disableFetchProfile(String profileName); /** * For entities with mutable natural ids, should Hibernate perform * "synchronization" prior to performing lookups? The default is * to perform "synchronization" (for correctness). * <p> * See {@link NaturalIdLoadAccess#setSynchronizationEnabled} for * detailed discussion. * * @param enabled Should synchronization be performed? * {@code true} indicates synchronization will be performed; * {@code false} indicates it will be circumvented. * * @return {@code this}, for method chaining */ SimpleNaturalIdLoadAccess<T> setSynchronizationEnabled(boolean enabled); /** * Return the persistent instance with the given natural id value, * assuming that the instance exists. This method might return a * proxied instance that is initialized on-demand, when a * non-identifier method is accessed. * <p> * You should not use this method to determine if an instance exists; * to check for existence, use {@link #load} instead. Use this only to * retrieve an instance that you assume exists, where non-existence * would be an actual error. * * @param naturalIdValue The value of the natural id * * @return The persistent instance or proxy, if an instance exists. * Otherwise, {@code null}. */ T getReference(Object naturalIdValue); /** * Return the persistent instance with the given natural id value, * or {@code null} if there is no such persistent instance. If the * instance is already associated with the session, return that * instance, initializing it if needed. This method never returns * an uninitialized instance. * * @param naturalIdValue The value of the natural-id * * @return The persistent instance or {@code null} */ T load(Object naturalIdValue); /** * Just like {@link #load}, except that here an {@link Optional} * is returned. * * @param naturalIdValue The identifier * * @return The persistent instance, if any, as an {@link Optional} */ Optional<T> loadOptional(Object naturalIdValue); }
SimpleNaturalIdLoadAccess
java
apache__logging-log4j2
log4j-taglib/src/main/java/org/apache/logging/log4j/taglib/InfoTag.java
{ "start": 897, "end": 970 }
class ____ the {@code <log:info>} tag. * * @since 2.0 */ public
implements
java
apache__flink
flink-connectors/flink-connector-files/src/test/java/org/apache/flink/connector/file/table/PartitionWriterTest.java
{ "start": 1641, "end": 7575 }
class ____ { private final LegacyRowResource usesLegacyRows = LegacyRowResource.INSTANCE; @TempDir private java.nio.file.Path tmpDir; private PartitionTempFileManager manager; @BeforeEach void before() throws IOException { manager = new PartitionTempFileManager(fsFactory, new Path(tmpDir.toUri()), 0, 0); usesLegacyRows.before(); } @AfterEach void after() { usesLegacyRows.after(); } private final Map<String, List<Row>> records = new LinkedHashMap<>(); private final OutputFormatFactory<Row> factory = path -> new OutputFormat<Row>() { private static final long serialVersionUID = -5797045183913321175L; @Override public void configure(Configuration parameters) {} @Override public void open(InitializationContext context) { records.put(getKey(), new ArrayList<>()); } private String getKey() { Path parent = path.getParent(); return parent.getName().startsWith("task-") ? parent.getName() : parent.getParent().getName() + Path.SEPARATOR + parent.getName(); } @Override public void writeRecord(Row record) { records.get(getKey()).add(record); } @Override public void close() {} }; private final Context<Row> context = new Context<>(null, path -> factory.createOutputFormat(path)); private FileSystemFactory fsFactory = FileSystem::get; private PartitionComputer<Row> computer = new PartitionComputer<Row>() { @Override public LinkedHashMap<String, String> generatePartValues(Row in) { LinkedHashMap<String, String> ret = CollectionUtil.newLinkedHashMapWithExpectedSize(1); ret.put("p", in.getField(0).toString()); return ret; } @Override public Row projectColumnsToWrite(Row in) { return in; } }; public PartitionWriterTest() throws Exception {} @Test void testEmptySingleDirectoryWriter() throws Exception { SingleDirectoryWriter<Row> writer = new SingleDirectoryWriter<>(context, manager, computer, new LinkedHashMap<>()); writer.close(); assertThat(records).isEmpty(); } @Test void testSingleDirectoryWriter() throws Exception { SingleDirectoryWriter<Row> writer = new SingleDirectoryWriter<>(context, manager, computer, new LinkedHashMap<>()); writer.write(Row.of("p1", 1)); writer.write(Row.of("p1", 2)); writer.write(Row.of("p2", 2)); writer.close(); assertThat(records.toString()).isEqualTo("{task-0-attempt-0=[p1,1, p1,2, p2,2]}"); manager = new PartitionTempFileManager(fsFactory, new Path(tmpDir.toUri()), 1, 0); writer = new SingleDirectoryWriter<>(context, manager, computer, new LinkedHashMap<>()); writer.write(Row.of("p3", 3)); writer.write(Row.of("p5", 5)); writer.write(Row.of("p2", 2)); writer.close(); assertThat(records.toString()) .isEqualTo( "{task-0-attempt-0=[p1,1, p1,2, p2,2], task-1-attempt-0=[p3,3, p5,5, p2,2]}"); } @Test void testGroupedPartitionWriter() throws Exception { GroupedPartitionWriter<Row> writer = new GroupedPartitionWriter<>(context, manager, computer); writer.write(Row.of("p1", 1)); writer.write(Row.of("p1", 2)); writer.write(Row.of("p2", 2)); writer.close(); assertThat(records.toString()) .isEqualTo("{task-0-attempt-0/p=p1=[p1,1, p1,2], task-0-attempt-0/p=p2=[p2,2]}"); manager = new PartitionTempFileManager(fsFactory, new Path(tmpDir.toUri()), 1, 1); writer = new GroupedPartitionWriter<>(context, manager, computer); writer.write(Row.of("p3", 3)); writer.write(Row.of("p4", 5)); writer.write(Row.of("p5", 2)); writer.close(); assertThat(records.toString()) .isEqualTo( "{task-0-attempt-0/p=p1=[p1,1, p1,2], task-0-attempt-0/p=p2=[p2,2], task-1-attempt-1/p=p3=[p3,3], task-1-attempt-1/p=p4=[p4,5], task-1-attempt-1/p=p5=[p5,2]}"); } @Test void testDynamicPartitionWriter() throws Exception { DynamicPartitionWriter<Row> writer = new DynamicPartitionWriter<>(context, manager, computer); writer.write(Row.of("p1", 1)); writer.write(Row.of("p2", 2)); writer.write(Row.of("p1", 2)); writer.close(); assertThat(records.toString()) .isEqualTo("{task-0-attempt-0/p=p1=[p1,1, p1,2], task-0-attempt-0/p=p2=[p2,2]}"); manager = new PartitionTempFileManager(fsFactory, new Path(tmpDir.toUri()), 1, 1); writer = new DynamicPartitionWriter<>(context, manager, computer); writer.write(Row.of("p4", 5)); writer.write(Row.of("p3", 3)); writer.write(Row.of("p5", 2)); writer.close(); assertThat(records.toString()) .isEqualTo( "{task-0-attempt-0/p=p1=[p1,1, p1,2], task-0-attempt-0/p=p2=[p2,2], task-1-attempt-1/p=p4=[p4,5], task-1-attempt-1/p=p3=[p3,3], task-1-attempt-1/p=p5=[p5,2]}"); } }
PartitionWriterTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/access/xml/RentalCar.java
{ "start": 329, "end": 619 }
class ____ { @Id @GeneratedValue private int id; private Driver driver; public int getId() { return id; } public void setId(int id) { this.id = id; } public Driver getDriver() { return driver; } public void setDriver(Driver driver) { this.driver = driver; } }
RentalCar
java
google__dagger
javatests/dagger/internal/codegen/InjectConstructorFactoryGeneratorTest.java
{ "start": 1856, "end": 2085 }
interface ____ {}"); private static final Source SCOPE_A = CompilerTests.javaSource("test.ScopeA", "package test;", "", "import javax.inject.Scope;", "", "@Scope @
QualifierB
java
apache__dubbo
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/aggregate/SlidingWindow.java
{ "start": 1315, "end": 9883 }
class ____<T> { /** * The number of panes the sliding window contains. */ protected int paneCount; /** * Total time interval of the sliding window in milliseconds. */ protected long intervalInMs; /** * Time interval of a pane in milliseconds. */ protected long paneIntervalInMs; /** * The panes reference, supports atomic operations. */ protected final AtomicReferenceArray<Pane<T>> referenceArray; /** * The lock is used only when current pane is deprecated. */ private final ReentrantLock updateLock = new ReentrantLock(); protected SlidingWindow(int paneCount, long intervalInMs) { Assert.assertTrue(paneCount > 0, "pane count is invalid: " + paneCount); Assert.assertTrue(intervalInMs > 0, "total time interval of the sliding window should be positive"); Assert.assertTrue(intervalInMs % paneCount == 0, "total time interval needs to be evenly divided"); this.paneCount = paneCount; this.intervalInMs = intervalInMs; this.paneIntervalInMs = intervalInMs / paneCount; this.referenceArray = new AtomicReferenceArray<>(paneCount); } /** * Get the pane at the current timestamp. * * @return the pane at current timestamp. */ public Pane<T> currentPane() { return currentPane(System.currentTimeMillis()); } /** * Get the pane at the specified timestamp in milliseconds. * * @param timeMillis a timestamp in milliseconds. * @return the pane at the specified timestamp if the time is valid; null if time is invalid. */ public Pane<T> currentPane(long timeMillis) { if (timeMillis < 0) { return null; } int paneIdx = calculatePaneIdx(timeMillis); long paneStartInMs = calculatePaneStart(timeMillis); while (true) { Pane<T> oldPane = referenceArray.get(paneIdx); // Create a pane instance when the pane does not exist. if (oldPane == null) { Pane<T> pane = new Pane<>(paneIntervalInMs, paneStartInMs, newEmptyValue(timeMillis)); if (referenceArray.compareAndSet(paneIdx, null, pane)) { return pane; } else { // Contention failed, the thread will yield its time slice to wait for pane available. Thread.yield(); } } // else if (paneStartInMs == oldPane.getStartInMs()) { return oldPane; } // The pane has deprecated. To avoid the overhead of creating a new instance, reset the original pane // directly. else if (paneStartInMs > oldPane.getStartInMs()) { if (updateLock.tryLock()) { try { return resetPaneTo(oldPane, paneStartInMs); } finally { updateLock.unlock(); } } else { // Contention failed, the thread will yield its time slice to wait for pane available. Thread.yield(); } } // The specified timestamp has passed. else if (paneStartInMs < oldPane.getStartInMs()) { return new Pane<>(paneIntervalInMs, paneStartInMs, newEmptyValue(timeMillis)); } } } /** * Get statistic value from pane at the specified timestamp. * * @param timeMillis the specified timestamp in milliseconds. * @return the statistic value if pane at the specified timestamp is up-to-date; otherwise null. */ public T getPaneValue(long timeMillis) { if (timeMillis < 0) { return null; } int paneIdx = calculatePaneIdx(timeMillis); Pane<T> pane = referenceArray.get(paneIdx); if (pane == null || !pane.isTimeInWindow(timeMillis)) { return null; } return pane.getValue(); } /** * Create a new statistic value for pane. * * @param timeMillis the specified timestamp in milliseconds. * @return new empty statistic value. */ public abstract T newEmptyValue(long timeMillis); /** * Reset given pane to the specified start time and reset the value. * * @param pane the given pane. * @param startInMs the start timestamp of the pane in milliseconds. * @return reset pane. */ protected abstract Pane<T> resetPaneTo(final Pane<T> pane, long startInMs); /** * Calculate the pane index corresponding to the specified timestamp. * * @param timeMillis the specified timestamp. * @return the pane index corresponding to the specified timestamp. */ private int calculatePaneIdx(long timeMillis) { return (int) ((timeMillis / paneIntervalInMs) % paneCount); } /** * Calculate the pane start corresponding to the specified timestamp. * * @param timeMillis the specified timestamp. * @return the pane start corresponding to the specified timestamp. */ protected long calculatePaneStart(long timeMillis) { return timeMillis - timeMillis % paneIntervalInMs; } /** * Checks if the specified pane is deprecated at the current timestamp. * * @param pane the specified pane. * @return true if the pane is deprecated; otherwise false. */ public boolean isPaneDeprecated(final Pane<T> pane) { return isPaneDeprecated(System.currentTimeMillis(), pane); } /** * Checks if the specified pane is deprecated at the specified timestamp. * * @param timeMillis the specified time. * @param pane the specified pane. * @return true if the pane is deprecated; otherwise false. */ public boolean isPaneDeprecated(long timeMillis, final Pane<T> pane) { // the pane is '[)' return (timeMillis - pane.getStartInMs()) > intervalInMs; } /** * Get valid pane list for entire sliding window at the current time. * The list will only contain "valid" panes. * * @return valid pane list for entire sliding window. */ public List<Pane<T>> list() { return list(System.currentTimeMillis()); } /** * Get valid pane list for entire sliding window at the specified time. * The list will only contain "valid" panes. * * @param timeMillis the specified time. * @return valid pane list for entire sliding window. */ public List<Pane<T>> list(long timeMillis) { if (timeMillis < 0) { return new ArrayList<>(); } List<Pane<T>> result = new ArrayList<>(paneCount); for (int idx = 0; idx < paneCount; idx++) { Pane<T> pane = referenceArray.get(idx); if (pane == null || isPaneDeprecated(timeMillis, pane)) { continue; } result.add(pane); } return result; } /** * Get aggregated value list for entire sliding window at the current time. * The list will only contain value from "valid" panes. * * @return aggregated value list for entire sliding window. */ public List<T> values() { return values(System.currentTimeMillis()); } /** * Get aggregated value list for entire sliding window at the specified time. * The list will only contain value from "valid" panes. * * @return aggregated value list for entire sliding window. */ public List<T> values(long timeMillis) { if (timeMillis < 0) { return new ArrayList<>(); } List<T> result = new ArrayList<>(paneCount); for (int idx = 0; idx < paneCount; idx++) { Pane<T> pane = referenceArray.get(idx); if (pane == null || isPaneDeprecated(timeMillis, pane)) { continue; } result.add(pane.getValue()); } return result; } /** * Get total interval of the sliding window in milliseconds. * * @return the total interval in milliseconds. */ public long getIntervalInMs() { return intervalInMs; } /** * Get pane interval of the sliding window in milliseconds. * * @return the interval of a pane in milliseconds. */ public long getPaneIntervalInMs() { return paneIntervalInMs; } }
SlidingWindow
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GoogleSecretManagerEndpointBuilderFactory.java
{ "start": 12181, "end": 12563 }
class ____ extends AbstractEndpointBuilder implements GoogleSecretManagerEndpointBuilder, AdvancedGoogleSecretManagerEndpointBuilder { public GoogleSecretManagerEndpointBuilderImpl(String path) { super(componentName, path); } } return new GoogleSecretManagerEndpointBuilderImpl(path); } }
GoogleSecretManagerEndpointBuilderImpl
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/server/jetty/JettyRequestUpgradeStrategy.java
{ "start": 2138, "end": 4848 }
class ____ implements RequestUpgradeStrategy, ServletContextAware { private static final String[] SUPPORTED_VERSIONS = new String[] {"13"}; private @Nullable Consumer<Configurable> webSocketConfigurer; @Override public String[] getSupportedVersions() { return SUPPORTED_VERSIONS; } @Override public List<WebSocketExtension> getSupportedExtensions(ServerHttpRequest request) { return Collections.emptyList(); } /** * Add a callback to configure WebSocket server parameters on * {@link JettyWebSocketServerContainer}. * @since 6.1 */ public void addWebSocketConfigurer(Consumer<Configurable> webSocketConfigurer) { this.webSocketConfigurer = (this.webSocketConfigurer != null ? this.webSocketConfigurer.andThen(webSocketConfigurer) : webSocketConfigurer); } @Override public void setServletContext(ServletContext servletContext) { JettyWebSocketServerContainer container = JettyWebSocketServerContainer.getContainer(servletContext); if (container != null && this.webSocketConfigurer != null) { this.webSocketConfigurer.accept(container); } } @Override public void upgrade(ServerHttpRequest request, ServerHttpResponse response, @Nullable String selectedProtocol, List<WebSocketExtension> selectedExtensions, @Nullable Principal user, WebSocketHandler handler, Map<String, Object> attributes) throws HandshakeFailureException { Assert.isInstanceOf(ServletServerHttpRequest.class, request, "ServletServerHttpRequest required"); HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); ServletContext servletContext = servletRequest.getServletContext(); Assert.isInstanceOf(ServletServerHttpResponse.class, response, "ServletServerHttpResponse required"); HttpServletResponse servletResponse = ((ServletServerHttpResponse) response).getServletResponse(); JettyWebSocketSession session = new JettyWebSocketSession(attributes, user); JettyWebSocketHandlerAdapter handlerAdapter = new JettyWebSocketHandlerAdapter(handler, session); JettyWebSocketCreator webSocketCreator = (upgradeRequest, upgradeResponse) -> { if (selectedProtocol != null) { upgradeResponse.setAcceptedSubProtocol(selectedProtocol); } return handlerAdapter; }; JettyWebSocketServerContainer container = JettyWebSocketServerContainer.getContainer(servletContext); try { container.upgrade(webSocketCreator, servletRequest, servletResponse); } catch (UndeclaredThrowableException ex) { throw new HandshakeFailureException("Failed to upgrade", ex.getUndeclaredThrowable()); } catch (Exception ex) { throw new HandshakeFailureException("Failed to upgrade", ex); } } }
JettyRequestUpgradeStrategy
java
resilience4j__resilience4j
resilience4j-micronaut/src/test/groovy/io/github/resilience4j/micronaut/retry/IgnoredException.java
{ "start": 56, "end": 107 }
class ____ extends RuntimeException{ }
IgnoredException
java
google__guice
core/test/com/google/inject/ScopesTest.java
{ "start": 19336, "end": 19517 }
class ____ implements Provider<ProvidedBySingleton> { @Override public ProvidedBySingleton get() { return new ProvidedBySingleton(); } } static
ProvidedByProvider
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java
{ "start": 56928, "end": 59515 }
class ____ extends ParserRuleContext { public TerminalNode LP() { return getToken(EsqlBaseParser.LP, 0); } public FromCommandContext fromCommand() { return getRuleContext(FromCommandContext.class,0); } public TerminalNode RP() { return getToken(EsqlBaseParser.RP, 0); } public List<TerminalNode> PIPE() { return getTokens(EsqlBaseParser.PIPE); } public TerminalNode PIPE(int i) { return getToken(EsqlBaseParser.PIPE, i); } public List<ProcessingCommandContext> processingCommand() { return getRuleContexts(ProcessingCommandContext.class); } public ProcessingCommandContext processingCommand(int i) { return getRuleContext(ProcessingCommandContext.class,i); } @SuppressWarnings("this-escape") public SubqueryContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_subquery; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterSubquery(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitSubquery(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitSubquery(this); else return visitor.visitChildren(this); } } public final SubqueryContext subquery() throws RecognitionException { SubqueryContext _localctx = new SubqueryContext(_ctx, getState()); enterRule(_localctx, 32, RULE_subquery); int _la; try { enterOuterAlt(_localctx, 1); { setState(313); match(LP); setState(314); fromCommand(); setState(319); _errHandler.sync(this); _la = _input.LA(1); while (_la==PIPE) { { { setState(315); match(PIPE); setState(316); processingCommand(); } } setState(321); _errHandler.sync(this); _la = _input.LA(1); } setState(322); match(RP); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
SubqueryContext
java
quarkusio__quarkus
extensions/scheduler/runtime/src/main/java/io/quarkus/scheduler/runtime/SchedulerRuntimeConfig.java
{ "start": 940, "end": 1656 }
enum ____ { /** * The scheduler is not started unless a {@link io.quarkus.scheduler.Scheduled} business method is found. */ NORMAL, /** * The scheduler will be started even if no scheduled business methods are found. * <p> * This is necessary for "pure" programmatic scheduling. */ FORCED, /** * Just like the {@link #FORCED} mode but the scheduler will not start triggering jobs until {@link Scheduler#resume()} * is called. * <p> * This can be useful to run some initialization logic that needs to be performed before the scheduler starts. */ HALTED; } }
StartMode
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/sql_load_script/ImportMultipleSqlLoadScriptsFileAbsentTestCase.java
{ "start": 340, "end": 1171 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .setExpectedException(ConfigurationException.class) .withApplicationRoot((jar) -> jar .addClasses(MyEntity.class, SqlLoadScriptTestResource.class) .addAsResource("application-import-multiple-load-scripts-test.properties", "application.properties") .addAsResource("import-multiple-load-scripts-1.sql", "import-1.sql")); @Test public void testImportMultipleSqlLoadScriptsTest() { // should not be called, deployment exception should happen first: // it's illegal to have Hibernate sql-load-script configuration property set // to an absent file Assertions.fail(); } }
ImportMultipleSqlLoadScriptsFileAbsentTestCase
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/IRDecorations.java
{ "start": 10696, "end": 11084 }
class ____ extends IRDecoration<PainlessMethod> { public IRDThisMethod(PainlessMethod value) { super(value); } @Override public String toString() { return PainlessLookupUtility.buildPainlessMethodKey(getValue().javaMethod().getName(), getValue().typeParameters().size()); } } /** describes the call to a
IRDThisMethod
java
quarkusio__quarkus
extensions/smallrye-graphql-client/deployment/src/test/java/io/quarkus/smallrye/graphql/client/deployment/DynamicGraphQLClientWebSocketAuthenticationHttpPermissionsTest.java
{ "start": 1241, "end": 3133 }
class ____ { static String url = "http://" + System.getProperty("quarkus.http.host", "localhost") + ":" + System.getProperty("quarkus.http.test-port", "8081") + "/graphql"; @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(SecuredApi.class, Foo.class) .addAsResource("application-secured-http-permissions.properties", "application.properties") .addAsResource("users.properties") .addAsResource("roles.properties") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")); @Test public void testUnauthenticatedForQueryWebSocket() throws Exception { DynamicGraphQLClientBuilder clientBuilder = DynamicGraphQLClientBuilder.newBuilder() .url(url) .executeSingleOperationsOverWebsocket(true); try (DynamicGraphQLClient client = clientBuilder.build()) { try { client.executeSync("{ baz { message} }"); Assertions.fail("WebSocket upgrade should fail"); } catch (UpgradeRejectedException e) { // ok } } } @Test public void testUnauthenticatedForSubscriptionWebSocket() throws Exception { DynamicGraphQLClientBuilder clientBuilder = DynamicGraphQLClientBuilder.newBuilder() .url(url); try (DynamicGraphQLClient client = clientBuilder.build()) { AssertSubscriber<Response> subscriber = new AssertSubscriber<>(); client.subscription("{ bazSub { message} }").subscribe().withSubscriber(subscriber); subscriber.awaitFailure().assertFailedWith(UpgradeRejectedException.class); } } public static
DynamicGraphQLClientWebSocketAuthenticationHttpPermissionsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/interceptor/Image.java
{ "start": 675, "end": 1092 }
class ____ { private long perm1 = -1; // all bits turned on. private String comment; protected long getPerm1() { return this.perm1; } protected void setPerm1(long value) { this.perm1 = value; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String toString() { return "Details=" + perm1; } } }
Details
java
quarkusio__quarkus
devtools/cli/src/main/java/io/quarkus/cli/config/RemoveConfig.java
{ "start": 433, "end": 1626 }
class ____ extends BaseConfigCommand implements Callable<Integer> { @CommandLine.Parameters(index = "0", arity = "1", paramLabel = "NAME", description = "Configuration name") String name; @Override public Integer call() throws Exception { Path properties = projectRoot().resolve("src/main/resources/application.properties"); if (!properties.toFile().exists()) { output.error("Could not find an application.properties file"); return -1; } List<String> lines = Files.readAllLines(properties); ConfigValue configValue = findKey(lines, name); if (configValue.getLineNumber() != -1) { output.info(SUCCESS_ICON + " Removing configuration @|bold " + name + "|@"); lines.remove(configValue.getLineNumber()); } else { output.error("Could not find configuration " + name); return -1; } try (BufferedWriter writer = Files.newBufferedWriter(properties)) { for (String i : lines) { writer.write(i); writer.newLine(); } } return CommandLine.ExitCode.OK; } }
RemoveConfig
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/dao/CannotSerializeTransactionException.java
{ "start": 1143, "end": 1675 }
class ____ extends PessimisticLockingFailureException { /** * Constructor for CannotSerializeTransactionException. * @param msg the detail message */ public CannotSerializeTransactionException(String msg) { super(msg); } /** * Constructor for CannotSerializeTransactionException. * @param msg the detail message * @param cause the root cause from the data access API in use */ public CannotSerializeTransactionException(String msg, Throwable cause) { super(msg, cause); } }
CannotSerializeTransactionException
java
apache__camel
components/camel-oauth/src/main/java/org/apache/camel/oauth/ClientCredentials.java
{ "start": 843, "end": 1437 }
class ____ extends Credentials { private String clientId; private String clientSecret; public ClientCredentials() { setFlowType(OAuthFlowType.CLIENT); } public String getClientId() { return clientId; } public ClientCredentials setClientId(String clientId) { this.clientId = clientId; return this; } public String getClientSecret() { return clientSecret; } public ClientCredentials setClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } }
ClientCredentials
java
redisson__redisson
redisson/src/main/java/org/redisson/api/ObjectListener.java
{ "start": 783, "end": 835 }
interface ____ extends EventListener { }
ObjectListener
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/external/request/elastic/ElasticInferenceServiceRerankRequestEntityTests.java
{ "start": 828, "end": 4663 }
class ____ extends ESTestCase { public void testToXContent_SingleDocument_NoTopN() throws IOException { var entity = new ElasticInferenceServiceRerankRequestEntity("query", List.of("document 1"), "rerank-model-id", null); String xContentString = xContentEntityToString(entity); assertThat(xContentString, equalToIgnoringWhitespaceInJsonString(""" { "query": "query", "model": "rerank-model-id", "documents": ["document 1"] }""")); } public void testToXContent_MultipleDocuments_NoTopN() throws IOException { var entity = new ElasticInferenceServiceRerankRequestEntity( "query", List.of("document 1", "document 2", "document 3"), "rerank-model-id", null ); String xContentString = xContentEntityToString(entity); assertThat(xContentString, equalToIgnoringWhitespaceInJsonString(""" { "query": "query", "model": "rerank-model-id", "documents": [ "document 1", "document 2", "document 3" ] } """)); } public void testToXContent_SingleDocument_WithTopN() throws IOException { var entity = new ElasticInferenceServiceRerankRequestEntity("query", List.of("document 1"), "rerank-model-id", 3); String xContentString = xContentEntityToString(entity); assertThat(xContentString, equalToIgnoringWhitespaceInJsonString(""" { "query": "query", "model": "rerank-model-id", "top_n": 3, "documents": ["document 1"] } """)); } public void testToXContent_MultipleDocuments_WithTopN() throws IOException { var entity = new ElasticInferenceServiceRerankRequestEntity( "query", List.of("document 1", "document 2", "document 3", "document 4", "document 5"), "rerank-model-id", 3 ); String xContentString = xContentEntityToString(entity); assertThat(xContentString, equalToIgnoringWhitespaceInJsonString(""" { "query": "query", "model": "rerank-model-id", "top_n": 3, "documents": [ "document 1", "document 2", "document 3", "document 4", "document 5" ] } """)); } public void testNullQueryThrowsException() { NullPointerException e = expectThrows( NullPointerException.class, () -> new ElasticInferenceServiceRerankRequestEntity(null, List.of("document 1"), "model-id", null) ); assertNotNull(e); } public void testNullDocumentsThrowsException() { NullPointerException e = expectThrows( NullPointerException.class, () -> new ElasticInferenceServiceRerankRequestEntity("query", null, "model-id", null) ); assertNotNull(e); } public void testNullModelIdThrowsException() { NullPointerException e = expectThrows( NullPointerException.class, () -> new ElasticInferenceServiceRerankRequestEntity("query", List.of("document 1"), null, null) ); assertNotNull(e); } private String xContentEntityToString(ElasticInferenceServiceRerankRequestEntity entity) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); entity.toXContent(builder, null); return Strings.toString(builder); } }
ElasticInferenceServiceRerankRequestEntityTests
java
apache__flink
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/junit/extensions/parameterized/ParameterizedTestExtension.java
{ "start": 5494, "end": 6442 }
class ____ implements TestTemplateInvocationContext { private final String testNameTemplate; private final Object[] parameterValues; public FieldInjectingInvocationContext(String testNameTemplate, Object[] parameterValues) { this.testNameTemplate = testNameTemplate; this.parameterValues = parameterValues; } @Override public String getDisplayName(int invocationIndex) { if (INDEX_TEMPLATE.equals(testNameTemplate)) { return TestTemplateInvocationContext.super.getDisplayName(invocationIndex); } else { return MessageFormat.format(testNameTemplate, parameterValues); } } @Override public List<Extension> getAdditionalExtensions() { return Collections.singletonList(new FieldInjectingHook(parameterValues)); } private static
FieldInjectingInvocationContext
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/delegation/AbstractDelegationTokenBinding.java
{ "start": 1576, "end": 1904 }
class ____ * handles the binding of its underlying authentication mechanism to the * Hadoop Delegation token mechanism. * * See also {@code org.apache.hadoop.fs.azure.security.WasbDelegationTokenManager} * but note that it assumes Kerberos tokens for which the renewal mechanism * is the sole plugin point. * This
which
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/security/authorize/TimelinePolicyProvider.java
{ "start": 1360, "end": 1667 }
class ____ extends PolicyProvider { @Override public Service[] getServices() { return new Service[] { new Service( YarnConfiguration.YARN_SECURITY_SERVICE_AUTHORIZATION_APPLICATIONHISTORY_PROTOCOL, ApplicationHistoryProtocolPB.class) }; } }
TimelinePolicyProvider
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptivebatch/DefaultVertexParallelismAndInputInfosDeciderTest.java
{ "start": 27023, "end": 30918 }
class ____ implements BlockingResultInfo { private final boolean isBroadcast; private final boolean singleSubpartitionContainsAllData; private final long producedBytes; private final int numPartitions; private final int numSubpartitions; private TestingBlockingResultInfo( boolean isBroadcast, boolean singleSubpartitionContainsAllData, long producedBytes) { this( isBroadcast, singleSubpartitionContainsAllData, producedBytes, MAX_PARALLELISM, MAX_PARALLELISM); } private TestingBlockingResultInfo( boolean isBroadcast, boolean singleSubpartitionContainsAllData, long producedBytes, int numPartitions, int numSubpartitions) { this.isBroadcast = isBroadcast; this.singleSubpartitionContainsAllData = singleSubpartitionContainsAllData; this.producedBytes = producedBytes; this.numPartitions = numPartitions; this.numSubpartitions = numSubpartitions; } @Override public IntermediateDataSetID getResultId() { return new IntermediateDataSetID(); } @Override public boolean isBroadcast() { return isBroadcast; } @Override public boolean isSingleSubpartitionContainsAllData() { return singleSubpartitionContainsAllData; } @Override public boolean isPointwise() { return false; } @Override public int getNumPartitions() { return numPartitions; } @Override public int getNumSubpartitions(int partitionIndex) { return numSubpartitions; } @Override public long getNumBytesProduced() { return producedBytes; } @Override public long getNumBytesProduced( IndexRange partitionIndexRange, IndexRange subpartitionIndexRange) { throw new UnsupportedOperationException(); } @Override public void recordPartitionInfo(int partitionIndex, ResultPartitionBytes partitionBytes) {} @Override public void resetPartitionInfo(int partitionIndex) {} @Override public Map<Integer, long[]> getSubpartitionBytesByPartitionIndex() { return Map.of(); } } private static BlockingResultInfo createFromBroadcastResult(long producedBytes) { return new TestingBlockingResultInfo(true, true, producedBytes); } private static BlockingResultInfo createFromNonBroadcastResult(long producedBytes) { return new TestingBlockingResultInfo(false, false, producedBytes); } public static BlockingInputInfo toBlockingInputInfoView(BlockingResultInfo blockingResultInfo) { boolean existIntraInputKeyCorrelation = blockingResultInfo instanceof AllToAllBlockingResultInfo; boolean existInterInputsKeyCorrelation = blockingResultInfo instanceof AllToAllBlockingResultInfo; return new BlockingInputInfo( blockingResultInfo, 0, existInterInputsKeyCorrelation, existIntraInputKeyCorrelation); } public static List<BlockingInputInfo> toBlockingInputInfoViews( List<BlockingResultInfo> blockingResultInfos) { List<BlockingInputInfo> blockingInputInfos = new ArrayList<>(); for (BlockingResultInfo blockingResultInfo : blockingResultInfos) { blockingInputInfos.add(toBlockingInputInfoView(blockingResultInfo)); } return blockingInputInfos; } }
TestingBlockingResultInfo
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/async/SpringAsyncDeadLetterChannelExecutorServiceRefTest.java
{ "start": 1159, "end": 1865 }
class ____ extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "org/apache/camel/spring/processor/async/SpringAsyncDeadLetterChannelExecutorServiceRefTest.xml"); } @Test public void testAsyncDLCExecutorServiceRefTest() throws Exception { getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); MockEndpoint mock = getMockEndpoint("mock:dead"); mock.expectedMessageCount(1); template.sendBody("direct:in", "Hello World"); assertMockEndpointsSatisfied(); } }
SpringAsyncDeadLetterChannelExecutorServiceRefTest
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/S3ATestUtils.java
{ "start": 6916, "end": 9742 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger( S3ATestUtils.class); /** Many threads for scale performance: {@value}. */ public static final int EXECUTOR_THREAD_COUNT = 64; /** * For submitting work. */ private static final ListeningExecutorService EXECUTOR = MoreExecutors.listeningDecorator( BlockingThreadPoolExecutorService.newInstance( EXECUTOR_THREAD_COUNT, EXECUTOR_THREAD_COUNT * 2, 30, TimeUnit.SECONDS, "test-operations")); /** * Value to set a system property to (in maven) to declare that * a property has been unset. */ public static final String UNSET_PROPERTY = "unset"; public static final int PURGE_DELAY_SECONDS = 60 * 60; /** Add any deprecated keys. */ @SuppressWarnings("deprecation") private static void addDeprecatedKeys() { // STS endpoint configuration option Configuration.DeprecationDelta[] deltas = { // STS endpoint configuration option new Configuration.DeprecationDelta( S3ATestConstants.TEST_STS_ENDPOINT, ASSUMED_ROLE_STS_ENDPOINT) }; if (deltas.length > 0) { Configuration.addDeprecations(deltas); Configuration.reloadExistingConfigurations(); } } static { addDeprecatedKeys(); } /** * Get S3A FS name. * @param conf configuration. * @return S3A fs name. */ public static String getFsName(Configuration conf) { return conf.getTrimmed(TEST_FS_S3A_NAME, ""); } /** * Create the test filesystem. * * If the test.fs.s3a.name property is not set, this will * trigger a JUnit failure. * * Multipart purging is enabled. * @param conf configuration * @return the FS * @throws IOException IO Problems * @throws TestAbortedException if the FS is not named */ public static S3AFileSystem createTestFileSystem(Configuration conf) throws IOException { return createTestFileSystem(conf, false); } /** * Create the test filesystem with or without multipart purging * * If the test.fs.s3a.name property is not set, this will * trigger a JUnit failure. * @param conf configuration * @param purge flag to enable Multipart purging * @return the FS * @throws IOException IO Problems */ public static S3AFileSystem createTestFileSystem(Configuration conf, boolean purge) throws IOException { String fsname = conf.getTrimmed(TEST_FS_S3A_NAME, ""); boolean liveTest = !StringUtils.isEmpty(fsname); URI testURI = null; if (liveTest) { testURI = URI.create(fsname); liveTest = testURI.getScheme().equals(Constants.FS_S3A); } // This doesn't work with our JUnit 3 style test cases, so instead we'll // make this whole
S3ATestUtils
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-data-redis/src/dockerTest/java/smoketest/data/redis/SampleRedisApplicationReactiveSslTests.java
{ "start": 1596, "end": 2547 }
class ____ { @Container @ServiceConnection @PemKeyStore(certificate = "classpath:ssl/test-client.crt", privateKey = "classpath:ssl/test-client.key") @PemTrustStore("classpath:ssl/test-ca.crt") static RedisContainer redis = TestImage.container(SecureRedisContainer.class); @Autowired private ReactiveRedisOperations<Object, Object> operations; @Test void testRepository() { String id = UUID.randomUUID().toString(); StepVerifier.create(this.operations.opsForValue().set(id, "Hello World")) .expectNext(Boolean.TRUE) .expectComplete() .verify(Duration.ofSeconds(30)); StepVerifier.create(this.operations.opsForValue().get(id)) .expectNext("Hello World") .expectComplete() .verify(Duration.ofSeconds(30)); StepVerifier.create(this.operations.execute((action) -> action.serverCommands().flushDb())) .expectNext("OK") .expectComplete() .verify(Duration.ofSeconds(30)); } }
SampleRedisApplicationReactiveSslTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/cluster/snapshots/create/CreateSnapshotRequestTests.java
{ "start": 1448, "end": 7413 }
class ____ extends ESTestCase { // tests creating XContent and parsing with source(Map) equivalency public void testToXContent() throws IOException { String repo = randomAlphaOfLength(5); String snap = randomAlphaOfLength(10); CreateSnapshotRequest original = new CreateSnapshotRequest(TEST_REQUEST_TIMEOUT, repo, snap); if (randomBoolean()) { List<String> indices = new ArrayList<>(); int count = randomInt(3) + 1; for (int i = 0; i < count; ++i) { indices.add(randomAlphaOfLength(randomInt(3) + 2)); } original.indices(indices); } if (randomBoolean()) { List<String> featureStates = new ArrayList<>(); int count = randomInt(3) + 1; for (int i = 0; i < count; ++i) { featureStates.add(randomAlphaOfLength(randomInt(3) + 2)); } original.featureStates(featureStates); } if (randomBoolean()) { original.partial(randomBoolean()); } if (randomBoolean()) { original.includeGlobalState(randomBoolean()); } if (randomBoolean()) { original.userMetadata(randomUserMetadata()); } if (randomBoolean()) { boolean defaultResolveAliasForThisRequest = original.indicesOptions().ignoreAliases() == false; original.indicesOptions( IndicesOptions.builder() .concreteTargetOptions(new IndicesOptions.ConcreteTargetOptions(randomBoolean())) .wildcardOptions( new IndicesOptions.WildcardOptions( randomBoolean(), randomBoolean(), randomBoolean(), defaultResolveAliasForThisRequest, randomBoolean() ) ) .gatekeeperOptions(IndicesOptions.GatekeeperOptions.builder().allowSelectors(false).includeFailureIndices(true).build()) .build() ); } if (randomBoolean()) { original.waitForCompletion(randomBoolean()); } if (randomBoolean()) { original.masterNodeTimeout(TimeValue.timeValueMinutes(1)); } XContentBuilder builder = original.toXContent(XContentFactory.jsonBuilder(), new MapParams(Collections.emptyMap())); try ( XContentParser parser = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, null, BytesReference.bytes(builder).streamInput()) ) { Map<String, Object> map = parser.mapOrdered(); CreateSnapshotRequest processed = new CreateSnapshotRequest( TEST_REQUEST_TIMEOUT, (String) map.get("repository"), (String) map.get("snapshot") ); processed.waitForCompletion(original.waitForCompletion()); processed.masterNodeTimeout(original.masterNodeTimeout()); processed.uuid(original.uuid()); processed.source(map); assertEquals(original, processed); } } public void testSizeCheck() { { Map<String, Object> simple = new HashMap<>(); simple.put(randomAlphaOfLength(5), randomAlphaOfLength(25)); assertNull(createSnapshotRequestWithMetadata(simple).validate()); } { Map<String, Object> complex = new HashMap<>(); Map<String, Object> nested = new HashMap<>(); nested.put(randomAlphaOfLength(5), randomAlphaOfLength(5)); nested.put(randomAlphaOfLength(6), randomAlphaOfLength(5)); complex.put(randomAlphaOfLength(7), nested); assertNull(createSnapshotRequestWithMetadata(complex).validate()); } { Map<String, Object> barelyFine = new HashMap<>(); barelyFine.put(randomAlphaOfLength(512), randomAlphaOfLength(505)); assertNull(createSnapshotRequestWithMetadata(barelyFine).validate()); } { Map<String, Object> barelyTooBig = new HashMap<>(); barelyTooBig.put(randomAlphaOfLength(512), randomAlphaOfLength(506)); ActionRequestValidationException validationException = createSnapshotRequestWithMetadata(barelyTooBig).validate(); assertNotNull(validationException); assertThat(validationException.validationErrors(), hasSize(1)); assertThat(validationException.validationErrors().get(0), equalTo("metadata must be smaller than 1024 bytes, but was [1025]")); } { Map<String, Object> tooBigOnlyIfNestedFieldsAreIncluded = new HashMap<>(); HashMap<Object, Object> nested = new HashMap<>(); nested.put(randomAlphaOfLength(500), randomAlphaOfLength(500)); tooBigOnlyIfNestedFieldsAreIncluded.put(randomAlphaOfLength(10), randomAlphaOfLength(10)); tooBigOnlyIfNestedFieldsAreIncluded.put(randomAlphaOfLength(11), nested); ActionRequestValidationException validationException = createSnapshotRequestWithMetadata(tooBigOnlyIfNestedFieldsAreIncluded) .validate(); assertNotNull(validationException); assertThat(validationException.validationErrors(), hasSize(1)); assertThat(validationException.validationErrors().get(0), equalTo("metadata must be smaller than 1024 bytes, but was [1049]")); } } private CreateSnapshotRequest createSnapshotRequestWithMetadata(Map<String, Object> metadata) { return new CreateSnapshotRequest(TEST_REQUEST_TIMEOUT, randomAlphaOfLength(5), randomAlphaOfLength(5)).indices( randomAlphaOfLength(5) ).userMetadata(metadata); } }
CreateSnapshotRequestTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/internal/StandardUserDefinedTypeExporter.java
{ "start": 779, "end": 5793 }
class ____ implements Exporter<UserDefinedType> { protected final Dialect dialect; public StandardUserDefinedTypeExporter(Dialect dialect) { this.dialect = dialect; } @Override public String[] getSqlCreateStrings( UserDefinedType userDefinedType, Metadata metadata, SqlStringGenerationContext context) { if ( userDefinedType instanceof UserDefinedObjectType userDefinedObjectType ) { return getSqlCreateStrings( userDefinedObjectType, metadata, context ); } else if ( userDefinedType instanceof UserDefinedArrayType userDefinedArrayType ) { return getSqlCreateStrings( userDefinedArrayType, metadata, context ); } else { throw new IllegalArgumentException( "Unsupported user-defined type: " + userDefinedType ); } } public String[] getSqlCreateStrings( UserDefinedObjectType userDefinedType, Metadata metadata, SqlStringGenerationContext context) { final var typeName = new QualifiedNameParser.NameParts( Identifier.toIdentifier( userDefinedType.getCatalog(), userDefinedType.isCatalogQuoted() ), Identifier.toIdentifier( userDefinedType.getSchema(), userDefinedType.isSchemaQuoted() ), userDefinedType.getNameIdentifier() ); try { final String formattedTypeName = context.format( typeName ); final var createType = new StringBuilder( "create type " ) .append( formattedTypeName ) .append( " as " ) .append( dialect.getCreateUserDefinedTypeKindString() ) .append( '(' ); boolean isFirst = true; for ( var col : userDefinedType.getColumns() ) { if ( isFirst ) { isFirst = false; } else { createType.append( ", " ); } createType.append( col.getQuotedName( dialect ) ); createType.append( ' ' ).append( col.getSqlType( metadata ) ); } createType.append( ')' ); applyUserDefinedTypeExtensionsString( createType ); List<String> sqlStrings = new ArrayList<>(); sqlStrings.add( createType.toString() ); applyComments( userDefinedType, formattedTypeName, sqlStrings ); return sqlStrings.toArray(StringHelper.EMPTY_STRINGS); } catch (Exception e) { throw new MappingException( "Error creating SQL create commands for UDT : " + typeName, e ); } } public String[] getSqlCreateStrings( UserDefinedArrayType userDefinedType, Metadata metadata, SqlStringGenerationContext context) { throw new IllegalArgumentException( "Exporter does not support name array types. Can't generate create strings for: " + userDefinedType ); } /** * @param udt The UDT. * @param formattedTypeName The formatted UDT name. * @param sqlStrings The list of SQL strings to add comments to. */ protected void applyComments(UserDefinedObjectType udt, String formattedTypeName, List<String> sqlStrings) { if ( dialect.supportsCommentOn() ) { if ( udt.getComment() != null ) { sqlStrings.add( "comment on type " + formattedTypeName + " is '" + udt.getComment() + "'" ); } for ( var column : udt.getColumns() ) { final String columnComment = column.getComment(); if ( columnComment != null ) { sqlStrings.add( "comment on column " + formattedTypeName + '.' + column.getQuotedName( dialect ) + " is '" + columnComment + "'" ); } } } } protected void applyUserDefinedTypeExtensionsString(StringBuilder buf) { buf.append( dialect.getCreateUserDefinedTypeExtensionsString() ); } @Override public String[] getSqlDropStrings(UserDefinedType userDefinedType, Metadata metadata, SqlStringGenerationContext context) { if ( userDefinedType instanceof UserDefinedObjectType userDefinedObjectType ) { return getSqlDropStrings( userDefinedObjectType, metadata, context ); } else if ( userDefinedType instanceof UserDefinedArrayType userDefinedArrayType ) { return getSqlDropStrings( userDefinedArrayType, metadata, context ); } else { throw new IllegalArgumentException( "Unsupported user-defined type: " + userDefinedType ); } } public String[] getSqlDropStrings(UserDefinedObjectType userDefinedType, Metadata metadata, SqlStringGenerationContext context) { final var dropType = new StringBuilder( "drop type " ); if ( dialect.supportsIfExistsBeforeTypeName() ) { dropType.append( "if exists " ); } final var typeName = new QualifiedNameParser.NameParts( Identifier.toIdentifier( userDefinedType.getCatalog(), userDefinedType.isCatalogQuoted() ), Identifier.toIdentifier( userDefinedType.getSchema(), userDefinedType.isSchemaQuoted() ), userDefinedType.getNameIdentifier() ); dropType.append( context.format( typeName ) ); if ( dialect.supportsIfExistsAfterTypeName() ) { dropType.append( " if exists" ); } return new String[] { dropType.toString() }; } public String[] getSqlDropStrings(UserDefinedArrayType userDefinedType, Metadata metadata, SqlStringGenerationContext context) { throw new IllegalArgumentException( "Exporter does not support name array types. Can't generate drop strings for: " + userDefinedType ); } }
StandardUserDefinedTypeExporter
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/test/java/org/apache/hadoop/yarn/server/router/webapp/TestRouterWebServices.java
{ "start": 3372, "end": 3453 }
class ____ validate the WebService interceptor model inside the Router. */ public
to
java
spring-projects__spring-boot
module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/servlet/DocumentRootTests.java
{ "start": 1047, "end": 2590 }
class ____ { @TempDir @SuppressWarnings("NullAway.Init") File tempDir; private final DocumentRoot documentRoot = new DocumentRoot(LogFactory.getLog(getClass())); @Test void explodedWarFileDocumentRootWhenRunningFromExplodedWar() throws Exception { File codeSourceFile = new File(this.tempDir, "test.war/WEB-INF/lib/spring-boot.jar"); codeSourceFile.getParentFile().mkdirs(); codeSourceFile.createNewFile(); File directory = this.documentRoot.getExplodedWarFileDocumentRoot(codeSourceFile); assertThat(directory).isEqualTo(codeSourceFile.getParentFile().getParentFile().getParentFile()); } @Test void explodedWarFileDocumentRootWhenRunningFromPackagedWar() { File codeSourceFile = new File(this.tempDir, "test.war"); File directory = this.documentRoot.getExplodedWarFileDocumentRoot(codeSourceFile); assertThat(directory).isNull(); } @Test void codeSourceArchivePath() throws Exception { CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), (Certificate[]) null); File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/some/test/path/")); } @Test void codeSourceArchivePathContainingSpaces() throws Exception { CodeSource codeSource = new CodeSource(new URL("file", "", "/test/path/with%20space/"), (Certificate[]) null); File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource); assertThat(codeSourceArchive).isEqualTo(new File("/test/path/with space/")); } }
DocumentRootTests
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestScopedControllerAdviceIntegrationTests.java
{ "start": 2379, "end": 2579 }
class ____ { @Bean @RequestScope RequestScopedControllerAdvice requestScopedControllerAdvice() { return new RequestScopedControllerAdvice(); } } @ControllerAdvice @Order(42) static
Config
java
quarkusio__quarkus
extensions/hal/runtime/src/main/java/io/quarkus/hal/HalCollectionWrapper.java
{ "start": 482, "end": 1264 }
class ____<T> extends HalWrapper { private final Collection<HalEntityWrapper<T>> collection; private final String collectionName; public HalCollectionWrapper(Collection<HalEntityWrapper<T>> collection, String collectionName, Link... links) { this(collection, collectionName, new HashMap<>()); addLinks(links); } public HalCollectionWrapper(Collection<HalEntityWrapper<T>> collection, String collectionName, Map<String, HalLink> links) { super(links); this.collection = collection; this.collectionName = collectionName; } public Collection<HalEntityWrapper<T>> getCollection() { return collection; } public String getCollectionName() { return collectionName; } }
HalCollectionWrapper
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/varia/DenyAllFilter.java
{ "start": 1197, "end": 2126 }
class ____ extends Filter { /** * Always returns the integer constant {@link Filter#DENY} regardless of the {@link LoggingEvent} parameter. * * @param event The LoggingEvent to filter. * @return Always returns {@link Filter#DENY}. */ @Override public int decide(final LoggingEvent event) { return Filter.DENY; } /** * Returns <code>null</code> as there are no options. * * @deprecated We now use JavaBeans introspection to configure components. Options strings are no longer needed. */ @Deprecated public String[] getOptionStrings() { return null; } /** * No options to set. * * @deprecated Use the setter method for the option directly instead of the generic <code>setOption</code> method. */ @Deprecated public void setOption(final String key, final String value) { // noop } }
DenyAllFilter
java
spring-projects__spring-framework
spring-orm/src/main/java/org/springframework/orm/jpa/hibernate/LocalSessionFactoryBuilder.java
{ "start": 4049, "end": 4640 }
interface ____ well now. * * <p>This builder supports Hibernate {@code BeanContainer} integration, * {@link MetadataSources} from custom {@link BootstrapServiceRegistryBuilder} * setup, as well as other advanced Hibernate configuration options beyond the * standard JPA bootstrap contract. * * @author Juergen Hoeller * @since 7.0 * @see HibernateTransactionManager * @see LocalSessionFactoryBean * @see #setBeanContainer * @see #LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources) * @see BootstrapServiceRegistryBuilder */ @SuppressWarnings("serial") public
as
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/filter/ProblemHandlerTest.java
{ "start": 1010, "end": 1437 }
class ____ extends DeserializationProblemHandler { protected final Object key; public WeirdKeyHandler(Object key0) { key = key0; } @Override public Object handleWeirdKey(DeserializationContext ctxt, Class<?> rawKeyType, String keyValue, String failureMsg) { return key; } } static
WeirdKeyHandler
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/main/java/org/springframework/boot/webmvc/test/autoconfigure/AutoConfigureMockMvc.java
{ "start": 2864, "end": 3591 }
interface ____ { /** * The URL that should be used when expanding relative paths. * @return the URL used to expand relative paths */ String url() default "http://localhost"; /** * If a {@link WebClient} should be auto-configured when HtmlUnit is on the * classpath. Defaults to {@code true}. * @return if a {@link WebClient} is auto-configured */ @PropertyMapping("webclient.enabled") boolean webClient() default true; /** * If a {@link WebDriver} should be auto-configured when Selenium is on the * classpath. Defaults to {@code true}. * @return if a {@link WebDriver} is auto-configured */ @PropertyMapping("webdriver.enabled") boolean webDriver() default true; } }
HtmlUnit
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-common/deployment/src/main/java/io/quarkus/resteasy/reactive/common/deployment/AggregatedParameterContainersBuildItem.java
{ "start": 176, "end": 839 }
class ____ extends SimpleBuildItem { /** * This contains all the parameter containers (bean param classes and records) as well as resources/endpoints */ private final Set<DotName> classNames; /** * This contains all the non-record parameter containers (bean param classes only) as well as resources/endpoints */ private final Set<DotName> nonRecordClassNames; public AggregatedParameterContainersBuildItem(Set<DotName> classNames, Set<DotName> nonRecordClassNames) { this.classNames = classNames; this.nonRecordClassNames = nonRecordClassNames; } /** * All
AggregatedParameterContainersBuildItem
java
spring-projects__spring-security
test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java
{ "start": 4188, "end": 8073 }
class ____ { @Autowired WebApplicationContext context; MockMvc mvc; @BeforeEach public void setup() { // @formatter:off this.mvc = MockMvcBuilders .webAppContextSetup(this.context) .apply(springSecurity()) .build(); // @formatter:on } @AfterEach public void cleanup() { TestSecurityContextHolder.clearContext(); } @Test public void oauth2ClientWhenUsingDefaultsThenException() throws Exception { assertThatIllegalArgumentException() .isThrownBy(() -> oauth2Client().postProcessRequest(new MockHttpServletRequest())) .withMessageContaining("ClientRegistration"); } @Test public void oauth2ClientWhenUsingDefaultsThenProducesDefaultAuthorizedClient() throws Exception { this.mvc.perform(get("/access-token").with(oauth2Client("registration-id"))) .andExpect(content().string("access-token")); this.mvc.perform(get("/client-id").with(oauth2Client("registration-id"))) .andExpect(content().string("test-client")); } @Test public void oauth2ClientWhenClientRegistrationThenUses() throws Exception { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() .registrationId("registration-id") .clientId("client-id") .build(); this.mvc.perform(get("/client-id").with(oauth2Client().clientRegistration(clientRegistration))) .andExpect(content().string("client-id")); } @Test public void oauth2ClientWhenClientRegistrationConsumerThenUses() throws Exception { this.mvc .perform(get("/client-id") .with(oauth2Client("registration-id").clientRegistration((c) -> c.clientId("client-id")))) .andExpect(content().string("client-id")); } @Test public void oauth2ClientWhenPrincipalNameThenUses() throws Exception { this.mvc.perform(get("/principal-name").with(oauth2Client("registration-id").principalName("test-subject"))) .andExpect(content().string("test-subject")); } @Test public void oauth2ClientWhenAccessTokenThenUses() throws Exception { OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes(); this.mvc.perform(get("/access-token").with(oauth2Client("registration-id").accessToken(accessToken))) .andExpect(content().string("no-scopes")); } @Test public void oauth2ClientWhenUsedOnceThenDoesNotAffectRemainingTests() throws Exception { this.mvc.perform(get("/client-id").with(oauth2Client("registration-id"))) .andExpect(content().string("test-client")); OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(), "sub", TestOAuth2AccessTokens.noScopes()); OAuth2AuthorizedClientRepository repository = this.context.getBean(OAuth2AuthorizedClientRepository.class); given(repository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(HttpServletRequest.class))) .willReturn(client); this.mvc.perform(get("/client-id")).andExpect(content().string("client-id")); verify(repository).loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(HttpServletRequest.class)); } // gh-13113 @Test public void oauth2ClientWhenUsedThenSetsClientToRepository() throws Exception { HttpServletRequest request = this.mvc.perform(get("/client-id").with(oauth2Client("registration-id"))) .andExpect(content().string("test-client")) .andReturn() .getRequest(); OAuth2AuthorizedClientManager manager = this.context.getBean(OAuth2AuthorizedClientManager.class); OAuth2AuthorizedClientRepository repository = (OAuth2AuthorizedClientRepository) ReflectionTestUtils .getField(manager, "authorizedClientRepository"); assertThat(repository).isInstanceOf(TestOAuth2AuthorizedClientRepository.class); assertThat((OAuth2AuthorizedClient) repository.loadAuthorizedClient("id", null, request)).isNotNull(); } @Configuration @EnableWebSecurity @EnableWebMvc static
SecurityMockMvcRequestPostProcessorsOAuth2ClientTests
java
apache__flink
flink-metrics/flink-metrics-datadog/src/main/java/org/apache/flink/metrics/datadog/DGauge.java
{ "start": 972, "end": 1346 }
class ____ extends DMetric { private final Gauge<Number> gauge; public DGauge(Gauge<Number> g, String metricName, String host, List<String> tags, Clock clock) { super(new MetricMetaData(MetricType.gauge, metricName, host, tags, clock)); gauge = g; } @Override public Number getMetricValue() { return gauge.getValue(); } }
DGauge
java
google__auto
service/annotations/src/main/java/com/google/auto/service/AutoService.java
{ "start": 1126, "end": 1351 }
class ____ conform to the service provider specification. Specifically, it must: * * <ul> * <li>be a non-inner, non-anonymous, concrete class * <li>have a publicly accessible no-arg constructor * <li>implement the
must
java
apache__flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/NFASerializerUpgradeTest.java
{ "start": 6437, "end": 7423 }
class ____ implements TypeSerializerUpgradeTestBase.UpgradeVerifier<NodeId> { @Override public TypeSerializer<NodeId> createUpgradedSerializer() { return new NodeId.NodeIdSerializer(); } @Override public Condition<NodeId> testDataCondition() { return new Condition<>( value -> value.equals(new NodeId(new EventId(42, 42L), "ciao")), "is 42"); } @Override public Condition<TypeSerializerSchemaCompatibility<NodeId>> schemaCompatibilityCondition( FlinkVersion version) { return TypeSerializerConditions.isCompatibleAsIs(); } } // ---------------------------------------------------------------------------------------------- // Specification for "dewey-number-serializer" // ---------------------------------------------------------------------------------------------- /** * This
NodeIdSerializerVerifier
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/IncompatibleModifiersChecker.java
{ "start": 2119, "end": 4207 }
class ____ extends BugChecker implements AnnotationTreeMatcher { private static final String INCOMPATIBLE_MODIFIERS = "com.google.errorprone.annotations.IncompatibleModifiers"; @Override public Description matchAnnotation(AnnotationTree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (sym == null) { return NO_MATCH; } Attribute.Compound annotation = sym.getRawAttributes().stream() .filter(a -> a.type.tsym.getQualifiedName().contentEquals(INCOMPATIBLE_MODIFIERS)) .findAny() .orElse(null); if (annotation == null) { return NO_MATCH; } Set<Modifier> incompatibleModifiers = new LinkedHashSet<>(); getValue(annotation, "value").ifPresent(a -> getModifiers(incompatibleModifiers, a)); getValue(annotation, "modifier").ifPresent(a -> getModifiers(incompatibleModifiers, a)); if (incompatibleModifiers.isEmpty()) { return NO_MATCH; } Tree parent = state.getPath().getParentPath().getLeaf(); if (!(parent instanceof ModifiersTree modifiersTree)) { // e.g. An annotated package name return NO_MATCH; } Set<Modifier> incompatible = Sets.intersection(incompatibleModifiers, modifiersTree.getFlags()); if (incompatible.isEmpty()) { return NO_MATCH; } String annotationName = ASTHelpers.getAnnotationName(tree); String nameString = annotationName != null ? String.format("The annotation '@%s'", annotationName) : "This annotation"; String message = String.format( "%s has specified that it should not be used together with the following modifiers: %s", nameString, incompatible); return buildDescription(tree) .addFix( SuggestedFixes.removeModifiers(modifiersTree, state, incompatible) .orElse(SuggestedFix.emptyFix())) .setMessage(message) .build(); } private static void getModifiers(Collection<Modifier> modifiers, Attribute attribute) {
IncompatibleModifiersChecker
java
apache__camel
components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/NettyHttpSendDynamicAware.java
{ "start": 995, "end": 1061 }
class ____ extends HttpSendDynamicAware { }
NettyHttpSendDynamicAware
java
apache__camel
components/camel-flatpack/src/generated/java/org/apache/camel/dataformat/flatpack/FlatpackDataFormatConfigurer.java
{ "start": 730, "end": 4698 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("AllowShortLines", boolean.class); map.put("Definition", java.lang.String.class); map.put("Delimiter", char.class); map.put("Fixed", boolean.class); map.put("IgnoreExtraColumns", boolean.class); map.put("IgnoreFirstRecord", boolean.class); map.put("ParserFactory", net.sf.flatpack.ParserFactory.class); map.put("TextQualifier", char.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { FlatpackDataFormat target = (FlatpackDataFormat) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "allowshortlines": case "allowShortLines": target.setAllowShortLines(property(camelContext, boolean.class, value)); return true; case "definition": target.setDefinition(property(camelContext, java.lang.String.class, value)); return true; case "delimiter": target.setDelimiter(property(camelContext, char.class, value)); return true; case "fixed": target.setFixed(property(camelContext, boolean.class, value)); return true; case "ignoreextracolumns": case "ignoreExtraColumns": target.setIgnoreExtraColumns(property(camelContext, boolean.class, value)); return true; case "ignorefirstrecord": case "ignoreFirstRecord": target.setIgnoreFirstRecord(property(camelContext, boolean.class, value)); return true; case "parserfactory": case "parserFactory": target.setParserFactory(property(camelContext, net.sf.flatpack.ParserFactory.class, value)); return true; case "textqualifier": case "textQualifier": target.setTextQualifier(property(camelContext, char.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "allowshortlines": case "allowShortLines": return boolean.class; case "definition": return java.lang.String.class; case "delimiter": return char.class; case "fixed": return boolean.class; case "ignoreextracolumns": case "ignoreExtraColumns": return boolean.class; case "ignorefirstrecord": case "ignoreFirstRecord": return boolean.class; case "parserfactory": case "parserFactory": return net.sf.flatpack.ParserFactory.class; case "textqualifier": case "textQualifier": return char.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { FlatpackDataFormat target = (FlatpackDataFormat) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "allowshortlines": case "allowShortLines": return target.isAllowShortLines(); case "definition": return target.getDefinition(); case "delimiter": return target.getDelimiter(); case "fixed": return target.isFixed(); case "ignoreextracolumns": case "ignoreExtraColumns": return target.isIgnoreExtraColumns(); case "ignorefirstrecord": case "ignoreFirstRecord": return target.isIgnoreFirstRecord(); case "parserfactory": case "parserFactory": return target.getParserFactory(); case "textqualifier": case "textQualifier": return target.getTextQualifier(); default: return null; } } }
FlatpackDataFormatConfigurer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/exec/manytoone/ManyToOneTest.java
{ "start": 11923, "end": 12307 }
class ____ { private Integer id; private String name; @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity(name = "AnotherSimpleEntity") @Table(name = "another_simple_entity") public static
SimpleEntity
java
apache__camel
components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpBindingModeJsonWithContractTest.java
{ "start": 1367, "end": 3301 }
class ____ extends BaseUndertowTest { @Test public void testBindingModeJsonWithContract() throws Exception { MockEndpoint mock = getMockEndpoint("mock:input"); mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(UserPojoEx.class); String body = "{\"id\": 123, \"name\": \"Donald Duck\"}"; Object answer = template.requestBody("undertow:http://localhost:{{port}}/users/new", body); assertNotNull(answer); String answerString = new String((byte[]) answer); assertTrue(answerString.contains("\"active\":true"), "Unexpected response: " + answerString); MockEndpoint.assertIsSatisfied(context); Object obj = mock.getReceivedExchanges().get(0).getIn().getBody(); assertEquals(UserPojoEx.class, obj.getClass()); UserPojoEx user = (UserPojoEx) obj; assertNotNull(user); assertEquals(123, user.getId()); assertEquals("Donald Duck", user.getName()); assertEquals(true, user.isActive()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.getTypeConverterRegistry().addTypeConverters(new MyTypeConverters()); restConfiguration().component("undertow").host("localhost").port(getPort()).bindingMode(RestBindingMode.json); rest("/users/") // REST binding converts from JSON to UserPojo .post("new").type(UserPojo.class) .to("direct:new"); from("direct:new") // then contract advice converts from UserPojo to UserPojoEx .inputType(UserPojoEx.class) .to("mock:input"); } }; } public static
RestUndertowHttpBindingModeJsonWithContractTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/ReloadWithPreviousRowEntityTest3.java
{ "start": 3354, "end": 4228 }
class ____ { private Integer id; private Set<Student> students = new HashSet<>(); private Set<Skill> skills = new HashSet<>(); public Teacher() { } public Teacher(Integer id) { this.id = id; } @Id @Column(name = "teacher_id") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @OneToMany(mappedBy = "teacher") public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } public void addStudent(Student student) { students.add( student ); } @ManyToMany public Set<Skill> getSkills() { return skills; } public void addSkill(Skill skill) { skills.add( skill ); } public void setSkills(Set<Skill> skills) { this.skills = skills; } } @Entity(name = "Skill") public static
Teacher
java
grpc__grpc-java
services/src/generated/test/grpc/io/grpc/reflection/testing/AnotherReflectableServiceGrpc.java
{ "start": 5461, "end": 5847 }
class ____ implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return AnotherReflectableServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service AnotherReflectableService. */ public static final
AnotherReflectableServiceImplBase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/onetoone/Body.java
{ "start": 352, "end": 655 }
class ____ { private Integer id; private Heart heart; @OneToOne @PrimaryKeyJoinColumn public Heart getHeart() { return heart; } public void setHeart(Heart heart) { this.heart = heart; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
Body
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/protobuf/PatchedProtoWriteSupport.java
{ "start": 28304, "end": 28484 }
class ____ extends FieldWriter { @Override final void writeRawValue(Object value) { recordConsumer.addFloat((Float) value); } }
FloatWriter
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/condition/Condition.java
{ "start": 537, "end": 667 }
interface ____ extends ToXContentObject { /** * @return the type of this condition */ String type();
Condition
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/updatemethods/ConstructableDepartmentEntity.java
{ "start": 238, "end": 379 }
class ____ extends DepartmentEntity { public ConstructableDepartmentEntity() { super( null ); } }
ConstructableDepartmentEntity
java
quarkusio__quarkus
extensions/websockets-next/spi/src/main/java/io/quarkus/websockets/next/runtime/spi/security/WebSocketIdentityUpdateRequest.java
{ "start": 480, "end": 1118 }
class ____ extends BaseAuthenticationRequest { private final TokenCredential credential; private final SecurityIdentity currentSecurityIdentity; public WebSocketIdentityUpdateRequest(TokenCredential credential, SecurityIdentity currentSecurityIdentity) { this.credential = Objects.requireNonNull(credential); this.currentSecurityIdentity = Objects.requireNonNull(currentSecurityIdentity); } public TokenCredential getCredential() { return credential; } public SecurityIdentity getCurrentSecurityIdentity() { return currentSecurityIdentity; } }
WebSocketIdentityUpdateRequest
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/azureopenai/AzureOpenAiModel.java
{ "start": 1126, "end": 3867 }
class ____ extends Model { protected URI uri; private final AzureOpenAiRateLimitServiceSettings rateLimitServiceSettings; public AzureOpenAiModel( ModelConfigurations configurations, ModelSecrets secrets, AzureOpenAiRateLimitServiceSettings rateLimitServiceSettings ) { super(configurations, secrets); this.rateLimitServiceSettings = Objects.requireNonNull(rateLimitServiceSettings); } protected AzureOpenAiModel(AzureOpenAiModel model, TaskSettings taskSettings) { super(model, taskSettings); this.uri = model.getUri(); rateLimitServiceSettings = model.rateLimitServiceSettings(); } protected AzureOpenAiModel(AzureOpenAiModel model, ServiceSettings serviceSettings) { super(model, serviceSettings); this.uri = model.getUri(); rateLimitServiceSettings = model.rateLimitServiceSettings(); } public abstract ExecutableAction accept(AzureOpenAiActionVisitor creator, Map<String, Object> taskSettings); public final URI buildUriString() throws URISyntaxException { return AzureOpenAiModel.buildUri(resourceName(), deploymentId(), apiVersion(), operationPathSegments()); } // use only for testing directly public static URI buildUri(String resourceName, String deploymentId, String apiVersion, String... pathSegments) throws URISyntaxException { String hostname = format("%s.%s", resourceName, AzureOpenAiUtils.HOST_SUFFIX); return new URIBuilder().setScheme("https") .setHost(hostname) .setPathSegments(createPathSegmentsList(deploymentId, pathSegments)) .addParameter(AzureOpenAiUtils.API_VERSION_PARAMETER, apiVersion) .build(); } private static List<String> createPathSegmentsList(String deploymentId, String[] pathSegments) { List<String> pathSegmentsList = new ArrayList<>( List.of(AzureOpenAiUtils.OPENAI_PATH, AzureOpenAiUtils.DEPLOYMENTS_PATH, deploymentId) ); pathSegmentsList.addAll(Arrays.asList(pathSegments)); return pathSegmentsList; } public URI getUri() { return uri; } // Needed for testing public void setUri(URI newUri) { this.uri = newUri; } public AzureOpenAiRateLimitServiceSettings rateLimitServiceSettings() { return rateLimitServiceSettings; } // TODO: can be inferred directly from modelConfigurations.getServiceSettings(); will be addressed with separate refactoring public abstract String resourceName(); public abstract String deploymentId(); public abstract String apiVersion(); public abstract String[] operationPathSegments(); }
AzureOpenAiModel
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestCommandLineJobSubmission.java
{ "start": 1365, "end": 5744 }
class ____ { // Input output paths for this.. // these are all dummy and does not test // much in map reduce except for the command line // params static final Path input = new Path("/test/input/"); static final Path output = new Path("/test/output"); File buildDir = new File(System.getProperty("test.build.data", "/tmp")); @Test public void testJobShell() throws Exception { MiniDFSCluster dfs = null; MiniMRCluster mr = null; FileSystem fs = null; Path testFile = new Path(input, "testfile"); try { Configuration conf = new Configuration(); //start the mini mr and dfs cluster. dfs = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); fs = dfs.getFileSystem(); FSDataOutputStream stream = fs.create(testFile); stream.write("teststring".getBytes()); stream.close(); mr = new MiniMRCluster(2, fs.getUri().toString(), 1); File thisbuildDir = new File(buildDir, "jobCommand"); assertTrue(thisbuildDir.mkdirs(), "create build dir"); File f = new File(thisbuildDir, "files_tmp"); FileOutputStream fstream = new FileOutputStream(f); fstream.write("somestrings".getBytes()); fstream.close(); File f1 = new File(thisbuildDir, "files_tmp1"); fstream = new FileOutputStream(f1); fstream.write("somestrings".getBytes()); fstream.close(); // copy files to dfs Path cachePath = new Path("/cacheDir"); if (!fs.mkdirs(cachePath)) { throw new IOException( "Mkdirs failed to create " + cachePath.toString()); } Path localCachePath = new Path(System.getProperty("test.cache.data")); Path txtPath = new Path(localCachePath, new Path("test.txt")); Path jarPath = new Path(localCachePath, new Path("test.jar")); Path zipPath = new Path(localCachePath, new Path("test.zip")); Path tarPath = new Path(localCachePath, new Path("test.tar")); Path tgzPath = new Path(localCachePath, new Path("test.tgz")); fs.copyFromLocalFile(txtPath, cachePath); fs.copyFromLocalFile(jarPath, cachePath); fs.copyFromLocalFile(zipPath, cachePath); // construct options for -files String[] files = new String[3]; files[0] = f.toString(); files[1] = f1.toString() + "#localfilelink"; files[2] = fs.getUri().resolve(cachePath + "/test.txt#dfsfilelink").toString(); // construct options for -libjars String[] libjars = new String[2]; libjars[0] = "build/test/mapred/testjar/testjob.jar"; libjars[1] = fs.getUri().resolve(cachePath + "/test.jar").toString(); // construct options for archives String[] archives = new String[3]; archives[0] = tgzPath.toString(); archives[1] = tarPath + "#tarlink"; archives[2] = fs.getUri().resolve(cachePath + "/test.zip#ziplink").toString(); String[] args = new String[10]; args[0] = "-files"; args[1] = StringUtils.arrayToString(files); args[2] = "-libjars"; // the testjob.jar as a temporary jar file // rather than creating its own args[3] = StringUtils.arrayToString(libjars); args[4] = "-archives"; args[5] = StringUtils.arrayToString(archives); args[6] = "-D"; args[7] = "mapred.output.committer.class=testjar.CustomOutputCommitter"; args[8] = input.toString(); args[9] = output.toString(); JobConf jobConf = mr.createJobConf(); //before running the job, verify that libjar is not in client classpath assertTrue(loadLibJar(jobConf)==null, "libjar not in client classpath"); int ret = ToolRunner.run(jobConf, new testshell.ExternalMapReduce(), args); //after running the job, verify that libjar is in the client classpath assertTrue(loadLibJar(jobConf)!=null, "libjar added to client classpath"); assertTrue(ret != -1, "not failed "); f.delete(); thisbuildDir.delete(); } finally { if (dfs != null) {dfs.shutdown();}; if (mr != null) {mr.shutdown();}; } } @SuppressWarnings("unchecked") private Class loadLibJar(JobConf jobConf) { try { return jobConf.getClassByName("testjar.ClassWordCount"); } catch (ClassNotFoundException e) { return null; } } }
TestCommandLineJobSubmission
java
quarkusio__quarkus
integration-tests/devtools/src/test/java/io/quarkus/devtools/codestarts/quarkus/ReactiveRoutesCodestartTest.java
{ "start": 470, "end": 1139 }
class ____ { @RegisterExtension public static QuarkusCodestartTest codestartTest = QuarkusCodestartTest.builder() .codestarts("reactive-routes-codestart") .languages(JAVA, KOTLIN) .build(); @Test void testContent() throws Throwable { codestartTest.checkGeneratedSource("org.acme.MyDeclarativeRoutes"); codestartTest.checkGeneratedTestSource("org.acme.MyDeclarativeRoutesTest"); } @Test @EnabledIfSystemProperty(named = "build-projects", matches = "true") void buildAllProjectsForLocalUse() throws Throwable { codestartTest.buildAllProjects(); } }
ReactiveRoutesCodestartTest
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/BeforeAll.java
{ "start": 2521, "end": 2704 }
class ____ * implements the interface. * * <p>JUnit Jupiter does not guarantee the execution order of multiple * {@code @BeforeAll} methods that are declared within a single test
that
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/indices/recovery/RecoverySourceHandlerTests.java
{ "start": 82329, "end": 83661 }
class ____ { final long chunkNumber; final ActionListener<Void> listener; FileChunkResponse(long chunkNumber, ActionListener<Void> listener) { this.chunkNumber = chunkNumber; this.listener = listener; } } private List<StoreFileMetadata> generateFiles(Store store, int numFiles, IntSupplier fileSizeSupplier) throws IOException { List<StoreFileMetadata> files = new ArrayList<>(); for (int i = 0; i < numFiles; i++) { byte[] buffer = randomByteArrayOfLength(fileSizeSupplier.getAsInt()); CRC32 digest = new CRC32(); digest.update(buffer, 0, buffer.length); StoreFileMetadata md = new StoreFileMetadata( "test-" + i, buffer.length + 8, Store.digestToString(digest.getValue()), org.apache.lucene.util.Version.LATEST.toString() ); try (OutputStream out = new IndexOutputOutputStream(store.createVerifyingOutput(md.name(), md, IOContext.DEFAULT))) { out.write(buffer); out.write(Numbers.longToBytes(digest.getValue())); } store.directory().sync(Collections.singleton(md.name())); files.add(md); } return files; }
FileChunkResponse