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
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/testkit/engine/TestExecutionResultConditionsTests.java
{ "start": 956, "end": 4220 }
class ____ { private static final String EXPECTED = "expected"; private static final String UNEXPECTED = "unexpected"; private static final Condition<Throwable> rootCauseCondition = rootCause(message(EXPECTED)); @Test void rootCauseFailsForNullThrowable() { assertPreconditionViolationNotNullFor("Throwable", () -> rootCauseCondition.matches(null)); } @Test void rootCauseFailsForThrowableWithoutCause() { Throwable throwable = new Throwable(); assertPreconditionViolationFor(() -> rootCauseCondition.matches(throwable))// .withMessage("Throwable does not have a cause"); } @Test void rootCauseMatchesForDirectCauseWithExpectedMessage() { RuntimeException cause = new RuntimeException(EXPECTED); Throwable throwable = new Throwable(cause); assertThat(rootCauseCondition.matches(throwable)).isTrue(); } @Test void rootCauseDoesNotMatchForDirectCauseWithDifferentMessage() { RuntimeException cause = new RuntimeException(UNEXPECTED); Throwable throwable = new Throwable(cause); assertThat(rootCauseCondition.matches(throwable)).isFalse(); } @Test void rootCauseMatchesForRootCauseWithExpectedMessage() { RuntimeException rootCause = new RuntimeException(EXPECTED); RuntimeException intermediateCause = new RuntimeException("intermediate cause", rootCause); Throwable throwable = new Throwable(intermediateCause); assertThat(rootCauseCondition.matches(throwable)).isTrue(); } @Test void rootCauseDoesNotMatchForRootCauseWithDifferentMessage() { RuntimeException rootCause = new RuntimeException(UNEXPECTED); RuntimeException intermediateCause = new RuntimeException("intermediate cause", rootCause); Throwable throwable = new Throwable(intermediateCause); assertThat(rootCauseCondition.matches(throwable)).isFalse(); } @Test void rootCauseMatchesForRootCauseWithExpectedMessageAndSingleLevelRecursiveCauseChain() { RuntimeException rootCause = new RuntimeException(EXPECTED); Throwable throwable = new Throwable(rootCause); rootCause.initCause(throwable); assertThat(rootCauseCondition.matches(throwable)).isTrue(); } @Test void rootCauseDoesNotMatchForRootCauseWithDifferentMessageAndSingleLevelRecursiveCauseChain() { RuntimeException rootCause = new RuntimeException(UNEXPECTED); Throwable throwable = new Throwable(rootCause); rootCause.initCause(throwable); assertThat(rootCauseCondition.matches(throwable)).isFalse(); } @Test void rootCauseMatchesForRootCauseWithExpectedMessageAndDoubleLevelRecursiveCauseChain() { RuntimeException rootCause = new RuntimeException(EXPECTED); Exception intermediateCause = new Exception("intermediate cause", rootCause); Throwable throwable = new Throwable(intermediateCause); rootCause.initCause(throwable); assertThat(rootCauseCondition.matches(throwable)).isTrue(); } @Test void rootCauseDoesNotMatchForRootCauseWithDifferentMessageAndDoubleLevelRecursiveCauseChain() { RuntimeException rootCause = new RuntimeException(UNEXPECTED); Exception intermediateCause = new Exception("intermediate cause", rootCause); Throwable throwable = new Throwable(intermediateCause); rootCause.initCause(throwable); assertThat(rootCauseCondition.matches(throwable)).isFalse(); } }
TestExecutionResultConditionsTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/EagerOneToOneMappedByInDoubleEmbeddedTest.java
{ "start": 4060, "end": 4325 }
class ____ implements Serializable { @OneToOne private EntityA entityA; public EmbeddedValueInB() { } public EntityA getEntityA() { return entityA; } public void setEntityA( EntityA entityA) { this.entityA = entityA; } } }
EmbeddedValueInB
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java
{ "start": 203491, "end": 204481 }
class ____ extends PrimaryExpressionContext { public CastExpressionContext castExpression() { return getRuleContext(CastExpressionContext.class, 0); } public CastContext(PrimaryExpressionContext ctx) { copyFrom(ctx); } @Override public void enterRule(ParseTreeListener listener) { if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).enterCast(this); } @Override public void exitRule(ParseTreeListener listener) { if (listener instanceof SqlBaseListener) ((SqlBaseListener) listener).exitCast(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if (visitor instanceof SqlBaseVisitor) return ((SqlBaseVisitor<? extends T>) visitor).visitCast(this); else return visitor.visitChildren(this); } } @SuppressWarnings("CheckReturnValue") public static
CastContext
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/stubbing/answers/ReturnsElementsOf.java
{ "start": 979, "end": 1638 }
class ____ implements Answer<Object> { private final LinkedList<Object> elements; public ReturnsElementsOf(Collection<?> elements) { if (elements == null) { throw new MockitoException( "ReturnsElementsOf does not accept null as constructor argument.\n" + "Please pass a collection instance"); } this.elements = new LinkedList<>(elements); } @Override public Object answer(InvocationOnMock invocation) throws Throwable { if (elements.size() == 1) { return elements.get(0); } else return elements.poll(); } }
ReturnsElementsOf
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java
{ "start": 3454, "end": 23004 }
class ____ { @SuppressWarnings("unused") static Stream<Arguments> pathPatternsArguments() { StaticWebApplicationContext wac1 = new StaticWebApplicationContext(); StaticWebApplicationContext wac2 = new StaticWebApplicationContext(); RequestMappingHandlerMapping mapping1 = new RequestMappingHandlerMapping(); mapping1.setApplicationContext(wac1); RequestMappingHandlerMapping mapping2 = new RequestMappingHandlerMapping(); mapping2.setPatternParser(null); mapping2.setApplicationContext(wac2); return Stream.of( arguments(named("PathPatternParser", mapping1), wac1), arguments(named("AntPathMatcher", mapping2), wac2) ); } @Test void builderConfiguration() { RequestMappingHandlerMapping mapping = createMapping(); RequestMappingInfo.BuilderConfiguration config = mapping.getBuilderConfiguration(); assertThat(config).isNotNull(); mapping.afterPropertiesSet(); assertThat(mapping.getBuilderConfiguration()).isNotNull().isNotSameAs(config); } @PathPatternsParameterizedTest void resolveEmbeddedValuesInPatterns(RequestMappingHandlerMapping mapping) { mapping.setEmbeddedValueResolver(value -> "/${pattern}/bar".equals(value) ? "/foo/bar" : value); String[] patterns = { "/foo", "/${pattern}/bar" }; String[] result = mapping.resolveEmbeddedValuesInPatterns(patterns); assertThat(result).containsExactly("/foo", "/foo/bar"); } @PathPatternsParameterizedTest void pathPrefix(RequestMappingHandlerMapping mapping) throws Exception { mapping.setEmbeddedValueResolver(value -> "/${prefix}".equals(value) ? "/api" : value); mapping.setPathPrefixes(Collections.singletonMap( "/${prefix}", HandlerTypePredicate.forAnnotation(RestController.class))); mapping.afterPropertiesSet(); Method method = UserController.class.getMethod("getUser"); RequestMappingInfo info = mapping.getMappingForMethod(method, UserController.class); assertThat(info).isNotNull(); assertThat(info.getPatternValues()).containsOnly("/api/user/{id}"); } @PathPatternsParameterizedTest // gh-23907 void pathPrefixPreservesPathMatchingSettings(RequestMappingHandlerMapping mapping) throws Exception { mapping.setPathPrefixes(Collections.singletonMap("/api", HandlerTypePredicate.forAnyHandlerType())); mapping.afterPropertiesSet(); Method method = ComposedAnnotationController.class.getMethod("get"); RequestMappingInfo info = mapping.getMappingForMethod(method, ComposedAnnotationController.class); assertThat(info).isNotNull(); assertThat(info.getActivePatternsCondition()).isNotNull(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/get"); initRequestPath(mapping, request); assertThat(info.getActivePatternsCondition().getMatchingCondition(request)).isNotNull(); request = new MockHttpServletRequest("GET", "/api/get.pdf"); initRequestPath(mapping, request); assertThat(info.getActivePatternsCondition().getMatchingCondition(request)).isNull(); } @SuppressWarnings("removal") private void initRequestPath(RequestMappingHandlerMapping mapping, MockHttpServletRequest request) { PathPatternParser parser = mapping.getPatternParser(); if (parser != null) { ServletRequestPathUtils.parseAndCache(request); } else { mapping.getUrlPathHelper().resolveAndCacheLookupPath(request); } } @PathPatternsParameterizedTest void resolveRequestMappingViaComposedAnnotation(RequestMappingHandlerMapping mapping) { RequestMappingInfo info = assertComposedAnnotationMapping( mapping, "postJson", "/postJson", RequestMethod.POST); Set<MediaType> consumableMediaTypes = info.getConsumesCondition().getConsumableMediaTypes(); Set<MediaType> producibleMediaTypes = info.getProducesCondition().getProducibleMediaTypes(); assertThat(consumableMediaTypes).singleElement().hasToString(MediaType.APPLICATION_JSON_VALUE); assertThat(producibleMediaTypes).singleElement().hasToString(MediaType.APPLICATION_JSON_VALUE); } @Test // SPR-14988 void postMappingOverridesConsumesFromTypeLevelAnnotation() { RequestMappingInfo requestMappingInfo = assertComposedAnnotationMapping(RequestMethod.POST); ConsumesRequestCondition condition = requestMappingInfo.getConsumesCondition(); assertThat(condition.getConsumableMediaTypes()).containsOnly(MediaType.APPLICATION_XML); } @PathPatternsParameterizedTest // gh-22010 void consumesWithOptionalRequestBody(RequestMappingHandlerMapping mapping, StaticWebApplicationContext wac) { wac.registerSingleton("testController", ComposedAnnotationController.class); wac.refresh(); mapping.afterPropertiesSet(); RequestMappingInfo result = mapping.getHandlerMethods().keySet().stream() .filter(info -> info.getPatternValues().equals(Collections.singleton("/post"))) .findFirst() .orElseThrow(() -> new AssertionError("No /post")); assertThat(result.getConsumesCondition().isBodyRequired()).isFalse(); } @Test void getMapping() { assertComposedAnnotationMapping(RequestMethod.GET); } @Test void postMapping() { assertComposedAnnotationMapping(RequestMethod.POST); } @Test void putMapping() { assertComposedAnnotationMapping(RequestMethod.PUT); } @Test void deleteMapping() { assertComposedAnnotationMapping(RequestMethod.DELETE); } @Test void patchMapping() { assertComposedAnnotationMapping(RequestMethod.PATCH); } @Test // gh-32049 void httpExchangeWithMultipleAnnotationsAtClassLevel() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = MultipleClassLevelAnnotationsHttpExchangeController.class; Method method = controllerClass.getDeclaredMethod("post"); assertThatIllegalStateException() .isThrownBy(() -> mapping.getMappingForMethod(method, controllerClass)) .withMessageContainingAll( "Multiple @HttpExchange annotations found on " + controllerClass, HttpExchange.class.getSimpleName(), ExtraHttpExchange.class.getSimpleName() ); } @Test // gh-32049 void httpExchangeWithMultipleAnnotationsAtMethodLevel() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = MultipleMethodLevelAnnotationsHttpExchangeController.class; Method method = controllerClass.getDeclaredMethod("post"); assertThatIllegalStateException() .isThrownBy(() -> mapping.getMappingForMethod(method, controllerClass)) .withMessageContainingAll( "Multiple @HttpExchange annotations found on " + method, PostExchange.class.getSimpleName(), PutExchange.class.getSimpleName() ); } @Test // gh-32065 void httpExchangeWithMixedAnnotationsAtClassLevel() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = MixedClassLevelAnnotationsController.class; Method method = controllerClass.getDeclaredMethod("post"); assertThatIllegalStateException() .isThrownBy(() -> mapping.getMappingForMethod(method, controllerClass)) .withMessageContainingAll( controllerClass.getName(), "is annotated with @RequestMapping and @HttpExchange annotations, but only one is allowed:", RequestMapping.class.getSimpleName(), HttpExchange.class.getSimpleName() ); } @Test // gh-32065 void httpExchangeWithMixedAnnotationsAtMethodLevel() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = MixedMethodLevelAnnotationsController.class; Method method = controllerClass.getDeclaredMethod("post"); assertThatIllegalStateException() .isThrownBy(() -> mapping.getMappingForMethod(method, controllerClass)) .withMessageContainingAll( method.toString(), "is annotated with @RequestMapping and @HttpExchange annotations, but only one is allowed:", PostMapping.class.getSimpleName(), PostExchange.class.getSimpleName() ); } @Test // gh-32065 void httpExchangeAnnotationsOverriddenAtClassLevel() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = ClassLevelOverriddenHttpExchangeAnnotationsController.class; Method method = controllerClass.getDeclaredMethod("post"); RequestMappingInfo info = mapping.getMappingForMethod(method, controllerClass); assertThat(info).isNotNull(); assertThat(info.getActivePatternsCondition()).isNotNull(); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/service/postExchange"); initRequestPath(mapping, request); assertThat(info.getActivePatternsCondition().getMatchingCondition(request)).isNull(); request = new MockHttpServletRequest("POST", "/controller/postExchange"); initRequestPath(mapping, request); assertThat(info.getActivePatternsCondition().getMatchingCondition(request)).isNotNull(); } @Test // gh-32065 void httpExchangeAnnotationsOverriddenAtMethodLevel() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = MethodLevelOverriddenHttpExchangeAnnotationsController.class; Method method = controllerClass.getDeclaredMethod("post"); RequestMappingInfo info = mapping.getMappingForMethod(method, controllerClass); assertThat(info).isNotNull(); assertThat(info.getActivePatternsCondition()).isNotNull(); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/service/postExchange"); initRequestPath(mapping, request); assertThat(info.getActivePatternsCondition().getMatchingCondition(request)).isNull(); request = new MockHttpServletRequest("POST", "/controller/postMapping"); initRequestPath(mapping, request); assertThat(info.getActivePatternsCondition().getMatchingCondition(request)).isNotNull(); } @SuppressWarnings("DataFlowIssue") @Test void httpExchangeWithDefaultValues() throws NoSuchMethodException { RequestMappingHandlerMapping mapping = createMapping(); RequestMappingInfo mappingInfo = mapping.getMappingForMethod( HttpExchangeController.class.getMethod("defaultValuesExchange"), HttpExchangeController.class); assertThat(mappingInfo.getPathPatternsCondition().getPatterns()) .extracting(PathPattern::toString) .containsOnly("/exchange"); assertThat(mappingInfo.getMethodsCondition().getMethods()).isEmpty(); assertThat(mappingInfo.getParamsCondition().getExpressions()).isEmpty(); assertThat(mappingInfo.getHeadersCondition().getExpressions()).isEmpty(); assertThat(mappingInfo.getConsumesCondition().getExpressions()).isEmpty(); assertThat(mappingInfo.getProducesCondition().getExpressions()).isEmpty(); } @SuppressWarnings("DataFlowIssue") @Test void httpExchangeWithCustomValues() throws Exception { RequestMappingHandlerMapping mapping = createMapping(); RequestMappingInfo mappingInfo = mapping.getMappingForMethod( HttpExchangeController.class.getMethod("customValuesExchange"), HttpExchangeController.class); assertThat(mappingInfo.getPathPatternsCondition().getPatterns()) .extracting(PathPattern::toString) .containsOnly("/exchange/custom"); assertThat(mappingInfo.getMethodsCondition().getMethods()).containsOnly(RequestMethod.POST); assertThat(mappingInfo.getParamsCondition().getExpressions()).isEmpty(); assertThat(mappingInfo.getHeadersCondition().getExpressions()).isEmpty(); assertThat(mappingInfo.getConsumesCondition().getExpressions()) .extracting(MediaTypeExpression::getMediaType) .containsOnly(MediaType.APPLICATION_JSON); assertThat(mappingInfo.getProducesCondition().getExpressions()) .extracting(MediaTypeExpression::getMediaType) .containsOnly(MediaType.valueOf("text/plain;charset=UTF-8")); } @SuppressWarnings("DataFlowIssue") @Test void httpExchangeWithCustomHeaders() throws Exception { RequestMappingHandlerMapping mapping = createMapping(); RequestMappingInfo mappingInfo = mapping.getMappingForMethod( HttpExchangeController.class.getMethod("customHeadersExchange"), HttpExchangeController.class); assertThat(mappingInfo.getPathPatternsCondition().getPatterns()) .extracting(PathPattern::toString) .containsOnly("/exchange/headers"); assertThat(mappingInfo.getMethodsCondition().getMethods()).containsOnly(RequestMethod.GET); assertThat(mappingInfo.getParamsCondition().getExpressions()).isEmpty(); assertThat(mappingInfo.getHeadersCondition().getExpressions().stream().map(Object::toString)) .containsExactly("h1=hv1", "!h2"); } @Test // gh-35086 void requestBodyAnnotationFromInterfaceIsRespected() throws Exception { String path = "/controller/postMapping"; MediaType mediaType = MediaType.APPLICATION_JSON; RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = InterfaceControllerImpl.class; Method method = controllerClass.getDeclaredMethod("post", Foo.class); RequestMappingInfo info = mapping.getMappingForMethod(method, controllerClass); assertThat(info).isNotNull(); // Original ConsumesCondition ConsumesRequestCondition consumesCondition = info.getConsumesCondition(); assertThat(consumesCondition).isNotNull(); assertThat(consumesCondition.isBodyRequired()).isTrue(); assertThat(consumesCondition.getConsumableMediaTypes()).containsOnly(mediaType); mapping.registerHandlerMethod(new InterfaceControllerImpl(), method, info); // Updated ConsumesCondition consumesCondition = info.getConsumesCondition(); assertThat(consumesCondition).isNotNull(); assertThat(consumesCondition.isBodyRequired()).isFalse(); assertThat(consumesCondition.getConsumableMediaTypes()).containsOnly(mediaType); MockHttpServletRequest request = new MockHttpServletRequest("POST", path); request.setContentType(mediaType.toString()); initRequestPath(mapping, request); RequestMappingInfo matchingInfo = info.getMatchingCondition(request); // Since the request has no body AND the required flag is false, the // ConsumesCondition in the matching condition in an EMPTY_CONDITION. // In other words, the "consumes" expressions are removed. assertThat(matchingInfo).isEqualTo(paths(path).methods(POST).build()); } @Test // gh-35086 void requestBodyAnnotationFromImplementationOverridesInterface() throws Exception { String path = "/controller/postMapping"; MediaType mediaType = MediaType.APPLICATION_JSON; RequestMappingHandlerMapping mapping = createMapping(); Class<?> controllerClass = InterfaceControllerImplOverridesRequestBody.class; Method method = controllerClass.getDeclaredMethod("post", Foo.class); RequestMappingInfo info = mapping.getMappingForMethod(method, controllerClass); assertThat(info).isNotNull(); // Original ConsumesCondition ConsumesRequestCondition consumesCondition = info.getConsumesCondition(); assertThat(consumesCondition).isNotNull(); assertThat(consumesCondition.isBodyRequired()).isTrue(); assertThat(consumesCondition.getConsumableMediaTypes()).containsOnly(mediaType); mapping.registerHandlerMethod(new InterfaceControllerImplOverridesRequestBody(), method, info); // Updated ConsumesCondition consumesCondition = info.getConsumesCondition(); assertThat(consumesCondition).isNotNull(); assertThat(consumesCondition.isBodyRequired()).isTrue(); assertThat(consumesCondition.getConsumableMediaTypes()).containsOnly(mediaType); MockHttpServletRequest request = new MockHttpServletRequest("POST", path); request.setContentType(mediaType.toString()); initRequestPath(mapping, request); RequestMappingInfo matchingInfo = info.getMatchingCondition(request); assertThat(matchingInfo).isEqualTo(paths(path).methods(POST).consumes(mediaType.toString()).build()); } @Test // gh-35352 void privateMethodOnCglibProxyShouldThrowException() throws Exception { RequestMappingHandlerMapping mapping = createMapping(); Class<?> handlerType = PrivateMethodController.class; String methodName = "privateMethod"; Method method = handlerType.getDeclaredMethod(methodName); Class<?> proxyClass = createProxyClass(handlerType); assertThatIllegalStateException() .isThrownBy(() -> mapping.getMappingForMethod(method, proxyClass)) .withMessage(""" Private method [%s] on CGLIB proxy class [%s] cannot be used as a request \ handler method, because private methods cannot be overridden. \ Change the method to non-private visibility, or use interface-based JDK \ proxying instead.""", methodName, proxyClass.getName()); } @Test // gh-35352 void protectedMethodOnCglibProxyShouldNotThrowException() throws Exception { RequestMappingHandlerMapping mapping = createMapping(); Class<?> handlerType = ProtectedMethodController.class; Method method = handlerType.getDeclaredMethod("protectedMethod"); Class<?> proxyClass = createProxyClass(handlerType); RequestMappingInfo info = mapping.getMappingForMethod(method, proxyClass); assertThat(info.getPatternValues()).containsOnly("/protected"); } @Test // gh-35352 void differentPackagePackagePrivateMethodOnCglibProxyShouldThrowException() throws Exception { RequestMappingHandlerMapping mapping = createMapping(); Class<?> handlerType = LocalPackagePrivateMethodControllerSubclass.class; Class<?> declaringClass = PackagePrivateMethodController.class; String methodName = "packagePrivateMethod"; Method method = declaringClass.getDeclaredMethod(methodName); Class<?> proxyClass = createProxyClass(handlerType); assertThatIllegalStateException() .isThrownBy(() -> mapping.getMappingForMethod(method, proxyClass)) .withMessage(""" Package-private method [%s] declared in class [%s] cannot be advised by \ CGLIB-proxied handler class [%s], because it is effectively private. Either \ make the method public or protected, or use interface-based JDK proxying instead.""", methodName, declaringClass.getName(), proxyClass.getName()); } private static Class<?> createProxyClass(Class<?> targetClass) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(targetClass); enhancer.setCallbackTypes(new Class[]{NoOp.class}); return enhancer.createClass(); } private static RequestMappingHandlerMapping createMapping() { RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); mapping.setApplicationContext(new StaticWebApplicationContext()); mapping.afterPropertiesSet(); return mapping; } private static RequestMappingInfo assertComposedAnnotationMapping(RequestMethod requestMethod) { RequestMappingHandlerMapping mapping = createMapping(); String methodName = requestMethod.name().toLowerCase(); String path = "/" + methodName; return assertComposedAnnotationMapping(mapping, methodName, path, requestMethod); } private static RequestMappingInfo assertComposedAnnotationMapping( RequestMappingHandlerMapping mapping, String methodName, String path, RequestMethod requestMethod) { Class<?> clazz = ComposedAnnotationController.class; Method method = ClassUtils.getMethod(clazz, methodName, (Class<?>[]) null); RequestMappingInfo info = mapping.getMappingForMethod(method, clazz); assertThat(info).isNotNull(); Set<String> paths = info.getPatternValues(); assertThat(paths).containsOnly(path); Set<RequestMethod> methods = info.getMethodsCondition().getMethods(); assertThat(methods).containsOnly(requestMethod); return info; } @Controller // gh-31962: The presence of multiple @RequestMappings is intentional. @RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ExtraRequestMapping static
RequestMappingHandlerMappingTests
java
google__auto
value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java
{ "start": 2812, "end": 3011 }
class ____ the inheritance hierarchy, * its {@link #mustBeFinal(Context)} method returns true. Only one Extension can return true for a * given context. Only generated classes that will be the final
in
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestLocatedFileStatusFetcher.java
{ "start": 2117, "end": 2291 }
class ____ based on tests in {@link ITestRestrictedReadAccess}, * but whereas that tests failure paths, this looks at the performance * of successful invocations. */ public
is
java
playframework__playframework
documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/guice/eager/ApplicationStart.java
{ "start": 458, "end": 846 }
class ____ { // Inject the application's Environment upon start-up and register hook(s) for shut-down. @Inject public ApplicationStart(ApplicationLifecycle lifecycle, Environment environment) { // Shut-down hook lifecycle.addStopHook( () -> { return CompletableFuture.completedFuture(null); }); // ... } } // #eager-guice-module
ApplicationStart
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestPolymorphicDeserialization676.java
{ "start": 920, "end": 2210 }
class ____ { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public Map<String, Object> map; public MapContainer() { } public MapContainer(Map<String, Object> map) { this.map = map; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MapContainer)) return false; return map.equals(((MapContainer) o).map); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[MapContainer:"); for (Map.Entry<String,Object> entry : map.entrySet()) { sb.append(" '").append(entry.getKey()).append("' : "); Object value = entry.getValue(); if (value == null) { sb.append("null"); } else { sb.append("(").append(value.getClass().getName()).append(") "); sb.append(String.valueOf(value)); } } return sb.append(']').toString(); } } @JsonInclude(JsonInclude.Include.NON_NULL) public static
MapContainer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/engine/LazySoftDeletesDirectoryReaderWrapper.java
{ "start": 4797, "end": 5895 }
class ____ extends FilterLeafReader { private final LeafReader reader; private final LazyBits bits; private final int numDocs; private final CacheHelper readerCacheHelper; public LazySoftDeletesFilterLeafReader(LeafReader reader, LazyBits bits, int numDocs) { super(reader); this.reader = reader; this.bits = bits; this.numDocs = numDocs; this.readerCacheHelper = reader.getReaderCacheHelper() == null ? null : new DelegatingCacheHelper(reader.getReaderCacheHelper()); } @Override public LazyBits getLiveDocs() { return bits; } @Override public int numDocs() { return numDocs; } @Override public CacheHelper getCoreCacheHelper() { return reader.getCoreCacheHelper(); } @Override public CacheHelper getReaderCacheHelper() { return readerCacheHelper; } } public static final
LazySoftDeletesFilterLeafReader
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
{ "start": 63989, "end": 65712 }
class ____ extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { if (event.getType() == RMAppAttemptEventType.LAUNCHED || event.getType() == RMAppAttemptEventType.REGISTERED) { appAttempt.launchAMEndTime = System.currentTimeMillis(); long delay = appAttempt.launchAMEndTime - appAttempt.launchAMStartTime; ClusterMetrics.getMetrics().addAMLaunchDelay(delay); } appAttempt.eventHandler.handle( new RMAppEvent(appAttempt.getAppAttemptId().getApplicationId(), RMAppEventType.ATTEMPT_LAUNCHED, event.getTimestamp())); appAttempt .updateAMLaunchDiagnostics(AMState.LAUNCHED.getDiagnosticMessage()); // Register with AMLivelinessMonitor appAttempt.attemptLaunched(); } } @Override public boolean shouldCountTowardsMaxAttemptRetry() { long attemptFailuresValidityInterval = this.submissionContext .getAttemptFailuresValidityInterval(); long end = System.currentTimeMillis(); if (attemptFailuresValidityInterval > 0 && this.getFinishTime() > 0 && this.getFinishTime() < (end - attemptFailuresValidityInterval)) { return false; } this.readLock.lock(); try { int exitStatus = getAMContainerExitStatus(); return !(exitStatus == ContainerExitStatus.PREEMPTED || exitStatus == ContainerExitStatus.ABORTED || exitStatus == ContainerExitStatus.DISKS_FAILED || exitStatus == ContainerExitStatus.KILLED_BY_RESOURCEMANAGER); } finally { this.readLock.unlock(); } } private static final
AMLaunchedTransition
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/bean/BeanDeserializerTest.java
{ "start": 1375, "end": 1907 }
class ____ extends SimpleModule { protected ValueDeserializerModifier modifier; public ModuleImpl(ValueDeserializerModifier modifier) { super("test", Version.unknownVersion()); this.modifier = modifier; } @Override public void setupModule(SetupContext context) { super.setupModule(context); if (modifier != null) { context.addDeserializerModifier(modifier); } } } static
ModuleImpl
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/CouchdbComponentBuilderFactory.java
{ "start": 1482, "end": 2059 }
interface ____ { /** * CouchDB (camel-couchdb) * Consume changesets for inserts, updates and deletes in a CouchDB * database, as well as get, save, update and delete documents from a * CouchDB database. * * Category: database * Since: 2.11 * Maven coordinates: org.apache.camel:camel-couchdb * * @return the dsl builder */ static CouchdbComponentBuilder couchdb() { return new CouchdbComponentBuilderImpl(); } /** * Builder for the CouchDB component. */
CouchdbComponentBuilderFactory
java
spring-projects__spring-boot
module/spring-boot-kafka/src/main/java/org/springframework/boot/kafka/testcontainers/ApacheKafkaContainerConnectionDetailsFactory.java
{ "start": 1933, "end": 2527 }
class ____ extends ContainerConnectionDetails<KafkaContainer> implements KafkaConnectionDetails { private ApacheKafkaContainerConnectionDetails(ContainerConnectionSource<KafkaContainer> source) { super(source); } @Override public List<String> getBootstrapServers() { return List.of(getContainer().getBootstrapServers()); } @Override public @Nullable SslBundle getSslBundle() { return super.getSslBundle(); } @Override public String getSecurityProtocol() { return (getSslBundle() != null) ? "SSL" : "PLAINTEXT"; } } }
ApacheKafkaContainerConnectionDetails
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/SchemaUpdateSQLServerTest.java
{ "start": 8019, "end": 8432 }
class ____ { @Id long id; String match; @ElementCollection @CollectionTable(catalog = "hibernate_orm_test_collation", schema = "dbo") private Map<Integer, Integer> timeline = new TreeMap<>(); } @Entity(name = "InheritanceRootEntity") @Table(name = "InheritanceRootEntity", catalog = "hibernate_orm_test_collation", schema = "dbo") @Inheritance(strategy = InheritanceType.JOINED) public static
Match
java
google__guava
android/guava/src/com/google/common/util/concurrent/ServiceManager.java
{ "start": 18980, "end": 20429 }
class ____ { final Monitor monitor = new Monitor(); @GuardedBy("monitor") final SetMultimap<State, Service> servicesByState = MultimapBuilder.enumKeys(State.class).linkedHashSetValues().build(); @GuardedBy("monitor") final Multiset<State> states = servicesByState.keys(); @GuardedBy("monitor") final IdentityHashMap<Service, Stopwatch> startupTimers = new IdentityHashMap<>(); /** * These two booleans are used to mark the state as ready to start. * * <p>{@link #ready}: is set by {@link #markReady} to indicate that all listeners have been * correctly installed * * <p>{@link #transitioned}: is set by {@link #transitionService} to indicate that some * transition has been performed. * * <p>Together, they allow us to enforce that all services have their listeners installed prior * to any service performing a transition, then we can fail in the ServiceManager constructor * rather than in a Service.Listener callback. */ @GuardedBy("monitor") boolean ready; @GuardedBy("monitor") boolean transitioned; final int numberOfServices; /** * Controls how long to wait for all the services to either become healthy or reach a state from * which it is guaranteed that it can never become healthy. */ final Monitor.Guard awaitHealthGuard = new AwaitHealthGuard(); @WeakOuter final
ServiceManagerState
java
quarkusio__quarkus
test-framework/oidc-server/src/test/java/io/quarkus/test/oidc/server/OidcWiremockTestResourceInjectionTest.java
{ "start": 422, "end": 819 }
class ____ { @Test void testWireMockServerInjection() { TestResourceManager manager = new TestResourceManager(CustomTest.class); manager.start(); CustomTest test = new CustomTest(); manager.inject(test); assertNotNull(test.server); } @QuarkusTestResource(OidcWiremockTestResource.class) public static
OidcWiremockTestResourceInjectionTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orderby/OrderByTest.java
{ "start": 4004, "end": 4520 }
class ____ { @Id private Long id; @OneToMany(mappedBy = "task", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OrderBy("id DESC") private List<TaskVersion> taskVersions; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<TaskVersion> getTaskVersions() { return taskVersions; } public void setTaskVersions(List<TaskVersion> taskVersions) { this.taskVersions = taskVersions; } } @Entity(name = "TaskVersion") public static
Task
java
quarkusio__quarkus
integration-tests/class-transformer/deployment/src/main/java/io/quarkus/it/classtransformer/ClassTransformerProcessor.java
{ "start": 936, "end": 1052 }
class ____ functionality, it should probably be removed * when we have better test frameworks */ public
transformation
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/config/nested/McpConfig.java
{ "start": 2341, "end": 3059 }
class ____ implements Serializable { private static final long serialVersionUID = 6943417856234837947L; /** * The path of mcp message * <p>The default value is '/mcp/message'. */ private String message; /** * The path of mcp sse * <p>The default value is '/mcp/sse'. */ private String sse; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSse() { return sse; } public void setSse(String sse) { this.sse = sse; } } }
MCPPath
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/ParquetColumnarRowInputFormat.java
{ "start": 2364, "end": 5488 }
class ____<SplitT extends FileSourceSplit> extends ParquetVectorizedInputFormat<RowData, SplitT> implements FileBasedStatisticsReportableInputFormat { private static final long serialVersionUID = 1L; private final TypeInformation<RowData> producedTypeInfo; /** Constructor to create parquet format without extra fields. */ public ParquetColumnarRowInputFormat( Configuration hadoopConfig, RowType projectedType, TypeInformation<RowData> producedTypeInfo, int batchSize, boolean isUtcTimestamp, boolean isCaseSensitive) { this( hadoopConfig, projectedType, producedTypeInfo, ColumnBatchFactory.withoutExtraFields(), batchSize, isUtcTimestamp, isCaseSensitive); } /** * Constructor to create parquet format with extra fields created by {@link ColumnBatchFactory}. * * @param projectedType the projected row type for parquet format, excludes extra fields. * @param producedTypeInfo the produced row type info for this input format, includes extra * fields. * @param batchFactory factory for creating column batch, can cram in extra fields. */ ParquetColumnarRowInputFormat( Configuration hadoopConfig, RowType projectedType, TypeInformation<RowData> producedTypeInfo, ColumnBatchFactory<SplitT> batchFactory, int batchSize, boolean isUtcTimestamp, boolean isCaseSensitive) { super( new SerializableConfiguration(hadoopConfig), projectedType, batchFactory, batchSize, isUtcTimestamp, isCaseSensitive); this.producedTypeInfo = producedTypeInfo; } @Override protected int numBatchesToCirculate(org.apache.flink.configuration.Configuration config) { // In a VectorizedColumnBatch, the dictionary will be lazied deserialized. // If there are multiple batches at the same time, there may be thread safety problems, // because the deserialization of the dictionary depends on some internal structures. // We need set numBatchesToCirculate to 1. return 1; } @Override protected ParquetReaderBatch<RowData> createReaderBatch( WritableColumnVector[] writableVectors, VectorizedColumnBatch columnarBatch, Pool.Recycler<ParquetReaderBatch<RowData>> recycler) { return new ColumnarRowReaderBatch(writableVectors, columnarBatch, recycler); } @Override public TypeInformation<RowData> getProducedType() { return producedTypeInfo; } @Override public TableStats reportStatistics(List<Path> files, DataType producedDataType) { return ParquetFormatStatisticsReportUtil.getTableStatistics( files, producedDataType, hadoopConfig.conf(), isUtcTimestamp); } private static
ParquetColumnarRowInputFormat
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/ha/DefaultHAService.java
{ "start": 1820, "end": 9474 }
class ____ implements HAService { private static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME); protected final AtomicInteger connectionCount = new AtomicInteger(0); protected final List<HAConnection> connectionList = new LinkedList<>(); protected AcceptSocketService acceptSocketService; protected DefaultMessageStore defaultMessageStore; protected WaitNotifyObject waitNotifyObject = new WaitNotifyObject(); protected AtomicLong push2SlaveMaxOffset = new AtomicLong(0); protected GroupTransferService groupTransferService; protected HAClient haClient; protected HAConnectionStateNotificationService haConnectionStateNotificationService; public DefaultHAService() { } @Override public void init(final DefaultMessageStore defaultMessageStore) throws IOException { this.defaultMessageStore = defaultMessageStore; this.acceptSocketService = new DefaultAcceptSocketService(defaultMessageStore.getMessageStoreConfig()); this.groupTransferService = new GroupTransferService(this, defaultMessageStore); if (this.defaultMessageStore.getMessageStoreConfig().getBrokerRole() == BrokerRole.SLAVE) { this.haClient = new DefaultHAClient(this.defaultMessageStore); } this.haConnectionStateNotificationService = new HAConnectionStateNotificationService(this, defaultMessageStore); } @Override public void updateMasterAddress(final String newAddr) { if (this.haClient != null) { this.haClient.updateMasterAddress(newAddr); } } @Override public void updateHaMasterAddress(String newAddr) { if (this.haClient != null) { this.haClient.updateHaMasterAddress(newAddr); } } @Override public void putRequest(final CommitLog.GroupCommitRequest request) { this.groupTransferService.putRequest(request); } @Override public boolean isSlaveOK(final long masterPutWhere) { boolean result = this.connectionCount.get() > 0; result = result && masterPutWhere - this.push2SlaveMaxOffset.get() < this.defaultMessageStore .getMessageStoreConfig().getHaMaxGapNotInSync(); return result; } public void notifyTransferSome(final long offset) { for (long value = this.push2SlaveMaxOffset.get(); offset > value; ) { boolean ok = this.push2SlaveMaxOffset.compareAndSet(value, offset); if (ok) { this.groupTransferService.notifyTransferSome(); break; } else { value = this.push2SlaveMaxOffset.get(); } } } @Override public AtomicInteger getConnectionCount() { return connectionCount; } @Override public void start() throws Exception { this.acceptSocketService.beginAccept(); this.acceptSocketService.start(); this.groupTransferService.start(); this.haConnectionStateNotificationService.start(); if (haClient != null) { this.haClient.start(); } } public void addConnection(final HAConnection conn) { synchronized (this.connectionList) { this.connectionList.add(conn); } } public void removeConnection(final HAConnection conn) { this.haConnectionStateNotificationService.checkConnectionStateAndNotify(conn); synchronized (this.connectionList) { this.connectionList.remove(conn); } } @Override public void shutdown() { if (this.haClient != null) { this.haClient.shutdown(); } if (this.acceptSocketService != null) { this.acceptSocketService.shutdown(true); } this.destroyConnections(); if (this.groupTransferService != null) { groupTransferService.shutdown(); } if (this.haConnectionStateNotificationService != null) { this.haConnectionStateNotificationService.shutdown(); } } public void destroyConnections() { synchronized (this.connectionList) { for (HAConnection c : this.connectionList) { c.shutdown(); } this.connectionList.clear(); } } public DefaultMessageStore getDefaultMessageStore() { return defaultMessageStore; } @Override public WaitNotifyObject getWaitNotifyObject() { return waitNotifyObject; } @Override public AtomicLong getPush2SlaveMaxOffset() { return push2SlaveMaxOffset; } @Override public int inSyncReplicasNums(final long masterPutWhere) { int inSyncNums = 1; for (HAConnection conn : this.connectionList) { if (this.isInSyncSlave(masterPutWhere, conn)) { inSyncNums++; } } return inSyncNums; } protected boolean isInSyncSlave(final long masterPutWhere, HAConnection conn) { if (masterPutWhere - conn.getSlaveAckOffset() < this.defaultMessageStore.getMessageStoreConfig() .getHaMaxGapNotInSync()) { return true; } return false; } @Override public void putGroupConnectionStateRequest(HAConnectionStateNotificationRequest request) { this.haConnectionStateNotificationService.setRequest(request); } @Override public List<HAConnection> getConnectionList() { return connectionList; } @Override public HAClient getHAClient() { return this.haClient; } @Override public HARuntimeInfo getRuntimeInfo(long masterPutWhere) { HARuntimeInfo info = new HARuntimeInfo(); if (BrokerRole.SLAVE.equals(this.getDefaultMessageStore().getMessageStoreConfig().getBrokerRole())) { info.setMaster(false); info.getHaClientRuntimeInfo().setMasterAddr(this.haClient.getHaMasterAddress()); info.getHaClientRuntimeInfo().setMaxOffset(this.getDefaultMessageStore().getMaxPhyOffset()); info.getHaClientRuntimeInfo().setLastReadTimestamp(this.haClient.getLastReadTimestamp()); info.getHaClientRuntimeInfo().setLastWriteTimestamp(this.haClient.getLastWriteTimestamp()); info.getHaClientRuntimeInfo().setTransferredByteInSecond(this.haClient.getTransferredByteInSecond()); info.getHaClientRuntimeInfo().setMasterFlushOffset(this.defaultMessageStore.getMasterFlushedOffset()); } else { info.setMaster(true); int inSyncNums = 0; info.setMasterCommitLogMaxOffset(masterPutWhere); for (HAConnection conn : this.connectionList) { HARuntimeInfo.HAConnectionRuntimeInfo cInfo = new HARuntimeInfo.HAConnectionRuntimeInfo(); long slaveAckOffset = conn.getSlaveAckOffset(); cInfo.setSlaveAckOffset(slaveAckOffset); cInfo.setDiff(masterPutWhere - slaveAckOffset); cInfo.setAddr(conn.getClientAddress().substring(1)); cInfo.setTransferredByteInSecond(conn.getTransferredByteInSecond()); cInfo.setTransferFromWhere(conn.getTransferFromWhere()); boolean isInSync = this.isInSyncSlave(masterPutWhere, conn); if (isInSync) { inSyncNums++; } cInfo.setInSync(isInSync); info.getHaConnectionInfo().add(cInfo); } info.setInSyncSlaveNums(inSyncNums); } return info; }
DefaultHAService
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/commands/reactive/ListReactiveCommandIntegrationTests.java
{ "start": 382, "end": 641 }
class ____ extends ListCommandIntegrationTests { @Inject ListReactiveCommandIntegrationTests(StatefulRedisConnection<String, String> connection) { super(ReactiveSyncInvocationHandler.sync(connection)); } }
ListReactiveCommandIntegrationTests
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/services/TestAbfsRestOperation.java
{ "start": 1981, "end": 4310 }
class ____ extends AbstractAbfsIntegrationTest { public TestAbfsRestOperation() throws Exception { } private void checkPrerequisites() { assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_METRIC_ACCOUNT_NAME); assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_METRIC_ACCOUNT_KEY); assumeValidTestConfigPresent(getRawConfiguration(), FS_AZURE_METRIC_URI); } /** * Test for backoff retry metrics. * * This method tests backoff retry metrics by creating an AzureBlobFileSystem, initializing an * AbfsClient, and performing mock operations on an AbfsRestOperation. The method then updates * backoff metrics using the AbfsRestOperation. * */ @Test public void testBackoffRetryMetrics() throws Exception { checkPrerequisites(); // Create an AzureBlobFileSystem instance. final Configuration configuration = getRawConfiguration(); configuration.set(FS_AZURE_METRIC_FORMAT, String.valueOf(MetricFormat.INTERNAL_BACKOFF_METRIC_FORMAT)); final AzureBlobFileSystem fs = (AzureBlobFileSystem) FileSystem.newInstance(configuration); AbfsConfiguration abfsConfiguration = fs.getAbfsStore().getAbfsConfiguration(); // Get an instance of AbfsClient and AbfsRestOperation. AbfsClient testClient = super.getAbfsClient(super.getAbfsStore(fs)); AbfsRestOperation op = ITestAbfsClient.getRestOp( DeletePath, testClient, HTTP_METHOD_DELETE, ITestAbfsClient.getTestUrl(testClient, "/NonExistingPath"), ITestAbfsClient.getTestRequestHeaders(testClient), getConfiguration()); // Mock retry counts and status code. ArrayList<String> retryCounts = new ArrayList<>(Arrays.asList("35", "28", "31", "45", "10", "2", "9")); int statusCode = HttpURLConnection.HTTP_UNAVAILABLE; // Update backoff metrics. for (String retryCount : retryCounts) { op.updateBackoffMetrics(Integer.parseInt(retryCount), statusCode); } // For retry count greater than the max configured value, the request should fail. assertEquals("3", String.valueOf(testClient.getAbfsCounters().getAbfsBackoffMetrics(). getMetricValue(NUMBER_OF_REQUESTS_FAILED)), "Number of failed requests does not match expected value."); // Close the AzureBlobFileSystem. fs.close(); } }
TestAbfsRestOperation
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/EnableWebSocket.java
{ "start": 998, "end": 1180 }
class ____ configure * processing WebSocket requests. A typical configuration would look like this: * * <pre class="code"> * &#064;Configuration * &#064;EnableWebSocket * public
to
java
apache__kafka
raft/src/main/java/org/apache/kafka/raft/internals/UpdateVoterHandler.java
{ "start": 2888, "end": 12348 }
class ____ { private final OptionalInt localId; private final KRaftControlRecordStateMachine partitionState; private final ListenerName defaultListenerName; private final Logger log; public UpdateVoterHandler( OptionalInt localId, KRaftControlRecordStateMachine partitionState, ListenerName defaultListenerName, LogContext logContext ) { this.localId = localId; this.partitionState = partitionState; this.defaultListenerName = defaultListenerName; this.log = logContext.logger(getClass()); } public CompletableFuture<UpdateRaftVoterResponseData> handleUpdateVoterRequest( LeaderState<?> leaderState, ListenerName requestListenerName, ReplicaKey voterKey, Endpoints voterEndpoints, UpdateRaftVoterRequestData.KRaftVersionFeature supportedKraftVersions, long currentTimeMs ) { // Check if there are any pending voter change requests if (leaderState.isOperationPending(currentTimeMs)) { return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.REQUEST_TIMED_OUT, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } // Check that the leader has established a HWM and committed the current epoch Optional<Long> highWatermark = leaderState.highWatermark().map(LogOffsetMetadata::offset); if (highWatermark.isEmpty()) { return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.REQUEST_TIMED_OUT, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } // Read the voter set from the log or leader state KRaftVersion kraftVersion = partitionState.lastKraftVersion(); final Optional<KRaftVersionUpgrade.Voters> inMemoryVoters; final Optional<VoterSet> voters; if (kraftVersion.isReconfigSupported()) { inMemoryVoters = Optional.empty(); // Check that there are no uncommitted VotersRecord Optional<LogHistory.Entry<VoterSet>> votersEntry = partitionState.lastVoterSetEntry(); if (votersEntry.isEmpty() || votersEntry.get().offset() >= highWatermark.get()) { voters = Optional.empty(); } else { voters = votersEntry.map(LogHistory.Entry::value); } } else { inMemoryVoters = leaderState.volatileVoters(); if (inMemoryVoters.isEmpty()) { /* This can happen if the remote voter sends an update voter request before the * updated kraft version has been written to the log */ return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.REQUEST_TIMED_OUT, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } voters = inMemoryVoters.map(KRaftVersionUpgrade.Voters::voters); } if (voters.isEmpty()) { log.info("Unable to read the current voter set with kraft version {}", kraftVersion); return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.REQUEST_TIMED_OUT, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } // Check that the supported version range is valid if (!validVersionRange(kraftVersion, supportedKraftVersions)) { return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.INVALID_REQUEST, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } // Check that endpoints includes the default listener if (voterEndpoints.address(defaultListenerName).isEmpty()) { return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.INVALID_REQUEST, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } // Update the voter Optional<VoterSet> updatedVoters = updateVoters( voters.get(), kraftVersion, VoterSet.VoterNode.of( voterKey, voterEndpoints, new SupportedVersionRange( supportedKraftVersions.minSupportedVersion(), supportedKraftVersions.maxSupportedVersion() ) ) ); if (updatedVoters.isEmpty()) { return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.VOTER_NOT_FOUND, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } return storeUpdatedVoters( leaderState, voterKey, inMemoryVoters, updatedVoters.get(), requestListenerName, currentTimeMs ); } private boolean validVersionRange( KRaftVersion finalizedVersion, UpdateRaftVoterRequestData.KRaftVersionFeature supportedKraftVersions ) { return supportedKraftVersions.minSupportedVersion() <= finalizedVersion.featureLevel() && supportedKraftVersions.maxSupportedVersion() >= finalizedVersion.featureLevel(); } private Optional<VoterSet> updateVoters( VoterSet voters, KRaftVersion kraftVersion, VoterSet.VoterNode updatedVoter ) { return kraftVersion.isReconfigSupported() ? voters.updateVoter(updatedVoter) : voters.updateVoterIgnoringDirectoryId(updatedVoter); } private CompletableFuture<UpdateRaftVoterResponseData> storeUpdatedVoters( LeaderState<?> leaderState, ReplicaKey voterKey, Optional<KRaftVersionUpgrade.Voters> inMemoryVoters, VoterSet newVoters, ListenerName requestListenerName, long currentTimeMs ) { if (inMemoryVoters.isEmpty()) { // Since the partition support reconfig then just write the update voter set directly to the log leaderState.appendVotersRecord(newVoters, currentTimeMs); } else { // Store the new voters set in the leader state since it cannot be written to the log var successful = leaderState.compareAndSetVolatileVoters( inMemoryVoters.get(), new KRaftVersionUpgrade.Voters(newVoters) ); if (successful) { log.info( "Updated in-memory voters from {} to {}", inMemoryVoters.get().voters(), newVoters ); } else { log.info( "Unable to update in-memory voters from {} to {}", inMemoryVoters.get().voters(), newVoters ); return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.REQUEST_TIMED_OUT, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } } // Reset the check quorum state since the leader received a successful request leaderState.updateCheckQuorumForFollowingVoter(voterKey, currentTimeMs); return CompletableFuture.completedFuture( RaftUtil.updateVoterResponse( Errors.NONE, requestListenerName, new LeaderAndEpoch( localId, leaderState.epoch() ), leaderState.leaderEndpoints() ) ); } }
UpdateVoterHandler
java
spring-projects__spring-framework
spring-context-support/src/test/java/org/springframework/cache/jcache/interceptor/JCacheInterceptorTests.java
{ "start": 4811, "end": 5059 }
class ____ implements CacheOperationInvoker { private final Object result; private DummyInvoker(Object result) { this.result = result; } @Override public Object invoke() throws ThrowableWrapper { return result; } } }
DummyInvoker
java
apache__dubbo
dubbo-remoting/dubbo-remoting-netty4/src/test/java/org/apache/dubbo/remoting/transport/netty4/RpcMessageHandler.java
{ "start": 1379, "end": 3115 }
class ____ implements Replier<RpcMessage> { private static final ConcurrentMap<String, Object> IMPLEMENT_MAP = new ConcurrentHashMap<>(); private static final ServiceProvider DEFAULT_PROVIDER = new ServiceProvider() { public Object getImplementation(String service) { String impl = service + "Impl"; return ConcurrentHashMapUtils.computeIfAbsent(IMPLEMENT_MAP, impl, (s) -> { try { Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(s); return cl.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; }); } }; private ServiceProvider mProvider; public RpcMessageHandler() { this(DEFAULT_PROVIDER); } public RpcMessageHandler(ServiceProvider prov) { mProvider = prov; } public Class<RpcMessage> interest() { return RpcMessage.class; } public Object reply(ExchangeChannel channel, RpcMessage msg) throws RemotingException { String desc = msg.getMethodDesc(); Object[] args = msg.getArguments(); Object impl = mProvider.getImplementation(msg.getClassName()); Wrapper wrap = Wrapper.getWrapper(impl.getClass()); try { return new MockResult(wrap.invokeMethod(impl, desc, msg.getParameterTypes(), args)); } catch (NoSuchMethodException e) { throw new RemotingException(channel, "Service method not found."); } catch (InvocationTargetException e) { return new MockResult(e.getTargetException()); } } public
RpcMessageHandler
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/join/TestJoinTupleWritable.java
{ "start": 1613, "end": 10080 }
class ____ { private TupleWritable makeTuple(Writable[] writs) { Writable[] sub1 = { writs[1], writs[2] }; Writable[] sub3 = { writs[4], writs[5] }; Writable[] sub2 = { writs[3], new TupleWritable(sub3), writs[6] }; Writable[] vals = { writs[0], new TupleWritable(sub1), new TupleWritable(sub2), writs[7], writs[8], writs[9] }; // [v0, [v1, v2], [v3, [v4, v5], v6], v7, v8, v9] TupleWritable ret = new TupleWritable(vals); for (int i = 0; i < 6; ++i) { ret.setWritten(i); } ((TupleWritable)sub2[1]).setWritten(0); ((TupleWritable)sub2[1]).setWritten(1); ((TupleWritable)vals[1]).setWritten(0); ((TupleWritable)vals[1]).setWritten(1); for (int i = 0; i < 3; ++i) { ((TupleWritable)vals[2]).setWritten(i); } return ret; } private Writable[] makeRandomWritables() { Random r = new Random(); Writable[] writs = { new BooleanWritable(r.nextBoolean()), new FloatWritable(r.nextFloat()), new FloatWritable(r.nextFloat()), new IntWritable(r.nextInt()), new LongWritable(r.nextLong()), new BytesWritable("dingo".getBytes()), new LongWritable(r.nextLong()), new IntWritable(r.nextInt()), new BytesWritable("yak".getBytes()), new IntWritable(r.nextInt()) }; return writs; } private Writable[] makeRandomWritables(int numWrits) { Writable[] writs = makeRandomWritables(); Writable[] manyWrits = new Writable[numWrits]; for (int i =0; i<manyWrits.length; i++) { manyWrits[i] = writs[i%writs.length]; } return manyWrits; } private int verifIter(Writable[] writs, TupleWritable t, int i) { for (Writable w : t) { if (w instanceof TupleWritable) { i = verifIter(writs, ((TupleWritable)w), i); continue; } assertTrue(w.equals(writs[i++]), "Bad value"); } return i; } @Test public void testIterable() throws Exception { Random r = new Random(); Writable[] writs = { new BooleanWritable(r.nextBoolean()), new FloatWritable(r.nextFloat()), new FloatWritable(r.nextFloat()), new IntWritable(r.nextInt()), new LongWritable(r.nextLong()), new BytesWritable("dingo".getBytes()), new LongWritable(r.nextLong()), new IntWritable(r.nextInt()), new BytesWritable("yak".getBytes()), new IntWritable(r.nextInt()) }; TupleWritable t = new TupleWritable(writs); for (int i = 0; i < 6; ++i) { t.setWritten(i); } verifIter(writs, t, 0); } @Test public void testNestedIterable() throws Exception { Random r = new Random(); Writable[] writs = { new BooleanWritable(r.nextBoolean()), new FloatWritable(r.nextFloat()), new FloatWritable(r.nextFloat()), new IntWritable(r.nextInt()), new LongWritable(r.nextLong()), new BytesWritable("dingo".getBytes()), new LongWritable(r.nextLong()), new IntWritable(r.nextInt()), new BytesWritable("yak".getBytes()), new IntWritable(r.nextInt()) }; TupleWritable sTuple = makeTuple(writs); assertTrue(writs.length == verifIter(writs, sTuple, 0), "Bad count"); } @Test public void testWritable() throws Exception { Random r = new Random(); Writable[] writs = { new BooleanWritable(r.nextBoolean()), new FloatWritable(r.nextFloat()), new FloatWritable(r.nextFloat()), new IntWritable(r.nextInt()), new LongWritable(r.nextLong()), new BytesWritable("dingo".getBytes()), new LongWritable(r.nextLong()), new IntWritable(r.nextInt()), new BytesWritable("yak".getBytes()), new IntWritable(r.nextInt()) }; TupleWritable sTuple = makeTuple(writs); ByteArrayOutputStream out = new ByteArrayOutputStream(); sTuple.write(new DataOutputStream(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); TupleWritable dTuple = new TupleWritable(); dTuple.readFields(new DataInputStream(in)); assertTrue(sTuple.equals(dTuple), "Failed to write/read tuple"); } @Test public void testWideWritable() throws Exception { Writable[] manyWrits = makeRandomWritables(131); TupleWritable sTuple = new TupleWritable(manyWrits); for (int i =0; i<manyWrits.length; i++) { if (i % 3 == 0) { sTuple.setWritten(i); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); sTuple.write(new DataOutputStream(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); TupleWritable dTuple = new TupleWritable(); dTuple.readFields(new DataInputStream(in)); assertThat(dTuple).withFailMessage("Failed to write/read tuple") .isEqualTo(sTuple); assertEquals(-1, in.read(), "All tuple data has not been read from the stream"); } @Test public void testWideWritable2() throws Exception { Writable[] manyWrits = makeRandomWritables(71); TupleWritable sTuple = new TupleWritable(manyWrits); for (int i =0; i<manyWrits.length; i++) { sTuple.setWritten(i); } ByteArrayOutputStream out = new ByteArrayOutputStream(); sTuple.write(new DataOutputStream(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); TupleWritable dTuple = new TupleWritable(); dTuple.readFields(new DataInputStream(in)); assertThat(dTuple).withFailMessage("Failed to write/read tuple") .isEqualTo(sTuple); assertEquals(-1, in.read(), "All tuple data has not been read from the stream"); } /** * Tests a tuple writable with more than 64 values and the values set written * spread far apart. */ @Test public void testSparseWideWritable() throws Exception { Writable[] manyWrits = makeRandomWritables(131); TupleWritable sTuple = new TupleWritable(manyWrits); for (int i =0; i<manyWrits.length; i++) { if (i % 65 == 0) { sTuple.setWritten(i); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); sTuple.write(new DataOutputStream(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); TupleWritable dTuple = new TupleWritable(); dTuple.readFields(new DataInputStream(in)); assertThat(dTuple).withFailMessage("Failed to write/read tuple") .isEqualTo(sTuple); assertEquals(-1, in.read(), "All tuple data has not been read from the stream"); } @Test public void testWideTuple() throws Exception { Text emptyText = new Text("Should be empty"); Writable[] values = new Writable[64]; Arrays.fill(values,emptyText); values[42] = new Text("Number 42"); TupleWritable tuple = new TupleWritable(values); tuple.setWritten(42); for (int pos=0; pos<tuple.size();pos++) { boolean has = tuple.has(pos); if (pos == 42) { assertTrue(has); } else { assertFalse(has, "Tuple position is incorrectly labelled as set: " + pos); } } } @Test public void testWideTuple2() throws Exception { Text emptyText = new Text("Should be empty"); Writable[] values = new Writable[64]; Arrays.fill(values,emptyText); values[9] = new Text("Number 9"); TupleWritable tuple = new TupleWritable(values); tuple.setWritten(9); for (int pos=0; pos<tuple.size();pos++) { boolean has = tuple.has(pos); if (pos == 9) { assertTrue(has); } else { assertFalse(has, "Tuple position is incorrectly labelled as set: " + pos); } } } /** * Tests that we can write more than 64 values. */ @Test public void testWideTupleBoundary() throws Exception { Text emptyText = new Text("Should not be set written"); Writable[] values = new Writable[65]; Arrays.fill(values,emptyText); values[64] = new Text("Should be the only value set written"); TupleWritable tuple = new TupleWritable(values); tuple.setWritten(64); for (int pos=0; pos<tuple.size();pos++) { boolean has = tuple.has(pos); if (pos == 64) { assertTrue(has); } else { assertFalse(has, "Tuple position is incorrectly labelled as set: " + pos); } } } }
TestJoinTupleWritable
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/condition/EnabledOnJre.java
{ "start": 825, "end": 993 }
class ____ * test method is only <em>enabled</em> on one or more specified Java Runtime * Environment (JRE) versions. * * <p>Versions can be specified as {@link JRE}
or
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/TopIntAggregatorFunctionTests.java
{ "start": 739, "end": 1640 }
class ____ extends AggregatorFunctionTestCase { private static final int LIMIT = 100; @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { return new SequenceIntBlockSourceOperator(blockFactory, IntStream.range(0, size).map(l -> randomInt())); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new TopIntAggregatorFunctionSupplier(LIMIT, true); } @Override protected String expectedDescriptionOfAggregator() { return "top of ints"; } @Override public void assertSimpleOutput(List<Page> input, Block result) { Object[] values = input.stream().flatMapToInt(p -> allInts(p.getBlock(0))).sorted().limit(LIMIT).boxed().toArray(Object[]::new); assertThat((List<?>) BlockUtils.toJavaObject(result, 0), contains(values)); } }
TopIntAggregatorFunctionTests
java
quarkusio__quarkus
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormUpload.java
{ "start": 1075, "end": 9799 }
class ____ implements ReadStream<Buffer>, Runnable { private static final UnpooledByteBufAllocator ALLOC = new UnpooledByteBufAllocator(false); private DefaultFullHttpRequest request; private PausableHttpPostRequestEncoder encoder; private Handler<Throwable> exceptionHandler; private Handler<Buffer> dataHandler; private Handler<Void> endHandler; private boolean ended; private final InboundBuffer<Object> pending; private final Context context; public QuarkusMultipartFormUpload(Context context, QuarkusMultipartForm parts, boolean multipart, int maxChunkSize, PausableHttpPostRequestEncoder.EncoderMode encoderMode) throws Exception { this.context = context; this.pending = new InboundBuffer<>(context) .handler(this::handleChunk) .drainHandler(v -> run()) .pause(); this.request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.POST, "/"); Charset charset = parts.getCharset() != null ? parts.getCharset() : HttpConstants.DEFAULT_CHARSET; DefaultHttpDataFactory httpDataFactory = new DefaultHttpDataFactory(-1, charset) { @Override public FileUpload createFileUpload(HttpRequest request, String name, String filename, String contentType, String contentTransferEncoding, Charset _charset, long size) { if (_charset == null) { _charset = charset; } return super.createFileUpload(request, name, filename, contentType, contentTransferEncoding, _charset, size); } }; this.encoder = new PausableHttpPostRequestEncoder(httpDataFactory, request, multipart, maxChunkSize, charset, encoderMode); for (QuarkusMultipartFormDataPart formDataPart : parts) { if (formDataPart.isAttribute()) { encoder.addBodyAttribute(formDataPart.name(), formDataPart.value()); } else if (formDataPart.isObject()) { MemoryFileUpload data = new MemoryFileUpload(formDataPart.name(), formDataPart.filename() != null ? formDataPart.filename() : "", formDataPart.mediaType(), formDataPart.isText() ? null : "binary", null, formDataPart.content().length()); data.setContent(formDataPart.content().getByteBuf()); encoder.addBodyHttpData(data); } else if (formDataPart.multiByteContent() != null) { String contentTransferEncoding = null; String contentType = formDataPart.mediaType(); if (contentType == null) { if (formDataPart.isText()) { contentType = "text/plain"; } else { contentType = "application/octet-stream"; } } if (!formDataPart.isText()) { contentTransferEncoding = "binary"; } encoder.addBodyHttpData(new MultiByteHttpData( formDataPart.name(), formDataPart.filename(), contentType, contentTransferEncoding, Charset.defaultCharset(), formDataPart.multiByteContent(), this::handleError, context, this)); } else { String pathname = formDataPart.pathname(); if (pathname != null) { encoder.addBodyFileUpload(formDataPart.name(), formDataPart.filename(), new File(formDataPart.pathname()), formDataPart.mediaType(), formDataPart.isText()); } else { String contentType = formDataPart.mediaType(); if (formDataPart.mediaType() == null) { if (formDataPart.isText()) { contentType = "text/plain"; } else { contentType = "application/octet-stream"; } } String transferEncoding = formDataPart.isText() ? null : "binary"; MemoryFileUpload fileUpload = new MemoryFileUpload( formDataPart.name(), formDataPart.filename(), contentType, transferEncoding, null, formDataPart.content().length()); fileUpload.setContent(formDataPart.content().getByteBuf()); encoder.addBodyHttpData(fileUpload); } } } encoder.finalizeRequest(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void handleChunk(Object item) { Handler handler; synchronized (QuarkusMultipartFormUpload.this) { if (item instanceof Buffer) { handler = dataHandler; } else if (item instanceof Throwable) { handler = exceptionHandler; } else if (item == InboundBuffer.END_SENTINEL) { handler = endHandler; item = null; } else { return; } } handler.handle(item); } private void clearEncoder() { if (encoder == null) { return; } encoder.cleanFiles(); encoder = null; } @Override public void run() { if (Vertx.currentContext() != context) { throw new IllegalArgumentException("Wrong Vert.x context used for multipart upload. Expected: " + context + ", actual: " + Vertx.currentContext()); } while (!ended) { if (encoder.isChunked()) { try { HttpContent chunk = encoder.readChunk(ALLOC); if (chunk == PausableHttpPostRequestEncoder.WAIT_MARKER) { return; // resumption will be scheduled by encoder } else if (chunk == LastHttpContent.EMPTY_LAST_CONTENT || encoder.isEndOfInput()) { ended = true; request = null; clearEncoder(); pending.write(InboundBuffer.END_SENTINEL); } else { ByteBuf content = chunk.content(); Buffer buff = Buffer.buffer(content); boolean writable = pending.write(buff); if (!writable) { break; } } } catch (Exception e) { handleError(e); break; } } else { ByteBuf content = request.content(); Buffer buffer = Buffer.buffer(content); request = null; clearEncoder(); pending.write(buffer); ended = true; pending.write(InboundBuffer.END_SENTINEL); } } } public boolean isChunked() { return encoder.isChunked(); } private void handleError(Throwable e) { ended = true; request = null; clearEncoder(); pending.write(e); } public MultiMap headers() { return new HeadersAdaptor(request.headers()); } @Override public synchronized QuarkusMultipartFormUpload exceptionHandler(Handler<Throwable> handler) { exceptionHandler = handler; return this; } @Override public synchronized QuarkusMultipartFormUpload handler(Handler<Buffer> handler) { dataHandler = handler; return this; } @Override public synchronized QuarkusMultipartFormUpload pause() { pending.pause(); return this; } @Override public ReadStream<Buffer> fetch(long amount) { pending.fetch(amount); return this; } @Override @Deprecated public synchronized QuarkusMultipartFormUpload resume() { pending.resume(); return this; } @Override public synchronized QuarkusMultipartFormUpload endHandler(Handler<Void> handler) { endHandler = handler; return this; } }
QuarkusMultipartFormUpload
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/mappingcontrol/ErroneousMethodAndConversionMapper.java
{ "start": 763, "end": 957 }
class ____ { private long time; public Target(long time) { this.time = time; } public long getTime() { return time; } } }
Target
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/MoreExecutorsTest.java
{ "start": 16185, "end": 19431 }
class ____ implements Runnable { final int throwAfterCount; final RuntimeException thrown; int count; ThrowingRunnable(int throwAfterCount, RuntimeException thrown) { this.throwAfterCount = throwAfterCount; this.thrown = thrown; } @Override public void run() { if (++count >= throwAfterCount) { throw thrown; } } } private static void assertExecutionException(Future<?> future, Exception expectedCause) throws Exception { try { future.get(); fail("Expected ExecutionException"); } catch (ExecutionException e) { assertThat(e).hasCauseThat().isSameInstanceAs(expectedCause); } } /** invokeAny(null) throws NPE */ public void testInvokeAnyImpl_nullTasks() throws Exception { ListeningExecutorService e = newDirectExecutorService(); try { invokeAnyImpl(e, null, false, 0, NANOSECONDS); fail(); } catch (NullPointerException success) { } finally { joinPool(e); } } /** invokeAny(empty collection) throws IAE */ public void testInvokeAnyImpl_emptyTasks() throws Exception { ListeningExecutorService e = newDirectExecutorService(); try { invokeAnyImpl(e, new ArrayList<Callable<String>>(), false, 0, NANOSECONDS); fail(); } catch (IllegalArgumentException success) { } finally { joinPool(e); } } /** invokeAny(c) throws NPE if c has null elements */ public void testInvokeAnyImpl_nullElement() throws Exception { ListeningExecutorService e = newDirectExecutorService(); List<Callable<Integer>> l = new ArrayList<>(); l.add( new Callable<Integer>() { @Override public Integer call() { throw new ArithmeticException("/ by zero"); } }); l.add(null); try { invokeAnyImpl(e, l, false, 0, NANOSECONDS); fail(); } catch (NullPointerException success) { } finally { joinPool(e); } } /** invokeAny(c) throws ExecutionException if no task in c completes */ public void testInvokeAnyImpl_noTaskCompletes() throws Exception { ListeningExecutorService e = newDirectExecutorService(); List<Callable<String>> l = new ArrayList<>(); l.add(new NPETask()); try { invokeAnyImpl(e, l, false, 0, NANOSECONDS); fail(); } catch (ExecutionException success) { assertThat(success).hasCauseThat().isInstanceOf(NullPointerException.class); } finally { joinPool(e); } } /** invokeAny(c) returns result of some task in c if at least one completes */ public void testInvokeAnyImpl() throws Exception { ListeningExecutorService e = newDirectExecutorService(); try { List<Callable<String>> l = new ArrayList<>(); l.add(new StringTask()); l.add(new StringTask()); String result = invokeAnyImpl(e, l, false, 0, NANOSECONDS); assertSame(TEST_STRING, result); } finally { joinPool(e); } } private static void assertListenerRunImmediately(ListenableFuture<?> future) { CountingRunnable listener = new CountingRunnable(); future.addListener(listener, directExecutor()); assertEquals(1, listener.count); } private static final
ThrowingRunnable
java
quarkusio__quarkus
independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/quarkus/QuarkusCodestartGenerationTest.java
{ "start": 6744, "end": 7040 }
class ____")) .satisfies(checkContains("\"/bonjour\"")); assertThatMatchSnapshot(testInfo, projectDir, "src/test/kotlin/com/andy/BonjourResourceIT.kt") .satisfies(checkContains("package com.andy")) .satisfies(checkContains("
BonjourResourceTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/BatchPaginationTest.java
{ "start": 3308, "end": 3814 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String categoryId; @BatchSize(size = 20) @ManyToMany private List<Tag> tags = new ArrayList<>(); public Article() { } public Article(String categoryId, List<Tag> tags) { this.categoryId = categoryId; this.tags = tags; } public int getId() { return id; } public String getCategoryId() { return categoryId; } public List<Tag> getTags() { return tags; } } }
Article
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/file/tfile/KVGenerator.java
{ "start": 1077, "end": 3292 }
class ____ { private final Random random; private final byte[][] dict; private final boolean sorted; private final DiscreteRNG keyLenRNG, valLenRNG; private BytesWritable lastKey; private static final int MIN_KEY_LEN = 4; private final byte prefix[] = new byte[MIN_KEY_LEN]; public KVGenerator(Random random, boolean sorted, DiscreteRNG keyLenRNG, DiscreteRNG valLenRNG, DiscreteRNG wordLenRNG, int dictSize) { this.random = random; dict = new byte[dictSize][]; this.sorted = sorted; this.keyLenRNG = keyLenRNG; this.valLenRNG = valLenRNG; for (int i = 0; i < dictSize; ++i) { int wordLen = wordLenRNG.nextInt(); dict[i] = new byte[wordLen]; random.nextBytes(dict[i]); } lastKey = new BytesWritable(); fillKey(lastKey); } private void fillKey(BytesWritable o) { int len = keyLenRNG.nextInt(); if (len < MIN_KEY_LEN) len = MIN_KEY_LEN; o.setSize(len); int n = MIN_KEY_LEN; while (n < len) { byte[] word = dict[random.nextInt(dict.length)]; int l = Math.min(word.length, len - n); System.arraycopy(word, 0, o.getBytes(), n, l); n += l; } if (sorted && WritableComparator.compareBytes( lastKey.getBytes(), MIN_KEY_LEN, lastKey.getLength() - MIN_KEY_LEN, o.getBytes(), MIN_KEY_LEN, o.getLength() - MIN_KEY_LEN) > 0) { incrementPrefix(); } System.arraycopy(prefix, 0, o.getBytes(), 0, MIN_KEY_LEN); lastKey.set(o); } private void fillValue(BytesWritable o) { int len = valLenRNG.nextInt(); o.setSize(len); int n = 0; while (n < len) { byte[] word = dict[random.nextInt(dict.length)]; int l = Math.min(word.length, len - n); System.arraycopy(word, 0, o.getBytes(), n, l); n += l; } } private void incrementPrefix() { for (int i = MIN_KEY_LEN - 1; i >= 0; --i) { ++prefix[i]; if (prefix[i] != 0) return; } throw new RuntimeException("Prefix overflown"); } public void next(BytesWritable key, BytesWritable value, boolean dupKey) { if (dupKey) { key.set(lastKey); } else { fillKey(key); } fillValue(value); } }
KVGenerator
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java
{ "start": 13340, "end": 13610 }
class ____ { @Inject Environment env; @Bean TestBean testBean() { return new TestBean(env.getProperty("testbean.name")); } } @Configuration @PropertySource("classpath:${path.to.properties}/p1.properties") static
ConfigWithUnresolvablePlaceholderAndDefault
java
apache__camel
components/camel-rest-openapi/src/test/java/org/apache/camel/component/rest/openapi/RestOpenApiComponentV3YamlTest.java
{ "start": 2559, "end": 11021 }
class ____ extends ManagedCamelTestSupport { public static WireMockServer petstore = new WireMockServer(wireMockConfig().dynamicPort()); static final Object NO_BODY = null; @BeforeAll public static void startWireMockServer() { petstore.start(); } @AfterAll public static void stopWireMockServer() { petstore.stop(); } @BeforeEach public void resetWireMock() { petstore.resetRequests(); } @ParameterizedTest @MethodSource("knownProducers") public void shouldBeAddingPets(String componentName) throws Exception { initializeContextForComponent(componentName); final Pet pet = new Pet(); pet.setName("Jean-Luc Picard"); final Pet created = template.requestBody("direct:addPet", pet, Pet.class); assertNotNull(created); assertEquals(14, created.getId()); petstore.verify( postRequestedFor(urlEqualTo("/api/v3/pet")).withHeader("Accept", equalTo("application/xml,application/json")) .withHeader("Content-Type", equalTo("application/xml"))); } @ParameterizedTest @MethodSource("knownProducers") public void shouldBeGettingPetsById(String componentName) throws Exception { initializeContextForComponent(componentName); final Pet pet = template.requestBodyAndHeader("direct:getPetById", NO_BODY, "petId", 14, Pet.class); assertNotNull(pet); assertEquals(14, pet.getId()); assertEquals("Olafur Eliason Arnalds", pet.getName()); petstore.verify(getRequestedFor(urlEqualTo("/api/v3/pet/14")).withHeader("Accept", equalTo("application/xml,application/json"))); } @ParameterizedTest @MethodSource("knownProducers") public void shouldBeGettingPetsByIdSpecifiedInEndpointParameters(String componentName) throws Exception { initializeContextForComponent(componentName); final Pet pet = template.requestBody("direct:getPetByIdWithEndpointParams", NO_BODY, Pet.class); assertNotNull(pet); assertEquals(14, pet.getId()); assertEquals("Olafur Eliason Arnalds", pet.getName()); petstore.verify(getRequestedFor(urlEqualTo("/api/v3/pet/14")).withHeader("Accept", equalTo("application/xml,application/json"))); } @ParameterizedTest @MethodSource("knownProducers") public void shouldBeGettingPetsByIdWithApiKeysInHeader(String componentName) throws Exception { initializeContextForComponent(componentName); final Map<String, Object> headers = new HashMap<>(); headers.put("petId", 14); headers.put("api_key", "dolphins"); final Pet pet = template.requestBodyAndHeaders("direct:getPetById", NO_BODY, headers, Pet.class); assertNotNull(pet); assertEquals(14, pet.getId()); assertEquals("Olafur Eliason Arnalds", pet.getName()); petstore.verify( getRequestedFor(urlEqualTo("/api/v3/pet/14")).withHeader("Accept", equalTo("application/xml,application/json")) .withHeader("api_key", equalTo("dolphins"))); } @ParameterizedTest @MethodSource("knownProducers") public void shouldBeGettingPetsByIdWithApiKeysInQueryParameter(String componentName) throws Exception { initializeContextForComponent(componentName); final Map<String, Object> headers = new HashMap<>(); headers.put("petId", 14); headers.put("api_key", "dolphins"); final Pet pet = template.requestBodyAndHeaders("altPetStore:getPetById", NO_BODY, headers, Pet.class); assertNotNull(pet); assertEquals(14, pet.getId()); assertEquals("Olafur Eliason Arnalds", pet.getName()); petstore.verify(getRequestedFor(urlEqualTo("/api/v3/pet/14?api_key=dolphins")).withHeader("Accept", equalTo("application/xml,application/json"))); } @ParameterizedTest @MethodSource("knownProducers") public void shouldBeGettingPetsByStatus(String componentName) throws Exception { initializeContextForComponent(componentName); final Pets pets = template.requestBodyAndHeader("direct:findPetsByStatus", NO_BODY, "status", "available", Pets.class); assertNotNull(pets); assertNotNull(pets.pets); assertEquals(2, pets.pets.size()); petstore.verify( getRequestedFor(urlPathEqualTo("/api/v3/pet/findByStatus")).withQueryParam("status", equalTo("available")) .withHeader("Accept", equalTo("application/xml,application/json"))); } @Override protected CamelContext createCamelContext(String componentName) { final CamelContext camelContext = new DefaultCamelContext(); final RestOpenApiComponent component = new RestOpenApiComponent(); component.setComponentName(componentName); component.setHost("http://localhost:" + petstore.port()); component.setSpecificationUri(RestOpenApiComponentV3YamlTest.class.getResource("/openapi-v3.yaml").toString()); camelContext.addComponent("petStore", component); final RestOpenApiComponent altPetStore = new RestOpenApiComponent(); altPetStore.setComponentName(componentName); altPetStore.setHost("http://localhost:" + petstore.port()); altPetStore.setSpecificationUri(RestOpenApiComponentV3YamlTest.class.getResource("/alt-openapi.yaml").toString()); camelContext.addComponent("altPetStore", altPetStore); return camelContext; } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() throws Exception { final JAXBContext jaxbContext = JAXBContext.newInstance(Pet.class, Pets.class); final JaxbDataFormat jaxb = new JaxbDataFormat(jaxbContext); jaxb.setJaxbProviderProperties(Collections.singletonMap(Marshaller.JAXB_FORMATTED_OUTPUT, false)); from("direct:getPetById").to("petStore:getPetById").unmarshal(jaxb); from("direct:getPetByIdWithEndpointParams").to("petStore:getPetById?petId=14").unmarshal(jaxb); from("direct:addPet").marshal(jaxb).to("petStore:addPet").unmarshal(jaxb); from("direct:findPetsByStatus").to("petStore:findPetsByStatus").unmarshal(jaxb); } }; } public static Iterable<String> knownProducers() { return Arrays.asList(RestEndpoint.DEFAULT_REST_PRODUCER_COMPONENTS); } @BeforeAll public static void setupStubs() throws IOException, URISyntaxException { petstore.stubFor(get(urlEqualTo("/openapi-v3.yaml")).willReturn(aResponse().withBody( Files.readAllBytes( Paths.get(RestOpenApiComponentV3YamlTest.class.getResource("/openapi-v3.yaml").getPath()))))); petstore.stubFor(post(urlEqualTo("/api/v3/pet")) .withRequestBody(equalTo( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><name>Jean-Luc Picard</name></Pet>")) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_CREATED) .withBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><id>14</id></Pet>"))); petstore.stubFor( get(urlEqualTo("/api/v3/pet/14")).willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><id>14</id><name>Olafur Eliason Arnalds</name></Pet>"))); petstore.stubFor(get(urlPathEqualTo("/api/v3/pet/findByStatus")).withQueryParam("status", equalTo("available")) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><pets><Pet><id>1</id><name>Olafur Eliason Arnalds</name></Pet><Pet><name>Jean-Luc Picard</name></Pet></pets>"))); petstore.stubFor(get(urlEqualTo("/api/v3/pet/14?api_key=dolphins")) .willReturn(aResponse().withStatus(HttpURLConnection.HTTP_OK).withBody( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Pet><id>14</id><name>Olafur Eliason Arnalds</name></Pet>"))); } }
RestOpenApiComponentV3YamlTest
java
quarkusio__quarkus
integration-tests/rest-client-reactive-http2/src/main/java/io/quarkus/it/rest/client/http2/Client.java
{ "start": 274, "end": 326 }
interface ____ { @GET Response ping(); }
Client
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/mapkeycolumn/MapKeyColumnManyToManyTest.java
{ "start": 4361, "end": 4606 }
class ____ { @Id public Integer id; public String street; @Column( name = "a_type" ) public String type; public Address2() { } public Address2(Integer id, String street) { this.id = id; this.street = street; } } }
Address2
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest129.java
{ "start": 1002, "end": 2591 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "select to_number(floor(months_between(sysdate,to_Date(t1.csny, 'yyyy-mm-dd')) / 12)) from dual;"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT to_number(floor(months_between(SYSDATE, to_Date(t1.csny, 'yyyy-mm-dd')) / 12))\n" + "FROM dual;", stmt.toString()); assertEquals("select to_number(floor(months_between(sysdate, to_Date(t1.csny, 'yyyy-mm-dd')) / 12))\n" + "from dual;", stmt.toLowerCaseString()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); assertEquals(0, visitor.getOrderByColumns().size()); // assertTrue(visitor.containsColumn("srm1.CONSIGNEE_ADDRESS", "id")); } }
OracleSelectTest129
java
apache__camel
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultUnitOfWorkFactory.java
{ "start": 1123, "end": 2488 }
class ____ implements UnitOfWorkFactory { private InflightRepository inflightRepository; private boolean usedMDCLogging; private String mdcLoggingKeysPattern; private boolean allowUseOriginalMessage; private boolean useBreadcrumb; @Override public UnitOfWork createUnitOfWork(Exchange exchange) { UnitOfWork answer; if (usedMDCLogging) { answer = new MDCUnitOfWork( exchange, inflightRepository, mdcLoggingKeysPattern, allowUseOriginalMessage, useBreadcrumb); } else { answer = new DefaultUnitOfWork(exchange, inflightRepository, allowUseOriginalMessage, useBreadcrumb); } return answer; } @Override public void afterPropertiesConfigured(CamelContext camelContext) { // optimize to read configuration once inflightRepository = camelContext.getInflightRepository(); usedMDCLogging = camelContext.isUseMDCLogging() != null && camelContext.isUseMDCLogging(); mdcLoggingKeysPattern = camelContext.getMDCLoggingKeysPattern(); allowUseOriginalMessage = camelContext.isAllowUseOriginalMessage() != null ? camelContext.isAllowUseOriginalMessage() : false; useBreadcrumb = camelContext.isUseBreadcrumb() != null ? camelContext.isUseBreadcrumb() : false; } }
DefaultUnitOfWorkFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/CriteriaUpdateWithParametersTest.java
{ "start": 998, "end": 4642 }
class ____ { @Test public void testCriteriaUpdate(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); final CriteriaUpdate<Person> criteriaUpdate = criteriaBuilder.createCriteriaUpdate( Person.class ); final Root<Person> root = criteriaUpdate.from( Person.class ); final ParameterExpression<Integer> intValueParameter = criteriaBuilder.parameter( Integer.class ); final ParameterExpression<String> stringValueParameter = criteriaBuilder.parameter( String.class ); final EntityType<Person> personEntityType = entityManager.getMetamodel().entity( Person.class ); criteriaUpdate.set( root.get( personEntityType.getSingularAttribute( "age", Integer.class ) ), intValueParameter ); criteriaUpdate.where( criteriaBuilder.equal( root.get( personEntityType.getSingularAttribute( "name", String.class ) ), stringValueParameter ) ); final Query query = entityManager.createQuery( criteriaUpdate ); query.setParameter( intValueParameter, 9 ); query.setParameter( stringValueParameter, "Luigi" ); query.executeUpdate(); } ); } @Test public void testCriteriaUpdate2(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); final CriteriaUpdate<Person> criteriaUpdate = criteriaBuilder.createCriteriaUpdate( Person.class ); final Root<Person> root = criteriaUpdate.from( Person.class ); final ParameterExpression<Integer> intValueParameter = criteriaBuilder.parameter( Integer.class ); final ParameterExpression<String> stringValueParameter = criteriaBuilder.parameter( String.class ); criteriaUpdate.set( "age", intValueParameter ); criteriaUpdate.where( criteriaBuilder.equal( root.get( "name" ), stringValueParameter ) ); final Query query = entityManager.createQuery( criteriaUpdate ); query.setParameter( intValueParameter, 9 ); query.setParameter( stringValueParameter, "Luigi" ); query.executeUpdate(); } ); } @Test public void testCriteriaUpdate3(EntityManagerFactoryScope scope) { scope.inTransaction( em -> { // test separate value-bind parameters final CriteriaBuilder cb = em.getCriteriaBuilder(); final CriteriaUpdate<Process> cu = cb.createCriteriaUpdate( Process.class ); final Root<Process> root = cu.from( Process.class ); cu.set( root.get( "name" ), (Object) null ); cu.set( root.get( "payload" ), (Object) null ); em.createQuery( cu ).executeUpdate(); } ); scope.inTransaction( em -> { // test with the same cb.value( null ) parameter instance final HibernateCriteriaBuilder cb = (HibernateCriteriaBuilder) em.getCriteriaBuilder(); final CriteriaUpdate<Process> cu = cb.createCriteriaUpdate( Process.class ); final Root<Process> root = cu.from( Process.class ); final Expression<Object> nullValue = cb.value( null ); // a bit unfortunate, but we need to cast here to prevent ambiguous method references final Path<String> name = root.get( "name" ); final Path<byte[]> payload = root.get( "payload" ); final Expression<? extends String> nullString = cast( nullValue ); final Expression<? extends byte[]> nullBytes = cast( nullValue ); cu.set( name, nullString ); cu.set( payload, nullBytes ); em.createQuery( cu ).executeUpdate(); } ); } private static <X> Expression<? extends X> cast(Expression<?> expression) { //noinspection unchecked return (Expression<? extends X>) expression; } @Entity(name = "Person") public static
CriteriaUpdateWithParametersTest
java
alibaba__nacos
client/src/test/java/com/alibaba/nacos/client/lock/remote/grpc/LockGrpcClientTest.java
{ "start": 2037, "end": 5613 }
class ____ { @Mock private RpcClient rpcClient; @Mock private SecurityProxy securityProxy; @Mock private ServerListFactory serverListFactory; private LockGrpcClient lockGrpcClient; @BeforeEach void setUp() throws NacosException, NoSuchFieldException, IllegalAccessException { lockGrpcClient = new LockGrpcClient(NacosClientProperties.PROTOTYPE, serverListFactory, securityProxy); Field rpcClientField = LockGrpcClient.class.getDeclaredField("rpcClient"); rpcClientField.setAccessible(true); rpcClientField.set(lockGrpcClient, rpcClient); } @AfterEach void tearDown() throws NacosException { lockGrpcClient.shutdown(); } private void mockRequest() { Map<String, String> context = new HashMap<>(); when(securityProxy.getIdentityContext(any())).thenReturn(context); when(rpcClient.getConnectionAbility(AbilityKey.SERVER_DISTRIBUTED_LOCK)).thenReturn(AbilityStatus.SUPPORTED); } @Test void lockNotSupportedFeature() { when(rpcClient.getConnectionAbility(AbilityKey.SERVER_DISTRIBUTED_LOCK)).thenReturn(AbilityStatus.NOT_SUPPORTED); assertThrows(NacosRuntimeException.class, () -> lockGrpcClient.lock(NLockFactory.getLock("test", -1L))); } @Test void lockWithNacosException() throws NacosException { mockRequest(); when(rpcClient.request(any(AbstractLockRequest.class))).thenThrow(new NacosException(NacosException.SERVER_ERROR, "test")); assertThrows(NacosException.class, () -> lockGrpcClient.lock(NLockFactory.getLock("test", -1L)), "test"); } @Test void lockWithOtherException() throws NacosException { mockRequest(); when(rpcClient.request(any(AbstractLockRequest.class))).thenThrow(new RuntimeException("test")); assertThrows(NacosException.class, () -> lockGrpcClient.lock(NLockFactory.getLock("test", -1L)), "Request nacos server failed: test"); } @Test void lockWithUnexpectedResponse() throws NacosException { mockRequest(); when(rpcClient.request(any(AbstractLockRequest.class))).thenReturn(new ServerCheckResponse()); assertThrows(NacosException.class, () -> lockGrpcClient.lock(NLockFactory.getLock("test", -1L)), "Server return invalid response"); } @Test void lockFailed() throws NacosException { mockRequest(); when(rpcClient.request(any(AbstractLockRequest.class))).thenReturn(ErrorResponse.build(500, "test fail code")); assertThrows(NacosException.class, () -> lockGrpcClient.lock(NLockFactory.getLock("test", -1L)), "test fail code"); } @Test void lockSuccess() throws NacosException { mockRequest(); when(rpcClient.request(any(AbstractLockRequest.class))).thenReturn(new LockOperationResponse(true)); assertTrue(lockGrpcClient.lock(NLockFactory.getLock("test", -1L))); } @Test void unLockNotSupportedFeature() { when(rpcClient.getConnectionAbility(AbilityKey.SERVER_DISTRIBUTED_LOCK)).thenReturn(AbilityStatus.NOT_SUPPORTED); assertThrows(NacosRuntimeException.class, () -> lockGrpcClient.unLock(NLockFactory.getLock("test", -1L))); } @Test void unlockSuccess() throws NacosException { mockRequest(); when(rpcClient.request(any(AbstractLockRequest.class))).thenReturn(new LockOperationResponse(true)); assertTrue(lockGrpcClient.unLock(NLockFactory.getLock("test", -1L))); } }
LockGrpcClientTest
java
netty__netty
common/src/main/java/io/netty/util/AttributeKey.java
{ "start": 1029, "end": 2523 }
class ____<T> extends AbstractConstant<AttributeKey<T>> { private static final ConstantPool<AttributeKey<Object>> pool = new ConstantPool<AttributeKey<Object>>() { @Override protected AttributeKey<Object> newConstant(int id, String name) { return new AttributeKey<Object>(id, name); } }; /** * Returns the singleton instance of the {@link AttributeKey} which has the specified {@code name}. */ @SuppressWarnings("unchecked") public static <T> AttributeKey<T> valueOf(String name) { return (AttributeKey<T>) pool.valueOf(name); } /** * Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}. */ public static boolean exists(String name) { return pool.exists(name); } /** * Creates a new {@link AttributeKey} for the given {@code name} or fail with an * {@link IllegalArgumentException} if a {@link AttributeKey} for the given {@code name} exists. */ @SuppressWarnings("unchecked") public static <T> AttributeKey<T> newInstance(String name) { return (AttributeKey<T>) pool.newInstance(name); } @SuppressWarnings("unchecked") public static <T> AttributeKey<T> valueOf(Class<?> firstNameComponent, String secondNameComponent) { return (AttributeKey<T>) pool.valueOf(firstNameComponent, secondNameComponent); } private AttributeKey(int id, String name) { super(id, name); } }
AttributeKey
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementWithP12WithAliasTest.java
{ "start": 3311, "end": 4076 }
class ____ implements Handler<RoutingContext> { @Override public void handle(RoutingContext rc) { Assertions.assertThat(rc.request().connection().isSsl()).isTrue(); Assertions.assertThat(rc.request().isSSL()).isTrue(); Assertions.assertThat(rc.request().connection().sslSession()).isNotNull(); rc.response().end("ssl"); } } @Test public void testSslWithP12() { RestAssured.given() .trustStore(new File("target/certs/ssl-management-interface-alias-test-truststore.jks"), "secret") .get("https://localhost:9001/management/my-route") .then().statusCode(200).body(Matchers.equalTo("ssl")); } @Singleton static
MyHandler
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/function/FailableTest.java
{ "start": 93105, "end": 93619 }
interface ____ properly defined to throw any exception using the top level generic types * Object and Throwable. */ @Test void testThrows_FailableIntToLongFunction_Throwable() { assertThrows(IOException.class, () -> new FailableIntToLongFunction<Throwable>() { @Override public long applyAsLong(final int value) throws Throwable { throw new IOException("test"); } }.applyAsLong(0)); } /** * Tests that our failable
is
java
spring-projects__spring-boot
module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/ManagementContextConfigurationTests.java
{ "start": 1097, "end": 1755 }
class ____ { @Test void proxyBeanMethodsIsEnabledByDefault() { AnnotationAttributes attributes = AnnotatedElementUtils .getMergedAnnotationAttributes(DefaultManagementContextConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", true); } @Test void proxyBeanMethodsCanBeDisabled() { AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes( NoBeanMethodProxyingManagementContextConfiguration.class, Configuration.class); assertThat(attributes).containsEntry("proxyBeanMethods", false); } @ManagementContextConfiguration static
ManagementContextConfigurationTests
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableDoOnSubscribeTest.java
{ "start": 1079, "end": 4853 }
class ____ extends RxJavaTest { @Test public void doOnSubscribe() throws Exception { final AtomicInteger count = new AtomicInteger(); Observable<Integer> o = Observable.just(1).doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { count.incrementAndGet(); } }); o.subscribe(); o.subscribe(); o.subscribe(); assertEquals(3, count.get()); } @Test public void doOnSubscribe2() throws Exception { final AtomicInteger count = new AtomicInteger(); Observable<Integer> o = Observable.just(1).doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { count.incrementAndGet(); } }).take(1).doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { count.incrementAndGet(); } }); o.subscribe(); assertEquals(2, count.get()); } @Test public void doOnUnSubscribeWorksWithRefCount() throws Exception { final AtomicInteger onSubscribed = new AtomicInteger(); final AtomicInteger countBefore = new AtomicInteger(); final AtomicInteger countAfter = new AtomicInteger(); final AtomicReference<Observer<? super Integer>> sref = new AtomicReference<>(); Observable<Integer> o = Observable.unsafeCreate(new ObservableSource<Integer>() { @Override public void subscribe(Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); onSubscribed.incrementAndGet(); sref.set(observer); } }).doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { countBefore.incrementAndGet(); } }).publish().refCount() .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { countAfter.incrementAndGet(); } }); o.subscribe(); o.subscribe(); o.subscribe(); assertEquals(1, countBefore.get()); assertEquals(1, onSubscribed.get()); assertEquals(3, countAfter.get()); sref.get().onComplete(); o.subscribe(); o.subscribe(); o.subscribe(); assertEquals(2, countBefore.get()); assertEquals(2, onSubscribed.get()); assertEquals(6, countAfter.get()); } @Test public void onSubscribeCrash() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { final Disposable bs = Disposable.empty(); new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(bs); observer.onError(new TestException("Second")); observer.onComplete(); } } .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) throws Exception { throw new TestException("First"); } }) .to(TestHelper.<Integer>testConsumer()) .assertFailureAndMessage(TestException.class, "First"); assertTrue(bs.isDisposed()); TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second"); } finally { RxJavaPlugins.reset(); } } }
ObservableDoOnSubscribeTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinedInheritanceTreatQueryTest.java
{ "start": 1486, "end": 9171 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final Description description = new Description( "description" ); session.persist( description ); final ProductOwner1 own1 = new ProductOwner1( description ); session.persist( own1 ); session.persist( new Product( own1 ) ); final ProductOwner2 own2 = new ProductOwner2( "basic_prop" ); session.persist( own2 ); session.persist( new Product( own2 ) ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.dropData(); } @Test public void testTreatedJoin(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { //noinspection removal final Product result = session.createQuery( "from Product p " + "join treat(p.owner AS ProductOwner1) as own1 " + "join own1.description", Product.class ).getSingleResult(); assertThat( result.getOwner() ).isInstanceOf( ProductOwner1.class ); assertThat( ( (ProductOwner1) result.getOwner() ).getDescription().getText() ).isEqualTo( "description" ); inspector.assertNumberOfJoins( 0, 3 ); } ); } @Test @Jira("https://hibernate.atlassian.net/browse/HHH-19883") public void testTreatedJoinWithCondition(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { final List<Product> result = session.createSelectionQuery( "from Product p " + "join treat(p.owner AS ProductOwner2) as own1 on own1.basicProp = 'unknown value'", Product.class ).getResultList(); assertThat( result ).isEmpty(); inspector.assertNumberOfJoins( 0, 2 ); } ); } @Test @Jira("https://hibernate.atlassian.net/browse/HHH-19883") public void testMultipleTreatedJoinWithCondition(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { final List<Product> result = session.createSelectionQuery( "from Product p " + "join treat(p.owner AS ProductOwner1) as own1 on own1.description is null " + "join treat(p.owner AS ProductOwner2) as own2 on own2.basicProp = 'unknown value'", Product.class ).getResultList(); assertThat( result ).isEmpty(); inspector.assertNumberOfJoins( 0, 4 ); } ); } @Test @Jira("https://hibernate.atlassian.net/browse/HHH-19883") public void testMultipleTreatedJoinSameAttribute(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { final List<Product> result = session.createSelectionQuery( "from Product p " + "join treat(p.owner AS ProductOwner1) as own1 " + "join treat(p.owner AS ProductOwner2) as own2", Product.class ).getResultList(); // No rows, because treat joining the same association with disjunct types can't emit results assertThat( result ).isEmpty(); inspector.assertNumberOfJoins( 0, 4 ); } ); } @Test @Jira("https://hibernate.atlassian.net/browse/HHH-19883") public void testMultipleTreatedJoinSameAttributeCriteria(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { final var cb = session.getCriteriaBuilder(); final var query = cb.createQuery(Product.class); final var p = query.from( Product.class ); p.join( "owner" ).treatAs( ProductOwner1.class ); p.join( "owner" ).treatAs( ProductOwner2.class ); final List<Product> result = session.createSelectionQuery( query ).getResultList(); // No rows, because treat joining the same association with disjunct types can't emit results assertThat( result ).isEmpty(); inspector.assertNumberOfJoins( 0, 4 ); } ); } @Test @Jira("https://hibernate.atlassian.net/browse/HHH-19883") public void testMultipleTreatedJoinCriteria(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { final var cb = session.getCriteriaBuilder(); final var query = cb.createQuery(Product.class); final var p = query.from( Product.class ); final var ownerJoin = p.join( "owner" ); ownerJoin.treatAs( ProductOwner1.class ); ownerJoin.treatAs( ProductOwner2.class ); final List<Product> result = session.createSelectionQuery( query ).getResultList(); // The owner attribute is inner joined, but since there are multiple subtype treats, // the type restriction for the treat usage does not filter rows assertThat( result ).hasSize( 2 ); inspector.assertNumberOfJoins( 0, 3 ); } ); } @Test public void testImplicitTreatedJoin(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { //noinspection removal final Product result = session.createQuery( "from Product p " + "join treat(p.owner as ProductOwner1).description", Product.class ).getSingleResult(); assertThat( result.getOwner() ).isInstanceOf( ProductOwner1.class ); assertThat( ( (ProductOwner1) result.getOwner() ).getDescription().getText() ).isEqualTo( "description" ); inspector.assertNumberOfJoins( 0, 3 ); } ); } @Test public void testTreatedRoot(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { //noinspection removal final ProductOwner result = session.createQuery( "from ProductOwner owner " + "join treat(owner as ProductOwner1).description", ProductOwner.class ).getSingleResult(); assertThat( result ).isInstanceOf( ProductOwner1.class ); assertThat( ( (ProductOwner1) result ).getDescription().getText() ).isEqualTo( "description" ); inspector.assertNumberOfJoins( 0, 3 ); } ); } @Test public void testTreatedEntityJoin(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { //noinspection removal final Product result = session.createQuery( "from Product p " + "join ProductOwner owner on p.ownerId = owner.id " + "join treat(owner as ProductOwner1).description", Product.class ).getSingleResult(); assertThat( result.getOwner() ).isInstanceOf( ProductOwner1.class ); assertThat( ( (ProductOwner1) result.getOwner() ).getDescription().getText() ).isEqualTo( "description" ); inspector.assertNumberOfJoins( 0, 3 ); } ); } @Test public void testBasicProperty(SessionFactoryScope scope) { final SQLStatementInspector inspector = scope.getCollectingStatementInspector(); inspector.clear(); scope.inTransaction( session -> { //noinspection removal final Product result = session.createQuery( "from Product p " + "join treat(p.owner AS ProductOwner2) as own2 " + "where own2.basicProp = 'basic_prop'", Product.class ).getSingleResult(); assertThat( result.getOwner() ).isInstanceOf( ProductOwner2.class ); assertThat( ( (ProductOwner2) result.getOwner() ).getBasicProp() ).isEqualTo( "basic_prop" ); inspector.assertNumberOfJoins( 0, 2 ); } ); } @SuppressWarnings("unused") @Entity( name = "Product" ) public static
JoinedInheritanceTreatQueryTest
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RVectorSetAsync.java
{ "start": 956, "end": 1026 }
interface ____ Vector Set * * @author Nikita Koksharov * */ public
for
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/netty/NettyRemotingServer.java
{ "start": 28999, "end": 33552 }
class ____ extends NettyRemotingAbstract implements RemotingServer { private volatile int listenPort; private volatile Channel serverChannel; SubRemotingServer(final int port, final int permitsOnway, final int permitsAsync) { super(permitsOnway, permitsAsync); listenPort = port; } @Override public void registerProcessor(final int requestCode, final NettyRequestProcessor processor, final ExecutorService executor) { ExecutorService executorThis = executor; if (null == executor) { executorThis = NettyRemotingServer.this.publicExecutor; } Pair<NettyRequestProcessor, ExecutorService> pair = new Pair<>(processor, executorThis); this.processorTable.put(requestCode, pair); } @Override public void registerDefaultProcessor(final NettyRequestProcessor processor, final ExecutorService executor) { this.defaultRequestProcessorPair = new Pair<>(processor, executor); } @Override public int localListenPort() { return listenPort; } @Override public Pair<NettyRequestProcessor, ExecutorService> getProcessorPair(final int requestCode) { return this.processorTable.get(requestCode); } @Override public Pair<NettyRequestProcessor, ExecutorService> getDefaultProcessorPair() { return this.defaultRequestProcessorPair; } @Override public RemotingServer newRemotingServer(final int port) { throw new UnsupportedOperationException("The SubRemotingServer of NettyRemotingServer " + "doesn't support new nested RemotingServer"); } @Override public void removeRemotingServer(final int port) { throw new UnsupportedOperationException("The SubRemotingServer of NettyRemotingServer " + "doesn't support remove nested RemotingServer"); } @Override public RemotingCommand invokeSync(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException { return this.invokeSyncImpl(channel, request, timeoutMillis); } @Override public void invokeAsync(final Channel channel, final RemotingCommand request, final long timeoutMillis, final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException { this.invokeAsyncImpl(channel, request, timeoutMillis, invokeCallback); } @Override public void invokeOneway(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException { this.invokeOnewayImpl(channel, request, timeoutMillis); } @Override public void start() { try { if (listenPort < 0) { listenPort = 0; } this.serverChannel = NettyRemotingServer.this.serverBootstrap.bind(listenPort).sync().channel(); if (0 == listenPort) { InetSocketAddress addr = (InetSocketAddress) this.serverChannel.localAddress(); this.listenPort = addr.getPort(); } } catch (InterruptedException e) { throw new RuntimeException("this.subRemotingServer.serverBootstrap.bind().sync() InterruptedException", e); } } @Override public void shutdown() { isShuttingDown.set(true); if (this.serverChannel != null) { try { this.serverChannel.close().await(5, TimeUnit.SECONDS); } catch (InterruptedException ignored) { } } } @Override public ChannelEventListener getChannelEventListener() { return NettyRemotingServer.this.getChannelEventListener(); } @Override public ExecutorService getCallbackExecutor() { return NettyRemotingServer.this.getCallbackExecutor(); } } public
SubRemotingServer
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/timer/TimerMessageStore.java
{ "start": 59400, "end": 60712 }
class ____ extends ServiceThread { @Override public String getServiceName() { return getServiceThreadName() + this.getClass().getSimpleName(); } @Override public void run() { TimerMessageStore.LOGGER.info(this.getServiceName() + " service start"); while (!this.isStopped()) { try { if (!TimerMessageStore.this.enqueue(0)) { waitForRunning(100L * precisionMs / 1000); } } catch (Throwable e) { TimerMessageStore.LOGGER.error("Error occurred in " + getServiceName(), e); } } TimerMessageStore.LOGGER.info(this.getServiceName() + " service end"); } } public String getServiceThreadName() { String brokerIdentifier = ""; if (TimerMessageStore.this.messageStore instanceof DefaultMessageStore) { DefaultMessageStore messageStore = (DefaultMessageStore) TimerMessageStore.this.messageStore; if (messageStore.getBrokerConfig().isInBrokerContainer()) { brokerIdentifier = messageStore.getBrokerConfig().getIdentifier(); } } return brokerIdentifier; } public
TimerEnqueueGetService
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/ClassesBaseTest.java
{ "start": 957, "end": 1120 }
class ____ { protected Classes classes; protected Class<?> actual; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) protected @
ClassesBaseTest
java
spring-projects__spring-security
oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/authorization/OAuth2AuthorizationManagersTests.java
{ "start": 1195, "end": 2871 }
class ____ { @Test void hasScopeWhenInvalidScopeThenThrowIllegalArgument() { String scope = "SCOPE_invalid"; assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> OAuth2AuthorizationManagers.hasScope(scope)) .withMessageContaining("SCOPE_invalid should not start with SCOPE_"); } @Test void hasAnyScopeWhenInvalidScopeThenThrowIllegalArgument() { String[] scopes = { "read", "write", "SCOPE_invalid" }; assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> OAuth2AuthorizationManagers.hasAnyScope(scopes)) .withMessageContaining("SCOPE_invalid should not start with SCOPE_"); } @Test void hasScopeWhenValidScopeThenAuthorizationManager() { String scope = "read"; AuthorizationManager<Object> authorizationManager = OAuth2AuthorizationManagers.hasScope(scope); authorizationManager.verify(() -> hasScope(scope), new Object()); assertThatExceptionOfType(AccessDeniedException.class) .isThrownBy(() -> authorizationManager.verify(() -> hasScope("wrong"), new Object())); } @Test void hasAnyScopeWhenValidScopesThenAuthorizationManager() { String[] scopes = { "read", "write" }; AuthorizationManager<Object> authorizationManager = OAuth2AuthorizationManagers.hasAnyScope(scopes); for (String scope : scopes) { authorizationManager.verify(() -> hasScope(scope), new Object()); } assertThatExceptionOfType(AccessDeniedException.class) .isThrownBy(() -> authorizationManager.verify(() -> hasScope("wrong"), new Object())); } Authentication hasScope(String scope) { return new TestingAuthenticationToken("user", "pass", "SCOPE_" + scope); } }
OAuth2AuthorizationManagersTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteSetEndpointBuilderFactory.java
{ "start": 12742, "end": 13074 }
class ____ extends AbstractEndpointBuilder implements IgniteSetEndpointBuilder, AdvancedIgniteSetEndpointBuilder { public IgniteSetEndpointBuilderImpl(String path) { super(componentName, path); } } return new IgniteSetEndpointBuilderImpl(path); } }
IgniteSetEndpointBuilderImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClashTest.java
{ "start": 2523, "end": 2966 }
class ____ extends Super { // BUG: Diagnostic contains: Super.foo(Function<String, String>) void foo(Consumer<String> c) {} } """) .doTest(); } @Test public void positiveArgs() { testHelper .addSourceLines( "Test.java", """ import java.util.function.Function; import java.util.function.Consumer; public
Test
java
resilience4j__resilience4j
resilience4j-core/src/main/java/io/github/resilience4j/core/Clock.java
{ "start": 762, "end": 1525 }
interface ____ { /** * Current time expressed as milliseconds since the Unix epoch. Should not be used for measuring time, * just for timestamps. * * @return wall time in milliseconds */ long wallTime(); /** * Current monotonic time in nanoseconds. Should be used for measuring time. * The value is not related to the wall time and is not subject to system clock changes. * * @return monotonic time in nanoseconds */ long monotonicTime(); Clock SYSTEM = new Clock() { @Override public long wallTime() { return System.currentTimeMillis(); } @Override public long monotonicTime() { return System.nanoTime(); } }; }
Clock
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/SimpleDecoratorOverloadingTest.java
{ "start": 1435, "end": 1800 }
class ____ implements Converter { @Inject @Delegate Converter delegate; @Override public String convert(String value) { return delegate.convert(value.trim()); } @Override public int convert(int value) { return -1 * delegate.convert(value); } } }
ConverterDecorator
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/transformations/GetTransitivePredecessorsTest.java
{ "start": 6195, "end": 6347 }
class ____ extends GenericTypeInfo<Integer> { public MockIntegerTypeInfo() { super(Integer.class); } } }
MockIntegerTypeInfo
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4203TransitiveDependencyExclusionTest.java
{ "start": 1183, "end": 2577 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that exclusions defined on a dependency apply to its transitive dependencies as well. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4203"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng4203"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("-s"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); List<String> artifacts = verifier.loadLines("target/artifacts.txt"); Collections.sort(artifacts); List<String> expected = new ArrayList<>(); expected.add("org.apache.maven.its.mng4203:b:jar:0.1"); expected.add("org.apache.maven.its.mng4203:c:jar:0.1"); assertEquals(expected, artifacts); verifier.verifyArtifactNotPresent("org.apache.maven.its.mng4203", "a", "0.1", "pom"); verifier.verifyArtifactNotPresent("org.apache.maven.its.mng4203", "a", "0.1", "jar"); } }
MavenITmng4203TransitiveDependencyExclusionTest
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopLongLongAggregator.java
{ "start": 4371, "end": 5433 }
class ____ implements AggregatorState { private final GroupingState internalState; private SingleState(BigArrays bigArrays, int limit, boolean ascending) { this.internalState = new GroupingState(bigArrays, limit, ascending); } public void add(long value, long outputValue) { internalState.add(0, value, outputValue); } @Override public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) { try (var intValues = driverContext.blockFactory().newConstantIntVector(0, 1)) { internalState.toIntermediate(blocks, offset, intValues, driverContext); } } Block toBlock(BlockFactory blockFactory) { try (var intValues = blockFactory.newConstantIntVector(0, 1)) { return internalState.toBlock(blockFactory, intValues); } } @Override public void close() { Releasables.closeExpectNoException(internalState); } } }
SingleState
java
apache__flink
flink-test-utils-parent/flink-connector-test-utils/src/main/java/org/apache/flink/connector/testframe/container/FlinkImageBuilder.java
{ "start": 1879, "end": 12270 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(FlinkImageBuilder.class); private static final String FLINK_BASE_IMAGE_BUILD_NAME = "flink-base"; private static final String DEFAULT_IMAGE_NAME_BUILD_PREFIX = "flink-configured"; private static final Duration DEFAULT_TIMEOUT = Duration.ofMinutes(5); private static final String LOG4J_PROPERTIES_FILENAME = "log4j-console.properties"; private final Map<Path, Path> filesToCopy = new HashMap<>(); private final Properties logProperties = new Properties(); private Path tempDirectory; private String imageNamePrefix = DEFAULT_IMAGE_NAME_BUILD_PREFIX; private String imageNameSuffix; private Path flinkDist; private String javaVersion; private Configuration conf; private Duration timeout = DEFAULT_TIMEOUT; private String startupCommand; private String baseImage; private String flinkHome = FlinkContainersSettings.getDefaultFlinkHome(); /** * Sets temporary path for holding temp files when building the image. * * <p>Note that this parameter is required, because the builder doesn't have lifecycle * management, and it is the caller's responsibility to create and remove the temp directory. */ public FlinkImageBuilder setTempDirectory(Path tempDirectory) { this.tempDirectory = tempDirectory; return this; } /** * Sets flink home. * * @param flinkHome The flink home. * @return The flink home. */ public FlinkImageBuilder setFlinkHome(String flinkHome) { this.flinkHome = flinkHome; return this; } /** * Sets the prefix name of building image. * * <p>If the name is not specified, {@link #DEFAULT_IMAGE_NAME_BUILD_PREFIX} will be used. */ public FlinkImageBuilder setImageNamePrefix(String imageNamePrefix) { this.imageNamePrefix = imageNamePrefix; return this; } /** * Sets the path of flink-dist directory. * * <p>If path is not specified, the dist directory under current project will be used. */ public FlinkImageBuilder setFlinkDistPath(Path flinkDist) { this.flinkDist = flinkDist; return this; } /** * Sets JDK version in the image. * * <p>This version string will be used as the tag of openjdk image. If version is not specified, * the JDK version of the current JVM will be used. * * @see <a href="https://hub.docker.com/_/openjdk">OpenJDK on Docker Hub</a> for all available * tags. */ public FlinkImageBuilder setJavaVersion(String javaVersion) { this.javaVersion = javaVersion; return this; } /** * Sets Flink configuration. This configuration will be used for generating config.yaml for * configuring JobManager and TaskManager. */ public FlinkImageBuilder setConfiguration(Configuration conf) { this.conf = conf; return this; } /** * Sets log4j properties. * * <p>Containers will use "log4j-console.properties" under flink-dist as the base configuration * of loggers. Properties specified by this method will be appended to the config file, or * overwrite the property if already exists in the base config file. */ public FlinkImageBuilder setLogProperties(Properties logProperties) { this.logProperties.putAll(logProperties); return this; } /** Copies file into the image. */ public FlinkImageBuilder copyFile(Path localPath, Path containerPath) { filesToCopy.put(localPath, containerPath); return this; } /** Sets timeout for building the image. */ public FlinkImageBuilder setTimeout(Duration timeout) { this.timeout = timeout; return this; } /** Use this image for building a JobManager. */ public FlinkImageBuilder asJobManager() { checkStartupCommandNotSet(); this.startupCommand = "bin/jobmanager.sh start-foreground && tail -f /dev/null"; this.imageNameSuffix = "jobmanager"; return this; } /** Use this image for building a TaskManager. */ public FlinkImageBuilder asTaskManager() { checkStartupCommandNotSet(); this.startupCommand = "bin/taskmanager.sh start-foreground && tail -f /dev/null"; this.imageNameSuffix = "taskmanager"; return this; } /** Use a custom command for starting up the container. */ public FlinkImageBuilder useCustomStartupCommand(String command) { checkStartupCommandNotSet(); this.startupCommand = command; this.imageNameSuffix = "custom"; return this; } /** * Sets base image. * * @param baseImage The base image. * @return A reference to this Builder. */ public FlinkImageBuilder setBaseImage(String baseImage) { this.baseImage = baseImage; return this; } /** Build the image. */ public ImageFromDockerfile build() throws ImageBuildException { sanityCheck(); final String finalImageName = imageNamePrefix + "-" + imageNameSuffix; try { if (baseImage == null) { baseImage = FLINK_BASE_IMAGE_BUILD_NAME; if (flinkDist == null) { flinkDist = FileUtils.findFlinkDist(); } // Build base image first buildBaseImage(flinkDist); } final Path flinkConfFile = createTemporaryFlinkConfFile(conf, tempDirectory); final Path log4jPropertiesFile = createTemporaryLog4jPropertiesFile(tempDirectory); // Copy config.yaml into image filesToCopy.put( flinkConfFile, Paths.get(flinkHome, "conf", GlobalConfiguration.FLINK_CONF_FILENAME)); filesToCopy.put( log4jPropertiesFile, Paths.get(flinkHome, "conf", LOG4J_PROPERTIES_FILENAME)); final ImageFromDockerfile image = new ImageFromDockerfile(finalImageName) .withDockerfileFromBuilder( builder -> { // Build from base image builder.from(baseImage); // Copy files into image filesToCopy.forEach( (from, to) -> builder.copy(to.toString(), to.toString())); builder.cmd(startupCommand); }); filesToCopy.forEach((from, to) -> image.withFileFromPath(to.toString(), from)); return image; } catch (Exception e) { throw new ImageBuildException(finalImageName, e); } } // ----------------------- Helper functions ----------------------- private void buildBaseImage(Path flinkDist) throws TimeoutException { if (baseImageExists()) { return; } LOG.info("Building Flink base image with flink-dist at {}", flinkDist); new ImageFromDockerfile(FLINK_BASE_IMAGE_BUILD_NAME) .withDockerfileFromBuilder( builder -> builder.from( "eclipse-temurin:" + getJavaVersionSuffix() + "-jre-jammy") .copy(flinkHome, flinkHome) .build()) .withFileFromPath(flinkHome, flinkDist) .get(timeout.toMillis(), TimeUnit.MILLISECONDS); } private boolean baseImageExists() { try { DockerClientFactory.instance() .client() .inspectImageCmd(FLINK_BASE_IMAGE_BUILD_NAME) .exec(); return true; } catch (NotFoundException e) { return false; } } private String getJavaVersionSuffix() { if (this.javaVersion != null) { return this.javaVersion; } else { String javaSpecVersion = System.getProperty("java.vm.specification.version"); LOG.info("Using JDK version {} of the current VM", javaSpecVersion); switch (javaSpecVersion) { case "1.8": return "8"; case "11": return "11"; case "17": return "17"; case "21": return "21"; default: throw new IllegalStateException("Unexpected Java version: " + javaSpecVersion); } } } private Path createTemporaryFlinkConfFile(Configuration finalConfiguration, Path tempDirectory) throws IOException { Path flinkConfFile = tempDirectory.resolve(GlobalConfiguration.FLINK_CONF_FILENAME); Files.write( flinkConfFile, ConfigurationUtils.convertConfigToWritableLines(finalConfiguration, false)); return flinkConfFile; } private Path createTemporaryLog4jPropertiesFile(Path tempDirectory) throws IOException { // Create a temporary log4j.properties file and write merged properties into it Path log4jPropFile = tempDirectory.resolve(LOG4J_PROPERTIES_FILENAME); try (OutputStream output = new FileOutputStream(log4jPropFile.toFile())) { logProperties.store(output, null); } return log4jPropFile; } private void checkStartupCommandNotSet() { if (this.startupCommand != null) { throw new IllegalStateException( "Cannot set startup command of container multiple times"); } } private void sanityCheck() { checkNotNull(this.tempDirectory, "Temporary path is not specified"); checkState(Files.isDirectory(this.tempDirectory)); checkNotNull( this.startupCommand, "JobManager or TaskManager is not specified for the image"); } }
FlinkImageBuilder
java
elastic__elasticsearch
x-pack/plugin/ml-package-loader/src/main/java/org/elasticsearch/xpack/ml/packageloader/action/TransportLoadTrainedModelPackage.java
{ "start": 2515, "end": 13862 }
class ____ extends TransportMasterNodeAction<Request, AcknowledgedResponse> { private static final Logger logger = LogManager.getLogger(TransportLoadTrainedModelPackage.class); private final Client client; private final CircuitBreakerService circuitBreakerService; final Map<String, List<DownloadTaskRemovedListener>> taskRemovedListenersByModelId; @Inject public TransportLoadTrainedModelPackage( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, Client client, CircuitBreakerService circuitBreakerService ) { super( LoadTrainedModelPackageAction.NAME, transportService, clusterService, threadPool, actionFilters, LoadTrainedModelPackageAction.Request::new, NodeAcknowledgedResponse::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.client = new OriginSettingClient(client, ML_ORIGIN); this.circuitBreakerService = circuitBreakerService; taskRemovedListenersByModelId = new HashMap<>(); } @Override protected ClusterBlockException checkBlock(Request request, ClusterState state) { return null; } @Override protected void masterOperation(Task task, Request request, ClusterState state, ActionListener<AcknowledgedResponse> listener) throws Exception { if (handleDownloadInProgress(request.getModelId(), request.isWaitForCompletion(), listener)) { logger.debug("Existing download of model [{}] in progress", request.getModelId()); // download in progress, nothing to do return; } ModelDownloadTask downloadTask = createDownloadTask(request); try { ParentTaskAssigningClient parentTaskAssigningClient = getParentTaskAssigningClient(downloadTask); ModelImporter modelImporter = new ModelImporter( parentTaskAssigningClient, request.getModelId(), request.getModelPackageConfig(), downloadTask, threadPool, circuitBreakerService ); var downloadCompleteListener = request.isWaitForCompletion() ? listener : ActionListener.<AcknowledgedResponse>noop(); importModel(client, () -> unregisterTask(downloadTask), request, modelImporter, downloadTask, downloadCompleteListener); } catch (Exception e) { taskManager.unregister(downloadTask); listener.onFailure(e); return; } if (request.isWaitForCompletion() == false) { listener.onResponse(AcknowledgedResponse.TRUE); } } private ParentTaskAssigningClient getParentTaskAssigningClient(Task originTask) { var parentTaskId = new TaskId(clusterService.localNode().getId(), originTask.getId()); return new ParentTaskAssigningClient(client, parentTaskId); } /** * Look for a current download task of the model and optionally wait * for that task to complete if there is one. * synchronized with {@code unregisterTask} to prevent the task being * removed before the remove listener is added. * @param modelId Model being downloaded * @param isWaitForCompletion Wait until the download completes before * calling the listener * @param listener Model download listener * @return True if a download task is in progress */ synchronized boolean handleDownloadInProgress( String modelId, boolean isWaitForCompletion, ActionListener<AcknowledgedResponse> listener ) { var description = ModelDownloadTask.taskDescription(modelId); var tasks = taskManager.getCancellableTasks().values(); ModelDownloadTask inProgress = null; for (var task : tasks) { if (task instanceof ModelDownloadTask downloadTask && (description.equals(downloadTask.getDescription()))) { inProgress = downloadTask; break; } } if (inProgress != null) { if (isWaitForCompletion == false) { // Not waiting for the download to complete, it is enough that the download is in progress // Respond now not when the download completes listener.onResponse(AcknowledgedResponse.TRUE); return true; } // Otherwise register a task removed listener which is called // once the tasks is complete and unregistered var tracker = new DownloadTaskRemovedListener(inProgress, listener); taskRemovedListenersByModelId.computeIfAbsent(modelId, s -> new ArrayList<>()).add(tracker); taskManager.registerRemovedTaskListener(tracker); return true; } return false; } /** * Unregister the completed task triggering any remove task listeners. * This method is synchronized to prevent the task being removed while * {@code waitForExistingDownload} is in progress. * @param task The completed task */ synchronized void unregisterTask(ModelDownloadTask task) { taskManager.unregister(task); // unregister will call the on remove function var trackers = taskRemovedListenersByModelId.remove(task.getModelId()); if (trackers != null) { for (var tracker : trackers) { taskManager.unregisterRemovedTaskListener(tracker); } } } /** * This is package scope so that we can test the logic directly. * This should only be called from the masterOperation method and the tests. * This method is static for testing. * * @param auditClient a client which should only be used to send audit notifications. This client cannot be associated with the passed * in task, that way when the task is cancelled the notification requests can * still be performed. If it is associated with the task (i.e. via ParentTaskAssigningClient), * then the requests will throw a TaskCancelledException. * @param unregisterTaskFn Runnable to unregister the task. Because this is a static function * a lambda is used rather than the instance method. * @param request The download request * @param modelImporter The importer * @param task Download task * @param listener Listener */ static void importModel( Client auditClient, Runnable unregisterTaskFn, Request request, ModelImporter modelImporter, ModelDownloadTask task, ActionListener<AcknowledgedResponse> listener ) { final String modelId = request.getModelId(); final long relativeStartNanos = System.nanoTime(); logAndWriteNotificationAtLevel(auditClient, modelId, "starting model import", Level.INFO); var finishListener = ActionListener.<AcknowledgedResponse>wrap(success -> { final long totalRuntimeNanos = System.nanoTime() - relativeStartNanos; logAndWriteNotificationAtLevel( auditClient, modelId, format("finished model import after [%d] seconds", TimeUnit.NANOSECONDS.toSeconds(totalRuntimeNanos)), Level.INFO ); listener.onResponse(AcknowledgedResponse.TRUE); }, exception -> { task.setTaskException(exception); listener.onFailure(processException(auditClient, modelId, exception)); }); modelImporter.doImport(ActionListener.runAfter(finishListener, unregisterTaskFn)); } static Exception processException(Client auditClient, String modelId, Exception e) { if (e instanceof TaskCancelledException te) { return recordError(auditClient, modelId, te, Level.WARNING); } else if (e instanceof ElasticsearchException es) { return recordError(auditClient, modelId, es, Level.ERROR); } else if (e instanceof MalformedURLException) { return recordError(auditClient, modelId, "an invalid URL", e, Level.ERROR, RestStatus.BAD_REQUEST); } else if (e instanceof URISyntaxException) { return recordError(auditClient, modelId, "an invalid URL syntax", e, Level.ERROR, RestStatus.BAD_REQUEST); } else if (e instanceof IOException) { return recordError(auditClient, modelId, "an IOException", e, Level.ERROR, RestStatus.SERVICE_UNAVAILABLE); } else { return recordError(auditClient, modelId, "an Exception", e, Level.ERROR, RestStatus.INTERNAL_SERVER_ERROR); } } private ModelDownloadTask createDownloadTask(Request request) { // Loading the model is done by a separate task, so needs a new trace context try (var ignored = threadPool.getThreadContext().newTraceContext()) { return (ModelDownloadTask) taskManager.register(MODEL_IMPORT_TASK_TYPE, MODEL_IMPORT_TASK_ACTION, new TaskAwareRequest() { @Override public void setParentTask(TaskId taskId) { request.setParentTask(taskId); } @Override public void setRequestId(long requestId) { request.setRequestId(requestId); } @Override public TaskId getParentTask() { return request.getParentTask(); } @Override public ModelDownloadTask createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) { return new ModelDownloadTask(id, type, action, request.getModelId(), parentTaskId, headers); } }, false); } } private static Exception recordError(Client client, String modelId, ElasticsearchException e, Level level) { String message = format("Model importing failed due to [%s]", e.getDetailedMessage()); logAndWriteNotificationAtLevel(client, modelId, message, level); return e; } private static Exception recordError(Client client, String modelId, String failureType, Exception e, Level level, RestStatus status) { String message = format("Model importing failed due to %s [%s]", failureType, e); logAndWriteNotificationAtLevel(client, modelId, message, level); return new ElasticsearchStatusException(message, status, e); } private static void logAndWriteNotificationAtLevel(Client client, String modelId, String message, Level level) { writeNotification(client, modelId, message, level); logger.log(level.log4jLevel(), format("[%s] %s", modelId, message)); } private static void writeNotification(Client client, String modelId, String message, Level level) { client.execute( AuditMlNotificationAction.INSTANCE, new AuditMlNotificationAction.Request(AuditMlNotificationAction.AuditType.INFERENCE, modelId, message, level), ActionListener.noop() ); } }
TransportLoadTrainedModelPackage
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ExifConverter.java
{ "start": 332, "end": 666 }
class ____ implements AttributeConverter<String, Exif> { @Override public Exif convertToDatabaseColumn(String attribute) { return new Exif( Collections.singletonMap( "fakeAttr", attribute ) ); } @Override public String convertToEntityAttribute(Exif dbData) { return dbData.getAttributes().get( "fakeAttr" ); } }
ExifConverter
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java
{ "start": 41171, "end": 42683 }
interface ____", method).isNotInterface(); } private static void assertPubliclyAccessible(Method method) { assertPublic(method); assertPublic(method.getDeclaringClass()); } private static void assertNotPubliclyAccessible(Method method) { assertThat(!isPublic(method) || !isPublic(method.getDeclaringClass())) .as("%s must not be publicly accessible", method) .isTrue(); } private static void assertPublic(Member member) { assertThat(isPublic(member)).as("%s must be public", member).isTrue(); } private static void assertPublic(Class<?> clazz) { assertThat(isPublic(clazz)).as("%s must be public", clazz).isTrue(); } private static void assertNotPublic(Member member) { assertThat(!isPublic(member)).as("%s must be not be public", member).isTrue(); } private static void assertNotPublic(Class<?> clazz) { assertThat(!isPublic(clazz)).as("%s must be not be public", clazz).isTrue(); } private static boolean isPublic(Class<?> clazz) { return Modifier.isPublic(clazz.getModifiers()); } private static boolean isPublic(Member member) { return Modifier.isPublic(member.getModifiers()); } private static void assertStatic(Member member) { assertThat(Modifier.isStatic(member.getModifiers())).as("%s must be static", member).isTrue(); } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @ValueSource(classes = { Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class }) @
method
java
apache__flink
flink-python/src/main/java/org/apache/flink/streaming/api/transformations/python/DelegateOperatorTransformation.java
{ "start": 3159, "end": 5203 }
class ____<OUT> extends AbstractPythonFunctionOperator<OUT> implements DataStreamPythonFunctionOperator<OUT> { private final Map<String, OutputTag<?>> sideOutputTags = new HashMap<>(); private @Nullable Integer numPartitions = null; public DelegateOperator() { super(new Configuration()); } @Override public void addSideOutputTags(Collection<OutputTag<?>> outputTags) { for (OutputTag<?> outputTag : outputTags) { sideOutputTags.put(outputTag.getId(), outputTag); } } @Override public Collection<OutputTag<?>> getSideOutputTags() { return sideOutputTags.values(); } @Override public void setNumPartitions(int numPartitions) { this.numPartitions = numPartitions; } @Nullable public Integer getNumPartitions() { return numPartitions; } @Override public TypeInformation<OUT> getProducedType() { throw new RuntimeException("This should not be invoked on a DelegateOperator!"); } @Override public DataStreamPythonFunctionInfo getPythonFunctionInfo() { throw new RuntimeException("This should not be invoked on a DelegateOperator!"); } @Override public <T> DataStreamPythonFunctionOperator<T> copy( DataStreamPythonFunctionInfo pythonFunctionInfo, TypeInformation<T> outputTypeInfo) { throw new RuntimeException("This should not be invoked on a DelegateOperator!"); } @Override protected void invokeFinishBundle() throws Exception { throw new RuntimeException("This should not be invoked on a DelegateOperator!"); } @Override protected PythonEnvironmentManager createPythonEnvironmentManager() { throw new RuntimeException("This should not be invoked on a DelegateOperator!"); } } }
DelegateOperator
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/leaderelection/TestingRetrievalBase.java
{ "start": 1401, "end": 3538 }
class ____ { private final BlockingQueue<LeaderInformation> leaderEventQueue = new LinkedBlockingQueue<>(); private final BlockingQueue<Throwable> errorQueue = new LinkedBlockingQueue<>(); private LeaderInformation leader = LeaderInformation.empty(); private String oldAddress; private Throwable error; public String waitForNewLeader() throws Exception { throwExceptionIfNotNull(); CommonTestUtils.waitUntilCondition( () -> { leader = leaderEventQueue.take(); return !leader.isEmpty() && !leader.getLeaderAddress().equals(oldAddress); }); oldAddress = leader.getLeaderAddress(); return leader.getLeaderAddress(); } public void waitForEmptyLeaderInformation() throws Exception { throwExceptionIfNotNull(); CommonTestUtils.waitUntilCondition( () -> { leader = leaderEventQueue.take(); return leader.isEmpty(); }); oldAddress = null; } public void waitForError() throws Exception { error = errorQueue.take(); } public void handleError(Throwable ex) { errorQueue.offer(ex); } public LeaderInformation getLeader() { return leader; } public String getAddress() { return leader.getLeaderAddress(); } public UUID getLeaderSessionID() { return leader.getLeaderSessionID(); } public void offerToLeaderQueue(LeaderInformation leaderInformation) { leaderEventQueue.offer(leaderInformation); } public int getLeaderEventQueueSize() { return leaderEventQueue.size(); } /** * Please use {@link #waitForError} before get the error. * * @return the error has been handled. */ @Nullable public Throwable getError() { return error == null ? errorQueue.poll() : error; } private void throwExceptionIfNotNull() throws Exception { if (error != null) { ExceptionUtils.rethrowException(error); } } }
TestingRetrievalBase
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/OperationWeight.java
{ "start": 932, "end": 1366 }
class ____ { private double weight; private Operation operation; OperationWeight(Operation op, double weight) { this.operation = op; this.weight = weight; } /** * Fetches the given operation weight * * @return Double */ double getWeight() { return weight; } /** * Gets the operation * * @return Operation */ Operation getOperation() { return operation; } }
OperationWeight
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/ClassWriter.java
{ "start": 11550, "end": 17468 }
class ____ also to * copy other fragments of original bytecode where applicable. * @param flags option flags that can be used to modify the default behavior of this class. Must * be zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. <i>These option flags * do not affect methods that are copied as is in the new class. This means that neither the * maximum stack size nor the stack frames will be computed for these methods</i>. */ public ClassWriter(final ClassReader classReader, final int flags) { super(/* latest api = */ Opcodes.ASM9); this.flags = flags; symbolTable = classReader == null ? new SymbolTable(this) : new SymbolTable(this, classReader); setFlags(flags); } // ----------------------------------------------------------------------------------------------- // Accessors // ----------------------------------------------------------------------------------------------- /** * Returns true if all the given flags were passed to the constructor. * * @param flags some option flags. Must be zero or more of {@link #COMPUTE_MAXS} and {@link * #COMPUTE_FRAMES}. * @return true if all the given flags, or more, were passed to the constructor. */ public boolean hasFlags(final int flags) { return (this.flags & flags) == flags; } // ----------------------------------------------------------------------------------------------- // Implementation of the ClassVisitor abstract class // ----------------------------------------------------------------------------------------------- @Override public final void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { this.version = version; this.accessFlags = access; this.thisClass = symbolTable.setMajorVersionAndClassName(version & 0xFFFF, name); if (signature != null) { this.signatureIndex = symbolTable.addConstantUtf8(signature); } this.superClass = superName == null ? 0 : symbolTable.addConstantClass(superName).index; if (interfaces != null && interfaces.length > 0) { interfaceCount = interfaces.length; this.interfaces = new int[interfaceCount]; for (int i = 0; i < interfaceCount; ++i) { this.interfaces[i] = symbolTable.addConstantClass(interfaces[i]).index; } } if (compute == MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL && (version & 0xFFFF) >= Opcodes.V1_7) { compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES; } } @Override public final void visitSource(final String file, final String debug) { if (file != null) { sourceFileIndex = symbolTable.addConstantUtf8(file); } if (debug != null) { debugExtension = new ByteVector().encodeUtf8(debug, 0, Integer.MAX_VALUE); } } @Override public final ModuleVisitor visitModule( final String name, final int access, final String version) { return moduleWriter = new ModuleWriter( symbolTable, symbolTable.addConstantModule(name).index, access, version == null ? 0 : symbolTable.addConstantUtf8(version)); } @Override public final void visitNestHost(final String nestHost) { nestHostClassIndex = symbolTable.addConstantClass(nestHost).index; } @Override public final void visitOuterClass( final String owner, final String name, final String descriptor) { enclosingClassIndex = symbolTable.addConstantClass(owner).index; if (name != null && descriptor != null) { enclosingMethodIndex = symbolTable.addConstantNameAndType(name, descriptor); } } @Override public final AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { if (visible) { return lastRuntimeVisibleAnnotation = AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); } else { return lastRuntimeInvisibleAnnotation = AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); } } @Override public final AnnotationVisitor visitTypeAnnotation( final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { if (visible) { return lastRuntimeVisibleTypeAnnotation = AnnotationWriter.create( symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); } else { return lastRuntimeInvisibleTypeAnnotation = AnnotationWriter.create( symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); } } @Override public final void visitAttribute(final Attribute attribute) { // Store the attributes in the <i>reverse</i> order of their visit by this method. attribute.nextAttribute = firstAttribute; firstAttribute = attribute; } @Override public final void visitNestMember(final String nestMember) { if (nestMemberClasses == null) { nestMemberClasses = new ByteVector(); } ++numberOfNestMemberClasses; nestMemberClasses.putShort(symbolTable.addConstantClass(nestMember).index); } @Override public final void visitPermittedSubclass(final String permittedSubclass) { if (permittedSubclasses == null) { permittedSubclasses = new ByteVector(); } ++numberOfPermittedSubclasses; permittedSubclasses.putShort(symbolTable.addConstantClass(permittedSubclass).index); } @Override public final void visitInnerClass( final String name, final String outerName, final String innerName, final int access) { if (innerClasses == null) { innerClasses = new ByteVector(); } // Section 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the constant_pool table // which represents a
and
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java
{ "start": 15550, "end": 16370 }
class ____ implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (supports(authentication.getClass())) { return authentication; } else { throw new AuthenticationServiceException("Don't support this class"); } } @Override public boolean supports(Class<?> authentication) { return TestingAuthenticationToken.class.isAssignableFrom(authentication) || UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } } /** * Represents a custom {@link Authentication} that does not override * {@link #toBuilder()}. We should remain passive to previous versions of Spring * Security and not change the {@link Authentication} type. */ private static final
MockProvider
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java
{ "start": 2829, "end": 3168 }
class ____ { int beanMethodCallCount = 0; @PostConstruct public void init() { beanMethod().setAge(beanMethod().getAge() + 1); // age == 2 } @Bean public TestBean beanMethod() { beanMethodCallCount++; TestBean testBean = new TestBean(); testBean.setAge(1); return testBean; } } @Configuration static
Config1
java
netty__netty
testsuite/src/main/java/io/netty/testsuite/transport/socket/AbstractClientSocketTest.java
{ "start": 1053, "end": 1576 }
class ____ extends AbstractTestsuiteTest<Bootstrap> { @Override protected List<TestsuitePermutation.BootstrapFactory<Bootstrap>> newFactories() { return SocketTestPermutation.INSTANCE.clientSocket(); } @Override protected void configure(Bootstrap bootstrap, ByteBufAllocator allocator) { bootstrap.option(ChannelOption.ALLOCATOR, allocator); } protected SocketAddress newSocketAddress() { return new InetSocketAddress(NetUtil.LOCALHOST, 0); } }
AbstractClientSocketTest
java
spring-projects__spring-boot
module/spring-boot-webclient/src/main/java/org/springframework/boot/webclient/autoconfigure/WebClientAutoConfiguration.java
{ "start": 2702, "end": 4003 }
class ____ { @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @ConditionalOnMissingBean WebClient.Builder webClientBuilder(ObjectProvider<WebClientCustomizer> customizerProvider) { WebClient.Builder builder = WebClient.builder(); customizerProvider.orderedStream().forEach((customizer) -> customizer.customize(builder)); return builder; } @Bean @Lazy @Order(0) @ConditionalOnBean(ClientHttpConnector.class) WebClientCustomizer webClientHttpConnectorCustomizer(ClientHttpConnector clientHttpConnector) { return (builder) -> builder.clientConnector(clientHttpConnector); } @Bean @ConditionalOnMissingBean(WebClientSsl.class) @ConditionalOnBean(SslBundles.class) AutoConfiguredWebClientSsl webClientSsl(ResourceLoader resourceLoader, ObjectProvider<ClientHttpConnectorBuilder<?>> clientHttpConnectorBuilder, ObjectProvider<HttpClientSettings> httpClientSettings, SslBundles sslBundles) { return new AutoConfiguredWebClientSsl( clientHttpConnectorBuilder .getIfAvailable(() -> ClientHttpConnectorBuilder.detect(resourceLoader.getClassLoader())), httpClientSettings.getIfAvailable(HttpClientSettings::defaults), sslBundles); } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(CodecCustomizer.class) protected static
WebClientAutoConfiguration
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/schema/SchemaTest.java
{ "start": 1006, "end": 4281 }
class ____ { private static final String BASE_SCHEMA_PATH = "src/test/resources/schema"; private static final String ADD = "ADD"; private static final String DELETE = "DELETE"; private static final String CHANGE = "CHANGE"; public void generate() throws Exception { SchemaDefiner.doLoad(); SchemaTools.write(SchemaTools.generate(SchemaDefiner.API_CLASS_LIST), BASE_SCHEMA_PATH, "api"); SchemaTools.write(SchemaTools.generate(SchemaDefiner.PROTOCOL_CLASS_LIST), BASE_SCHEMA_PATH, "protocol"); } @Test @Ignore public void checkSchema() throws Exception { SchemaDefiner.doLoad(); Map<String, Map<String, String>> schemaFromFile = new HashMap<>(); { schemaFromFile.putAll(SchemaTools.load(BASE_SCHEMA_PATH, SchemaTools.PATH_API)); schemaFromFile.putAll(SchemaTools.load(BASE_SCHEMA_PATH, SchemaTools.PATH_PROTOCOL)); } Map<String, Map<String, String>> schemaFromCode = new HashMap<>(); { schemaFromCode.putAll(SchemaTools.generate(SchemaDefiner.API_CLASS_LIST)); schemaFromCode.putAll(SchemaTools.generate(SchemaDefiner.PROTOCOL_CLASS_LIST)); } Map<String, String> fileChanges = new TreeMap<>(); schemaFromFile.keySet().forEach(x -> { if (!schemaFromCode.containsKey(x)) { fileChanges.put(x, DELETE); } }); schemaFromCode.keySet().forEach(x -> { if (!schemaFromFile.containsKey(x)) { fileChanges.put(x, ADD); } }); Map<String, Map<String, String>> changesByFile = new HashMap<>(); schemaFromFile.forEach((file, oldSchema) -> { Map<String, String> newSchema = schemaFromCode.get(file); Map<String, String> schemaChanges = new TreeMap<>(); oldSchema.forEach((k, v) -> { if (!newSchema.containsKey(k)) { schemaChanges.put(k, DELETE); } else if (!newSchema.get(k).equals(v)) { schemaChanges.put(k, CHANGE); } }); newSchema.forEach((k, v) -> { if (!oldSchema.containsKey(k)) { schemaChanges.put(k, ADD); } }); if (!schemaChanges.isEmpty()) { changesByFile.put(file, schemaChanges); } }); fileChanges.forEach((k,v) -> { System.out.printf("%s file %s\n", v, k); }); changesByFile.forEach((k, v) -> { System.out.printf("%s file %s:\n", CHANGE, k); v.forEach((kk, vv) -> { System.out.printf("\t%s %s\n", vv, kk); }); }); String message = "The schema test failed, which means you have changed the API or Protocol defined in org.apache.rocketmq.test.schema.SchemaDefiner.\n" + "Please submit a pr only contains the API/Protocol changes and request at least one PMC Member's review.\n" + "For original motivation of this test, please refer to https://github.com/apache/rocketmq/pull/4565 ."; Assert.assertTrue(message, fileChanges.isEmpty() && changesByFile.isEmpty()); } }
SchemaTest
java
elastic__elasticsearch
libs/tdigest/src/main/java/org/elasticsearch/tdigest/arrays/TDigestDoubleArray.java
{ "start": 1079, "end": 1150 }
interface ____ DoubleArray-like classes used within TDigest. */ public
for
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyHttpEndpointDisconnectTest.java
{ "start": 1267, "end": 2499 }
class ____ extends BaseJettyTest { private final String serverUri = "http://localhost:" + getPort() + "/myservice"; @Test public void testContextShutdownRemovesHttpConnector() { context.stop(); assertEquals(0, JettyHttpComponent.CONNECTORS.size(), () -> { StringBuilder sb = new StringBuilder("Connector should have been removed\n"); for (String key : JettyHttpComponent.CONNECTORS.keySet()) { Throwable t = JettyHttpComponent12.connectorCreation.get(key); if (t == null) { t = new Throwable("Unable to find connector creation"); } final String stackTrace = ExceptionHelper.stackTraceToString(t); sb.append(key).append(": ").append(stackTrace); } return sb.toString(); }); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("jetty:" + serverUri).to("mock:result"); } }; } }
JettyHttpEndpointDisconnectTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelPropagateCausedExceptionTest.java
{ "start": 1177, "end": 7321 }
class ____ extends ContextTestSupport { @Test public void testDLCPropagateCaused() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { // goes directly to mock:dead but we want the caused exception // propagated errorHandler(deadLetterChannel("mock:dead")); from("direct:start").to("mock:a").throwException(new IllegalArgumentException("Damn")); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:dead").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the caused exception should be propagated Exception cause = getMockEndpoint("mock:dead").getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); assertNotNull(cause); assertIsInstanceOf(IllegalArgumentException.class, cause); assertEquals("Damn", cause.getMessage()); } @Test public void testDLCPropagateCausedInRoute() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { errorHandler(deadLetterChannel("direct:dead")); // use a route as DLC to test the cause exception is still // propagated from("direct:dead").to("log:dead").to("mock:dead"); from("direct:start").to("mock:a").throwException(new IllegalArgumentException("Damn")); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:dead").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the caused exception should be propagated Exception cause = getMockEndpoint("mock:dead").getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); assertNotNull(cause); assertIsInstanceOf(IllegalArgumentException.class, cause); assertEquals("Damn", cause.getMessage()); } @Test public void testDLCPropagateCausedUseOriginalMessage() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { // goes directly to mock:dead but we want the caused exception // propagated errorHandler(deadLetterChannel("mock:dead").useOriginalMessage()); from("direct:start").to("mock:a").throwException(new IllegalArgumentException("Damn")); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:dead").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the caused exception should be propagated Exception cause = getMockEndpoint("mock:dead").getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); assertNotNull(cause); assertIsInstanceOf(IllegalArgumentException.class, cause); assertEquals("Damn", cause.getMessage()); } @Test public void testDLCPropagateCausedInRouteUseOriginalMessage() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { errorHandler(deadLetterChannel("direct:dead").useOriginalMessage()); // use a route as DLC to test the cause exception is still // propagated from("direct:dead").to("log:dead").to("mock:dead"); from("direct:start").to("mock:a").throwException(new IllegalArgumentException("Damn")); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:dead").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); // the caused exception should be propagated Exception cause = getMockEndpoint("mock:dead").getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); assertNotNull(cause); assertIsInstanceOf(IllegalArgumentException.class, cause); assertEquals("Damn", cause.getMessage()); } @Test public void testDLCPropagateCausedInSplitter() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { errorHandler(deadLetterChannel("mock:dead")); from("direct:start").to("mock:a").split(body().tokenize(",")).stopOnException().process(new Processor() { @Override public void process(Exchange exchange) { String body = exchange.getIn().getBody(String.class); if ("Kaboom".equals(body)) { throw new IllegalArgumentException("Damn"); } } }).to("mock:line"); } }); context.start(); getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:line").expectedBodiesReceived("A", "B", "C"); getMockEndpoint("mock:dead").expectedMessageCount(1); template.sendBody("direct:start", "A,B,C,Kaboom"); assertMockEndpointsSatisfied(); // the caused exception should be propagated Exception cause = getMockEndpoint("mock:dead").getReceivedExchanges().get(0).getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); assertNotNull(cause); assertIsInstanceOf(IllegalArgumentException.class, cause); assertEquals("Damn", cause.getMessage()); } }
DeadLetterChannelPropagateCausedExceptionTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/doublearray/DoubleArrayAssert_isNotEmpty_Test.java
{ "start": 905, "end": 1229 }
class ____ extends DoubleArrayAssertBaseTest { @Override protected DoubleArrayAssert invoke_api_method() { return assertions.isNotEmpty(); } @Override protected void verify_internal_effects() { verify(arrays).assertNotEmpty(getInfo(assertions), getActual(assertions)); } }
DoubleArrayAssert_isNotEmpty_Test
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
{ "start": 21025, "end": 24719 }
interface ____<T> { /** * Returns list of parts from metadata */ Map<String, T> parts(ClusterState clusterState); /** * Puts the part back into metadata */ ClusterState.Builder put(ClusterState.Builder builder, T part); /** * Remove the part from metadata */ ClusterState.Builder remove(ClusterState.Builder builder, String name); /** * Returns a random part with the specified name */ T randomCreate(String name); /** * Makes random modifications to the part */ T randomChange(T part); } /** * Takes an existing cluster state and randomly adds, removes or updates a cluster state part using randomPart generator. * If a new part is added the prefix value is used as a prefix of randomly generated part name. */ private <T> ClusterState randomClusterStateParts(ClusterState clusterState, String prefix, RandomClusterPart<T> randomPart) { ClusterState.Builder builder = ClusterState.builder(clusterState); Map<String, T> parts = randomPart.parts(clusterState); int partCount = parts.size(); if (partCount > 0) { List<String> randomParts = randomSubsetOf( randomInt(partCount - 1), randomPart.parts(clusterState).keySet().toArray(new String[0]) ); for (String part : randomParts) { if (randomBoolean()) { randomPart.remove(builder, part); } else { randomPart.put(builder, randomPart.randomChange(parts.get(part))); } } } int additionalPartCount = randomIntBetween(1, 20); for (int i = 0; i < additionalPartCount; i++) { String name = randomName(prefix); randomPart.put(builder, randomPart.randomCreate(name)); } return builder.build(); } /** * Makes random metadata changes */ private ClusterState.Builder randomMetadataChanges(ClusterState clusterState) { Metadata metadata = clusterState.metadata(); int changesCount = randomIntBetween(1, 10); for (int i = 0; i < changesCount; i++) { metadata = switch (randomInt(4)) { case 0 -> randomMetadataSettings(metadata); case 1 -> randomIndices(metadata); case 2 -> randomTemplates(metadata); case 3 -> randomMetadataClusterCustoms(metadata); case 4 -> randomMetadataProjectCustoms(metadata); default -> throw new IllegalArgumentException("Shouldn't be here"); }; } return ClusterState.builder(clusterState).metadata(Metadata.builder(metadata).version(metadata.version() + 1).build()); } /** * Makes random settings changes */ private Settings randomSettings(Settings settings) { Settings.Builder builder = Settings.builder(); if (randomBoolean()) { builder.put(settings); } int settingsCount = randomInt(10); for (int i = 0; i < settingsCount; i++) { builder.put(randomAlphaOfLength(10), randomAlphaOfLength(10)); } return builder.build(); } /** * Updates persistent cluster settings of the given metadata */ private Metadata randomMetadataSettings(Metadata metadata) { return Metadata.builder(metadata).persistentSettings(randomSettings(metadata.persistentSettings())).build(); } /** * Random metadata part generator */ private
RandomClusterPart
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java
{ "start": 13486, "end": 14594 }
class ____ {", " final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();", " final Lock readLock = lock.readLock();", " final Lock writeLock = lock.writeLock();", " @GuardedBy(\"lock\") boolean b = false;", " void m() {", " readLock.lock();", " try {", " b = true;", " } finally {", " readLock.unlock();", " }", " }", " void n() {", " writeLock.lock();", " try {", " b = true;", " } finally {", " writeLock.unlock();", " }", " }", "}") .doTest(); } @Test public void readWriteLock() { compilationHelper .addSourceLines( "threadsafety/Test.java", """ package threadsafety; import com.google.errorprone.annotations.concurrent.GuardedBy; import java.util.concurrent.locks.ReentrantReadWriteLock;
Test
java
elastic__elasticsearch
client/rest/src/test/java/org/elasticsearch/client/ResponseExceptionTests.java
{ "start": 1649, "end": 3735 }
class ____ extends RestClientTestCase { public void testResponseException() throws IOException { ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 500, "Internal Server Error"); HttpResponse httpResponse = new BasicHttpResponse(statusLine); String responseBody = "{\"error\":{\"root_cause\": {}}}"; boolean hasBody = getRandom().nextBoolean(); if (hasBody) { HttpEntity entity; if (getRandom().nextBoolean()) { entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON); } else { // test a non repeatable entity entity = new InputStreamEntity( new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON ); } httpResponse.setEntity(entity); } RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion); HttpHost httpHost = new HttpHost("localhost", 9200); Response response = new Response(requestLine, httpHost, httpResponse); ResponseException responseException = new ResponseException(response); assertSame(response, responseException.getResponse()); if (hasBody) { assertEquals(responseBody, EntityUtils.toString(responseException.getResponse().getEntity())); } else { assertNull(responseException.getResponse().getEntity()); } String message = String.format( Locale.ROOT, "method [%s], host [%s], URI [%s], status line [%s]", response.getRequestLine().getMethod(), response.getHost(), response.getRequestLine().getUri(), response.getStatusLine().toString() ); if (hasBody) { message += "\n" + responseBody; } assertEquals(message, responseException.getMessage()); } }
ResponseExceptionTests
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/TypeReference.java
{ "start": 1835, "end": 2074 }
class ____ the referenced type is appearing (for example, an * 'extends', 'implements' or 'throws' clause, a 'new' instruction, a 'catch' clause, a type cast, a * local variable declaration, etc). * * @author Eric Bruneton */ public
where
java
google__guice
extensions/grapher/src/com/google/inject/grapher/AbstractInjectorGrapher.java
{ "start": 3848, "end": 7608 }
interface ____ to the graph. */ protected abstract void newInterfaceNode(InterfaceNode node) throws IOException; /** Adds a new implementation node to the graph. */ protected abstract void newImplementationNode(ImplementationNode node) throws IOException; /** Adds a new instance node to the graph. */ protected abstract void newInstanceNode(InstanceNode node) throws IOException; /** Adds a new dependency edge to the graph. */ protected abstract void newDependencyEdge(DependencyEdge edge) throws IOException; /** Adds a new binding edge to the graph. */ protected abstract void newBindingEdge(BindingEdge edge) throws IOException; /** Performs any post processing required after all nodes and edges have been added. */ protected abstract void postProcess() throws IOException; private void createNodes(Iterable<Node> nodes, Map<NodeId, NodeId> aliases) throws IOException { for (Node node : nodes) { NodeId originalId = node.getId(); NodeId resolvedId = resolveAlias(aliases, originalId); node = node.copy(resolvedId); // Only render nodes that aren't aliased to some other node. if (resolvedId.equals(originalId)) { if (node instanceof InterfaceNode) { newInterfaceNode((InterfaceNode) node); } else if (node instanceof ImplementationNode) { newImplementationNode((ImplementationNode) node); } else { newInstanceNode((InstanceNode) node); } } } } private void createEdges(Iterable<Edge> edges, Map<NodeId, NodeId> aliases) throws IOException { for (Edge edge : edges) { edge = edge.copy(resolveAlias(aliases, edge.getFromId()), resolveAlias(aliases, edge.getToId())); if (!edge.getFromId().equals(edge.getToId())) { if (edge instanceof BindingEdge) { newBindingEdge((BindingEdge) edge); } else { newDependencyEdge((DependencyEdge) edge); } } } } private NodeId resolveAlias(Map<NodeId, NodeId> aliases, NodeId nodeId) { return aliases.getOrDefault(nodeId, nodeId); } /** * Transitively resolves aliases. Given aliases (X to Y) and (Y to Z), it will return mappings (X * to Z) and (Y to Z). */ private Map<NodeId, NodeId> resolveAliases(Iterable<Alias> aliases) { Map<NodeId, NodeId> resolved = Maps.newHashMap(); SetMultimap<NodeId, NodeId> inverse = HashMultimap.create(); for (Alias alias : aliases) { NodeId from = alias.getFromId(); NodeId to = alias.getToId(); if (resolved.containsKey(to)) { to = resolved.get(to); } resolved.put(from, to); inverse.put(to, from); Set<NodeId> prev = inverse.get(from); if (prev != null) { for (NodeId id : prev) { resolved.remove(id); inverse.remove(from, id); resolved.put(id, to); inverse.put(to, id); } } } return resolved; } /** Returns the bindings for the root keys and their transitive dependencies. */ private Iterable<Binding<?>> getBindings(Injector injector, Set<Key<?>> root) { Set<Key<?>> keys = Sets.newHashSet(root); Set<Key<?>> visitedKeys = Sets.newHashSet(); List<Binding<?>> bindings = Lists.newArrayList(); TransitiveDependencyVisitor keyVisitor = new TransitiveDependencyVisitor(); while (!keys.isEmpty()) { Iterator<Key<?>> iterator = keys.iterator(); Key<?> key = iterator.next(); iterator.remove(); if (!visitedKeys.contains(key)) { Binding<?> binding = injector.getBinding(key); bindings.add(binding); visitedKeys.add(key); keys.addAll(binding.acceptTargetVisitor(keyVisitor)); } } return bindings; } }
node
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
{ "start": 51782, "end": 52433 }
class ____ extends Base { @Override protected void doStuff(String actuallyUsed) { System.out.println(actuallyUsed); } } public static void main(String[] args) { Base b = new Descendant(); b.doStuff("some string"); } } """) .expectUnchanged() .doTest(); } @Test public void underscoreVariable() { assume().that(Runtime.version().feature()).isAtLeast(22); refactoringHelper .addInputLines( "Test.java", """
Descendant
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java
{ "start": 17541, "end": 17833 }
class ____ { @Bean Parser<Integer> parser() { return (text, locale) -> Integer.valueOf(text); } } record ExampleRecord(String value) { @Override public final String toString() { return value(); } } record OtherRecord(String value) { }
ParserBeanMethodConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/batch/SimpleBatchFetchBaselineTests.java
{ "start": 4628, "end": 5111 }
class ____ { @Id private Integer id; private String name; @SuppressWarnings("unused") private Employee() { } public Employee(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Employee(" + id.toString() + " : " + name + ")"; } } }
Employee
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/jdk/JDKKeyDeserializer.java
{ "start": 12677, "end": 14726 }
class ____ extends JDKKeyDeserializer { protected final EnumResolver _byNameResolver; protected final AnnotatedMethod _factory; /** * Alternative resolver to parse enums with {@code toString()} method as the source. * Works when {@link EnumFeature#READ_ENUMS_USING_TO_STRING} is enabled. */ protected final EnumResolver _byToStringResolver; /** * Alternative resolver to parse enums with {@link Enum#ordinal()} method as the source. * Works when {@link EnumFeature#READ_ENUM_KEYS_USING_INDEX} is enabled. */ protected final EnumResolver _byIndexResolver; /** * Look up map with <b>key</b> as <code>Enum.name()</code> converted by * {@link EnumNamingStrategy#convertEnumToExternalName(MapperConfig, AnnotatedClass, String)} * and <b>value</b> as Enums. */ protected final EnumResolver _byEnumNamingResolver; protected final Enum<?> _enumDefaultValue; protected EnumKD(EnumResolver er, AnnotatedMethod factory, EnumResolver byEnumNamingResolver, EnumResolver byToStringResolver, EnumResolver byIndexResolver) { super(-1, er.getEnumClass()); _byNameResolver = er; _factory = factory; _enumDefaultValue = er.getDefaultValue(); _byEnumNamingResolver = byEnumNamingResolver; _byToStringResolver = byToStringResolver; _byIndexResolver = byIndexResolver; } @Override public Object _parse(String key, DeserializationContext ctxt) throws JacksonException { if (_factory != null) { try { return _factory.call1(key); } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE(e); } } EnumResolver res = _resolveCurrentResolver(ctxt); Enum<?> e = res.findEnum(key); // If
EnumKD
java
spring-projects__spring-boot
module/spring-boot-quartz/src/main/java/org/springframework/boot/quartz/actuate/endpoint/QuartzEndpoint.java
{ "start": 19186, "end": 19260 }
class ____ descriptions of a {@link Trigger}. */ public abstract static
for
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/synonyms/GetSynonymsAction.java
{ "start": 2480, "end": 3316 }
class ____ extends AbstractPagedResultResponse<SynonymRule> { public Response(StreamInput in) throws IOException { super(in); } public Response(PagedResult<SynonymRule> result) { super(result); } @Override protected String resultFieldName() { return SynonymsManagementAPIService.SYNONYMS_SET_FIELD; } @Override protected Reader<SynonymRule> reader() { return SynonymRule::new; } @Override protected IntFunction<SynonymRule[]> arraySupplier() { return SynonymRule[]::new; } @SuppressWarnings("unchecked") @Override PagedResult<SynonymRule> getResults() { return (PagedResult<SynonymRule>) super.getResults(); } } }
Response
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/http/server/response/textplain/TextPlainControllerTest.java
{ "start": 537, "end": 1517 }
class ____ { @Client("/txt") @Inject HttpClient httpClient; @Test void textPlainBoolean() { asserTextResult("/boolean", "true"); } @Test void textPlainMonoBoolean() { asserTextResult("/boolean/mono", "true"); } @Test void textPlainFluxBoolean() { asserTextResult("/boolean/flux", "true"); } @Test void textPlainBigDecimal() { asserTextResult("/bigdecimal", BigDecimal.valueOf(Long.MAX_VALUE).toString()); } @Test void textPlainDate() { asserTextResult("/date", new Calendar.Builder().setDate(2023,7,4).build().toString()); } @Test void textPlainPerson() { asserTextResult("/person", new Person("Dean Wette", 65).toString()); } private void asserTextResult(String url, String expectedResult) { final String result = httpClient.toBlocking().retrieve(url); assertEquals(expectedResult, result); } }
TextPlainControllerTest
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java
{ "start": 10373, "end": 10513 }
class ____ { } @SelfAnnotating(excludeAutoConfiguration = AnotherImportedAutoConfiguration.class) static
ImportWithSelfAnnotatingAnnotation
java
apache__camel
components/camel-amqp/src/test/java/org/apache/camel/component/amqp/AMQPToDTest.java
{ "start": 1365, "end": 3010 }
class ____ extends AMQPTestSupport { private ProducerTemplate template; @Test public void testToD() throws Exception { contextExtension.getMockEndpoint("mock:bar").expectedBodiesReceived("Hello bar"); contextExtension.getMockEndpoint("mock:beer").expectedBodiesReceived("Hello beer"); template.sendBodyAndHeader("direct:start", "Hello bar", "where", "bar"); template.sendBodyAndHeader("direct:start", "Hello beer", "where", "beer"); MockEndpoint.assertIsSatisfied(contextExtension.getContext()); } @BeforeAll static void startContext() { System.setProperty(AMQPConnectionDetails.AMQP_PORT, String.valueOf(service.brokerPort())); } @BeforeEach void setupTemplate() { template = contextExtension.getProducerTemplate(); } @ContextFixture public void configureContext(CamelContext camelContext) { System.setProperty(AMQPConnectionDetails.AMQP_PORT, String.valueOf(service.brokerPort())); camelContext.getRegistry().bind("amqpConnection", discoverAMQP(camelContext)); } @RouteFixture public void createRouteBuilder(CamelContext context) throws Exception { context.addRoutes(createRouteBuilder()); } private RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // route message dynamic using toD from("direct:start").toD("amqp:queue:${header.where}"); from("amqp:queue:bar").to("mock:bar"); from("amqp:queue:beer").to("mock:beer"); } }; } }
AMQPToDTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/PartitionAggregateOperatorTest.java
{ "start": 3554, "end": 4984 }
class ____ extends RichAggregateFunction<Integer, TestAccumulator, String> { private final CompletableFuture<Object> openIdentifier; private final CompletableFuture<Object> closeIdentifier; public Aggregate( CompletableFuture<Object> openIdentifier, CompletableFuture<Object> closeIdentifier) { this.openIdentifier = openIdentifier; this.closeIdentifier = closeIdentifier; } @Override public void open(OpenContext openContext) throws Exception { super.open(openContext); openIdentifier.complete(null); } @Override public TestAccumulator createAccumulator() { return new TestAccumulator(); } @Override public TestAccumulator add(Integer value, TestAccumulator accumulator) { accumulator.addNumber(value); return accumulator; } @Override public String getResult(TestAccumulator accumulator) { return accumulator.getResult(); } @Override public TestAccumulator merge(TestAccumulator a, TestAccumulator b) { return null; } @Override public void close() throws Exception { super.close(); closeIdentifier.complete(null); } } /** The test accumulator. */ private static
Aggregate
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/ltr/FeatureExtractor.java
{ "start": 437, "end": 664 }
interface ____ { void setNextReader(LeafReaderContext segmentContext) throws IOException; void addFeatures(Map<String, Object> featureMap, int docId) throws IOException; List<String> featureNames(); }
FeatureExtractor
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/event/JobEventType.java
{ "start": 893, "end": 1562 }
enum ____ { //Producer:Client JOB_KILL, //Producer:MRAppMaster JOB_INIT, JOB_INIT_FAILED, JOB_START, //Producer:Task JOB_TASK_COMPLETED, JOB_MAP_TASK_RESCHEDULED, JOB_TASK_ATTEMPT_COMPLETED, //Producer:CommitterEventHandler JOB_SETUP_COMPLETED, JOB_SETUP_FAILED, JOB_COMMIT_COMPLETED, JOB_COMMIT_FAILED, JOB_ABORT_COMPLETED, //Producer:Job JOB_COMPLETED, JOB_FAIL_WAIT_TIMEDOUT, //Producer:Any component JOB_DIAGNOSTIC_UPDATE, INTERNAL_ERROR, JOB_COUNTER_UPDATE, //Producer:TaskAttemptListener JOB_TASK_ATTEMPT_FETCH_FAILURE, //Producer:RMContainerAllocator JOB_UPDATED_NODES, JOB_AM_REBOOT }
JobEventType
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldBeInTheFutureTest_create_Test.java
{ "start": 1034, "end": 1640 }
class ____ { @Test void should_create_error_message() { // GIVEN LocalDate pastDate = LocalDate.of(1993, 7, 28); ErrorMessageFactory factory = shouldBeInTheFuture(pastDate); // WHEN String message = factory.create(new TestDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting actual:%n" + " 1993-07-28 (java.time.LocalDate)%n" + "to be in the future but was not.")); } }
ShouldBeInTheFutureTest_create_Test
java
google__dagger
dagger-producers/main/java/dagger/producers/monitoring/TimingRecorders.java
{ "start": 6965, "end": 8536 }
class ____ implements ProductionComponentTimingRecorder.Factory { private final ImmutableList<? extends ProductionComponentTimingRecorder.Factory> delegates; Factory(Iterable<? extends ProductionComponentTimingRecorder.Factory> delegates) { this.delegates = ImmutableList.copyOf(delegates); } @Override public ProductionComponentTimingRecorder create(Object component) { ImmutableList.Builder<ProductionComponentTimingRecorder> recordersBuilder = ImmutableList.builder(); for (ProductionComponentTimingRecorder.Factory delegate : delegates) { try { ProductionComponentTimingRecorder recorder = delegate.create(component); if (recorder != null) { recordersBuilder.add(recorder); } } catch (RuntimeException e) { logCreateException(e, delegate, component); } } ImmutableList<ProductionComponentTimingRecorder> recorders = recordersBuilder.build(); switch (recorders.size()) { case 0: return noOpProductionComponentTimingRecorder(); case 1: return new NonThrowingProductionComponentTimingRecorder( Iterables.getOnlyElement(recorders)); default: return new DelegatingProductionComponentTimingRecorder(recorders); } } } } /** * A producer recorder that delegates to several recorders, and catches and logs all exceptions * that the delegates throw. */ private static final
Factory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/id/UUIDGenerationStrategy.java
{ "start": 388, "end": 1370 }
interface ____ extends Serializable { /** * Which variant, according to IETF RFC 4122, of UUID does this strategy generate? RFC 4122 defines * 5 variants (though it only describes algorithms to generate 4):<ul> * <li>1 = time based</li> * <li>2 = DCE based using POSIX UIDs</li> * <li>3 = name based (md5 hash)</li> * <li>4 = random numbers based</li> * <li>5 = name based (sha-1 hash)</li> * </ul> * <p> * Returning the values above should be reserved to those generators creating variants compliant with the * corresponding RFC definition; others can feel free to return other values as they see fit. * <p> * Informational only, and not used at this time. * * @return The supported generation version */ int getGeneratedVersion(); /** * Generate the UUID. * * @param session The session asking for the generation * * @return The generated UUID. */ UUID generateUUID(SharedSessionContractImplementor session); }
UUIDGenerationStrategy