language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java
{ "start": 6029, "end": 7604 }
interface ____ extends _Script, _Object { /** * Add a style element. * @return a style element builder */ STYLE style(); /** * Add a css style element. * @param lines content of the style sheet * @return the current element builder */ HeadMisc style(Object... lines); /** * Add a meta element. * @return a meta element builder */ META meta(); /** * Add a meta element. * Shortcut of <code>meta().$name(name).$content(content).__();</code> * @param name of the meta element * @param content of the meta element * @return the current element builder */ HeadMisc meta(String name, String content); /** * Add a meta element with http-equiv attribute. * Shortcut of <br> * <code>meta().$http_equiv(header).$content(content).__();</code> * @param header for the http-equiv attribute * @param content of the header * @return the current element builder */ HeadMisc meta_http(String header, String content); /** * Add a link element. * @return a link element builder */ LINK link(); /** * Add a link element. * Implementation should try to figure out type by the suffix of href. * So <code>link("style.css");</code> is a shortcut of * <code>link().$rel("stylesheet").$type("text/css").$href("style.css").__(); * </code> * @param href of the link * @return the current element builder */ HeadMisc link(String href); } /** %heading */ public
HeadMisc
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AnnotationPositionTest.java
{ "start": 10629, "end": 10907 }
interface ____ { public @EitherUse /** Javadoc */ @NonTypeUse String baz(); /* a */ public /* b */ @EitherUse /* c */ static /* d */ @NonTypeUse /* e */ int quux() { return 1; } } """) .addOutputLines( "Test.java", """
Test
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/beans/SyntheticInjectionPointUnavailableTest.java
{ "start": 1995, "end": 2265 }
class ____ implements BeanCreator<List<String>> { @Override public List<String> create(SyntheticCreationalContext<List<String>> context) { return List.of(context.getInjectedReference(BigDecimal.class).toString()); } } }
ListCreator
java
google__dagger
dagger-grpc-server-processor/main/java/dagger/grpc/server/processor/SourceGenerator.java
{ "start": 2852, "end": 3595 }
class ____ { private IoGrpc() {} static final ClassName BINDABLE_SERVICE = ClassName.get("io.grpc", "BindableService"); static final ClassName METADATA = ClassName.get("io.grpc", "Metadata"); static final ClassName METHOD_DESCRIPTOR = ClassName.get("io.grpc", "MethodDescriptor"); static final ClassName SERVER_INTERCEPTOR = ClassName.get("io.grpc", "ServerInterceptor"); static final ClassName SERVER_INTERCEPTORS = ClassName.get("io.grpc", "ServerInterceptors"); static final ClassName SERVER_SERVICE_DEFINITION = ClassName.get("io.grpc", "ServerServiceDefinition"); } /** Class names and annotation specs for types in the {@link javax.inject} package. */ protected static final
IoGrpc
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client-jackson/runtime/src/main/java/io/quarkus/rest/client/reactive/jackson/runtime/serialisers/ClientJacksonMessageBodyReader.java
{ "start": 1228, "end": 4255 }
class ____ extends AbstractJsonMessageBodyReader implements ClientMessageBodyReader<Object> { private static final Logger log = Logger.getLogger(ClientJacksonMessageBodyReader.class); private final ConcurrentMap<ObjectMapper, ObjectReader> objectReaderMap = new ConcurrentHashMap<>(); private final ObjectReader defaultReader; @Inject public ClientJacksonMessageBodyReader(ObjectMapper mapper) { this.defaultReader = mapper.reader(); } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { return doRead(type, genericType, mediaType, annotations, entityStream, null); } private Object doRead(Class<Object> type, Type genericType, MediaType mediaType, Annotation[] annotations, InputStream entityStream, RestClientRequestContext context) throws IOException { try { if (entityStream instanceof EmptyInputStream) { return null; } ObjectReader reader = getEffectiveReader(mediaType, annotations, context); return reader.forType(reader.getTypeFactory().constructType(genericType != null ? genericType : type)) .readValue(entityStream); } catch (JsonParseException e) { log.debug("Server returned invalid json data", e); throw new ClientWebApplicationException(e, Response.Status.OK); } } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream, RestClientRequestContext context) throws java.io.IOException, jakarta.ws.rs.WebApplicationException { return doRead(type, genericType, mediaType, annotations, entityStream, context); } private ObjectReader getEffectiveReader(MediaType responseMediaType, Annotation[] annotations, RestClientRequestContext context) { ObjectMapper effectiveMapper = getObjectMapperFromContext(responseMediaType, context); if (effectiveMapper == null) { return defaultReader; } return applyJsonViewIfPresent(objectReaderMap.computeIfAbsent(effectiveMapper, new Function<>() { @Override public ObjectReader apply(ObjectMapper objectMapper) { return objectMapper.reader(); } }), annotations); } private static ObjectReader applyJsonViewIfPresent(ObjectReader reader, Annotation[] annotations) { Optional<Class<?>> maybeView = JacksonUtil.matchingView(annotations); if (maybeView.isPresent()) { return reader.withView(maybeView.get()); } else { return reader; } } }
ClientJacksonMessageBodyReader
java
google__guice
extensions/assistedinject/src/com/google/inject/assistedinject/FactoryModuleBuilder.java
{ "start": 2808, "end": 4002 }
class ____ implements Payment { * {@literal @}AssistedInject * public RealPayment( * CreditService creditService, * AuthService authService, * <strong>{@literal @}Assisted Date startDate</strong>, * <strong>{@literal @}Assisted Money amount</strong>) { * ... * } * * {@literal @}AssistedInject * public RealPayment( * CreditService creditService, * AuthService authService, * <strong>{@literal @}Assisted Money amount</strong>) { * ... * } * }</pre> * * <h3>Configuring simple factories</h3> * * In your {@link Module module}, install a {@code FactoryModuleBuilder} that creates the factory: * * <pre>install(new FactoryModuleBuilder() * .implement(Payment.class, RealPayment.class) * .build(PaymentFactory.class));</pre> * * As a side-effect of this binding, Guice will inject the factory to initialize it for use. The * factory cannot be used until the injector has been initialized. * * <h3>Configuring complex factories</h3> * * Factories can create an arbitrary number of objects, one per each method. Each factory method can * be configured using <code>.implement</code>. * * <pre>public
RealPayment
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/indexing/IndexerJobStats.java
{ "start": 631, "end": 935 }
class ____ the runtime statistics of a job. The stats are not used by any internal process * and are only for external monitoring/reference. Statistics are not persisted with the job, so if the * allocated task is shutdown/restarted on a different node all the stats will reset. */ public abstract
holds
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/StreamUtils.java
{ "start": 1054, "end": 1464 }
class ____ similar to those defined in * {@link FileCopyUtils} except that all affected streams are left open when done. * All copy methods use a block size of {@value #BUFFER_SIZE} bytes. * * <p>Mainly for use within the framework, but also useful for application code. * * @author Juergen Hoeller * @author Phillip Webb * @author Brian Clozel * @since 3.2.2 * @see FileCopyUtils */ public abstract
are
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/event/ReactiveTransactionalEventListenerTests.java
{ "start": 15556, "end": 16536 }
class ____ extends BaseTransactionalTestListener { @TransactionalEventListener(phase = BEFORE_COMMIT, fallbackExecution = true) public void handleBeforeCommit(String data) { handleEvent(EventCollector.BEFORE_COMMIT, data); } @TransactionalEventListener(phase = AFTER_COMMIT, fallbackExecution = true) public void handleAfterCommit(String data) { handleEvent(EventCollector.AFTER_COMMIT, data); } @TransactionalEventListener(phase = AFTER_ROLLBACK, fallbackExecution = true) public void handleAfterRollback(String data) { handleEvent(EventCollector.AFTER_ROLLBACK, data); } @TransactionalEventListener(phase = AFTER_COMPLETION, fallbackExecution = true) public void handleAfterCompletion(String data) { handleEvent(EventCollector.AFTER_COMPLETION, data); } } @TransactionalEventListener(phase = AFTER_COMMIT, condition = "!'SKIP'.equals(#p0)") @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @
FallbackExecutionTestListener
java
greenrobot__greendao
examples/DaoExample/src/main/java/org/greenrobot/greendao/example/App.java
{ "start": 911, "end": 1615 }
class ____ extends DaoMaster.OpenHelper { public ExampleOpenHelper(Context context, String name) { super(context, name); } @Override public void onCreate(Database db) { super.onCreate(db); // Insert some example data. // INSERT INTO NOTE (_id, DATE, TEXT) VALUES(1, 0, 'Example Note') db.execSQL("INSERT INTO " + NoteDao.TABLENAME + " (" + NoteDao.Properties.Id.columnName + ", " + NoteDao.Properties.Date.columnName + ", " + NoteDao.Properties.Text.columnName + ") VALUES(1, 0, 'Example Note')"); } } }
ExampleOpenHelper
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/expressions/resolver/ExpressionResolver.java
{ "start": 15459, "end": 17974 }
class ____ { public CallExpression as(ResolvedExpression expression, String alias) { return createCallExpression( BuiltInFunctionDefinitions.AS, Arrays.asList(expression, valueLiteral(alias)), expression.getOutputDataType()); } public CallExpression cast(ResolvedExpression expression, DataType dataType) { return createCallExpression( BuiltInFunctionDefinitions.CAST, Arrays.asList(expression, typeLiteral(dataType)), dataType); } public CallExpression row(DataType dataType, ResolvedExpression... expression) { return createCallExpression( BuiltInFunctionDefinitions.ROW, Arrays.asList(expression), dataType); } public CallExpression array(DataType dataType, ResolvedExpression... expression) { return createCallExpression( BuiltInFunctionDefinitions.ARRAY, Arrays.asList(expression), dataType); } public CallExpression map(DataType dataType, ResolvedExpression... expression) { return createCallExpression( BuiltInFunctionDefinitions.MAP, Arrays.asList(expression), dataType); } public CallExpression wrappingCall( BuiltInFunctionDefinition definition, ResolvedExpression expression) { return createCallExpression( definition, Collections.singletonList(expression), expression.getOutputDataType()); // the output type is equal to the input type } public CallExpression get( ResolvedExpression composite, ValueLiteralExpression key, DataType dataType) { return createCallExpression( BuiltInFunctionDefinitions.GET, Arrays.asList(composite, key), dataType); } private CallExpression createCallExpression( BuiltInFunctionDefinition builtInDefinition, List<ResolvedExpression> resolvedArgs, DataType outputDataType) { final ContextResolvedFunction resolvedFunction = functionLookup.lookupBuiltInFunction(builtInDefinition); return resolvedFunction.toCallExpression(resolvedArgs, outputDataType); } } /** Builder for creating {@link ExpressionResolver}. */ @Internal public static
PostResolverFactory
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/qualifiers/compose/ThirdThing.java
{ "start": 703, "end": 808 }
class ____ implements Thing { @Override public int getNumber() { return 3; } }
ThirdThing
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/test/TestValueResolver.java
{ "start": 144, "end": 301 }
class ____ implements ValueResolver { @Override public String resolve(Object parameter) { return "prefix_" + parameter; } }
TestValueResolver
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/util/reflection/FieldInitializer.java
{ "start": 8719, "end": 13798 }
class ____ implements ConstructorInstantiator { private final Object testClass; private final Field field; private final ConstructorArgumentResolver argResolver; private final Comparator<Constructor<?>> byParameterNumber = new Comparator<Constructor<?>>() { @Override public int compare(Constructor<?> constructorA, Constructor<?> constructorB) { int argLengths = constructorB.getParameterTypes().length - constructorA.getParameterTypes().length; if (argLengths == 0) { int constructorAMockableParamsSize = countMockableParams(constructorA); int constructorBMockableParamsSize = countMockableParams(constructorB); return constructorBMockableParamsSize - constructorAMockableParamsSize; } return argLengths; } private int countMockableParams(Constructor<?> constructor) { int constructorMockableParamsSize = 0; for (Class<?> aClass : constructor.getParameterTypes()) { // The argResolver already knows the concrete types it can provide. // Instead of checking for mockability, I think it would be better to // ask the argResolver whether it can resolve this type. // Anyway, I keep it for now to avoid breaking any existing code. if (MockUtil.typeMockabilityOf(aClass, null).mockable()) { constructorMockableParamsSize++; } } return constructorMockableParamsSize; } }; /** * Internal, checks are done by FieldInitializer. * Fields are assumed to be accessible. */ ParameterizedConstructorInstantiator( Object testClass, Field field, ConstructorArgumentResolver argumentResolver) { this.testClass = testClass; this.field = field; this.argResolver = argumentResolver; } @Override public FieldInitializationReport instantiate() { final MemberAccessor accessor = Plugins.getMemberAccessor(); Constructor<?> constructor = biggestConstructor(field.getType()); final Object[] args = argResolver.resolveTypeInstances(constructor.getParameterTypes()); try { Object newFieldInstance = accessor.newInstance(constructor, args); accessor.set(field, testClass, newFieldInstance); return new FieldInitializationReport(accessor.get(field, testClass), false, true); } catch (IllegalArgumentException e) { throw new MockitoException( "internal error : argResolver provided incorrect types for constructor " + constructor + " of type " + field.getType().getSimpleName(), e); } catch (InvocationTargetException e) { throw new MockitoException( "the constructor of type '" + field.getType().getSimpleName() + "' has raised an exception (see the stack trace for cause): " + e.getTargetException(), e); } catch (InstantiationException e) { throw new MockitoException( "InstantiationException (see the stack trace for cause): " + e, e); } catch (IllegalAccessException e) { throw new MockitoException( "IllegalAccessException (see the stack trace for cause): " + e, e); } } private void checkParameterized(Constructor<?> constructor, Field field) { if (constructor.getParameterTypes().length == 0) { throw new MockitoException( "the field " + field.getName() + " of type " + field.getType() + " has no parameterized constructor"); } } private Constructor<?> biggestConstructor(Class<?> clazz) { final List<? extends Constructor<?>> constructors = Arrays.asList(clazz.getDeclaredConstructors()); Collections.sort(constructors, byParameterNumber); Constructor<?> constructor = constructors.get(0); checkParameterized(constructor, field); return constructor; } } }
ParameterizedConstructorInstantiator
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/destination/DestinationClassNameWithJsr330Mapper.java
{ "start": 435, "end": 518 }
interface ____ { Target map(Integer source); }
DestinationClassNameWithJsr330Mapper
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/transformer/NonstaticExceptionTransformerTest.java
{ "start": 545, "end": 1550 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(MyService.class) .beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> { MethodInfo method = bean.getImplClazz().firstMethod("hello"); invokers.put(method.name(), factory.createInvoker(bean, method) .withExceptionTransformer(Exception.class, "getMessage") .build()); })) .build(); @Test public void test() throws Exception { InvokerHelper helper = Arc.container().instance(InvokerHelper.class).get(); InstanceHandle<MyService> service = Arc.container().instance(MyService.class); Invoker<MyService, String> hello = helper.getInvoker("hello"); assertEquals("foobar", hello.invoke(service.get(), new Object[] { "quux" })); } @Singleton static
NonstaticExceptionTransformerTest
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/SpringEndpointRegistrationTest.java
{ "start": 1520, "end": 1927 }
class ____ extends ClassPathXmlApplicationContext { public NoRebindClassPathXmlApplicationContext(String configLocation) throws BeansException { super((ApplicationContext) null); this.setAllowBeanDefinitionOverriding(false); this.setConfigLocations(new String[] { configLocation }); this.refresh(); } } }
NoRebindClassPathXmlApplicationContext
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/http/sender/ChatCompletionInput.java
{ "start": 908, "end": 1403 }
class ____ extends InferenceInputs { private final List<String> input; public ChatCompletionInput(List<String> input) { this(input, false); } public ChatCompletionInput(List<String> input, boolean stream) { super(stream); this.input = Objects.requireNonNull(input); } public List<String> getInputs() { return this.input; } @Override public boolean isSingleInput() { return input.size() == 1; } }
ChatCompletionInput
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/xslt/XsltCustomErrorListenerTest.java
{ "start": 1405, "end": 3079 }
class ____ implements ErrorListener { private boolean warning; private boolean error; private boolean fatalError; @Override public void warning(TransformerException exception) throws TransformerException { warning = true; } @Override public void error(TransformerException exception) throws TransformerException { error = true; } @Override public void fatalError(TransformerException exception) throws TransformerException { fatalError = true; } public boolean isWarning() { return warning; } public boolean isError() { return error; } public boolean isFatalError() { return fatalError; } } @Test public void testErrorListener() throws Exception { RouteBuilder builder = createRouteBuilder(); CamelContext context = new DefaultCamelContext(); context.getRegistry().bind("myListener", listener); context.addRoutes(builder); assertThrows(RuntimeCamelException.class, () -> context.start()); assertFalse(listener.isWarning()); assertTrue(listener.isError(), "My error listener should been invoked"); assertTrue(listener.isFatalError(), "My error listener should been invoked"); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("seda:a").to("xslt:org/apache/camel/builder/xml/example-with-errors.xsl?errorListener=#myListener"); } }; } }
MyErrorListener
java
elastic__elasticsearch
x-pack/plugin/spatial/src/internalClusterTest/java/org/elasticsearch/xpack/spatial/search/CartesianShapeQueryTests.java
{ "start": 476, "end": 835 }
class ____ extends CartesianShapeQueryTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return Collections.singleton(LocalStateSpatialPlugin.class); } @Override public void testQueryRandomGeoCollection() throws Exception { super.testQueryRandomGeoCollection(); } }
CartesianShapeQueryTests
java
apache__camel
components/camel-thymeleaf/src/test/java/org/apache/camel/component/thymeleaf/ThymeleafWebApplicationResolverAllParamsTest.java
{ "start": 1785, "end": 7111 }
class ____ extends ThymeleafAbstractBaseTest { private static final String TEST_ENDPOINT = "testEndpoint"; private ServletContext servletContext; private JakartaServletWebApplication jakartaServletWebApplication; @Override public void doPostSetup() throws Exception { File initialFile = new File("src/test/resources/WEB-INF/templates/letter.html"); InputStream targetStream = FileUtils.openInputStream(initialFile); Mockito.when(servletContext.getResourceAsStream(anyString())).thenReturn(targetStream); Mockito.when(servletContext.getResource(anyString())).thenReturn(new URL("http://localhost/letter.html")); } @Test public void testThymeleaf() throws InterruptedException { MockEndpoint mock = getMockEndpoint(MOCK_RESULT); mock.expectedMessageCount(1); mock.message(0).body().contains(THANK_YOU_FOR_YOUR_ORDER); mock.message(0).body().endsWith(SPAZZ_TESTING_SERVICE); mock.message(0).header(ThymeleafConstants.THYMELEAF_TEMPLATE).isNull(); mock.message(0).header(ThymeleafConstants.THYMELEAF_VARIABLE_MAP).isNull(); mock.message(0).header(FIRST_NAME).isEqualTo(JANE); template.request(DIRECT_START, basicHeaderProcessor); mock.assertIsSatisfied(); ThymeleafEndpoint thymeleafEndpoint = context.getEndpoint(TEST_ENDPOINT, ThymeleafEndpoint.class); assertAll("properties", () -> assertNotNull(thymeleafEndpoint), () -> assertTrue(thymeleafEndpoint.isAllowContextMapAll()), () -> assertTrue(thymeleafEndpoint.getCacheable()), () -> assertEquals(CACHE_TIME_TO_LIVE, thymeleafEndpoint.getCacheTimeToLive()), () -> assertTrue(thymeleafEndpoint.getCheckExistence()), () -> assertEquals(UTF_8_ENCODING, thymeleafEndpoint.getEncoding()), () -> assertEquals(ExchangePattern.InOut, thymeleafEndpoint.getExchangePattern()), () -> assertEquals(ORDER, thymeleafEndpoint.getOrder()), () -> assertEquals(PREFIX_WEB_INF_TEMPLATES, thymeleafEndpoint.getPrefix()), () -> assertEquals(ThymeleafResolverType.WEB_APP, thymeleafEndpoint.getResolver()), () -> assertEquals(HTML_SUFFIX, thymeleafEndpoint.getSuffix()), () -> assertNotNull(thymeleafEndpoint.getTemplateEngine()), () -> assertEquals(HTML, thymeleafEndpoint.getTemplateMode())); assertEquals(1, thymeleafEndpoint.getTemplateEngine().getTemplateResolvers().size()); ITemplateResolver resolver = thymeleafEndpoint.getTemplateEngine().getTemplateResolvers().stream().findFirst().get(); assertTrue(resolver instanceof WebApplicationTemplateResolver); WebApplicationTemplateResolver templateResolver = (WebApplicationTemplateResolver) resolver; assertAll("templateResolver", () -> assertTrue(templateResolver.isCacheable()), () -> assertEquals(CACHE_TIME_TO_LIVE, templateResolver.getCacheTTLMs()), () -> assertEquals(UTF_8_ENCODING, templateResolver.getCharacterEncoding()), () -> assertTrue(templateResolver.getCheckExistence()), () -> assertEquals(ORDER, templateResolver.getOrder()), () -> assertEquals(PREFIX_WEB_INF_TEMPLATES, templateResolver.getPrefix()), () -> assertEquals(HTML_SUFFIX, templateResolver.getSuffix()), () -> assertEquals(TemplateMode.HTML, templateResolver.getTemplateMode())); } private ServletContext servletContext() { if (servletContext == null) { servletContext = mock(ServletContext.class); } return servletContext; } private JakartaServletWebApplication jakartaServletWebApplication() { if (jakartaServletWebApplication == null) { jakartaServletWebApplication = JakartaServletWebApplication.buildApplication(servletContext()); } return jakartaServletWebApplication; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() throws Exception { ThymeleafEndpoint endpoint = new ThymeleafEndpoint(); endpoint.setCamelContext(context); endpoint.setJakartaServletWebApplication(jakartaServletWebApplication()); endpoint.setAllowContextMapAll(true); endpoint.setResourceUri("letter"); endpoint.setPrefix("WEB-INF/templates/"); endpoint.setSuffix(".html"); endpoint.setResolver(ThymeleafResolverType.WEB_APP); endpoint.setCacheable(true); endpoint.setCacheTimeToLive(500L); endpoint.setEncoding("UTF-8"); endpoint.setCheckExistence(true); endpoint.setOrder(1); endpoint.setTemplateMode("HTML"); context.addEndpoint(TEST_ENDPOINT, endpoint); from(DIRECT_START) .setBody(simple(SPAZZ_TESTING_SERVICE)) .to(TEST_ENDPOINT) .to(MOCK_RESULT); } }; } }
ThymeleafWebApplicationResolverAllParamsTest
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/pkg/TestNativeConfig.java
{ "start": 172, "end": 4019 }
class ____ implements NativeConfig { private final NativeConfig.BuilderImageConfig builderImage; public TestNativeConfig(String builderImage) { this(builderImage, ImagePullStrategy.ALWAYS); } public TestNativeConfig(ImagePullStrategy builderImagePull) { this("mandrel", builderImagePull); } public TestNativeConfig(String builderImage, ImagePullStrategy builderImagePull) { this.builderImage = new TestBuildImageConfig(builderImage, builderImagePull); } public boolean enabled() { return true; } public boolean sourcesOnly() { return true; } @Override public Optional<List<String>> additionalBuildArgs() { return Optional.empty(); } @Override public Optional<List<String>> additionalBuildArgsAppend() { return Optional.empty(); } @Override public boolean enableHttpUrlHandler() { return false; } @Override public boolean enableHttpsUrlHandler() { return false; } @Override public boolean headless() { return false; } @Override public String fileEncoding() { return null; } @Override public boolean addAllCharsets() { return false; } @Override public Optional<String> graalvmHome() { return Optional.empty(); } @Override public File javaHome() { return null; } @Override public Optional<String> nativeImageXmx() { return Optional.empty(); } @Override public boolean debugBuildProcess() { return false; } @Override public boolean publishDebugBuildProcessPort() { return false; } @Override public boolean enableIsolates() { return false; } @Override public boolean enableFallbackImages() { return false; } @Override public boolean autoServiceLoaderRegistration() { return false; } @Override public boolean dumpProxies() { return false; } @Override public Optional<Boolean> containerBuild() { return Optional.empty(); } @Override public Optional<Boolean> pie() { return Optional.empty(); } @Override public Optional<String> march() { return Optional.empty(); } @Override public boolean remoteContainerBuild() { return false; } @Override public BuilderImageConfig builderImage() { return builderImage; } @Override public Optional<ContainerRuntimeUtil.ContainerRuntime> containerRuntime() { return Optional.empty(); } @Override public Optional<List<String>> containerRuntimeOptions() { return Optional.empty(); } @Override public boolean enableVmInspection() { return false; } @Override public Optional<List<MonitoringOption>> monitoring() { return Optional.empty(); } @Override public boolean enableReports() { return false; } @Override public boolean reportExceptionStackTraces() { return false; } @Override public boolean reportErrorsAtRuntime() { return false; } @Override public boolean reuseExisting() { return false; } @Override public ResourcesConfig resources() { return null; } @Override public Debug debug() { return null; } @Override public boolean enableDashboardDump() { return false; } @Override public boolean includeReasonsInConfigFiles() { return false; } @Override public Compression compression() { return null; } @Override public boolean agentConfigurationApply() { return false; } private
TestNativeConfig
java
spring-projects__spring-framework
spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/ConfigurableObject.java
{ "start": 692, "end": 806 }
interface ____ domain objects that need DI through aspects. * * @author Ramnivas Laddad * @since 2.5 */ public
for
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/reflect/FastClassEmitter.java
{ "start": 9392, "end": 10262 }
class ____ implements ObjectSwitchCallback { private CodeEmitter e; private Map indexes = new HashMap(); public GetIndexCallback(CodeEmitter e, List methods) { this.e = e; int index = 0; for (Iterator it = methods.iterator(); it.hasNext();) { indexes.put(it.next(), index++); } } @Override public void processCase(Object key, Label end) { e.push(((Integer)indexes.get(key))); e.return_value(); } @Override public void processDefault() { e.push(-1); e.return_value(); } } private static int[] getIntRange(int length) { int[] range = new int[length]; for (int i = 0; i < length; i++) { range[i] = i; } return range; } }
GetIndexCallback
java
apache__hadoop
hadoop-common-project/hadoop-auth/src/main/java/org/apache/hadoop/security/authentication/util/CertificateUtil.java
{ "start": 1206, "end": 2551 }
class ____ { private static final String PEM_HEADER = "-----BEGIN CERTIFICATE-----\n"; private static final String PEM_FOOTER = "\n-----END CERTIFICATE-----"; /** * Gets an RSAPublicKey from the provided PEM encoding. * * @param pem * - the pem encoding from config without the header and footer * @return RSAPublicKey the RSA public key * @throws ServletException thrown if a processing error occurred */ public static RSAPublicKey parseRSAPublicKey(String pem) throws ServletException { String fullPem = PEM_HEADER + pem + PEM_FOOTER; PublicKey key = null; try { CertificateFactory fact = CertificateFactory.getInstance("X.509"); ByteArrayInputStream is = new ByteArrayInputStream( fullPem.getBytes(StandardCharsets.UTF_8)); X509Certificate cer = (X509Certificate) fact.generateCertificate(is); key = cer.getPublicKey(); } catch (CertificateException ce) { String message = null; if (pem.startsWith(PEM_HEADER)) { message = "CertificateException - be sure not to include PEM header " + "and footer in the PEM configuration element."; } else { message = "CertificateException - PEM may be corrupt"; } throw new ServletException(message, ce); } return (RSAPublicKey) key; } }
CertificateUtil
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/state/MapStateDescriptor.java
{ "start": 2178, "end": 3847 }
class ____<UK, UV> extends StateDescriptor<MapState<UK, UV>, Map<UK, UV>> { private static final long serialVersionUID = 1L; /** * Create a new {@code MapStateDescriptor} with the given name and the given type serializers. * * @param name The name of the {@code MapStateDescriptor}. * @param keySerializer The type serializer for the keys in the state. * @param valueSerializer The type serializer for the values in the state. */ public MapStateDescriptor( String name, TypeSerializer<UK> keySerializer, TypeSerializer<UV> valueSerializer) { super(name, new MapSerializer<>(keySerializer, valueSerializer), null); } /** * Create a new {@code MapStateDescriptor} with the given name and the given type information. * * @param name The name of the {@code MapStateDescriptor}. * @param keyTypeInfo The type information for the keys in the state. * @param valueTypeInfo The type information for the values in the state. */ public MapStateDescriptor( String name, TypeInformation<UK> keyTypeInfo, TypeInformation<UV> valueTypeInfo) { super(name, new MapTypeInfo<>(keyTypeInfo, valueTypeInfo), null); } /** * Create a new {@code MapStateDescriptor} with the given name and the given type information. * * <p>If this constructor fails (because it is not possible to describe the type via a class), * consider using the {@link #MapStateDescriptor(String, TypeInformation, TypeInformation)} * constructor. * * @param name The name of the {@code MapStateDescriptor}. * @param keyClass The
MapStateDescriptor
java
quarkusio__quarkus
extensions/azure-functions/deployment/src/main/java/io/quarkus/azure/functions/deployment/QuarkusAzureActionManagerProvider.java
{ "start": 210, "end": 406 }
class ____ implements AzureActionManagerProvider { @Override public AzureActionManager getActionManager() { return new QuarkusActionManager(); } }
QuarkusAzureActionManagerProvider
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/store/RoleReferenceIntersectionTests.java
{ "start": 1030, "end": 3266 }
class ____ extends ESTestCase { public void testBuildRoleForSingleRoleReference() { final RoleReference roleReference = mock(RoleReference.class); final Role role = mock(Role.class); final RoleReferenceIntersection roleReferenceIntersection = new RoleReferenceIntersection(roleReference); final BiConsumer<RoleReference, ActionListener<Role>> singleRoleBuilder = (r, l) -> { assertThat(r, is(roleReference)); l.onResponse(role); }; final PlainActionFuture<Role> future = new PlainActionFuture<>(); roleReferenceIntersection.buildRole(singleRoleBuilder, future); assertThat(future.actionGet(), is(role)); } public void testBuildRoleForListOfRoleReferences() { final int size = randomIntBetween(2, 3); final List<RoleReference> roleReferences = new ArrayList<>(size); final List<Role> roles = new ArrayList<>(size); for (int i = 0; i < size; i++) { final RoleReference roleReference = mock(RoleReference.class); when(roleReference.id()).thenReturn(new RoleKey(Set.of(), String.valueOf(i))); roleReferences.add(roleReference); final Role role = mock(Role.class); when(role.limitedBy(any())).thenCallRealMethod(); roles.add(role); } final RoleReferenceIntersection roleReferenceIntersection = new RoleReferenceIntersection(roleReferences); final BiConsumer<RoleReference, ActionListener<Role>> singleRoleBuilder = (rf, l) -> { l.onResponse(roles.get(Integer.parseInt(rf.id().getSource()))); }; final PlainActionFuture<Role> future = new PlainActionFuture<>(); roleReferenceIntersection.buildRole(singleRoleBuilder, future); final Role role = future.actionGet(); assertThat(role, instanceOf(LimitedRole.class)); verify(roles.get(0)).limitedBy(roles.get(1)); if (size == 2) { assertThat(role, equalTo(new LimitedRole(roles.get(0), roles.get(1)))); } else { assertThat(role, equalTo(new LimitedRole(new LimitedRole(roles.get(0), roles.get(1)), roles.get(2)))); } } }
RoleReferenceIntersectionTests
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/test/LettuceExtension.java
{ "start": 10993, "end": 11281 }
enum ____ implements Supplier<StatefulRedisConnection<String, String>> { INSTANCE; @Override public StatefulRedisConnection<String, String> get() { return RedisClientSupplier.INSTANCE.get().connect(); } }
StatefulRedisConnectionSupplier
java
google__guice
core/src/com/google/inject/internal/util/ContinuousStopwatch.java
{ "start": 985, "end": 1793 }
class ____ { private final Logger logger = Logger.getLogger(ContinuousStopwatch.class.getName()); private final Stopwatch stopwatch; /** * Constructs a ContinuousStopwatch, which will start timing immediately after construction. * * @param stopwatch the internal stopwatch used by ContinuousStopwatch */ public ContinuousStopwatch(Stopwatch stopwatch) { this.stopwatch = stopwatch; reset(); } /** Resets and returns elapsed time in milliseconds. */ public long reset() { long elapsedTimeMs = stopwatch.elapsed(MILLISECONDS); stopwatch.reset(); stopwatch.start(); return elapsedTimeMs; } /** Resets and logs elapsed time in milliseconds. */ public void resetAndLog(String label) { logger.fine(label + ": " + reset() + "ms"); } }
ContinuousStopwatch
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsSmartNullsTest.java
{ "start": 3915, "end": 3969 }
interface ____<T> { T get(); }
GenericFoo
java
spring-projects__spring-boot
module/spring-boot-resttestclient/src/main/java/org/springframework/boot/resttestclient/autoconfigure/AutoConfigureRestTestClient.java
{ "start": 1118, "end": 1392 }
class ____ enable a {@link RestTestClient}. * * @author Stephane Nicoll * @since 4.0.0 * @see RestTestClientAutoConfiguration */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @ImportAutoConfiguration public @
to
java
apache__camel
components/camel-ai/camel-milvus/src/main/java/org/apache/camel/component/milvus/Milvus.java
{ "start": 1054, "end": 1223 }
class ____ been moved to its own class. Use * {@link org.apache.camel.component.milvus.MilvusHeaders} instead. */ @Deprecated public static
has
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/sqm/DelegatingSqmSelectionQueryImplementorTest.java
{ "start": 290, "end": 437 }
class ____ serves as compilation unit to verify we implemented all methods in the {@link DelegatingSqmSelectionQueryImplementor} class. */ public
just
java
elastic__elasticsearch
x-pack/plugin/transform/qa/single-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/transform/integration/TransformUpgradeModeIT.java
{ "start": 1095, "end": 8300 }
class ____ extends TransformRestTestCase { private static boolean indicesCreated = false; // preserve indices in order to reuse source indices in several test cases @Override protected boolean preserveIndicesUponCompletion() { return true; } @Before public void createIndexes() throws IOException { setupUser(TEST_USER_NAME, singletonList("transform_user")); setupUser(TEST_ADMIN_USER_NAME, singletonList("transform_admin")); // it's not possible to run it as @BeforeClass as clients aren't initialized then, so we need this little hack if (indicesCreated) { return; } createReviewsIndex(); indicesCreated = true; } public void testUpgradeMode() throws Exception { var transformId = startTransform(); assertAcknowledged(setUpgradeMode(BASIC_AUTH_VALUE_TRANSFORM_ADMIN, true)); var statsAndState = getTransformStateAndStats(transformId); assertThat(readString(statsAndState, "state"), equalTo(TransformStats.State.WAITING.value())); assertThat(readString(statsAndState, "reason"), equalTo("Transform task will not be assigned while upgrade mode is enabled.")); assertAcknowledged(setUpgradeMode(BASIC_AUTH_VALUE_TRANSFORM_ADMIN, false)); // upgrade mode only waits for the assignment block to be removed, not for the transform to restart // so we need to wait until the transform restarts assertBusy(() -> { var nextStatsAndState = getTransformStateAndStats(transformId); assertThat(readString(nextStatsAndState, "state"), equalTo(TransformStats.State.STARTED.value())); assertThat(readString(nextStatsAndState, "reason"), nullValue()); }, 30, TimeUnit.SECONDS); } private String startTransform() throws Exception { var transformId = "pivot_continuous"; createContinuousPivotReviewsTransform(transformId, "pivot_reviews_continuous", null); startAndWaitForContinuousTransform(transformId, "pivot_reviews_continuous", null); return transformId; } private Response setUpgradeMode(String auth, boolean enabled) throws Exception { var path = enabled ? "set_upgrade_mode?enabled" : "set_upgrade_mode"; var setUpgradeMode = createRequestWithAuth("POST", getTransformEndpoint() + path, auth); return client().performRequest(setUpgradeMode); } private String readString(Map<?, ?> statsAndState, String key) { return statsAndState == null ? null : (String) XContentMapValues.extractValue(key, statsAndState); } public void testUpgradeModeFailsWithNonAdminUser() throws Exception { assertRestException( () -> setUpgradeMode(TEST_USER_NAME, true), e -> assertThat( "Expected security error using non-admin transform user", e.getResponse().getStatusLine().getStatusCode(), is(401) ) ); } @SuppressWarnings("unchecked") public void testUpgradeModeBlocksRestApi() throws Exception { var stoppedTransform = "stopped-transform"; createContinuousPivotReviewsTransform(stoppedTransform, "pivot_reviews_continuous", null); var startedTransform = startTransform(); var uncreatedTransform = "some-new-transform"; assertAcknowledged(setUpgradeMode(BASIC_AUTH_VALUE_TRANSFORM_ADMIN, true)); // start an existing transform assertConflict(() -> startTransform(stoppedTransform), "Cannot start any Transform while the Transform feature is upgrading."); // stop an existing transform assertConflict(() -> stopTransform(startedTransform, false), "Cannot stop any Transform while the Transform feature is upgrading."); // create a new transform assertConflict( () -> createContinuousPivotReviewsTransform(uncreatedTransform, "pivot_reviews_continuous", null), "Cannot create new Transform while the Transform feature is upgrading." ); // update an existing transform assertConflict( () -> updateTransform(stoppedTransform, "{ \"settings\": { \"max_page_search_size\": 123 } }", false), "Cannot update any Transform while the Transform feature is upgrading." ); // upgrade all transforms assertConflict(this::upgrade, "Cannot upgrade Transforms while the Transform feature is upgrading."); // schedule transform assertConflict( () -> scheduleNowTransform(startedTransform), "Cannot schedule any Transform while the Transform feature is upgrading." ); // reset transform assertConflict( () -> resetTransform(startedTransform, false), "Cannot reset any Transform while the Transform feature is upgrading." ); assertAcknowledged(setUpgradeMode(BASIC_AUTH_VALUE_TRANSFORM_ADMIN, false)); // started transform should go back into started assertBusy(() -> { var statsAndState = getTransformStateAndStats(startedTransform); assertThat(readString(statsAndState, "state"), equalTo(TransformStats.State.STARTED.value())); assertThat(readString(statsAndState, "reason"), nullValue()); }, 30, TimeUnit.SECONDS); // stopped transform should have never started var statsAndState = getTransformStateAndStats(stoppedTransform); assertThat(readString(statsAndState, "state"), equalTo(TransformStats.State.STOPPED.value())); assertThat(readString(statsAndState, "reason"), nullValue()); // new transform shouldn't exist assertRestException(() -> getTransformConfig(uncreatedTransform, BASIC_AUTH_VALUE_TRANSFORM_ADMIN), e -> { assertThat(e.getResponse().getStatusLine().getStatusCode(), is(404)); assertThat(e.getMessage(), containsString("Transform with id [" + uncreatedTransform + "] could not be found")); }); // stopped transform should not have been updated var stoppedConfig = getTransformConfig(stoppedTransform, BASIC_AUTH_VALUE_TRANSFORM_ADMIN); assertThat((Map<String, Object>) stoppedConfig.get("settings"), is(anEmptyMap())); } private void assertConflict(CheckedRunnable<Exception> runnable, String message) throws Exception { assertRestException(runnable, e -> { assertThat(e.getResponse().getStatusLine().getStatusCode(), is(409)); assertThat(e.getMessage(), containsString(message)); }); } private void assertRestException(CheckedRunnable<Exception> runnable, Consumer<ResponseException> assertThat) throws Exception { try { runnable.run(); fail("Expected code to throw ResponseException."); } catch (ResponseException e) { assertThat.accept(e); } } private void upgrade() throws IOException { client().performRequest( createRequestWithAuth("POST", TransformField.REST_BASE_PATH_TRANSFORMS + "_upgrade", BASIC_AUTH_VALUE_TRANSFORM_ADMIN) ); } }
TransformUpgradeModeIT
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/PropertyBindingException.java
{ "start": 882, "end": 3286 }
class ____ extends RuntimeCamelException { private final Object target; private final String propertyName; private final Object value; private final String optionPrefix; private final String optionKey; public PropertyBindingException(Object target, String propertyName, Object value) { this.target = target; this.propertyName = propertyName; this.value = value; this.optionPrefix = null; this.optionKey = null; } public PropertyBindingException(Object target, String propertyName, Object value, Throwable e) { initCause(e); this.target = target; this.propertyName = propertyName; this.value = value; this.optionPrefix = null; this.optionKey = null; } public PropertyBindingException(Object target, Throwable e) { initCause(e); this.target = target; this.propertyName = null; this.value = null; this.optionPrefix = null; this.optionKey = null; } public PropertyBindingException(Object target, String propertyName, Object value, String optionPrefix, String optionKey, Throwable e) { initCause(e); this.target = target; this.propertyName = propertyName; this.value = value; this.optionPrefix = optionPrefix; this.optionKey = optionKey; } @Override public String getMessage() { String stringValue = value != null ? value.toString() : ""; String key = propertyName; if (optionPrefix != null && optionKey != null) { key = optionPrefix.endsWith(".") ? optionPrefix + optionKey : optionPrefix + "." + optionKey; } if (key != null) { return "Error binding property (" + key + "=" + stringValue + ") with name: " + propertyName + " on bean: " + target + " with value: " + stringValue; } else { return "Error binding properties on bean: " + target; } } public Object getTarget() { return target; } public String getPropertyName() { return propertyName; } public Object getValue() { return value; } public String getOptionPrefix() { return optionPrefix; } public String getOptionKey() { return optionKey; } }
PropertyBindingException
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/fetch/Stay.java
{ "start": 232, "end": 1985 }
class ____ implements Serializable { // member declaration private Long id; private Person person; private Person oldPerson; private Person veryOldPerson; private Date startDate; private Date endDate; private String vessel; private String authoriser; private String comments; // constructors public Stay() { } public Stay(Person person, Date startDate, Date endDate, String vessel, String authoriser, String comments) { this.authoriser = authoriser; this.endDate = endDate; this.person = person; this.startDate = startDate; this.vessel = vessel; this.comments = comments; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Person getOldPerson() { return oldPerson; } public void setOldPerson(Person oldPerson) { this.oldPerson = oldPerson; } public Person getVeryOldPerson() { return veryOldPerson; } public void setVeryOldPerson(Person veryOldPerson) { this.veryOldPerson = veryOldPerson; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getVessel() { return vessel; } public void setVessel(String vessel) { this.vessel = vessel; } public String getAuthoriser() { return authoriser; } public void setAuthoriser(String authoriser) { this.authoriser = authoriser; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } }
Stay
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/loader/internal/LoadAccessContext.java
{ "start": 452, "end": 1090 }
interface ____ { /** * The session from which the load originates */ SessionImplementor getSession(); /** * Callback to check whether the session is "active" */ void checkOpenOrWaitingForAutoClose(); /** * Callback to pulse the transaction coordinator */ void pulseTransactionCoordinator(); void delayedAfterCompletion(); /** * Efficiently fire a {@link LoadEvent} with the given type * and return the resulting entity instance or proxy. * * @since 7.0 */ Object load( LoadEventListener.LoadType loadType, Object id, String entityName, LockOptions lockOptions, Boolean readOnly); }
LoadAccessContext
java
quarkusio__quarkus
independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/classloading/QuarkusClassLoader.java
{ "start": 24784, "end": 26820 }
class ____ was closed byte[] data = classPathElementResource.getData(); definePackage(name, classPathElement); Class<?> cl = defineClass(name, data, 0, data.length, protectionDomains.computeIfAbsent(classPathElement, ClassPathElement::getProtectionDomain)); if (Driver.class.isAssignableFrom(cl)) { driverLoaded = true; } return cl; } } if (!parentFirst) { return parent.loadClass(name); } throw new ClassNotFoundException(name); } } finally { if (interrupted) { //restore interrupt state Thread.currentThread().interrupt(); } } } @VisibleForTesting void definePackage(String name, ClassPathElement classPathElement) { var pkgName = getPackageNameFromClassName(name); if (pkgName == null) { return; } if (getDefinedPackage(pkgName) != null) { return; } try { var manifest = classPathElement.getManifestAttributes(); if (manifest != null) { definePackage(pkgName, manifest.getSpecificationTitle(), manifest.getSpecificationVersion(), manifest.getSpecificationVendor(), manifest.getImplementationTitle(), manifest.getImplementationVersion(), manifest.getImplementationVendor(), null); } else { definePackage(pkgName, null, null, null, null, null, null, null); } } catch (IllegalArgumentException e) { // retry, thrown by definePackage(), if a package for the same name is already defines by this
loader
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatRequest.java
{ "start": 1616, "end": 3073 }
class ____ extends AbstractRequest.Builder<StreamsGroupHeartbeatRequest> { private final StreamsGroupHeartbeatRequestData data; public Builder(StreamsGroupHeartbeatRequestData data) { super(ApiKeys.STREAMS_GROUP_HEARTBEAT); this.data = data; } @Override public StreamsGroupHeartbeatRequest build(short version) { return new StreamsGroupHeartbeatRequest(data, version); } @Override public String toString() { return data.toString(); } } private final StreamsGroupHeartbeatRequestData data; public StreamsGroupHeartbeatRequest(StreamsGroupHeartbeatRequestData data, short version) { super(ApiKeys.STREAMS_GROUP_HEARTBEAT, version); this.data = data; } @Override public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) { return new StreamsGroupHeartbeatResponse( new StreamsGroupHeartbeatResponseData() .setThrottleTimeMs(throttleTimeMs) .setErrorCode(Errors.forException(e).code()) ); } @Override public StreamsGroupHeartbeatRequestData data() { return data; } public static StreamsGroupHeartbeatRequest parse(Readable readable, short version) { return new StreamsGroupHeartbeatRequest(new StreamsGroupHeartbeatRequestData( readable, version), version); } }
Builder
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/writer/SchedConfUpdateInfoWriter.java
{ "start": 1794, "end": 3369 }
class ____ implements MessageBodyWriter<SchedConfUpdateInfo> { private JettisonMarshaller jettisonMarshaller; private Marshaller marshaller; public SchedConfUpdateInfoWriter(){ try { JettisonJaxbContext jettisonJaxbContext = new JettisonJaxbContext( SchedConfUpdateInfo.class); jettisonMarshaller = jettisonJaxbContext.createJsonMarshaller(); marshaller = jettisonJaxbContext.createMarshaller(); } catch (JAXBException e) { } } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == SchedConfUpdateInfo.class; } @Override public void writeTo(SchedConfUpdateInfo schedConfUpdateInfo, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { StringWriter stringWriter = new StringWriter(); try { if (mediaType.toString().equals(MediaType.APPLICATION_JSON)) { jettisonMarshaller.marshallToJSON(schedConfUpdateInfo, stringWriter); entityStream.write(stringWriter.toString().getBytes(StandardCharsets.UTF_8)); } if (mediaType.toString().equals(MediaType.APPLICATION_XML)) { marshaller.marshal(schedConfUpdateInfo, stringWriter); entityStream.write(stringWriter.toString().getBytes(StandardCharsets.UTF_8)); } } catch (JAXBException e) { throw new IOException(e); } } }
SchedConfUpdateInfoWriter
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
{ "start": 36077, "end": 36164 }
enum ____ { DEFAULT, SYSTEM_ENVIRONMENT, LEGACY_SYSTEM_ENVIRONMENT } }
ToStringFormat
java
google__error-prone
check_api/src/main/java/com/google/errorprone/ErrorProneFlags.java
{ "start": 1576, "end": 1760 }
class ____ takes * one parameter of type ErrorProneFlags. * * <p>See <a href="https://errorprone.info/docs/flags">documentation</a> for full syntax * description. */ public final
that
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJAdvisorBeanRegistrationAotProcessorTests.java
{ "start": 2897, "end": 2979 }
class ____ { private static java.lang.Throwable initFailureCause; } }
RegularClass
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/util/NettyLogger.java
{ "start": 1419, "end": 2807 }
class ____ extends LoggingHandler { NoContentLoggingHandler(Class<?> clazz, LogLevel level) { super(clazz, level); } @Override protected String format(ChannelHandlerContext ctx, String eventName, Object arg) { if (arg instanceof ByteBuf byteBuf) { return format(ctx, eventName) + " " + byteBuf.readableBytes() + "B"; } else if (arg instanceof ByteBufHolder byteBufHolder) { return format(ctx, eventName) + " " + byteBufHolder.content().readableBytes() + "B"; } else if (arg instanceof InputStream inputStream) { int available = -1; try { available = inputStream.available(); } catch (IOException ex) { // Swallow, but return -1 to indicate an error happened } return format(ctx, eventName, arg) + " " + available + "B"; } else { return super.format(ctx, eventName, arg); } } } private final LoggingHandler loggingHandler; public NettyLogger() { if (logger.isTraceEnabled()) { loggingHandler = new LoggingHandler(NettyLogger.class, LogLevel.TRACE); } else if (logger.isDebugEnabled()) { loggingHandler = new NoContentLoggingHandler(NettyLogger.class, LogLevel.DEBUG); } else { loggingHandler = null; } } public LoggingHandler getLoggingHandler() { return loggingHandler; } }
NoContentLoggingHandler
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/FileBasedIPList.java
{ "start": 1426, "end": 3502 }
class ____ implements IPList { private static final Logger LOG = LoggerFactory.getLogger(FileBasedIPList.class); private final String fileName; private final MachineList addressList; public FileBasedIPList(String fileName) { this.fileName = fileName; String[] lines; try { lines = readLines(fileName); } catch (IOException e) { lines = null; } if (lines != null) { addressList = new MachineList(new HashSet<>(Arrays.asList(lines))); } else { addressList = null; } } public FileBasedIPList reload() { return new FileBasedIPList(fileName); } @Override public boolean isIn(String ipAddress) { if (ipAddress == null || addressList == null) { return false; } return addressList.includes(ipAddress); } /** * Reads the lines in a file. * @param fileName * @return lines in a String array; null if the file does not exist or if the * file name is null * @throws IOException */ private static String[] readLines(String fileName) throws IOException { try { if (fileName != null) { File file = new File (fileName); if (file.exists()) { try ( Reader fileReader = new InputStreamReader( Files.newInputStream(file.toPath()), StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(fileReader)) { List<String> lines = new ArrayList<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } if (LOG.isDebugEnabled()) { LOG.debug("Loaded IP list of size = " + lines.size() + " from file = " + fileName); } return (lines.toArray(new String[lines.size()])); } } else { LOG.debug("Missing ip list file : "+ fileName); } } } catch (IOException ioe) { LOG.error(ioe.toString()); throw ioe; } return null; } }
FileBasedIPList
java
apache__camel
components/camel-telemetry/src/test/java/org/apache/camel/telemetry/decorators/CqlSpanDecoratorTest.java
{ "start": 1297, "end": 3278 }
class ____ { @Test public void testPreCqlFromUri() { String cql = "select%20*%20from%20users"; String keyspace = "test"; Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("cql://host1,host2:8080/" + keyspace + "?cql=" + cql + "&consistencyLevel=quorum"); Mockito.when(exchange.getIn()).thenReturn(message); SpanDecorator decorator = new CqlSpanDecorator(); MockSpanAdapter span = new MockSpanAdapter(); decorator.beforeTracingEvent(span, exchange, endpoint); assertEquals(CqlSpanDecorator.CASSANDRA_DB_TYPE, span.tags().get(TagConstants.DB_SYSTEM)); assertEquals(cql, span.tags().get(TagConstants.DB_STATEMENT)); assertEquals(keyspace, span.tags().get(TagConstants.DB_NAME)); } @Test public void testPreCqlFromHeader() { String cql = "select * from users"; Endpoint endpoint = Mockito.mock(Endpoint.class); Exchange exchange = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(endpoint.getEndpointUri()).thenReturn("cql://host1,host2?consistencyLevel=quorum"); Mockito.when(exchange.getIn()).thenReturn(message); Mockito.when(message.getHeader(CqlSpanDecorator.CAMEL_CQL_QUERY, String.class)).thenReturn(cql); SpanDecorator decorator = new CqlSpanDecorator(); MockSpanAdapter span = new MockSpanAdapter(); decorator.beforeTracingEvent(span, exchange, endpoint); assertEquals(CqlSpanDecorator.CASSANDRA_DB_TYPE, span.tags().get(TagConstants.DB_SYSTEM)); assertEquals(cql, span.tags().get(TagConstants.DB_STATEMENT)); assertNull(span.tags().get(TagConstants.DB_NAME)); } }
CqlSpanDecoratorTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/util/asyncprocessing/AsyncKeyedTwoInputStreamOperatorTestHarness.java
{ "start": 3057, "end": 12603 }
class ____<K, IN1, IN2, OUT> extends KeyedTwoInputStreamOperatorTestHarness<K, IN1, IN2, OUT> { private final TwoInputStreamOperator<IN1, IN2, OUT> twoInputOperator; private ThrowingConsumer<StreamRecord<IN1>, Exception> processor1; private ThrowingConsumer<StreamRecord<IN2>, Exception> processor2; /** The executor service for async state processing. */ private final ExecutorService executor; /** Create an instance of the subclass of this class. */ public static < K, IN1, IN2, OUT, OP extends AsyncKeyedTwoInputStreamOperatorTestHarness<K, IN1, IN2, OUT>> OP create(FunctionWithException<ExecutorService, OP, Exception> constructor) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<OP> future = new CompletableFuture<>(); executor.execute( () -> { try { future.complete(constructor.apply(executor)); } catch (Exception e) { throw new RuntimeException(e); } }); return future.get(); } public static <K, IN1, IN2, OUT> AsyncKeyedTwoInputStreamOperatorTestHarness<K, IN1, IN2, OUT> create( TwoInputStreamOperator<IN1, IN2, OUT> operator, KeySelector<IN1, K> keySelector1, KeySelector<IN2, K> keySelector2, TypeInformation<K> keyType) throws Exception { return create(operator, keySelector1, keySelector2, keyType, 1, 1, 0); } public static <K, IN1, IN2, OUT> AsyncKeyedTwoInputStreamOperatorTestHarness<K, IN1, IN2, OUT> create( TwoInputStreamOperator<IN1, IN2, OUT> operator, KeySelector<IN1, K> keySelector1, KeySelector<IN2, K> keySelector2, TypeInformation<K> keyType, int maxParallelism, int numSubtasks, int subtaskIndex) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<AsyncKeyedTwoInputStreamOperatorTestHarness<K, IN1, IN2, OUT>> future = new CompletableFuture<>(); executor.execute( () -> { try { future.complete( new AsyncKeyedTwoInputStreamOperatorTestHarness<>( executor, operator, keySelector1, keySelector2, keyType, maxParallelism, numSubtasks, subtaskIndex)); } catch (Exception e) { throw new RuntimeException(e); } }); return future.get(); } public AsyncKeyedTwoInputStreamOperatorTestHarness( ExecutorService executor, TwoInputStreamOperator<IN1, IN2, OUT> operator, KeySelector<IN1, K> keySelector1, KeySelector<IN2, K> keySelector2, TypeInformation<K> keyType, int maxParallelism, int numSubtasks, int subtaskIndex) throws Exception { super( operator, keySelector1, keySelector2, keyType, maxParallelism, numSubtasks, subtaskIndex); Preconditions.checkState( operator instanceof AsyncKeyOrderedProcessingOperator, "Operator is not an AsyncKeyOrderedProcessingOperator"); this.twoInputOperator = operator; this.executor = executor; // Make environment record any failure getEnvironment().setExpectedExternalFailureCause(Throwable.class); } private ThrowingConsumer<StreamRecord<IN1>, Exception> getRecordProcessor1() { if (processor1 == null) { processor1 = RecordProcessorUtils.getRecordProcessor1(twoInputOperator); } return processor1; } private ThrowingConsumer<StreamRecord<IN2>, Exception> getRecordProcessor2() { if (processor2 == null) { processor2 = RecordProcessorUtils.getRecordProcessor2(twoInputOperator); } return processor2; } @Override public void processElement1(StreamRecord<IN1> element) throws Exception { executeAndGet(() -> getRecordProcessor1().accept(element)); } @Override public void processElement1(IN1 value, long timestamp) throws Exception { processElement1(new StreamRecord<>(value, timestamp)); } @Override public void processElement2(StreamRecord<IN2> element) throws Exception { executeAndGet(() -> getRecordProcessor2().accept(element)); } @Override public void processElement2(IN2 value, long timestamp) throws Exception { processElement2(new StreamRecord<>(value, timestamp)); } @Override public void processWatermark1(Watermark mark) throws Exception { executeAndGet(() -> twoInputOperator.processWatermark1(mark)); } @Override public void processWatermark2(Watermark mark) throws Exception { executeAndGet(() -> twoInputOperator.processWatermark2(mark)); } @Override public void processBothWatermarks(Watermark mark) throws Exception { executeAndGet(() -> twoInputOperator.processWatermark1(mark)); executeAndGet(() -> twoInputOperator.processWatermark2(mark)); } @Override public void processWatermarkStatus1(WatermarkStatus watermarkStatus) throws Exception { executeAndGet(() -> twoInputOperator.processWatermarkStatus1(watermarkStatus)); } @Override public void processWatermarkStatus2(WatermarkStatus watermarkStatus) throws Exception { executeAndGet(() -> twoInputOperator.processWatermarkStatus2(watermarkStatus)); } @Override public void processRecordAttributes1(RecordAttributes recordAttributes) throws Exception { executeAndGet(() -> twoInputOperator.processRecordAttributes1(recordAttributes)); } @Override public void processRecordAttributes2(RecordAttributes recordAttributes) throws Exception { executeAndGet(() -> twoInputOperator.processRecordAttributes2(recordAttributes)); } public void endInput1() throws Exception { if (operator instanceof BoundedMultiInput) { executeAndGet(() -> ((BoundedMultiInput) operator).endInput(1)); } } public void endInput2() throws Exception { if (operator instanceof BoundedMultiInput) { executeAndGet(() -> ((BoundedMultiInput) operator).endInput(2)); } } public void drainStateRequests() throws Exception { executeAndGet(() -> drain(operator)); } @Override public void close() throws Exception { executeAndGet(super::close); executor.shutdown(); } @Override public int numKeyedStateEntries() { AbstractAsyncStateStreamOperator<OUT> asyncOp = (AbstractAsyncStateStreamOperator<OUT>) operator; AsyncKeyedStateBackend<Object> asyncKeyedStateBackend = asyncOp.getAsyncKeyedStateBackend(); KeyedStateBackend<?> keyedStateBackend; if (asyncKeyedStateBackend instanceof AsyncKeyedStateBackendAdaptor) { keyedStateBackend = ((AsyncKeyedStateBackendAdaptor<?>) asyncKeyedStateBackend) .getKeyedStateBackend(); } else { throw new UnsupportedOperationException( String.format( "Unsupported async keyed state backend: %s", asyncKeyedStateBackend.getClass().getCanonicalName())); } if (keyedStateBackend instanceof HeapKeyedStateBackend) { return ((HeapKeyedStateBackend) keyedStateBackend).numKeyValueStateEntries(); } else { throw new UnsupportedOperationException( String.format( "Unsupported keyed state backend: %s", keyedStateBackend.getClass().getCanonicalName())); } } private void executeAndGet(RunnableWithException runnable) throws Exception { try { execute( executor, () -> { checkEnvState(); runnable.run(); }) .get(); checkEnvState(); } catch (Exception e) { execute(executor, () -> mockTask.cleanUp(e)).get(); throw unwrapAsyncException(e); } } private void checkEnvState() { if (getEnvironment().getActualExternalFailureCause().isPresent()) { fail( "There is an error on other threads", getEnvironment().getActualExternalFailureCause().get()); } } }
AsyncKeyedTwoInputStreamOperatorTestHarness
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/TargetEmbeddableOnEmbeddedTest.java
{ "start": 1630, "end": 1714 }
interface ____ { double x(); double y(); } @Embeddable public static
Coordinates
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/optimizer/AbstractLogicalPlanOptimizerTests.java
{ "start": 2603, "end": 3642 }
class ____ extends ESTestCase { protected static EsqlParser parser; protected static LogicalOptimizerContext logicalOptimizerCtx; protected static LogicalPlanOptimizer logicalOptimizer; protected static LogicalPlanOptimizer logicalOptimizerWithLatestVersion; protected static Map<String, EsField> mapping; protected static Analyzer analyzer; protected static Map<String, EsField> mappingAirports; protected static Analyzer analyzerAirports; protected static Map<String, EsField> mappingTypes; protected static Analyzer analyzerTypes; protected static Map<String, EsField> mappingExtra; protected static Analyzer analyzerExtra; protected static Map<String, EsField> metricMapping; protected static Analyzer metricsAnalyzer; protected static Analyzer multiIndexAnalyzer; protected static Analyzer sampleDataIndexAnalyzer; protected static Analyzer subqueryAnalyzer; protected static EnrichResolution enrichResolution; public static
AbstractLogicalPlanOptimizerTests
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java
{ "start": 31078, "end": 31300 }
class ____ implements Converter<String, Collection<?>> { @Override public Collection<?> convert(String source) { return Collections.singleton(source + "X"); } } private static
MyStringToGenericCollectionConverter
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/OAuth2ProtectedResourceMetadataFilter.java
{ "start": 2502, "end": 5728 }
class ____ extends OncePerRequestFilter { private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<>() { }; private static final GenericHttpMessageConverter<Object> JSON_MESSAGE_CONVERTER = HttpMessageConverters .getJsonMessageConverter(); /** * The default endpoint {@code URI} for OAuth 2.0 Protected Resource Metadata * requests. */ static final String DEFAULT_OAUTH2_PROTECTED_RESOURCE_METADATA_ENDPOINT_URI = "/.well-known/oauth-protected-resource"; private final RequestMatcher requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, DEFAULT_OAUTH2_PROTECTED_RESOURCE_METADATA_ENDPOINT_URI.concat("/**")); private Consumer<OAuth2ProtectedResourceMetadata.Builder> protectedResourceMetadataCustomizer = ( protectedResourceMetadata) -> { }; /** * Sets the {@code Consumer} providing access to the * {@link OAuth2ProtectedResourceMetadata.Builder} allowing the ability to customize * the claims of the Resource Server's configuration. * @param protectedResourceMetadataCustomizer the {@code Consumer} providing access to * the {@link OAuth2ProtectedResourceMetadata.Builder} */ public void setProtectedResourceMetadataCustomizer( Consumer<OAuth2ProtectedResourceMetadata.Builder> protectedResourceMetadataCustomizer) { Assert.notNull(protectedResourceMetadataCustomizer, "protectedResourceMetadataCustomizer cannot be null"); this.protectedResourceMetadataCustomizer = protectedResourceMetadataCustomizer; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.requestMatcher.matches(request)) { filterChain.doFilter(request, response); return; } OAuth2ProtectedResourceMetadata.Builder builder = OAuth2ProtectedResourceMetadata.builder() .resource(resolveResourceIdentifier(request)) .bearerMethod("header") .tlsClientCertificateBoundAccessTokens(true); this.protectedResourceMetadataCustomizer.accept(builder); OAuth2ProtectedResourceMetadata protectedResourceMetadata = builder.build(); try { ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); JSON_MESSAGE_CONVERTER.write(protectedResourceMetadata.getClaims(), STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, httpResponse); } catch (Exception ex) { throw new HttpMessageNotWritableException( "An error occurred writing the OAuth 2.0 Protected Resource Metadata: " + ex.getMessage(), ex); } } private static String resolveResourceIdentifier(HttpServletRequest request) { // Resolve Resource Identifier dynamically from request String path = request.getRequestURI(); if (!StringUtils.hasText(path)) { path = ""; } else { path = path.replace(DEFAULT_OAUTH2_PROTECTED_RESOURCE_METADATA_ENDPOINT_URI, ""); } // @formatter:off return UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request)) .replacePath(path) .replaceQuery(null) .fragment(null) .build() .toUriString(); // @formatter:on } private static final
OAuth2ProtectedResourceMetadataFilter
java
apache__camel
test-infra/camel-test-infra-aws-v2/src/test/java/org/apache/camel/test/infra/aws2/services/AWSTestServices.java
{ "start": 2221, "end": 2347 }
class ____ extends AWSS3LocalContainerInfraService implements AWSService { } public static
AWSS3LocalContainerTestService
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/webapp/AppControllerForTest.java
{ "start": 1370, "end": 3127 }
class ____ extends AppController { final private static Map<String, String> properties = new HashMap<String, String>(); private ResponseInfo responseInfo = new ResponseInfo(); private View view = new ViewForTest(); private Class<?> clazz; private HttpServletResponse response; protected AppControllerForTest(App app, Configuration configuration, RequestContext ctx) { super(app, configuration, ctx); } public Class<?> getClazz() { return clazz; } @SuppressWarnings("unchecked") public <T> T getInstance(Class<T> cls) { clazz = cls; if (cls.equals(ResponseInfo.class)) { return (T) responseInfo; } return (T) view; } public ResponseInfo getResponseInfo() { return responseInfo; } public String get(String key, String defaultValue) { String result = properties.get(key); if (result == null) { result = defaultValue; } return result; } public void set(String key, String value) { properties.put(key, value); } public HttpServletRequest request() { HttpServletRequest result = mock(HttpServletRequest.class); when(result.getRemoteUser()).thenReturn("user"); return result; } @Override public HttpServletResponse response() { if (response == null) { response = mock(HttpServletResponse.class); } return response; } public Map<String, String> getProperty() { return properties; } OutputStream data = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(data); public String getData() { writer.flush(); return data.toString(); } protected PrintWriter writer() { if (writer == null) { writer = new PrintWriter(data); } return writer; } }
AppControllerForTest
java
apache__flink
flink-core/src/test/java/org/apache/flink/core/fs/AbstractAutoCloseableRegistryTest.java
{ "start": 6141, "end": 6898 }
class ____ extends FSDataInputStream { private final AtomicInteger refCount; public TestStream(AtomicInteger refCount) { this.refCount = refCount; refCount.incrementAndGet(); } @Override public void seek(long desired) throws IOException {} @Override public long getPos() throws IOException { return 0; } @Override public int read() throws IOException { return 0; } @Override public synchronized void close() throws IOException { refCount.decrementAndGet(); } } /** A noop {@link Closeable} implementation that blocks inside {@link #close()}. */ private static
TestStream
java
apache__camel
components/camel-aws/camel-aws-cloudtrail/src/test/java/org/apache/camel/component/aws/cloudtrail/CloudtrailClientFactoryTest.java
{ "start": 1402, "end": 2992 }
class ____ { @Test public void getStandardCloudtrailClientDefault() { CloudtrailConfiguration cloudtrailConf = new CloudtrailConfiguration(); CloudtrailInternalClient cloudtrailClient = CloudtrailClientFactory.getCloudtrailClient(cloudtrailConf); assertTrue(cloudtrailClient instanceof CloudtrailClientStandardImpl); } @Test public void getStandardCloudtrailClient() { CloudtrailConfiguration cloudtrailConf = new CloudtrailConfiguration(); cloudtrailConf.setUseDefaultCredentialsProvider(false); CloudtrailInternalClient cloudtrailClient = CloudtrailClientFactory.getCloudtrailClient(cloudtrailConf); assertTrue(cloudtrailClient instanceof CloudtrailClientStandardImpl); } @Test public void getIAMOptimizedCloudtrailClient() { CloudtrailConfiguration cloudtrailConf = new CloudtrailConfiguration(); cloudtrailConf.setUseDefaultCredentialsProvider(true); CloudtrailInternalClient cloudtrailClient = CloudtrailClientFactory.getCloudtrailClient(cloudtrailConf); assertTrue(cloudtrailClient instanceof CloudtrailClientIAMOptimizedImpl); } @Test public void getIAMSessionTokenCloudtrailClient() { CloudtrailConfiguration cloudtrailConf = new CloudtrailConfiguration(); cloudtrailConf.setUseSessionCredentials(true); CloudtrailInternalClient cloudtrailClient = CloudtrailClientFactory.getCloudtrailClient(cloudtrailConf); assertTrue(cloudtrailClient instanceof CloudtrailClientSessionTokenImpl); } }
CloudtrailClientFactoryTest
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupport.java
{ "start": 8810, "end": 9206 }
class ____<T> extends ConvertingEncoderDecoderSupport<T, ByteBuffer> implements Decoder.Binary<T> { } /** * A text {@link jakarta.websocket.Encoder.Text jakarta.websocket.Encoder} that delegates * to Spring's conversion service. See {@link ConvertingEncoderDecoderSupport} for * details. * @param <T> the type that this Encoder can convert to */ public abstract static
BinaryDecoder
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_first_with_InstanceOfAssertFactory_Test.java
{ "start": 1674, "end": 2987 }
class ____ { private final Iterable<Object> iterable = asList("string", 42, 0.0); @Test void should_fail_if_iterable_is_empty() { // GIVEN Iterable<String> iterable = emptyList(); // WHEN var assertionError = expectAssertionError(() -> assertThat(iterable).first(STRING)); // THEN then(assertionError).hasMessage(actualIsEmpty()); } @Test void should_fail_throwing_npe_if_assert_factory_is_null() { // WHEN Throwable thrown = catchThrowable(() -> assertThat(iterable).first(null)); // THEN then(thrown).isInstanceOf(NullPointerException.class) .hasMessage(shouldNotBeNull("instanceOfAssertFactory").create()); } @Test void should_pass_allowing_type_narrowed_assertions_if_first_element_is_an_instance_of_the_factory_type() { // WHEN AbstractStringAssert<?> result = assertThat(iterable).first(STRING); // THEN result.startsWith("str"); } @Test void should_fail_if_first_element_is_not_an_instance_of_the_factory_type() { // WHEN var assertionError = expectAssertionError(() -> assertThat(iterable).first(INTEGER)); // THEN then(assertionError).hasMessageContainingAll("Expecting actual:", "to be an instance of:", "but was instance of:"); } }
IterableAssert_first_with_InstanceOfAssertFactory_Test
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractReactiveTransactionAspectTests.java
{ "start": 1798, "end": 2448 }
class ____ { protected Method getNameMethod; protected Method setNameMethod; protected Method exceptionalMethod; @BeforeEach void setup() throws Exception { getNameMethod = TestBean.class.getMethod("getName"); setNameMethod = TestBean.class.getMethod("setName", String.class); exceptionalMethod = TestBean.class.getMethod("exceptional", Throwable.class); } @Test void noTransaction() throws Exception { ReactiveTransactionManager rtm = mock(); DefaultTestBean tb = new DefaultTestBean(); TransactionAttributeSource tas = new MapTransactionAttributeSource(); // All the methods in this
AbstractReactiveTransactionAspectTests
java
grpc__grpc-java
android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateClientConfigureServiceGrpc.java
{ "start": 6849, "end": 8062 }
class ____ extends io.grpc.stub.AbstractAsyncStub<XdsUpdateClientConfigureServiceStub> { private XdsUpdateClientConfigureServiceStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected XdsUpdateClientConfigureServiceStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new XdsUpdateClientConfigureServiceStub(channel, callOptions); } /** * <pre> * Update the tes client's configuration. * </pre> */ public void configure(io.grpc.testing.integration.Messages.ClientConfigureRequest request, io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.ClientConfigureResponse> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getConfigureMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service XdsUpdateClientConfigureService. * <pre> * A service to dynamically update the configuration of an xDS test client. * </pre> */ public static final
XdsUpdateClientConfigureServiceStub
java
google__guice
core/src/com/google/inject/internal/ProviderMethod.java
{ "start": 14043, "end": 16134 }
class ____<T> extends ProviderMethod<T> { ReflectionProviderMethod( Key<T> key, Method method, Object instance, ImmutableSet<Dependency<?>> dependencies, Class<? extends Annotation> scopeAnnotation, Annotation annotation) { super(key, method, instance, dependencies, scopeAnnotation, annotation); } @SuppressWarnings("unchecked") @Override T doProvision(Object[] parameters) throws IllegalAccessException, InvocationTargetException { return (T) method.invoke(instance, parameters); } @Override MethodHandle doProvisionHandle(MethodHandle[] parameters) { // We can hit this case if // 1. the method/class/parameters are non-public and we are using bytecode gen but a security // manager or modules configuration are installed that blocks access to our fastclass // generation and the setAccessible method. // 2. The method has too many parameters to be supported by method handles (and fastclass also // fails) // So we fall back to reflection. // You might be wondering... why is it that MethodHandles cannot handle methods with the // maximum number of parameters but java reflection can? And yes it is true that java // reflection is based on MethodHandles, but it supports a fallback for exactly this case that // goes through a JVM native method... le sigh... // bind to the `Method` object // (Object, Object[]) -> Object var handle = InternalMethodHandles.invokeHandle(method); // insert the instance // (Object[]) -> Object handle = MethodHandles.insertArguments(handle, 0, instance); // Pass the parameters // (InternalContext)->Object handle = MethodHandles.filterArguments( handle, 0, InternalMethodHandles.buildObjectArrayFactory(parameters)); return handle; } } /** * A {@link ProviderMethod} implementation that uses bytecode generation to invoke the provider * method. */ private static final
ReflectionProviderMethod
java
spring-projects__spring-security
messaging/src/test/java/org/springframework/security/messaging/handler/invocation/reactive/CurrentSecurityContextArgumentResolverTests.java
{ "start": 9007, "end": 9136 }
interface ____ { } @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @CurrentSecurityContext @
CurrentUser
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/SelectNewEmbeddedIdTest.java
{ "start": 2837, "end": 3067 }
class ____ { @EmbeddedId private SimpleId simpleId; private int id; public Simple() { } public Simple(SimpleId simpleId, int id) { this.simpleId = simpleId; this.id = id; } } @Embeddable public static
Simple
java
square__retrofit
retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableWithSchedulerTest.java
{ "start": 1163, "end": 2757 }
interface ____ { @GET("/") Flowable<String> body(); @GET("/") Flowable<Response<String>> response(); @GET("/") Flowable<Result<String>> result(); } private final TestScheduler scheduler = new TestScheduler(); private Service service; @Before public void setUp() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new StringConverterFactory()) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(scheduler)) .build(); service = retrofit.create(Service.class); } @Test public void bodyUsesScheduler() { server.enqueue(new MockResponse()); RecordingSubscriber<Object> subscriber = subscriberRule.create(); service.body().subscribe(subscriber); subscriber.assertNoEvents(); scheduler.triggerActions(); subscriber.assertAnyValue().assertComplete(); } @Test public void responseUsesScheduler() { server.enqueue(new MockResponse()); RecordingSubscriber<Object> subscriber = subscriberRule.create(); service.response().subscribe(subscriber); subscriber.assertNoEvents(); scheduler.triggerActions(); subscriber.assertAnyValue().assertComplete(); } @Test public void resultUsesScheduler() { server.enqueue(new MockResponse()); RecordingSubscriber<Object> subscriber = subscriberRule.create(); service.result().subscribe(subscriber); subscriber.assertNoEvents(); scheduler.triggerActions(); subscriber.assertAnyValue().assertComplete(); } }
Service
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/externalconfig/typesafeconfigurationproperties/mergingcomplextypes/map/MyProperties.java
{ "start": 916, "end": 1067 }
class ____ { private final Map<String, MyPojo> map = new LinkedHashMap<>(); public Map<String, MyPojo> getMap() { return this.map; } }
MyProperties
java
apache__dubbo
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/ZookeeperRegistryCenter.java
{ "start": 10125, "end": 10238 }
enum ____ { Windows, Unix } /** * The commands to support the zookeeper. */
OS
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java
{ "start": 28784, "end": 29363 }
class ____ { private String id; private List<String> lineItems; Order() { } Order(String id, List<String> lineItems) { this.id = id; this.lineItems = lineItems; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getLineItems() { return this.lineItems; } public void setLineItems(List<String> lineItems) { this.lineItems = lineItems; } @Override public String toString() { return "Order [id=" + this.id + ", lineItems=" + this.lineItems + "]"; } } private
Order
java
apache__camel
components/camel-ai/camel-weaviate/src/main/java/org/apache/camel/component/weaviate/WeaviateVectorDb.java
{ "start": 895, "end": 1078 }
class ____ { public static final String SCHEME = "weaviate"; private WeaviateVectorDb() { } /** * @deprecated As of Camel 4.15, this nested Headers
WeaviateVectorDb
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/util/FluentBitSet.java
{ "start": 1183, "end": 21862 }
class ____ implements Cloneable, Serializable { private static final long serialVersionUID = 1L; /** * Working BitSet. */ private final BitSet bitSet; /** * Creates a new bit set. All bits are initially {@code false}. */ public FluentBitSet() { this(new BitSet()); } /** * Creates a new instance for the given bit set. * * @param set The bit set to wrap. */ public FluentBitSet(final BitSet set) { this.bitSet = Objects.requireNonNull(set, "set"); } /** * Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range {@code 0} * through {@code nbits-1}. All bits are initially {@code false}. * * @param nbits the initial size of the bit set. * @throws NegativeArraySizeException if the specified initial size is negative. */ public FluentBitSet(final int nbits) { this(new BitSet(nbits)); } /** * Performs a logical <strong>AND</strong> of this target bit set with the argument bit set. This bit set is modified so that each * bit in it has the value {@code true} if and only if it both initially had the value {@code true} and the * corresponding bit in the bit set argument also had the value {@code true}. * * @param set a bit set. * @return {@code this} instance. */ public FluentBitSet and(final BitSet set) { bitSet.and(set); return this; } /** * Performs a logical <strong>AND</strong> of this target bit set with the argument bit set. This bit set is modified so that each * bit in it has the value {@code true} if and only if it both initially had the value {@code true} and the * corresponding bit in the bit set argument also had the value {@code true}. * * @param set a bit set. * @return {@code this} instance. */ public FluentBitSet and(final FluentBitSet set) { bitSet.and(set.bitSet); return this; } /** * Clears all of the bits in this {@link BitSet} whose corresponding bit is set in the specified {@link BitSet}. * * @param set the {@link BitSet} with which to mask this {@link BitSet}. * @return {@code this} instance. */ public FluentBitSet andNot(final BitSet set) { bitSet.andNot(set); return this; } /** * Clears all of the bits in this {@link BitSet} whose corresponding bit is set in the specified {@link BitSet}. * * @param set the {@link BitSet} with which to mask this {@link BitSet}. * @return {@code this} instance. */ public FluentBitSet andNot(final FluentBitSet set) { this.bitSet.andNot(set.bitSet); return this; } /** * Gets the wrapped bit set. * * @return the wrapped bit set. */ public BitSet bitSet() { return bitSet; } /** * Returns the number of bits set to {@code true} in this {@link BitSet}. * * @return the number of bits set to {@code true} in this {@link BitSet}. */ public int cardinality() { return bitSet.cardinality(); } /** * Sets all of the bits in this BitSet to {@code false}. * * @return {@code this} instance. */ public FluentBitSet clear() { bitSet.clear(); return this; } /** * Sets the bits specified by the indexes to {@code false}. * * @param bitIndexArray the index of the bit to be cleared. * @throws IndexOutOfBoundsException if the specified index is negative. * @return {@code this} instance. */ public FluentBitSet clear(final int... bitIndexArray) { for (final int e : bitIndexArray) { this.bitSet.clear(e); } return this; } /** * Sets the bit specified by the index to {@code false}. * * @param bitIndex the index of the bit to be cleared. * @throws IndexOutOfBoundsException if the specified index is negative. * @return {@code this} instance. */ public FluentBitSet clear(final int bitIndex) { bitSet.clear(bitIndex); return this; } /** * Sets the bits from the specified {@code fromIndex} (inclusive) to the specified {@code toIndex} (exclusive) to * {@code false}. * * @param fromIndex index of the first bit to be cleared. * @param toIndex index after the last bit to be cleared. * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or {@code toIndex} is negative, or * {@code fromIndex} is larger than {@code toIndex}. * @return {@code this} instance. */ public FluentBitSet clear(final int fromIndex, final int toIndex) { bitSet.clear(fromIndex, toIndex); return this; } /** * Cloning this {@link BitSet} produces a new {@link BitSet} that is equal to it. The clone of the bit set is another * bit set that has exactly the same bits set to {@code true} as this bit set. * * @return a clone of this bit set * @see #size() */ @Override public Object clone() { return new FluentBitSet((BitSet) bitSet.clone()); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof FluentBitSet)) { return false; } final FluentBitSet other = (FluentBitSet) obj; return Objects.equals(bitSet, other.bitSet); } /** * Sets the bit at the specified index to the complement of its current value. * * @param bitIndex the index of the bit to flip. * @throws IndexOutOfBoundsException if the specified index is negative. * @return {@code this} instance. */ public FluentBitSet flip(final int bitIndex) { bitSet.flip(bitIndex); return this; } /** * Sets each bit from the specified {@code fromIndex} (inclusive) to the specified {@code toIndex} (exclusive) to the * complement of its current value. * * @param fromIndex index of the first bit to flip. * @param toIndex index after the last bit to flip. * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or {@code toIndex} is negative, or * {@code fromIndex} is larger than {@code toIndex}. * @return {@code this} instance. */ public FluentBitSet flip(final int fromIndex, final int toIndex) { bitSet.flip(fromIndex, toIndex); return this; } /** * Gets the value of the bit with the specified index. The value is {@code true} if the bit with the index * {@code bitIndex} is currently set in this {@link BitSet}; otherwise, the result is {@code false}. * * @param bitIndex the bit index. * @return the value of the bit with the specified index. * @throws IndexOutOfBoundsException if the specified index is negative. */ public boolean get(final int bitIndex) { return bitSet.get(bitIndex); } /** * Gets a new {@link BitSet} composed of bits from this {@link BitSet} from {@code fromIndex} (inclusive) to * {@code toIndex} (exclusive). * * @param fromIndex index of the first bit to include. * @param toIndex index after the last bit to include. * @return a new {@link BitSet} from a range of this {@link BitSet}. * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or {@code toIndex} is negative, or * {@code fromIndex} is larger than {@code toIndex}. */ public FluentBitSet get(final int fromIndex, final int toIndex) { return new FluentBitSet(bitSet.get(fromIndex, toIndex)); } @Override public int hashCode() { return bitSet.hashCode(); } /** * Returns true if the specified {@link BitSet} has any bits set to {@code true} that are also set to {@code true} in * this {@link BitSet}. * * @param set {@link BitSet} to intersect with. * @return boolean indicating whether this {@link BitSet} intersects the specified {@link BitSet}. */ public boolean intersects(final BitSet set) { return bitSet.intersects(set); } /** * Returns true if the specified {@link BitSet} has any bits set to {@code true} that are also set to {@code true} in * this {@link BitSet}. * * @param set {@link BitSet} to intersect with. * @return boolean indicating whether this {@link BitSet} intersects the specified {@link BitSet}. */ public boolean intersects(final FluentBitSet set) { return bitSet.intersects(set.bitSet); } /** * Tests whether if this {@link BitSet} contains no bits that are set to {@code true}. * * @return boolean indicating whether this {@link BitSet} is empty. */ public boolean isEmpty() { return bitSet.isEmpty(); } /** * Returns the "logical size" of this {@link BitSet}: the index of the highest set bit in the {@link BitSet} plus one. * Returns zero if the {@link BitSet} contains no set bits. * * @return the logical size of this {@link BitSet}. */ public int length() { return bitSet.length(); } /** * Returns the index of the first bit that is set to {@code false} that occurs on or after the specified starting index. * * @param fromIndex the index to start checking from (inclusive). * @return the index of the next clear bit. * @throws IndexOutOfBoundsException if the specified index is negative. */ public int nextClearBit(final int fromIndex) { return bitSet.nextClearBit(fromIndex); } /** * Returns the index of the first bit that is set to {@code true} that occurs on or after the specified starting index. * If no such bit exists then {@code -1} is returned. * <p> * To iterate over the {@code true} bits in a {@link BitSet}, use the following loop: * </p> * * <pre> * {@code * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { * // operate on index i here * if (i == Integer.MAX_VALUE) { * break; // or (i+1) would overflow * } * }} * </pre> * * @param fromIndex the index to start checking from (inclusive). * @return the index of the next set bit, or {@code -1} if there is no such bit. * @throws IndexOutOfBoundsException if the specified index is negative. */ public int nextSetBit(final int fromIndex) { return bitSet.nextSetBit(fromIndex); } /** * Performs a logical <strong>OR</strong> of this bit set with the bit set argument. This bit set is modified so that a bit in it * has the value {@code true} if and only if it either already had the value {@code true} or the corresponding bit in * the bit set argument has the value {@code true}. * * @param set a bit set. * @return {@code this} instance. */ public FluentBitSet or(final BitSet set) { bitSet.or(set); return this; } /** * Performs a logical <strong>OR</strong> of this bit set with the bit set arguments. This bit set is modified so that a bit in it * has the value {@code true} if and only if it either already had the value {@code true} or the corresponding bit in * the bit set argument has the value {@code true}. * * @param set a bit set. * @return {@code this} instance. */ public FluentBitSet or(final FluentBitSet... set) { for (final FluentBitSet e : set) { this.bitSet.or(e.bitSet); } return this; } /** * Performs a logical <strong>OR</strong> of this bit set with the bit set argument. This bit set is modified so that a bit in it * has the value {@code true} if and only if it either already had the value {@code true} or the corresponding bit in * the bit set argument has the value {@code true}. * * @param set a bit set. * @return {@code this} instance. */ public FluentBitSet or(final FluentBitSet set) { this.bitSet.or(set.bitSet); return this; } /** * Returns the index of the nearest bit that is set to {@code false} that occurs on or before the specified starting * index. If no such bit exists, or if {@code -1} is given as the starting index, then {@code -1} is returned. * * @param fromIndex the index to start checking from (inclusive). * @return the index of the previous clear bit, or {@code -1} if there is no such bit. * @throws IndexOutOfBoundsException if the specified index is less than {@code -1}. */ public int previousClearBit(final int fromIndex) { return bitSet.previousClearBit(fromIndex); } /** * Returns the index of the nearest bit that is set to {@code true} that occurs on or before the specified starting * index. If no such bit exists, or if {@code -1} is given as the starting index, then {@code -1} is returned. * * <p> * To iterate over the {@code true} bits in a {@link BitSet}, use the following loop: * * <pre> * {@code * for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) { * // operate on index i here * }} * </pre> * * @param fromIndex the index to start checking from (inclusive) * @return the index of the previous set bit, or {@code -1} if there is no such bit * @throws IndexOutOfBoundsException if the specified index is less than {@code -1} */ public int previousSetBit(final int fromIndex) { return bitSet.previousSetBit(fromIndex); } /** * Sets the bit at the specified indexes to {@code true}. * * @param bitIndexArray a bit index array. * @throws IndexOutOfBoundsException if the specified index is negative. * @return {@code this} instance. */ public FluentBitSet set(final int... bitIndexArray) { for (final int e : bitIndexArray) { bitSet.set(e); } return this; } /** * Sets the bit at the specified index to {@code true}. * * @param bitIndex a bit index * @throws IndexOutOfBoundsException if the specified index is negative * @return {@code this} instance. */ public FluentBitSet set(final int bitIndex) { bitSet.set(bitIndex); return this; } /** * Sets the bit at the specified index to the specified value. * * @param bitIndex a bit index. * @param value a boolean value to set. * @throws IndexOutOfBoundsException if the specified index is negative. * @return {@code this} instance. */ public FluentBitSet set(final int bitIndex, final boolean value) { bitSet.set(bitIndex, value); return this; } /** * Sets the bits from the specified {@code fromIndex} (inclusive) to the specified {@code toIndex} (exclusive) to * {@code true}. * * @param fromIndex index of the first bit to be set. * @param toIndex index after the last bit to be set. * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or {@code toIndex} is negative, or * {@code fromIndex} is larger than {@code toIndex}. * @return {@code this} instance. */ public FluentBitSet set(final int fromIndex, final int toIndex) { bitSet.set(fromIndex, toIndex); return this; } /** * Sets the bits from the specified {@code fromIndex} (inclusive) to the specified {@code toIndex} (exclusive) to the * specified value. * * @param fromIndex index of the first bit to be set. * @param toIndex index after the last bit to be set. * @param value value to set the selected bits to. * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or {@code toIndex} is negative, or * {@code fromIndex} is larger than {@code toIndex}. * @return {@code this} instance. */ public FluentBitSet set(final int fromIndex, final int toIndex, final boolean value) { bitSet.set(fromIndex, toIndex, value); return this; } /** * Sets the bits from the specified {@code fromIndex} (inclusive) to the specified {@code toIndex} (inclusive) to * {@code true}. * * @param fromIndex index of the first bit to be set * @param toIndex index of the last bit to be set * @throws IndexOutOfBoundsException if {@code fromIndex} is negative, or {@code toIndex} is negative, or * {@code fromIndex} is larger than {@code toIndex} * @return {@code this} instance. */ public FluentBitSet setInclusive(final int fromIndex, final int toIndex) { bitSet.set(fromIndex, toIndex + 1); return this; } /** * Returns the number of bits of space actually in use by this {@link BitSet} to represent bit values. The maximum * element in the set is the size - 1st element. * * @return the number of bits currently in this bit set. */ public int size() { return bitSet.size(); } /** * Returns a stream of indices for which this {@link BitSet} contains a bit in the set state. The indices are returned * in order, from lowest to highest. The size of the stream is the number of bits in the set state, equal to the value * returned by the {@link #cardinality()} method. * * <p> * The bit set must remain constant during the execution of the terminal stream operation. Otherwise, the result of the * terminal stream operation is undefined. * </p> * * @return a stream of integers representing set indices. * @since 1.8 */ public IntStream stream() { return bitSet.stream(); } /** * Returns a new byte array containing all the bits in this bit set. * * <p> * More precisely, if: * </p> * <ol> * <li>{@code byte[] bytes = s.toByteArray();}</li> * <li>then {@code bytes.length == (s.length()+7)/8} and</li> * <li>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}</li> * <li>for all {@code n < 8 * bytes.length}.</li> * </ol> * * @return a byte array containing a little-endian representation of all the bits in this bit set */ public byte[] toByteArray() { return bitSet.toByteArray(); } /** * Returns a new byte array containing all the bits in this bit set. * * <p> * More precisely, if: * </p> * <ol> * <li>{@code long[] longs = s.toLongArray();}</li> * <li>then {@code longs.length == (s.length()+63)/64} and</li> * <li>{@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}</li> * <li>for all {@code n < 64 * longs.length}.</li> * </ol> * * @return a byte array containing a little-endian representation of all the bits in this bit set */ public long[] toLongArray() { return bitSet.toLongArray(); } @Override public String toString() { return bitSet.toString(); } /** * Performs a logical <strong>XOR</strong> of this bit set with the bit set argument. This bit set is modified so that a bit in it * has the value {@code true} if and only if one of the following statements holds: * <ul> * <li>The bit initially has the value {@code true}, and the corresponding bit in the argument has the value * {@code false}. * <li>The bit initially has the value {@code false}, and the corresponding bit in the argument has the value * {@code true}. * </ul> * * @param set a bit set * @return {@code this} instance. */ public FluentBitSet xor(final BitSet set) { bitSet.xor(set); return this; } /** * Performs a logical <strong>XOR</strong> of this bit set with the bit set argument. This bit set is modified so that a bit in it * has the value {@code true} if and only if one of the following statements holds: * <ul> * <li>The bit initially has the value {@code true}, and the corresponding bit in the argument has the value * {@code false}. * <li>The bit initially has the value {@code false}, and the corresponding bit in the argument has the value * {@code true}. * </ul> * * @param set a bit set * @return {@code this} instance. */ public FluentBitSet xor(final FluentBitSet set) { bitSet.xor(set.bitSet); return this; } }
FluentBitSet
java
apache__camel
components/camel-http/src/test/java/org/apache/camel/component/http/HttpNoConnectionTest.java
{ "start": 1620, "end": 3247 }
class ____ extends BaseHttpTest { private HttpServer localServer; private String endpointUrl; @Override public void setupResources() throws Exception { localServer = ServerBootstrap.bootstrap() .setCanonicalHostName("localhost").setHttpProcessor(getBasicHttpProcessor()) .setConnectionReuseStrategy(getConnectionReuseStrategy()).setResponseFactory(getHttpResponseFactory()) .setSslContext(getSSLContext()) .register("/search", new BasicValidationHandler(GET.name(), null, null, getExpectedContent())).create(); localServer.start(); endpointUrl = "http://localhost:" + localServer.getLocalPort(); } @Override public void cleanupResources() throws Exception { if (localServer != null) { localServer.stop(); } } @Test public void httpConnectionOk() { Exchange exchange = template.request(endpointUrl + "/search", exchange1 -> { }); assertExchange(exchange); } @Test public void httpConnectionNotOk() throws Exception { String url = endpointUrl + "/search"; // stop server so there are no connection localServer.stop(); localServer.awaitTermination(TimeValue.ofSeconds(1)); Exchange reply = template.request(url, null); Exception e = reply.getException(); assertNotNull(e, "Should have thrown an exception"); ConnectException cause = assertIsInstanceOf(ConnectException.class, e); assertTrue(cause.getMessage().contains("failed")); } }
HttpNoConnectionTest
java
dropwizard__dropwizard
dropwizard-validation/src/main/java/io/dropwizard/validation/MinDurationValidator.java
{ "start": 336, "end": 1214 }
class ____ implements ConstraintValidator<MinDuration, Duration> { private long minQty = 0; private TimeUnit minUnit = TimeUnit.MILLISECONDS; private boolean inclusive = true; @Override public void initialize(MinDuration constraintAnnotation) { this.minQty = constraintAnnotation.value(); this.minUnit = constraintAnnotation.unit(); this.inclusive = constraintAnnotation.inclusive(); } @Override public boolean isValid(Duration value, ConstraintValidatorContext context) { if (value == null) { return true; } long valueNanos = value.toNanoseconds(); long annotationNanos = minUnit.toNanos(minQty); if (inclusive) { return valueNanos >= annotationNanos; } else { return valueNanos > annotationNanos; } } }
MinDurationValidator
java
apache__kafka
metadata/src/main/java/org/apache/kafka/metadata/properties/MetaPropertiesEnsemble.java
{ "start": 16351, "end": 23396 }
enum ____ { REQUIRE_V0, REQUIRE_METADATA_LOG_DIR, REQUIRE_AT_LEAST_ONE_VALID } /** * Verify that the metadata properties ensemble is valid. * * We verify that v1 meta.properties files always have cluster.id set. v0 files may or may not * have it set. If it is set, the cluster ID must be the same in all directories. * * We verify that v1 meta.properties files always have node.id set. v0 files may or may not have * it set. If it is set in v0, it will be called broker.id rather than node.id. Node ID must be * the same in call directories. * * directory.id may or may not be set, in both v0 and v1. If it is set, it must not be the same * in multiple directories, and it must be safe. * * @param expectedClusterId The cluster ID to expect, or the empty string if we don't know yet. * @param expectedNodeId The node ID to expect, or -1 if we don't know yet. * @param verificationFlags The flags to use. */ public void verify( Optional<String> expectedClusterId, OptionalInt expectedNodeId, EnumSet<VerificationFlag> verificationFlags ) { Map<Uuid, String> seenUuids = new HashMap<>(); if (verificationFlags.contains(VerificationFlag.REQUIRE_AT_LEAST_ONE_VALID)) { if (logDirProps.isEmpty()) { throw new RuntimeException("No readable meta.properties files found."); } } for (Entry<String, MetaProperties> entry : logDirProps.entrySet()) { String logDir = entry.getKey(); String path = new File(logDir, META_PROPERTIES_NAME).toString(); MetaProperties metaProps = entry.getValue(); if (verificationFlags.contains(VerificationFlag.REQUIRE_V0)) { if (!metaProps.version().equals(MetaPropertiesVersion.V0)) { throw new RuntimeException("Found unexpected version in " + path + ". " + "ZK-based brokers that are not migrating only support version 0 " + "(which is implicit when the `version` field is missing)."); } } if (metaProps.clusterId().isEmpty()) { if (metaProps.version().alwaysHasClusterId()) { throw new RuntimeException("cluster.id was not specified in the v1 file: " + path); } } else if (expectedClusterId.isEmpty()) { expectedClusterId = metaProps.clusterId(); } else if (!metaProps.clusterId().get().equals(expectedClusterId.get())) { throw new RuntimeException("Invalid cluster.id in: " + path + ". Expected " + expectedClusterId.get() + ", but read " + metaProps.clusterId().get()); } if (metaProps.nodeId().isEmpty()) { if (metaProps.version().alwaysHasNodeId()) { throw new RuntimeException("node.id was not specified in " + path); } } else if (expectedNodeId.isEmpty()) { expectedNodeId = metaProps.nodeId(); } else if (metaProps.nodeId().getAsInt() != expectedNodeId.getAsInt()) { throw new RuntimeException("Stored node id " + metaProps.nodeId().getAsInt() + " doesn't match previous node id " + expectedNodeId.getAsInt() + " in " + path + ". If you moved your data, make sure your configured node id matches. If you " + "intend to create a new node, you should remove all data in your data " + "directories."); } if (metaProps.directoryId().isPresent()) { if (DirectoryId.reserved(metaProps.directoryId().get())) { throw new RuntimeException("Invalid reserved directory ID " + metaProps.directoryId().get() + " found in " + logDir); } String prevLogDir = seenUuids.put(metaProps.directoryId().get(), logDir); if (prevLogDir != null) { throw new RuntimeException("Duplicate directory ID " + metaProps.directoryId() + " found. It was the ID of " + prevLogDir + ", " + "but also of " + logDir); } } } if (verificationFlags.contains(VerificationFlag.REQUIRE_METADATA_LOG_DIR)) { if (metadataLogDir.isEmpty()) { throw new RuntimeException("No metadata log directory was specified."); } } if (metadataLogDir.isPresent()) { if (errorLogDirs.contains(metadataLogDir.get())) { throw new RuntimeException("Encountered I/O error in metadata log directory " + metadataLogDir.get() + ". Cannot continue."); } } } /** * Find the node ID of this meta.properties ensemble. * * @return The node ID, or OptionalInt.empty if none could be found. */ public OptionalInt nodeId() { for (MetaProperties metaProps : logDirProps.values()) { if (metaProps.nodeId().isPresent()) { return metaProps.nodeId(); } } return OptionalInt.empty(); } /** * Find the cluster ID of this meta.properties ensemble. * * @return The cluster ID, or Optional.empty if none could be found. */ public Optional<String> clusterId() { for (MetaProperties metaProps : logDirProps.values()) { if (metaProps.clusterId().isPresent()) { return metaProps.clusterId(); } } return Optional.empty(); } @Override public boolean equals(Object o) { if (o == null || (!(o.getClass().equals(MetaPropertiesEnsemble.class)))) { return false; } MetaPropertiesEnsemble other = (MetaPropertiesEnsemble) o; return emptyLogDirs.equals(other.emptyLogDirs) && errorLogDirs.equals(other.errorLogDirs) && logDirProps.equals(other.logDirProps) && metadataLogDir.equals(other.metadataLogDir); } @Override public int hashCode() { return Objects.hash(emptyLogDirs, errorLogDirs, logDirProps, metadataLogDir); } @Override public String toString() { TreeMap<String, String> outputMap = new TreeMap<>(); emptyLogDirs.forEach(e -> outputMap.put(e, "EMPTY")); errorLogDirs.forEach(e -> outputMap.put(e, "ERROR")); logDirProps.forEach((key, value) -> outputMap.put(key, value.toString())); return "MetaPropertiesEnsemble" + "(metadataLogDir=" + metadataLogDir + ", dirs={" + outputMap.entrySet().stream(). map(e -> e.getKey() + ": " + e.getValue()). collect(Collectors.joining(", ")) + "})"; } }
VerificationFlag
java
reactor__reactor-core
reactor-tools/src/jarFileTest/java/reactor/tools/AbstractJarFileTest.java
{ "start": 875, "end": 923 }
class ____ access the content of a shaded JAR */
to
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/config/ConstructorArgumentValues.java
{ "start": 1465, "end": 16685 }
class ____ { private final Map<Integer, ValueHolder> indexedArgumentValues = new LinkedHashMap<>(); private final List<ValueHolder> genericArgumentValues = new ArrayList<>(); /** * Create a new empty ConstructorArgumentValues object. */ public ConstructorArgumentValues() { } /** * Deep copy constructor. * @param original the ConstructorArgumentValues to copy */ public ConstructorArgumentValues(ConstructorArgumentValues original) { addArgumentValues(original); } /** * Copy all given argument values into this object, using separate holder * instances to keep the values independent of the original object. * <p>Note: Identical ValueHolder instances will only be registered once, * to allow for merging and re-merging of argument value definitions. Distinct * ValueHolder instances carrying the same content are of course allowed. */ public void addArgumentValues(@Nullable ConstructorArgumentValues other) { if (other != null) { other.indexedArgumentValues.forEach( (index, argValue) -> addOrMergeIndexedArgumentValue(index, argValue.copy()) ); other.genericArgumentValues.stream() .filter(valueHolder -> !this.genericArgumentValues.contains(valueHolder)) .forEach(valueHolder -> addOrMergeGenericArgumentValue(valueHolder.copy())); } } /** * Add an argument value for the given index in the constructor argument list. * @param index the index in the constructor argument list * @param value the argument value */ public void addIndexedArgumentValue(int index, @Nullable Object value) { addIndexedArgumentValue(index, new ValueHolder(value)); } /** * Add an argument value for the given index in the constructor argument list. * @param index the index in the constructor argument list * @param value the argument value * @param type the type of the constructor argument */ public void addIndexedArgumentValue(int index, @Nullable Object value, String type) { addIndexedArgumentValue(index, new ValueHolder(value, type)); } /** * Add an argument value for the given index in the constructor argument list. * @param index the index in the constructor argument list * @param newValue the argument value in the form of a ValueHolder */ public void addIndexedArgumentValue(int index, ValueHolder newValue) { Assert.isTrue(index >= 0, "Index must not be negative"); Assert.notNull(newValue, "ValueHolder must not be null"); addOrMergeIndexedArgumentValue(index, newValue); } /** * Add an argument value for the given index in the constructor argument list, * merging the new value (typically a collection) with the current value * if demanded: see {@link org.springframework.beans.Mergeable}. * @param key the index in the constructor argument list * @param newValue the argument value in the form of a ValueHolder */ private void addOrMergeIndexedArgumentValue(Integer key, ValueHolder newValue) { ValueHolder currentValue = this.indexedArgumentValues.get(key); if (currentValue != null && newValue.getValue() instanceof Mergeable mergeable) { if (mergeable.isMergeEnabled()) { newValue.setValue(mergeable.merge(currentValue.getValue())); } } this.indexedArgumentValues.put(key, newValue); } /** * Check whether an argument value has been registered for the given index. * @param index the index in the constructor argument list */ public boolean hasIndexedArgumentValue(int index) { return this.indexedArgumentValues.containsKey(index); } /** * Get argument value for the given index in the constructor argument list. * @param index the index in the constructor argument list * @param requiredType the type to match (can be {@code null} to match * untyped values only) * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getIndexedArgumentValue(int index, @Nullable Class<?> requiredType) { return getIndexedArgumentValue(index, requiredType, null); } /** * Get argument value for the given index in the constructor argument list. * @param index the index in the constructor argument list * @param requiredType the type to match (can be {@code null} to match * untyped values only) * @param requiredName the type to match (can be {@code null} to match * unnamed values only, or empty String to match any name) * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getIndexedArgumentValue(int index, @Nullable Class<?> requiredType, @Nullable String requiredName) { Assert.isTrue(index >= 0, "Index must not be negative"); ValueHolder valueHolder = this.indexedArgumentValues.get(index); if (valueHolder != null && (valueHolder.getType() == null || (requiredType != null && ClassUtils.matchesTypeName(requiredType, valueHolder.getType()))) && (valueHolder.getName() == null || (requiredName != null && (requiredName.isEmpty() || requiredName.equals(valueHolder.getName()))))) { return valueHolder; } return null; } /** * Return the map of indexed argument values. * @return unmodifiable Map with Integer index as key and ValueHolder as value * @see ValueHolder */ public Map<Integer, ValueHolder> getIndexedArgumentValues() { return Collections.unmodifiableMap(this.indexedArgumentValues); } /** * Add a generic argument value to be matched by type. * <p>Note: A single generic argument value will just be used once, * rather than matched multiple times. * @param value the argument value */ public void addGenericArgumentValue(@Nullable Object value) { this.genericArgumentValues.add(new ValueHolder(value)); } /** * Add a generic argument value to be matched by type. * <p>Note: A single generic argument value will just be used once, * rather than matched multiple times. * @param value the argument value * @param type the type of the constructor argument */ public void addGenericArgumentValue(Object value, String type) { this.genericArgumentValues.add(new ValueHolder(value, type)); } /** * Add a generic argument value to be matched by type or name (if available). * <p>Note: A single generic argument value will just be used once, * rather than matched multiple times. * @param newValue the argument value in the form of a ValueHolder * <p>Note: Identical ValueHolder instances will only be registered once, * to allow for merging and re-merging of argument value definitions. Distinct * ValueHolder instances carrying the same content are of course allowed. */ public void addGenericArgumentValue(ValueHolder newValue) { Assert.notNull(newValue, "ValueHolder must not be null"); if (!this.genericArgumentValues.contains(newValue)) { addOrMergeGenericArgumentValue(newValue); } } /** * Add a generic argument value, merging the new value (typically a collection) * with the current value if demanded: see {@link org.springframework.beans.Mergeable}. * @param newValue the argument value in the form of a ValueHolder */ private void addOrMergeGenericArgumentValue(ValueHolder newValue) { if (newValue.getName() != null) { for (Iterator<ValueHolder> it = this.genericArgumentValues.iterator(); it.hasNext();) { ValueHolder currentValue = it.next(); if (newValue.getName().equals(currentValue.getName())) { if (newValue.getValue() instanceof Mergeable mergeable) { if (mergeable.isMergeEnabled()) { newValue.setValue(mergeable.merge(currentValue.getValue())); } } it.remove(); } } } this.genericArgumentValues.add(newValue); } /** * Look for a generic argument value that matches the given type. * @param requiredType the type to match * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getGenericArgumentValue(Class<?> requiredType) { return getGenericArgumentValue(requiredType, null, null); } /** * Look for a generic argument value that matches the given type. * @param requiredType the type to match * @param requiredName the name to match * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getGenericArgumentValue(Class<?> requiredType, String requiredName) { return getGenericArgumentValue(requiredType, requiredName, null); } /** * Look for the next generic argument value that matches the given type, * ignoring argument values that have already been used in the current * resolution process. * @param requiredType the type to match (can be {@code null} to find * an arbitrary next generic argument value) * @param requiredName the name to match (can be {@code null} to not * match argument values by name, or empty String to match any name) * @param usedValueHolders a Set of ValueHolder objects that have already been used * in the current resolution process and should therefore not be returned again * @return the ValueHolder for the argument, or {@code null} if none found */ public @Nullable ValueHolder getGenericArgumentValue(@Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) { for (ValueHolder valueHolder : this.genericArgumentValues) { if (usedValueHolders != null && usedValueHolders.contains(valueHolder)) { continue; } if (valueHolder.getName() != null && (requiredName == null || (!requiredName.isEmpty() && !requiredName.equals(valueHolder.getName())))) { continue; } if (valueHolder.getType() != null && (requiredType == null || !ClassUtils.matchesTypeName(requiredType, valueHolder.getType()))) { continue; } if (requiredType != null && valueHolder.getType() == null && valueHolder.getName() == null && !ClassUtils.isAssignableValue(requiredType, valueHolder.getValue())) { continue; } return valueHolder; } return null; } /** * Return the list of generic argument values. * @return unmodifiable List of ValueHolders * @see ValueHolder */ public List<ValueHolder> getGenericArgumentValues() { return Collections.unmodifiableList(this.genericArgumentValues); } /** * Look for an argument value that either corresponds to the given index * in the constructor argument list or generically matches by type. * @param index the index in the constructor argument list * @param requiredType the parameter type to match * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getArgumentValue(int index, Class<?> requiredType) { return getArgumentValue(index, requiredType, null, null); } /** * Look for an argument value that either corresponds to the given index * in the constructor argument list or generically matches by type. * @param index the index in the constructor argument list * @param requiredType the parameter type to match * @param requiredName the parameter name to match * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getArgumentValue(int index, Class<?> requiredType, String requiredName) { return getArgumentValue(index, requiredType, requiredName, null); } /** * Look for an argument value that either corresponds to the given index * in the constructor argument list or generically matches by type. * @param index the index in the constructor argument list * @param requiredType the parameter type to match (can be {@code null} * to find an untyped argument value) * @param requiredName the parameter name to match (can be {@code null} * to find an unnamed argument value, or empty String to match any name) * @param usedValueHolders a Set of ValueHolder objects that have already * been used in the current resolution process and should therefore not * be returned again (allowing to return the next generic argument match * in case of multiple generic argument values of the same type) * @return the ValueHolder for the argument, or {@code null} if none set */ public @Nullable ValueHolder getArgumentValue(int index, @Nullable Class<?> requiredType, @Nullable String requiredName, @Nullable Set<ValueHolder> usedValueHolders) { Assert.isTrue(index >= 0, "Index must not be negative"); ValueHolder valueHolder = getIndexedArgumentValue(index, requiredType, requiredName); if (valueHolder == null) { valueHolder = getGenericArgumentValue(requiredType, requiredName, usedValueHolders); } return valueHolder; } /** * Determine whether at least one argument value refers to a name. * @since 6.0.3 * @see ValueHolder#getName() */ public boolean containsNamedArgument() { for (ValueHolder valueHolder : this.indexedArgumentValues.values()) { if (valueHolder.getName() != null) { return true; } } for (ValueHolder valueHolder : this.genericArgumentValues) { if (valueHolder.getName() != null) { return true; } } return false; } /** * Return the number of argument values held in this instance, * counting both indexed and generic argument values. */ public int getArgumentCount() { return (this.indexedArgumentValues.size() + this.genericArgumentValues.size()); } /** * Return if this holder does not contain any argument values, * neither indexed ones nor generic ones. */ public boolean isEmpty() { return (this.indexedArgumentValues.isEmpty() && this.genericArgumentValues.isEmpty()); } /** * Clear this holder, removing all argument values. */ public void clear() { this.indexedArgumentValues.clear(); this.genericArgumentValues.clear(); } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (!(other instanceof ConstructorArgumentValues that)) { return false; } if (this.genericArgumentValues.size() != that.genericArgumentValues.size() || this.indexedArgumentValues.size() != that.indexedArgumentValues.size()) { return false; } Iterator<ValueHolder> it1 = this.genericArgumentValues.iterator(); Iterator<ValueHolder> it2 = that.genericArgumentValues.iterator(); while (it1.hasNext() && it2.hasNext()) { ValueHolder vh1 = it1.next(); ValueHolder vh2 = it2.next(); if (!vh1.contentEquals(vh2)) { return false; } } for (Map.Entry<Integer, ValueHolder> entry : this.indexedArgumentValues.entrySet()) { ValueHolder vh1 = entry.getValue(); ValueHolder vh2 = that.indexedArgumentValues.get(entry.getKey()); if (vh2 == null || !vh1.contentEquals(vh2)) { return false; } } return true; } @Override public int hashCode() { int hashCode = 7; for (ValueHolder valueHolder : this.genericArgumentValues) { hashCode = 31 * hashCode + valueHolder.contentHashCode(); } hashCode = 29 * hashCode; for (Map.Entry<Integer, ValueHolder> entry : this.indexedArgumentValues.entrySet()) { hashCode = 31 * hashCode + (entry.getValue().contentHashCode() ^ entry.getKey().hashCode()); } return hashCode; } /** * Holder for a constructor argument value, with an optional type * attribute indicating the target type of the actual constructor argument. */ public static
ConstructorArgumentValues
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldContainNull_create_Test.java
{ "start": 980, "end": 1432 }
class ____ { @Test void should_create_error_message() { // GIVEN String[] array = array("Luke", "Yoda"); ErrorMessageFactory factory = shouldContainNull(array); // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo("[Test] %nExpecting actual:%n [\"Luke\", \"Yoda\"]%nto contain a null element".formatted()); } }
ShouldContainNull_create_Test
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/convention/TestBeanForMultipleNestingLevelsIntegrationTests.java
{ "start": 1771, "end": 2044 }
class ____ { @TestBean(name = "field2", methodName = "testField2") String field2; @Test void test() { assertThat(field0).isEqualTo("zero"); assertThat(field1).isEqualTo("one"); assertThat(field2).isEqualTo("two"); } @Nested
NestedLevel2Tests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/record/FileRecords.java
{ "start": 20029, "end": 21448 }
class ____ { public final long offset; public final int position; public final int size; public static LogOffsetPosition fromBatch(FileChannelRecordBatch batch) { return new LogOffsetPosition(batch.baseOffset(), batch.position(), batch.sizeInBytes()); } public LogOffsetPosition(long offset, int position, int size) { this.offset = offset; this.position = position; this.size = size; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LogOffsetPosition that = (LogOffsetPosition) o; return offset == that.offset && position == that.position && size == that.size; } @Override public int hashCode() { int result = Long.hashCode(offset); result = 31 * result + position; result = 31 * result + size; return result; } @Override public String toString() { return "LogOffsetPosition(" + "offset=" + offset + ", position=" + position + ", size=" + size + ')'; } } public static
LogOffsetPosition
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMerge.java
{ "start": 2311, "end": 7235 }
class ____ { private static final int NUM_HADOOP_DATA_NODES = 2; // Number of input files is same as the number of mappers. private static final int NUM_MAPPERS = 10; // Number of reducers. private static final int NUM_REDUCERS = 4; // Number of lines per input file. private static final int NUM_LINES = 1000; // Where MR job's input will reside. private static final Path INPUT_DIR = new Path("/testplugin/input"); // Where output goes. private static final Path OUTPUT = new Path("/testplugin/output"); @Test public void testMerge() throws Exception { MiniDFSCluster dfsCluster = null; MiniMRClientCluster mrCluster = null; FileSystem fileSystem = null; try { Configuration conf = new Configuration(); // Start the mini-MR and mini-DFS clusters dfsCluster = new MiniDFSCluster.Builder(conf) .numDataNodes(NUM_HADOOP_DATA_NODES).build(); fileSystem = dfsCluster.getFileSystem(); mrCluster = MiniMRClientClusterFactory.create(this.getClass(), NUM_HADOOP_DATA_NODES, conf); // Generate input. createInput(fileSystem); // Run the test. runMergeTest(new JobConf(mrCluster.getConfig()), fileSystem); } finally { if (mrCluster != null) { mrCluster.stop(); } if (dfsCluster != null) { dfsCluster.shutdown(); } } } private void createInput(FileSystem fs) throws Exception { fs.delete(INPUT_DIR, true); for (int i = 0; i < NUM_MAPPERS; i++) { OutputStream os = fs.create(new Path(INPUT_DIR, "input_" + i + ".txt")); Writer writer = new OutputStreamWriter(os); for (int j = 0; j < NUM_LINES; j++) { // Create sorted key, value pairs. int k = j + 1; String formattedNumber = String.format("%09d", k); writer.write(formattedNumber + " " + formattedNumber + "\n"); } writer.close(); } } private void runMergeTest(JobConf job, FileSystem fileSystem) throws Exception { // Delete any existing output. fileSystem.delete(OUTPUT, true); job.setJobName("MergeTest"); JobClient client = new JobClient(job); RunningJob submittedJob = null; FileInputFormat.setInputPaths(job, INPUT_DIR); FileOutputFormat.setOutputPath(job, OUTPUT); job.set("mapreduce.output.textoutputformat.separator", " "); job.setInputFormat(TextInputFormat.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(MyMapper.class); job.setPartitionerClass(MyPartitioner.class); job.setOutputFormat(TextOutputFormat.class); job.setNumReduceTasks(NUM_REDUCERS); job.set(JobContext.MAP_OUTPUT_COLLECTOR_CLASS_ATTR, MapOutputCopier.class.getName()); try { submittedJob = client.submitJob(job); try { if (! client.monitorAndPrintJob(job, submittedJob)) { throw new IOException("Job failed!"); } } catch(InterruptedException ie) { Thread.currentThread().interrupt(); } } catch(IOException ioe) { System.err.println("Job failed with: " + ioe); } finally { verifyOutput(submittedJob, fileSystem); } } private void verifyOutput(RunningJob submittedJob, FileSystem fileSystem) throws Exception { FSDataInputStream dis = null; long numValidRecords = 0; long numInvalidRecords = 0; long numMappersLaunched = NUM_MAPPERS; String prevKeyValue = "000000000"; Path[] fileList = FileUtil.stat2Paths(fileSystem.listStatus(OUTPUT, new Utils.OutputFileUtils.OutputFilesFilter())); for (Path outFile : fileList) { try { dis = fileSystem.open(outFile); String record; while((record = dis.readLine()) != null) { // Split the line into key and value. int blankPos = record.indexOf(" "); String keyString = record.substring(0, blankPos); String valueString = record.substring(blankPos+1); // Check for sorted output and correctness of record. if (keyString.compareTo(prevKeyValue) >= 0 && keyString.equals(valueString)) { prevKeyValue = keyString; numValidRecords++; } else { numInvalidRecords++; } } } finally { if (dis != null) { dis.close(); dis = null; } } } // Make sure we got all input records in the output in sorted order. assertEquals((long)(NUM_MAPPERS*NUM_LINES), numValidRecords); // Make sure there is no extraneous invalid record. assertEquals(0, numInvalidRecords); } /** * A mapper implementation that assumes that key text contains valid integers * in displayable form. */ public static
TestMerge
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/FailingBeforeAndAfterMethodsSpringExtensionTests.java
{ "start": 5750, "end": 5992 }
class ____ implements TestExecutionListener { @Override public void beforeTestExecution(TestContext testContext) { fail("always failing beforeTestExecution()"); } } private static
AlwaysFailingBeforeTestExecutionTestExecutionListener
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/atomic/long_/AtomicLongAssert_hasNegativeValue_Test.java
{ "start": 805, "end": 1146 }
class ____ extends AtomicLongAssertBaseTest { @Override protected AtomicLongAssert invoke_api_method() { return assertions.hasNegativeValue(); } @Override protected void verify_internal_effects() { verify(longs).assertIsNegative(getInfo(assertions), getActual(assertions).get()); } }
AtomicLongAssert_hasNegativeValue_Test
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowHMSMetaStatement.java
{ "start": 849, "end": 1532 }
class ____ extends MySqlStatementImpl implements MySqlShowStatement { private SQLName name; public SQLName getName() { return name; } public void setName(SQLName name) { this.name = name; } public String getSchema() { if (name instanceof SQLPropertyExpr) { return ((SQLPropertyExpr) name).getOwnernName(); } return null; } public String getTableName() { return name.getSimpleName(); } public void accept0(MySqlASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, name); } visitor.endVisit(this); } }
MySqlShowHMSMetaStatement
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/components/MappedSuperclassComponentWithCollectionTest.java
{ "start": 6878, "end": 7155 }
class ____ extends AbstractEntity { @Embedded private Information information; public Information getInformation() { return information; } public void setInformation(Information information) { this.information = information; } } @Entity public static
Person
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/FluentQuerySupport.java
{ "start": 3540, "end": 3660 }
interface ____<Q> { Q createQuery(FluentQuerySupport<?, ?> query, ScrollPosition scrollPosition); } }
ScrollQueryFactory
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java
{ "start": 2559, "end": 2837 }
class ____ { @Bean(destroyMethod="destroy") Object foo() { return null; } } assertThat(beanDef(Config.class).getDestroyMethodName()).as("destroy method name was not propagated").isEqualTo("destroy"); } @Test void dependsOnMetadataIsPropagated() { @Configuration
Config
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/SQLDialectTest.java
{ "start": 274, "end": 1986 }
class ____ { @Test public void odps() { DbType dbType = DbType.odps; SQLDialect dialect = SQLDialect.of(dbType); assertEquals(dbType, dialect.getDbType()); assertTrue(SQLDialect.Quote.isValidQuota(dialect.getQuoteChars(), SQLDialect.Quote.BACK_QUOTE)); assertFalse(dialect.isKeyword("")); assertTrue(dialect.isKeyword("AND")); assertTrue(dialect.isAliasKeyword("ALTER")); assertFalse(dialect.isAliasKeyword("AND")); } @Test public void hive() { DbType dbType = DbType.hive; SQLDialect dialect = SQLDialect.of(dbType); assertEquals(dbType, dialect.getDbType()); assertTrue(dialect.isBuiltInDataType("TIMESTAMP")); } @Test public void mysql() { DbType dbType = DbType.mysql; SQLDialect dialect = SQLDialect.of(dbType); assertEquals(dbType, dialect.getDbType()); assertFalse(dialect.isKeyword("")); assertTrue(dialect.isKeyword("zerofill")); } @Test public void oracle() { DbType dbType = DbType.oracle; SQLDialect dialect = SQLDialect.of(dbType); assertEquals(dbType, dialect.getDbType()); assertFalse(dialect.isKeyword("")); assertTrue(dialect.isKeyword("whenever")); } @Test public void postgresql() { DbType dbType = DbType.postgresql; SQLDialect dialect = SQLDialect.of(dbType); assertEquals(dbType, dialect.getDbType()); assertTrue(SQLDialect.Quote.isValidQuota(dialect.getQuoteChars(), SQLDialect.Quote.DOUBLE_QUOTE)); assertFalse(dialect.isKeyword("")); assertTrue(dialect.isKeyword("asymmetric")); } }
SQLDialectTest
java
redisson__redisson
redisson-tomcat/redisson-tomcat-7/src/main/java/org/redisson/tomcat/RedissonSession.java
{ "start": 1311, "end": 19241 }
class ____ extends StandardSession { private static final String IS_NEW_ATTR = "session:isNew"; private static final String IS_VALID_ATTR = "session:isValid"; private static final String THIS_ACCESSED_TIME_ATTR = "session:thisAccessedTime"; private static final String MAX_INACTIVE_INTERVAL_ATTR = "session:maxInactiveInterval"; private static final String LAST_ACCESSED_TIME_ATTR = "session:lastAccessedTime"; private static final String CREATION_TIME_ATTR = "session:creationTime"; private static final String IS_EXPIRATION_LOCKED = "session:isExpirationLocked"; private static final String PRINCIPAL_ATTR = "session:principal"; private static final String AUTHTYPE_ATTR = "session:authtype"; public static final Set<String> ATTRS = new HashSet<String>(Arrays.asList( IS_NEW_ATTR, IS_VALID_ATTR, THIS_ACCESSED_TIME_ATTR, MAX_INACTIVE_INTERVAL_ATTR, LAST_ACCESSED_TIME_ATTR, CREATION_TIME_ATTR, IS_EXPIRATION_LOCKED, PRINCIPAL_ATTR, AUTHTYPE_ATTR )); private boolean isExpirationLocked; private boolean loaded; private final RedissonSessionManager redissonManager; private final Map<String, Object> attrs; private RMap<String, Object> map; private final RTopic topic; private final ReadMode readMode; private final UpdateMode updateMode; private final AtomicInteger usages = new AtomicInteger(); private Map<String, Object> loadedAttributes = Collections.emptyMap(); private Map<String, Object> updatedAttributes = Collections.emptyMap(); private Set<String> removedAttributes = Collections.emptySet(); private final boolean broadcastSessionEvents; private final boolean broadcastSessionUpdates; public RedissonSession(RedissonSessionManager manager, ReadMode readMode, UpdateMode updateMode, boolean broadcastSessionEvents, boolean broadcastSessionUpdates) { super(manager); this.redissonManager = manager; this.readMode = readMode; this.updateMode = updateMode; this.topic = redissonManager.getTopic(); this.broadcastSessionEvents = broadcastSessionEvents; this.broadcastSessionUpdates = broadcastSessionUpdates; if (updateMode == UpdateMode.AFTER_REQUEST) { removedAttributes = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); } if (readMode == ReadMode.REDIS) { loadedAttributes = new ConcurrentHashMap<>(); updatedAttributes = new ConcurrentHashMap<>(); } try { Field attr = StandardSession.class.getDeclaredField("attributes"); attrs = (Map<String, Object>) attr.get(this); } catch (Exception e) { throw new IllegalStateException(e); } } private static final long serialVersionUID = -2518607181636076487L; @Override public Object getAttribute(String name) { if (readMode == ReadMode.REDIS) { if (!isValidInternal()) { throw new IllegalStateException(sm.getString("standardSession.getAttribute.ise")); } if (name == null) { return null; } if (removedAttributes.contains(name)) { return super.getAttribute(name); } Object value = loadedAttributes.get(name); if (value == null) { value = map.get(name); if (value != null) { loadedAttributes.put(name, value); } } return value; } else { if (!loaded) { synchronized (this) { if (!loaded) { Map<String, Object> storedAttrs = map.readAllMap(); load(storedAttrs); loaded = true; } } } } return super.getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { if (readMode == ReadMode.REDIS) { if (!isValidInternal()) { throw new IllegalStateException (sm.getString("standardSession.getAttributeNames.ise")); } Set<String> attributeKeys = new HashSet<>(); attributeKeys.addAll(map.readAllKeySet()); attributeKeys.addAll(loadedAttributes.keySet()); return Collections.enumeration(attributeKeys); } return super.getAttributeNames(); } @Override public String[] getValueNames() { if (readMode == ReadMode.REDIS) { if (!isValidInternal()) { throw new IllegalStateException (sm.getString("standardSession.getAttributeNames.ise")); } Set<String> keys = map.readAllKeySet(); return keys.toArray(new String[keys.size()]); } return super.getValueNames(); } public void delete() { if (map == null) { map = redissonManager.getMap(id); } if (broadcastSessionEvents) { RSet<String> set = redissonManager.getNotifiedNodes(id); set.add(redissonManager.getNodeId()); set.expire(Duration.ofSeconds(60)); map.fastPut(IS_EXPIRATION_LOCKED, true); map.expire(Duration.ofSeconds(60)); } else { map.delete(); } if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates) { topic.publish(new AttributesClearMessage(redissonManager.getNodeId(), getId())); } map = null; loadedAttributes.clear(); updatedAttributes.clear(); } @Override public void setCreationTime(long time) { super.setCreationTime(time); if (map != null) { Map<String, Object> newMap = new HashMap<String, Object>(3); newMap.put(CREATION_TIME_ATTR, creationTime); newMap.put(LAST_ACCESSED_TIME_ATTR, lastAccessedTime); newMap.put(THIS_ACCESSED_TIME_ATTR, thisAccessedTime); map.putAll(newMap); if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates) { topic.publish(createPutAllMessage(newMap)); } } } @Override public void access() { super.access(); fastPut(THIS_ACCESSED_TIME_ATTR, thisAccessedTime); expireSession(); } public void superAccess() { super.access(); } public void superEndAccess() { super.endAccess(); } protected void expireSession() { RMap<String, Object> m = map; if (isExpirationLocked || m == null) { return; } if (maxInactiveInterval >= 0) { m.expire(Duration.ofSeconds(maxInactiveInterval + 60)); } } protected AttributesPutAllMessage createPutAllMessage(Map<String, Object> newMap) { try { return new AttributesPutAllMessage(redissonManager, getId(), newMap, this.map.getCodec().getMapValueEncoder()); } catch (Exception e) { throw new IllegalStateException(e); } } @Override public void setMaxInactiveInterval(int interval) { super.setMaxInactiveInterval(interval); fastPut(MAX_INACTIVE_INTERVAL_ATTR, maxInactiveInterval); expireSession(); } private void fastPut(String name, Object value) { RMap<String, Object> m = map; if (m == null) { return; } m.fastPut(name, value); if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates) { try { Encoder encoder = m.getCodec().getMapValueEncoder(); topic.publish(new AttributeUpdateMessage(redissonManager.getNodeId(), getId(), name, value, encoder)); } catch (IOException e) { throw new IllegalStateException(e); } } } @Override public void setPrincipal(Principal principal) { super.setPrincipal(principal); if (principal == null) { removeRedisAttribute(PRINCIPAL_ATTR); } else { fastPut(PRINCIPAL_ATTR, principal); } } @Override public void setAuthType(String authType) { super.setAuthType(authType); if (authType == null) { removeRedisAttribute(AUTHTYPE_ATTR); } else { fastPut(AUTHTYPE_ATTR, authType); } } @Override public void setValid(boolean isValid) { super.setValid(isValid); if (map != null) { if (!isValid && !map.isExists()) { return; } fastPut(IS_VALID_ATTR, isValid); } } @Override public void setNew(boolean isNew) { super.setNew(isNew); fastPut(IS_NEW_ATTR, isNew); } @Override public void endAccess() { boolean oldValue = isNew; super.endAccess(); RMap<String, Object> m = map; if (m != null) { Map<String, Object> newMap = new HashMap<>(3); if (isNew != oldValue) { newMap.put(IS_NEW_ATTR, isNew); } newMap.put(LAST_ACCESSED_TIME_ATTR, lastAccessedTime); newMap.put(THIS_ACCESSED_TIME_ATTR, thisAccessedTime); m.putAll(newMap); if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates) { topic.publish(createPutAllMessage(newMap)); } expireSession(); } } @Override public void setAttribute(String name, Object value, boolean notify) { super.setAttribute(name, value, notify); if (value == null) { return; } if (updateMode == UpdateMode.DEFAULT) { fastPut(name, value); } if (readMode == ReadMode.REDIS) { loadedAttributes.put(name, value); updatedAttributes.put(name, value); } if (updateMode == UpdateMode.AFTER_REQUEST) { removedAttributes.remove(name); } } public void superRemoveAttributeInternal(String name, boolean notify) { super.removeAttributeInternal(name, notify); } @Override public boolean isValid() { if (!this.isValid) { return false; } else if (this.expiring) { return true; } else if (ACTIVITY_CHECK && this.accessCount.get() > 0) { return true; } else { if (this.maxInactiveInterval > 0) { long idleTime = getIdleTimeInternal(); if (map != null && readMode == ReadMode.REDIS) { if (idleTime >= getMaxInactiveInterval() * 1000) { load(map.getAll(RedissonSession.ATTRS)); idleTime = getIdleTimeInternal(); } } if (idleTime >= getMaxInactiveInterval() * 1000) { this.expire(true); } } return this.isValid; } } private long getIdleTimeInternal() { long timeNow = System.currentTimeMillis(); if (LAST_ACCESS_AT_START) { return timeNow - lastAccessedTime; } return timeNow - thisAccessedTime; } @Override protected void removeAttributeInternal(String name, boolean notify) { super.removeAttributeInternal(name, notify); removeRedisAttribute(name); } private void removeRedisAttribute(String name) { if (updateMode == UpdateMode.DEFAULT && map != null) { map.fastRemove(name); if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates) { topic.publish(new AttributeRemoveMessage(redissonManager.getNodeId(), getId(), new HashSet<String>(Arrays.asList(name)))); } } if (readMode == ReadMode.REDIS) { loadedAttributes.remove(name); updatedAttributes.remove(name); } if (updateMode == UpdateMode.AFTER_REQUEST) { removedAttributes.add(name); } } @Override public void setId(String id, boolean notify) { if ((this.id != null) && (manager != null)) { redissonManager.superRemove(this); if (map == null) { map = redissonManager.getMap(this.id); } String newName = redissonManager.getTomcatSessionKeyName(id); if (!map.getName().equals(newName)) { map.rename(newName); } } boolean idWasNull = this.id == null; this.id = id; if (manager != null) { if (idWasNull) { redissonManager.add(this); } else { redissonManager.superAdd(this); } } if (notify) { tellNew(); } } public void save() { if (map == null) { map = redissonManager.getMap(id); } Map<String, Object> newMap = new HashMap<String, Object>(); newMap.put(CREATION_TIME_ATTR, creationTime); newMap.put(LAST_ACCESSED_TIME_ATTR, lastAccessedTime); newMap.put(THIS_ACCESSED_TIME_ATTR, thisAccessedTime); newMap.put(MAX_INACTIVE_INTERVAL_ATTR, maxInactiveInterval); newMap.put(IS_VALID_ATTR, isValid); newMap.put(IS_NEW_ATTR, isNew); if (principal != null) { newMap.put(PRINCIPAL_ATTR, principal); } if (authType != null) { newMap.put(AUTHTYPE_ATTR, authType); } if (broadcastSessionEvents) { newMap.put(IS_EXPIRATION_LOCKED, isExpirationLocked); } if (readMode == ReadMode.MEMORY) { if (attrs != null) { for (Entry<String, Object> entry : attrs.entrySet()) { newMap.put(entry.getKey(), copy(entry.getValue())); } } } else { newMap.putAll(updatedAttributes); updatedAttributes.clear(); } map.putAll(newMap); map.fastRemove(removedAttributes.toArray(new String[0])); if (readMode == ReadMode.MEMORY && this.broadcastSessionUpdates) { topic.publish(createPutAllMessage(newMap)); if (updateMode == UpdateMode.AFTER_REQUEST) { if (!removedAttributes.isEmpty()) { topic.publish(new AttributeRemoveMessage(redissonManager.getNodeId(), getId(), new HashSet<>(removedAttributes))); } } } removedAttributes.clear(); expireSession(); } private Object copy(Object value) { try { if (value instanceof Collection) { Collection newInstance = (Collection) value.getClass().getDeclaredConstructor().newInstance(); newInstance.addAll((Collection) value); value = newInstance; } if (value instanceof Map) { Map newInstance = (Map) value.getClass().getDeclaredConstructor().newInstance(); newInstance.putAll((Map) value); value = newInstance; } } catch (Exception e) { // can't be copied } return value; } public void load(Map<String, Object> attrs) { Long creationTime = (Long) attrs.remove(CREATION_TIME_ATTR); if (creationTime != null) { this.creationTime = creationTime; } Long lastAccessedTime = (Long) attrs.remove(LAST_ACCESSED_TIME_ATTR); if (lastAccessedTime != null) { this.lastAccessedTime = lastAccessedTime; } Integer maxInactiveInterval = (Integer) attrs.remove(MAX_INACTIVE_INTERVAL_ATTR); if (maxInactiveInterval != null) { this.maxInactiveInterval = maxInactiveInterval; } Long thisAccessedTime = (Long) attrs.remove(THIS_ACCESSED_TIME_ATTR); if (thisAccessedTime != null) { this.thisAccessedTime = thisAccessedTime; } Boolean isValid = (Boolean) attrs.remove(IS_VALID_ATTR); if (isValid != null) { this.isValid = isValid; } Boolean isNew = (Boolean) attrs.remove(IS_NEW_ATTR); if (isNew != null) { this.isNew = isNew; } Boolean isExpirationLocked = (Boolean) attrs.remove(IS_EXPIRATION_LOCKED); if (isExpirationLocked != null) { this.isExpirationLocked = isExpirationLocked; } Principal p = (Principal) attrs.remove(PRINCIPAL_ATTR); if (p != null) { this.principal = p; } String authType = (String) attrs.remove(AUTHTYPE_ATTR); if (authType != null) { this.authType = authType; } if (readMode == ReadMode.MEMORY) { for (Entry<String, Object> entry : attrs.entrySet()) { super.setAttribute(entry.getKey(), entry.getValue(), false); } } } @Override public void recycle() { super.recycle(); map = null; loadedAttributes.clear(); updatedAttributes.clear(); removedAttributes.clear(); } public void startUsage() { usages.incrementAndGet(); } public void endUsage() { // don't decrement usages if startUsage wasn't called // if (usages.decrementAndGet() == 0) { if (usages.get() == 0 || usages.decrementAndGet() == 0) { loadedAttributes.clear(); } } }
RedissonSession
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/conditional/LeastIntEvaluator.java
{ "start": 4866, "end": 5616 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory[] values; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory[] values) { this.source = source; this.values = values; } @Override public LeastIntEvaluator get(DriverContext context) { EvalOperator.ExpressionEvaluator[] values = Arrays.stream(this.values).map(a -> a.get(context)).toArray(EvalOperator.ExpressionEvaluator[]::new); return new LeastIntEvaluator(source, values, context); } @Override public String toString() { return "LeastIntEvaluator[" + "values=" + Arrays.toString(values) + "]"; } } }
Factory
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/main/java/org/springframework/boot/webmvc/test/autoconfigure/WebDriverContextCustomizer.java
{ "start": 1110, "end": 1574 }
class ____ implements ContextCustomizer { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { WebDriverScope.registerWith(context); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } return obj != null && obj.getClass() == getClass(); } @Override public int hashCode() { return getClass().hashCode(); } }
WebDriverContextCustomizer
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java
{ "start": 10513, "end": 10666 }
class ____ { } @Retention(RetentionPolicy.RUNTIME) @ImportAutoConfiguration(ImportedAutoConfiguration.class) @
ImportWithSelfAnnotatingAnnotationExclude
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhance/internal/bytebuddy/DirtyCheckingWithEmbeddableAndNonVisibleGenericMappedSuperclassWithDifferentGenericParameterNameTest.java
{ "start": 2892, "end": 3311 }
class ____ extends MyAbstractEmbeddable { @Column private String text; public MyEmbeddable() { } private MyEmbeddable(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } } @MappedSuperclass // The key to reproducing the problem is to use a different name for the generic parameter // in this
MyEmbeddable
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/ScanArgs.java
{ "start": 1588, "end": 4592 }
class ____ { /** * Utility constructor. */ private Builder() { } /** * Creates new {@link ScanArgs} with {@literal LIMIT} set. * * @param count number of elements to scan * @return new {@link ScanArgs} with {@literal LIMIT} set. * @see ScanArgs#limit(long) */ public static ScanArgs limit(long count) { return new ScanArgs().limit(count); } /** * Creates new {@link ScanArgs} with {@literal MATCH} set. * * @param matches the filter. * @return new {@link ScanArgs} with {@literal MATCH} set. * @see ScanArgs#match(String) */ public static ScanArgs matches(String matches) { return new ScanArgs().match(matches); } /** * Creates new {@link ScanArgs} with {@literal MATCH} set. * * @param matches the filter. * @return new {@link ScanArgs} with {@literal MATCH} set. * @since 6.0.4 * @see ScanArgs#match(byte[]) */ public static ScanArgs matches(byte[] matches) { return new ScanArgs().match(matches); } } /** * Set the match filter. Uses {@link StandardCharsets#UTF_8 UTF-8} to encode {@code match}. * * @param match the filter, must not be {@code null}. * @return {@literal this} {@link ScanArgs}. */ public ScanArgs match(String match) { return match(match, StandardCharsets.UTF_8); } /** * Set the match filter along the given {@link Charset}. * * @param match the filter, must not be {@code null}. * @param charset the charset for match, must not be {@code null}. * @return {@literal this} {@link ScanArgs}. * @since 6.0 */ public ScanArgs match(String match, Charset charset) { LettuceAssert.notNull(match, "Match must not be null"); LettuceAssert.notNull(charset, "Charset must not be null"); return match(match.getBytes(charset)); } /** * Set the match filter. * * @param match the filter, must not be {@code null}. * @return {@literal this} {@link ScanArgs}. * @since 6.0.4 */ public ScanArgs match(byte[] match) { LettuceAssert.notNull(match, "Match must not be null"); this.match = new byte[match.length]; System.arraycopy(match, 0, this.match, 0, match.length); return this; } /** * Limit the scan by count * * @param count number of elements to scan * @return {@literal this} {@link ScanArgs}. */ public ScanArgs limit(long count) { this.count = count; return this; } @Override public <K, V> void build(CommandArgs<K, V> args) { if (match != null) { args.add(MATCH).add(match); } if (count != null) { args.add(COUNT).add(count); } } }
Builder
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/async/AsyncExecutionIdWireTests.java
{ "start": 491, "end": 1195 }
class ____ extends AbstractWireSerializingTestCase<AsyncExecutionId> { @Override protected Writeable.Reader<AsyncExecutionId> instanceReader() { return AsyncExecutionId::readFrom; } @Override protected AsyncExecutionId createTestInstance() { return new AsyncExecutionId(randomAlphaOfLength(15), new TaskId(randomAlphaOfLength(10), randomLong())); } @Override protected AsyncExecutionId mutateInstance(AsyncExecutionId instance) throws IOException { return new AsyncExecutionId( instance.getDocId(), new TaskId(instance.getTaskId().getNodeId(), instance.getTaskId().getId() * 12345) ); } }
AsyncExecutionIdWireTests
java
apache__camel
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/HazelcastUtil.java
{ "start": 1028, "end": 1703 }
class ____ { private HazelcastUtil() { } public static HazelcastInstance newInstance() { Config cfg = new XmlConfigBuilder().build(); // hazelcast.version.check.enabled is deprecated cfg.setProperty( "hazelcast.phone.home.enabled", System.getProperty("hazelcast.phone.home.enabled", "false")); cfg.setProperty( "hazelcast.logging.type", System.getProperty("hazelcast.logging.type", "slf4j")); return newInstance(cfg); } public static HazelcastInstance newInstance(Config cfg) { return Hazelcast.newHazelcastInstance(cfg); } }
HazelcastUtil
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/util/RestUtils.java
{ "start": 7002, "end": 8508 }
interface ____ { int START = 0; int DOLLAR = 1; int BRACE_OPEN = 2; int COLON = 3; int DOLLAR_NAME_START = 4; int NAME_START = 5; int VALUE_START = 6; } public static boolean isMaybeJSONObject(String str) { if (str == null) { return false; } int i = 0, n = str.length(); if (n < 3) { return false; } char expected = 0; for (; i < n; i++) { char c = str.charAt(i); if (Character.isWhitespace(c)) { continue; } if (c == '{') { expected = '}'; break; } return false; } for (int j = n - 1; j > i; j--) { char c = str.charAt(j); if (Character.isWhitespace(c)) { continue; } return c == expected; } return false; } public static int getPriority(Object obj) { if (obj instanceof Prioritized) { int priority = ((Prioritized) obj).getPriority(); if (priority != 0) { return priority; } } Activate activate = obj.getClass().getAnnotation(Activate.class); return activate == null ? 0 : activate.order(); } public static String[] getPattens(Object obj) { return obj instanceof RestExtension ? ((RestExtension) obj).getPatterns() : null; } }
State
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/client/RestClient.java
{ "start": 37210, "end": 41628 }
interface ____ { /** * Provide a function to map specific error status codes to an error handler. * <p>By default, if there are no matching status handlers, responses with * status codes &gt;= 400 will throw a {@link RestClientResponseException}. * <p>Note that {@link IOException IOExceptions}, * {@link java.io.UncheckedIOException UncheckedIOExceptions}, and * {@link org.springframework.http.converter.HttpMessageNotReadableException HttpMessageNotReadableExceptions} * thrown from {@code errorHandler} will be wrapped in a * {@link RestClientException}. * @param statusPredicate to match responses with * @param errorHandler handler that typically, though not necessarily, * throws an exception * @return this builder */ ResponseSpec onStatus(Predicate<HttpStatusCode> statusPredicate, ErrorHandler errorHandler); /** * Provide a function to map specific error status codes to an error handler. * <p>By default, if there are no matching status handlers, responses with * status codes &gt;= 400 will throw a {@link RestClientResponseException}. * <p>Note that {@link IOException IOExceptions}, * {@link java.io.UncheckedIOException UncheckedIOExceptions}, and * {@link org.springframework.http.converter.HttpMessageNotReadableException HttpMessageNotReadableExceptions} * thrown from {@code errorHandler} will be wrapped in a * {@link RestClientException}. * @param errorHandler the error handler * @return this builder */ ResponseSpec onStatus(ResponseErrorHandler errorHandler); /** * Extract the body as an object of the given type. * @param bodyType the type of return value * @param <T> the body type * @return the body, or {@code null} if no response body was available * @throws RestClientResponseException by default when receiving a * response with a status code of 4xx or 5xx. Use * {@link #onStatus(Predicate, ErrorHandler)} to customize error response * handling. */ <T> @Nullable T body(Class<T> bodyType); /** * Extract the body as an object of the given type. * @param bodyType the type of return value * @param <T> the body type * @return the body, or {@code null} if no response body was available * @throws RestClientResponseException by default when receiving a * response with a status code of 4xx or 5xx. Use * {@link #onStatus(Predicate, ErrorHandler)} to customize error response * handling. */ <T> @Nullable T body(ParameterizedTypeReference<T> bodyType); /** * Return a {@code ResponseEntity} with the body decoded to an Object of * the given type. * @param bodyType the expected response body type * @param <T> response body type * @return the {@code ResponseEntity} with the decoded body * @throws RestClientResponseException by default when receiving a * response with a status code of 4xx or 5xx. Use * {@link #onStatus(Predicate, ErrorHandler)} to customize error response * handling. */ <T> ResponseEntity<T> toEntity(Class<T> bodyType); /** * Return a {@code ResponseEntity} with the body decoded to an Object of * the given type. * @param bodyType the expected response body type * @param <T> response body type * @return the {@code ResponseEntity} with the decoded body * @throws RestClientResponseException by default when receiving a * response with a status code of 4xx or 5xx. Use * {@link #onStatus(Predicate, ErrorHandler)} to customize error response * handling. */ <T> ResponseEntity<T> toEntity(ParameterizedTypeReference<T> bodyType); /** * Return a {@code ResponseEntity} without a body. * @return the {@code ResponseEntity} * @throws RestClientResponseException by default when receiving a * response with a status code of 4xx or 5xx. Use * {@link #onStatus(Predicate, ErrorHandler)} to customize error response * handling. */ ResponseEntity<Void> toBodilessEntity(); /** * Set the hint with the given name to the given value for * {@link org.springframework.http.converter.SmartHttpMessageConverter}s * supporting them. * @param key the key of the hint to add * @param value the value of the hint to add * @return this builder * @since 7.0 */ ResponseSpec hint(String key, Object value); /** * Used in {@link #onStatus(Predicate, ErrorHandler)}. */ @FunctionalInterface
ResponseSpec
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/valueextractor/NestedContainerTypeCustomValueExtractorTest.java
{ "start": 1315, "end": 1662 }
class ____ { public NestedContainerType<@NotBlank String> constrainedContainer; public TestBean() { NestedContainerType<String> invalidContainer = new NestedContainerType<>(); invalidContainer.value = " "; this.constrainedContainer = invalidContainer; } } public static
TestBean
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/Assertions_sync_with_BDDAssertions_WithAssertions_and_soft_assertions_variants_Test.java
{ "start": 1447, "end": 8215 }
class ____ extends BaseAssertionsTest { // Assertions - BDDAssertions sync tests @ParameterizedTest @MethodSource("standard_and_bdd_assertion_methods") void standard_assertions_and_bdd_assertions_should_have_the_same_assertions_methods(String assertionMethod, String bddAssertionMethod) { // GIVEN Method[] assertThat_Assertions_methods = findMethodsWithName(Assertions.class, assertionMethod); Method[] then_Assertions_methods = findMethodsWithName(BDDAssertions.class, bddAssertionMethod); // THEN then(then_Assertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) .containsExactlyInAnyOrder(assertThat_Assertions_methods); } @Test void standard_assertions_and_bdd_assertions_should_have_the_same_non_assertions_methods() { // GIVEN List<String> methodsToIgnore = List.of("failBecauseExceptionWasNotThrown", "filter", "offset"); Set<Method> non_assertThat_methods = non_assertThat_methodsOf(Assertions.class.getDeclaredMethods()); non_assertThat_methods = removeMethods(non_assertThat_methods, methodsToIgnore); Set<Method> non_then_methods = non_then_methodsOf(BDDAssertions.class.getDeclaredMethods()); non_then_methods = removeMethods(non_then_methods, methodsToIgnore); // THEN then(non_then_methods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_METHOD_NAME) .containsExactlyInAnyOrderElementsOf(non_assertThat_methods); } // Assertions - WithAssertions sync tests @ParameterizedTest @MethodSource("assertion_methods") void standard_assertions_and_with_assertions_should_have_the_same_assertions_methods(String assertionMethod) { // GIVEN Method[] assertThat_Assertions_methods = findMethodsWithName(Assertions.class, assertionMethod); Method[] assertThat_WithAssertions_methods = findMethodsWithName(WithAssertions.class, assertionMethod); // THEN then(assertThat_WithAssertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) .containsExactlyInAnyOrder(assertThat_Assertions_methods); } @Test void standard_assertions_and_with_assertions_should_have_the_same_non_assertions_methods() { // GIVEN Set<Method> non_assertThat_Assertions_methods = non_assertThat_methodsOf(Assertions.class.getDeclaredMethods()); Set<Method> non_assertThat_WithAssertions_methods = non_assertThat_methodsOf(WithAssertions.class.getDeclaredMethods()); // THEN then(non_assertThat_WithAssertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_ONLY) .containsExactlyInAnyOrderElementsOf(non_assertThat_Assertions_methods); } // Assertions - SoftAssertions sync tests @ParameterizedTest @MethodSource("assertion_methods") void standard_assertions_and_soft_assertions_should_have_the_same_assertions_methods(String assertionMethod) { // GIVEN Method[] assertThat_Assertions_methods = findMethodsWithName(Assertions.class, assertionMethod, SPECIAL_IGNORED_RETURN_TYPES); Method[] assertThat_SoftAssertions_methods = findMethodsWithName(StandardSoftAssertionsProvider.class, assertionMethod); // THEN // ignore the return type of soft assertions until they have the same as the Assertions then(assertThat_Assertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE) .containsExactlyInAnyOrder(assertThat_SoftAssertions_methods); } // BDDAssertions - BDDSoftAssertions sync tests @ParameterizedTest @MethodSource("bdd_assertion_methods") void bdd_assertions_and_bdd_soft_assertions_should_have_the_same_assertions_methods(String assertionMethod) { // GIVEN // Until the SpecialIgnoredReturnTypes like AssertProvider, XXXNavigableXXXAssert are implemented for // the soft assertions we need to ignore them Method[] then_Assertions_methods = findMethodsWithName(BDDAssertions.class, assertionMethod, SPECIAL_IGNORED_RETURN_TYPES); Method[] then_BDDSoftAssertions_methods = findMethodsWithName(BDDSoftAssertionsProvider.class, assertionMethod); // THEN // ignore the return type of soft assertions until they have the same as the Assertions then(then_Assertions_methods).usingElementComparator(IGNORING_DECLARING_CLASS_AND_RETURN_TYPE) .containsExactlyInAnyOrder(then_BDDSoftAssertions_methods); } private static Stream<String> assertion_methods() { return Stream.of("assertThat", "assertThatCollection", "assertThatComparable", "assertThatIterable", "assertThatIterator", "assertThatList", "assertThatPath", "assertThatPredicate", "assertThatStream", "assertThatException", "assertThatRuntimeException", "assertThatNullPointerException", "assertThatIllegalArgumentException", "assertThatIOException", "assertThatIndexOutOfBoundsException", "assertThatReflectiveOperationException"); } private static String toBDDAssertionMethod(String assertionMethod) { return assertionMethod.replace("assertThat", "then"); } private static Stream<String> bdd_assertion_methods() { return assertion_methods().map(method -> toBDDAssertionMethod(method)); } private static Stream<Arguments> standard_and_bdd_assertion_methods() { return assertion_methods().map(method -> arguments(method, toBDDAssertionMethod(method))); } private static Set<Method> non_assertThat_methodsOf(Method[] declaredMethods) { return stream(declaredMethods).filter(method -> !method.getName().startsWith("assert")) .filter(method -> !method.isSynthetic()) .collect(toSet()); } private static Set<Method> non_then_methodsOf(Method[] declaredMethods) { return stream(declaredMethods).filter(method -> !method.getName().startsWith("then")) .filter(method -> !method.isSynthetic()) .collect(toSet()); } private static Set<Method> removeMethods(Set<Method> methods, List<String> methodsToRemove) { return methods.stream() .filter(method -> !methodsToRemove.contains(method.getName())) .collect(toSet()); } }
Assertions_sync_with_BDDAssertions_WithAssertions_and_soft_assertions_variants_Test
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/jackson/BytesMixin.java
{ "start": 990, "end": 1133 }
class ____ { @JsonCreator static Bytes fromBase64(String value) { return Bytes.fromBase64(value); } private BytesMixin() { } }
BytesMixin
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/StubConnectionFactory.java
{ "start": 869, "end": 1467 }
class ____ implements ConnectionFactory { @Override public Connection createConnection() { return null; } @Override public Connection createConnection(String username, String password) { return null; } @Override public JMSContext createContext() { return null; } @Override public JMSContext createContext(String userName, String password) { return null; } @Override public JMSContext createContext(String userName, String password, int sessionMode) { return null; } @Override public JMSContext createContext(int sessionMode) { return null; } }
StubConnectionFactory
java
apache__camel
components/camel-milo/src/main/java/org/apache/camel/component/milo/client/MiloClientConnectionManager.java
{ "start": 897, "end": 1245 }
interface ____ { /** * Creates the connection */ MiloClientConnection createConnection( MiloClientConfiguration configuration, MonitorFilterConfiguration monitorFilterConfiguration); /** * Releases the connection */ void releaseConnection(MiloClientConnection connection); }
MiloClientConnectionManager