language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/operations/SqlNodeToCallOperationTest.java
{ "start": 10636, "end": 10832 }
class ____ implements Procedure { public Number[] call(ProcedureContext procedureContext, Number n) { return null; } } private static
DifferentTypeMappingProcedure
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/handler/predicate/GatewayPredicate.java
{ "start": 3822, "end": 4574 }
class ____ implements GatewayPredicate { private final GatewayPredicate left; private final GatewayPredicate right; public OrGatewayPredicate(GatewayPredicate left, GatewayPredicate right) { Objects.requireNonNull(left, "Left GatewayPredicate must not be null"); Objects.requireNonNull(right, "Right GatewayPredicate must not be null"); this.left = left; this.right = right; } @Override public boolean test(ServerWebExchange t) { return (this.left.test(t) || this.right.test(t)); } @Override public void accept(Visitor visitor) { left.accept(visitor); right.accept(visitor); } @Override public String toString() { return String.format("(%s || %s)", this.left, this.right); } } }
OrGatewayPredicate
java
alibaba__nacos
lock/src/main/java/com/alibaba/nacos/lock/raft/request/MutexLockRequest.java
{ "start": 834, "end": 1163 }
class ____ implements Serializable { private static final long serialVersionUID = -925543547156890549L; private LockInfo lockInfo; public LockInfo getLockInfo() { return lockInfo; } public void setLockInfo(LockInfo lockInfo) { this.lockInfo = lockInfo; } }
MutexLockRequest
java
processing__processing4
core/src/processing/opengl/FontTexture.java
{ "start": 1275, "end": 1928 }
class ____ needed because * fonts in Processing are handled by a separate PImage for each * glyph. For performance reasons, all these glyphs should be * stored in a single OpenGL texture (otherwise, rendering a * string of text would involve binding and un-binding several * textures. * PFontTexture manages the correspondence between individual * glyphs and the large OpenGL texture containing them. Also, * in the case that the font size is very large, one single * OpenGL texture might not be enough to store all the glyphs, * so PFontTexture also takes care of spreading a single font * over several textures. * @author Andres Colubri */
is
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/asm/ClassWriter.java
{ "start": 3913, "end": 4048 }
class ____ interface. */ private int interfaceCount; /** * The interfaces implemented or extended by this
or
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/InverseDistributionFunction.java
{ "start": 1722, "end": 4810 }
class ____ extends AbstractSqmSelfRenderingFunctionDescriptor { public InverseDistributionFunction(String name, FunctionParameterType parameterType, TypeConfiguration typeConfiguration) { super( name, FunctionKind.ORDERED_SET_AGGREGATE, parameterType == null ? StandardArgumentsValidators.exactly( 0 ) : new ArgumentTypesValidator( StandardArgumentsValidators.exactly( 1 ), parameterType ), null, parameterType == null ? null : StandardFunctionArgumentTypeResolvers.invariant( typeConfiguration, parameterType ) ); } @Override public <T> SelfRenderingSqmOrderedSetAggregateFunction<T> generateSqmOrderedSetAggregateFunctionExpression( List<? extends SqmTypedNode<?>> arguments, SqmPredicate filter, SqmOrderByClause withinGroupClause, ReturnableType<T> impliedResultType, QueryEngine queryEngine) { return new SelfRenderingInverseDistributionFunction<>( arguments, filter, withinGroupClause, impliedResultType, queryEngine ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { render( sqlAppender, sqlAstArguments, null, Collections.emptyList(), returnType, walker ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, Predicate filter, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { render( sqlAppender, sqlAstArguments, filter, Collections.emptyList(), returnType, walker ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, Predicate filter, List<SortSpecification> withinGroup, ReturnableType<?> returnType, SqlAstTranslator<?> translator) { if ( filter != null && !filterClauseSupported( translator ) ) { throw new IllegalArgumentException( "Can't emulate filter clause for inverse distribution function [" + getName() + "]" ); } sqlAppender.appendSql( getName() ); sqlAppender.appendSql( '(' ); if ( !sqlAstArguments.isEmpty() ) { sqlAstArguments.get( 0 ).accept( translator ); for ( int i = 1; i < sqlAstArguments.size(); i++ ) { sqlAppender.append( ',' ); sqlAstArguments.get( i ).accept( translator ); } } sqlAppender.appendSql( ')' ); if ( withinGroup != null && !withinGroup.isEmpty() ) { translator.getCurrentClauseStack().push( Clause.WITHIN_GROUP ); sqlAppender.appendSql( " within group (order by " ); withinGroup.get( 0 ).accept( translator ); for ( int i = 1; i < withinGroup.size(); i++ ) { sqlAppender.appendSql( ',' ); withinGroup.get( i ).accept( translator ); } sqlAppender.appendSql( ')' ); translator.getCurrentClauseStack().pop(); } if ( filter != null ) { translator.getCurrentClauseStack().push( Clause.WHERE ); sqlAppender.appendSql( " filter (where " ); filter.accept( translator ); sqlAppender.appendSql( ')' ); translator.getCurrentClauseStack().pop(); } } protected
InverseDistributionFunction
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
{ "start": 9488, "end": 11089 }
class ____ test * @param hasIntroductions whether the advisor chain * for this bean includes any introductions * @return whether the pointcut can apply on any method */ public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { Assert.notNull(pc, "Pointcut must not be null"); if (!pc.getClassFilter().matches(targetClass)) { return false; } MethodMatcher methodMatcher = pc.getMethodMatcher(); if (methodMatcher == MethodMatcher.TRUE) { // No need to iterate the methods if we're matching any method anyway... return true; } IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null; if (methodMatcher instanceof IntroductionAwareMethodMatcher iamm) { introductionAwareMethodMatcher = iamm; } Set<Class<?>> classes = new LinkedHashSet<>(); if (!Proxy.isProxyClass(targetClass)) { classes.add(ClassUtils.getUserClass(targetClass)); } classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); for (Class<?> clazz : classes) { Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); for (Method method : methods) { if (introductionAwareMethodMatcher != null ? introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) : methodMatcher.matches(method, targetClass)) { return true; } } } return false; } /** * Can the given advisor apply at all on the given class? * This is an important test as it can be used to optimize * out an advisor for a class. * @param advisor the advisor to check * @param targetClass
to
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/deployment/src/test/java/io/quarkus/restclient/registerprovider/ProviderClientRegistrationTest.java
{ "start": 2914, "end": 3728 }
class ____ { private WebTarget webTarget; @PostConstruct void init() { webTarget = ClientBuilder.newClient().target("http://localhost:" + server.getAddress().getPort()).path("/hello"); ; } String hello() { return hello(null); } String hello(final String name) { WebTarget webTarget = this.webTarget; if (name != null) { webTarget = webTarget.queryParam("name", name); } Response response = webTarget.request(MediaType.TEXT_PLAIN_TYPE).get(Response.class); assertEquals(200, response.getStatus()); return response.readEntity(String.class); } } @Provider @Priority(Priorities.USER - 1) public static
ClientBean
java
quarkusio__quarkus
core/processor/src/main/java/io/quarkus/annotation/processor/util/AccessorGenerator.java
{ "start": 1289, "end": 4232 }
class ____ { private static final String QUARKUS_GENERATED = "io.quarkus.Generated"; private static final String INSTANCE_SYM = "__instance"; private final ProcessingEnvironment processingEnv; private final ElementUtil elementUtil; private final Set<String> generatedAccessors = new ConcurrentHashMap<String, Boolean>().keySet(Boolean.TRUE); AccessorGenerator(ProcessingEnvironment processingEnv, ElementUtil elementUtil) { this.processingEnv = processingEnv; this.elementUtil = elementUtil; } public void generateAccessor(final TypeElement clazz) { if (!generatedAccessors.add(clazz.getQualifiedName().toString())) { return; } final FormatPreferences fp = new FormatPreferences(); final JSources sources = JDeparser.createSources(JFiler.newInstance(processingEnv.getFiler()), fp); final PackageElement packageElement = elementUtil.getPackageOf(clazz); final String className = elementUtil.buildRelativeBinaryName(clazz, new StringBuilder()).append("$$accessor") .toString(); final JSourceFile sourceFile = sources.createSourceFile(packageElement.getQualifiedName() .toString(), className); JType clazzType = JTypes.typeOf(clazz.asType()); if (clazz.asType() instanceof DeclaredType declaredType) { TypeMirror enclosingType = declaredType.getEnclosingType(); if (enclosingType != null && enclosingType.getKind() == TypeKind.DECLARED && clazz.getModifiers() .contains(Modifier.STATIC)) { // Ugly workaround for Eclipse APT and static nested types clazzType = unnestStaticNestedType(declaredType); } } final JClassDef classDef = sourceFile._class(JMod.PUBLIC | JMod.FINAL, className); classDef.constructor(JMod.PRIVATE); // no construction classDef.annotate(QUARKUS_GENERATED) .value("Quarkus annotation processor"); final JAssignableExpr instanceName = JExprs.name(INSTANCE_SYM); boolean isEnclosingClassPublic = clazz.getModifiers() .contains(Modifier.PUBLIC); // iterate fields boolean generationNeeded = false; for (VariableElement field : fieldsIn(clazz.getEnclosedElements())) { final Set<Modifier> mods = field.getModifiers(); if (mods.contains(Modifier.PRIVATE) || mods.contains(Modifier.STATIC) || mods.contains(Modifier.FINAL)) { // skip it continue; } final TypeMirror fieldType = field.asType(); if (mods.contains(Modifier.PUBLIC) && isEnclosingClassPublic) { // we don't need to generate a method accessor when the following conditions are met: // 1) the field is public // 2) the enclosing
AccessorGenerator
java
apache__flink
flink-connectors/flink-connector-files/src/test/java/org/apache/flink/connector/file/sink/utils/FileSinkTestUtils.java
{ "start": 6088, "end": 6530 }
class ____ implements BucketAssigner<String, String> { private static final long serialVersionUID = 1L; @Override public String getBucketId(String element, BucketAssigner.Context context) { return element; } @Override public SimpleVersionedSerializer<String> getSerializer() { return SimpleVersionedStringSerializer.INSTANCE; } } }
StringIdentityBucketAssigner
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/CapacitySchedulerPage.java
{ "start": 16205, "end": 23114 }
class ____ extends HtmlBlock { final CapacityScheduler cs; final CSQInfo csqinfo; private final ResourceManager rm; private List<RMNodeLabel> nodeLabelsInfo; @Inject QueuesBlock(ResourceManager rm, CSQInfo info) { cs = (CapacityScheduler) rm.getResourceScheduler(); csqinfo = info; this.rm = rm; RMNodeLabelsManager nodeLabelManager = rm.getRMContext().getNodeLabelManager(); nodeLabelsInfo = nodeLabelManager.pullRMNodeLabelsInfo(); } @Override public void render(Block html) { html.__(MetricsOverviewTable.class); UserGroupInformation callerUGI = this.getCallerUGI(); boolean isAdmin = false; ApplicationACLsManager aclsManager = rm.getApplicationACLsManager(); if (aclsManager.areACLsEnabled()) { if (callerUGI != null && aclsManager.isAdmin(callerUGI)) { isAdmin = true; } } else { isAdmin = true; } // only show button to dump CapacityScheduler debug logs to admins if (isAdmin) { html.div() .button() .$style( "border-style: solid; border-color: #000000; border-width: 1px;" + " cursor: hand; cursor: pointer; border-radius: 4px") .$onclick("confirmAction()").b("Dump scheduler logs").__().select() .$id("time").option().$value("60").__("1 min").__().option() .$value("300").__("5 min").__().option().$value("600").__("10 min").__() .__().__(); StringBuilder script = new StringBuilder(); script .append("function confirmAction() {") .append(" b = confirm(\"Are you sure you wish to generate" + " scheduler logs?\");") .append(" if (b == true) {") .append(" var timePeriod = $(\"#time\").val();") .append(" $.ajax({") .append(" type: 'POST',") .append(" url: '/ws/v1/cluster/scheduler/logs',") .append(" contentType: 'text/plain',") .append(AppBlock.getCSRFHeaderString(rm.getConfig())) .append(" data: 'time=' + timePeriod,") .append(" dataType: 'text'") .append(" }).done(function(data){") .append(" setTimeout(function(){") .append(" alert(\"Scheduler log is being generated.\");") .append(" }, 1000);") .append(" }).fail(function(data){") .append( " alert(\"Scheduler log generation failed. Please check the" + " ResourceManager log for more information.\");") .append(" console.log(data);").append(" });").append(" }") .append("}"); html.script().$type("text/javascript").__(script.toString()).__(); } UL<DIV<DIV<Hamlet>>> ul = html. div("#cs-wrapper.ui-widget"). div(".ui-widget-header.ui-corner-top"). __("Application Queues").__(). div("#cs.ui-widget-content.ui-corner-bottom"). ul(); if (cs == null) { ul. li(). a(_Q).$style(width(Q_MAX_WIDTH)). span().$style(Q_END).__("100% ").__(). span(".q", "default").__().__(); } else { ul. li().$style("margin-bottom: 1em"). span().$style("font-weight: bold").__("Legend:").__(). span().$class("qlegend ui-corner-all").$style(Q_GIVEN). __("Capacity").__(). span().$class("qlegend ui-corner-all").$style(Q_UNDER). __("Used").__(). span().$class("qlegend ui-corner-all").$style(Q_OVER). __("Used (over capacity)").__(). span().$class("qlegend ui-corner-all ui-state-default"). __("Max Capacity").__(). span().$class("qlegend ui-corner-all").$style(ACTIVE_USER). __("Users Requesting Resources").__(). span().$class("qlegend ui-corner-all").$style(Q_AUTO_CREATED). __("Auto Created Queues").__(). __(); float used = 0; CSQueue root = cs.getRootQueue(); CapacitySchedulerInfo sinfo = new CapacitySchedulerInfo(root, cs); csqinfo.csinfo = sinfo; boolean hasAnyLabelLinkedToNM = false; if (null != nodeLabelsInfo) { for (RMNodeLabel label : nodeLabelsInfo) { if (label.getLabelName().length() == 0) { // Skip DEFAULT_LABEL continue; } if (label.getNumActiveNMs() > 0) { hasAnyLabelLinkedToNM = true; break; } } } if (!hasAnyLabelLinkedToNM) { used = sinfo.getUsedCapacity() / 100; //label is not enabled in the cluster or there's only "default" label, ul.li(). a(_Q).$style(width(Q_MAX_WIDTH)). span().$style(join(width(used), ";left:0%;", used > 1 ? Q_OVER : Q_UNDER)).__(".").__(). span(".q", "root").__(). span().$class("qstats").$style(left(Q_STATS_POS)). __(join(percent(used), " used")).__(). __(QueueBlock.class).__(); } else { for (RMNodeLabel label : nodeLabelsInfo) { csqinfo.qinfo = null; csqinfo.label = label.getLabelName(); csqinfo.isExclusiveNodeLabel = label.getIsExclusive(); String nodeLabelDisplay = csqinfo.label.length() == 0 ? NodeLabel.DEFAULT_NODE_LABEL_PARTITION : csqinfo.label; PartitionQueueCapacitiesInfo capacities = sinfo.getCapacities() .getPartitionQueueCapacitiesInfo(csqinfo.label); used = capacities.getUsedCapacity() / 100; String partitionUiTag = "Partition: " + nodeLabelDisplay + " " + label.getResource(); ul.li(). a(_Q).$style(width(Q_MAX_WIDTH)). span().$style(join(width(used), ";left:0%;", used > 1 ? Q_OVER : Q_UNDER)).__(".").__(). span(".q", partitionUiTag).__(). span().$class("qstats").$style(left(Q_STATS_POS)). __(join(percent(used), " used")).__().__(); //for the queue hierarchy under label UL<Hamlet> underLabel = html.ul("#pq"); underLabel.li(). a(_Q).$style(width(Q_MAX_WIDTH)). span().$style(join(width(used), ";left:0%;", used > 1 ? Q_OVER : Q_UNDER)).__(".").__(). span(".q", "root").__(). span().$class("qstats").$style(left(Q_STATS_POS)). __(join(percent(used), " used")).__(). __(QueueBlock.class).__().__(); } } } ul.__().__(). script().$type("text/javascript"). __("$('#cs').hide();").__().__(). __(RMAppsBlock.class); html.__(HealthBlock.class); } } public static
QueuesBlock
java
elastic__elasticsearch
x-pack/plugin/stack/src/test/java/org/elasticsearch/xpack/stack/StackTemplateRegistryTests.java
{ "start": 3829, "end": 29249 }
class ____ extends ESTestCase { private StackTemplateRegistry registry; private ClusterService clusterService; private ThreadPool threadPool; private VerifyingClient client; @Before public void createRegistryAndClient() { threadPool = new TestThreadPool(this.getClass().getName()); client = new VerifyingClient(threadPool); clusterService = ClusterServiceUtils.createClusterService(threadPool); registry = new StackTemplateRegistry(Settings.EMPTY, clusterService, threadPool, client, NamedXContentRegistry.EMPTY); } @After @Override public void tearDown() throws Exception { super.tearDown(); threadPool.shutdownNow(); } public void testDisabledDoesNotAddIndexTemplates() { Settings settings = Settings.builder().put(StackTemplateRegistry.STACK_TEMPLATES_ENABLED.getKey(), false).build(); StackTemplateRegistry disabledRegistry = new StackTemplateRegistry( settings, clusterService, threadPool, client, NamedXContentRegistry.EMPTY ); assertThat(disabledRegistry.getComposableTemplateConfigs(), anEmptyMap()); } public void testDisabledStillAddsComponentTemplatesAndIlmPolicies() { Settings settings = Settings.builder().put(StackTemplateRegistry.STACK_TEMPLATES_ENABLED.getKey(), false).build(); StackTemplateRegistry disabledRegistry = new StackTemplateRegistry( settings, clusterService, threadPool, client, NamedXContentRegistry.EMPTY ); assertThat(disabledRegistry.getComponentTemplateConfigs(), not(anEmptyMap())); assertThat( disabledRegistry.getComponentTemplateConfigs() .keySet() .stream() // We have a naming convention that internal component templates contain `@`. See also put-component-template.asciidoc. .filter(t -> t.contains("@") == false) .collect(Collectors.toSet()), empty() ); assertThat(disabledRegistry.getLifecyclePolicies(), not(empty())); assertThat( // We have a naming convention that internal ILM policies contain `@`. See also put-lifecycle.asciidoc. disabledRegistry.getLifecyclePolicies().stream().filter(p -> p.getName().contains("@") == false).collect(Collectors.toSet()), empty() ); } public void testThatNonExistingTemplatesAreAddedImmediately() throws Exception { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), nodes); AtomicInteger calledTimes = new AtomicInteger(0); client.setVerifier((action, request, listener) -> verifyComponentTemplateInstalled(calledTimes, action, request, listener)); registry.clusterChanged(event); assertBusy(() -> assertThat(calledTimes.get(), equalTo(registry.getComponentTemplateConfigs().size()))); calledTimes.set(0); // attempting to register the event multiple times as a race condition can yield this test flaky, namely: // when calling registry.clusterChanged(newEvent) the templateCreationsInProgress state that the IndexTemplateRegistry maintains // might've not yet been updated to reflect that the first template registration was complete, so a second template registration // will not be issued anymore, leaving calledTimes to 0 assertBusy(() -> { // now delete one template from the cluster state and lets retry ClusterChangedEvent newEvent = createClusterChangedEvent(Collections.emptyMap(), nodes); registry.clusterChanged(newEvent); assertThat(calledTimes.get(), greaterThan(1)); }); } public void testThatNonExistingPoliciesAreAddedImmediately() throws Exception { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); AtomicInteger calledTimes = new AtomicInteger(0); client.setVerifier((action, request, listener) -> { if (action == ILMActions.PUT) { calledTimes.incrementAndGet(); assertThat(request, instanceOf(PutLifecycleRequest.class)); final PutLifecycleRequest putRequest = (PutLifecycleRequest) request; assertThat( putRequest.getPolicy().getName(), anyOf( equalTo(StackTemplateRegistry.LOGS_ILM_POLICY_NAME), equalTo(StackTemplateRegistry.METRICS_ILM_POLICY_NAME), equalTo(StackTemplateRegistry.SYNTHETICS_ILM_POLICY_NAME), equalTo(StackTemplateRegistry.TRACES_ILM_POLICY_NAME), equalTo(StackTemplateRegistry.ILM_7_DAYS_POLICY_NAME), equalTo(StackTemplateRegistry.ILM_30_DAYS_POLICY_NAME), equalTo(StackTemplateRegistry.ILM_90_DAYS_POLICY_NAME), equalTo(StackTemplateRegistry.ILM_180_DAYS_POLICY_NAME), equalTo(StackTemplateRegistry.ILM_365_DAYS_POLICY_NAME) ) ); assertNotNull(listener); return AcknowledgedResponse.TRUE; } else if (action instanceof PutComponentTemplateAction) { // Ignore this, it's verified in another test return new StackTemplateRegistryTests.TestPutIndexTemplateResponse(true); } else if (action == TransportPutComposableIndexTemplateAction.TYPE) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else { fail("client called with unexpected request: " + request.toString()); return null; } }); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), nodes); registry.clusterChanged(event); assertBusy(() -> assertThat(calledTimes.get(), equalTo(9))); } public void testPolicyAlreadyExists() { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); Map<String, LifecyclePolicy> policyMap = new HashMap<>(); List<LifecyclePolicy> policies = registry.getLifecyclePolicies(); assertThat(policies, hasSize(9)); policies.forEach(p -> policyMap.put(p.getName(), p)); client.setVerifier((action, request, listener) -> { if (action instanceof PutComponentTemplateAction) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == TransportPutComposableIndexTemplateAction.TYPE) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == ILMActions.PUT) { fail("if the policy already exists it should not be re-put"); } else { fail("client called with unexpected request: " + request.toString()); } return null; }); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), policyMap, nodes, true); registry.clusterChanged(event); } public void testThatIndependentPipelinesAreAdded() throws Exception { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); AtomicInteger calledTimes = new AtomicInteger(0); client.setVerifier((action, request, listener) -> { if (action == PutPipelineTransportAction.TYPE) { calledTimes.incrementAndGet(); return AcknowledgedResponse.TRUE; } if (action instanceof PutComponentTemplateAction) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == ILMActions.PUT) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == TransportPutComposableIndexTemplateAction.TYPE) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else { fail("client called with unexpected request: " + request.toString()); } return null; }); ClusterChangedEvent event = createInitialClusterChangedEvent(nodes); registry.clusterChanged(event); assertBusy( () -> assertThat( calledTimes.get(), equalTo( Long.valueOf( registry.getIngestPipelines() .stream() .filter(ingestPipelineConfig -> ingestPipelineConfig.getPipelineDependencies().isEmpty()) .count() ).intValue() ) ) ); } public void testPolicyAlreadyExistsButDiffers() throws IOException { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); Map<String, LifecyclePolicy> policyMap = new HashMap<>(); String policyStr = "{\"phases\":{\"delete\":{\"min_age\":\"1m\",\"actions\":{\"delete\":{}}}}}"; List<LifecyclePolicy> policies = registry.getLifecyclePolicies(); assertThat(policies, hasSize(9)); policies.forEach(p -> policyMap.put(p.getName(), p)); client.setVerifier((action, request, listener) -> { if (action instanceof PutComponentTemplateAction) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == TransportPutComposableIndexTemplateAction.TYPE) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == ILMActions.PUT) { fail("if the policy already exists it should not be re-put"); } else { fail("client called with unexpected request: " + request.toString()); } return null; }); try ( XContentParser parser = XContentType.JSON.xContent() .createParser( XContentParserConfiguration.EMPTY.withRegistry( new NamedXContentRegistry( List.of( new NamedXContentRegistry.Entry( LifecycleAction.class, new ParseField(DeleteAction.NAME), DeleteAction::parse ) ) ) ), policyStr ) ) { LifecyclePolicy different = LifecyclePolicy.parse(parser, policies.get(0).getName()); policyMap.put(policies.get(0).getName(), different); ClusterChangedEvent event = createClusterChangedEvent(Collections.emptyMap(), policyMap, nodes, true); registry.clusterChanged(event); } } public void testThatVersionedOldTemplatesAreUpgraded() throws Exception { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); ClusterChangedEvent event = createClusterChangedEvent( Collections.singletonMap( StackTemplateRegistry.LOGS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION - 1 ), nodes ); AtomicInteger calledTimes = new AtomicInteger(0); client.setVerifier((action, request, listener) -> verifyComponentTemplateInstalled(calledTimes, action, request, listener)); registry.clusterChanged(event); assertBusy(() -> assertThat(calledTimes.get(), equalTo(registry.getComponentTemplateConfigs().size()))); } public void testThatUnversionedOldTemplatesAreUpgraded() throws Exception { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); ClusterChangedEvent event = createClusterChangedEvent( Collections.singletonMap(StackTemplateRegistry.LOGS_SETTINGS_COMPONENT_TEMPLATE_NAME, null), nodes ); AtomicInteger calledTimes = new AtomicInteger(0); client.setVerifier((action, request, listener) -> verifyComponentTemplateInstalled(calledTimes, action, request, listener)); registry.clusterChanged(event); assertBusy(() -> assertThat(calledTimes.get(), equalTo(registry.getComponentTemplateConfigs().size()))); } public void testMissingNonRequiredTemplates() throws Exception { StackRegistryWithNonRequiredTemplates registryWithNonRequiredTemplate = new StackRegistryWithNonRequiredTemplates( Settings.EMPTY, clusterService, threadPool, client, NamedXContentRegistry.EMPTY ); DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); ClusterChangedEvent event = createClusterChangedEvent( Collections.singletonMap(StackTemplateRegistry.LOGS_SETTINGS_COMPONENT_TEMPLATE_NAME, null), nodes ); final AtomicInteger calledTimes = new AtomicInteger(0); client.setVerifier((action, request, listener) -> { if (action instanceof PutComponentTemplateAction) { // Ignore such return AcknowledgedResponse.TRUE; } else if (action == ILMActions.PUT) { // Ignore such return AcknowledgedResponse.TRUE; } else if (action == TransportPutComposableIndexTemplateAction.TYPE) { calledTimes.incrementAndGet(); assertThat(request, instanceOf(TransportPutComposableIndexTemplateAction.Request.class)); TransportPutComposableIndexTemplateAction.Request putComposableTemplateRequest = (TransportPutComposableIndexTemplateAction.Request) request; assertThat(putComposableTemplateRequest.name(), equalTo("syslog")); ComposableIndexTemplate composableIndexTemplate = putComposableTemplateRequest.indexTemplate(); assertThat(composableIndexTemplate.composedOf(), hasSize(2)); assertThat(composableIndexTemplate.composedOf().get(0), equalTo("logs@settings")); assertThat(composableIndexTemplate.composedOf().get(1), equalTo("syslog@custom")); assertThat(composableIndexTemplate.getIgnoreMissingComponentTemplates(), hasSize(1)); assertThat(composableIndexTemplate.getIgnoreMissingComponentTemplates().get(0), equalTo("syslog@custom")); return AcknowledgedResponse.TRUE; } else { fail("client called with unexpected request:" + request.toString()); return null; } }); registryWithNonRequiredTemplate.clusterChanged(event); assertBusy(() -> assertThat(calledTimes.get(), equalTo(1))); } @TestLogging(value = "org.elasticsearch.xpack.core.template:DEBUG", reason = "test") public void testSameOrHigherVersionTemplateNotUpgraded() { DiscoveryNode node = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").masterNodeId("node").add(node).build(); Map<String, Integer> versions = new HashMap<>(); versions.put(StackTemplateRegistry.DATA_STREAMS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.ECS_DYNAMIC_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.LOGS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.LOGS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.METRICS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.METRICS_TSDB_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.METRICS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.SYNTHETICS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.SYNTHETICS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.AGENTLESS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.AGENTLESS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.KIBANA_REPORTING_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.TRACES_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); versions.put(StackTemplateRegistry.TRACES_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION); ClusterChangedEvent sameVersionEvent = createClusterChangedEvent(versions, nodes); client.setVerifier((action, request, listener) -> { if (request instanceof PutComponentTemplateAction.Request put) { fail("template should not have been re-installed: " + put.name()); return null; } else if (action == ILMActions.PUT) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else if (action == TransportPutComposableIndexTemplateAction.TYPE) { // Ignore this, it's verified in another test return AcknowledgedResponse.TRUE; } else { fail("client called with unexpected request:" + request.toString()); return null; } }); registry.clusterChanged(sameVersionEvent); versions.clear(); versions.put( StackTemplateRegistry.DATA_STREAMS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.ECS_DYNAMIC_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.LOGS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.LOGS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.METRICS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.METRICS_TSDB_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.METRICS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.SYNTHETICS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.SYNTHETICS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.AGENTLESS_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.AGENTLESS_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.KIBANA_REPORTING_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.TRACES_MAPPINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); versions.put( StackTemplateRegistry.TRACES_SETTINGS_COMPONENT_TEMPLATE_NAME, StackTemplateRegistry.REGISTRY_VERSION + randomIntBetween(1, 1000) ); ClusterChangedEvent higherVersionEvent = createClusterChangedEvent(versions, nodes); registry.clusterChanged(higherVersionEvent); } public void testThatMissingMasterNodeDoesNothing() { DiscoveryNode localNode = DiscoveryNodeUtils.create("node"); DiscoveryNodes nodes = DiscoveryNodes.builder().localNodeId("node").add(localNode).build(); client.setVerifier((a, r, l) -> { fail("if the master is missing nothing should happen"); return null; }); ClusterChangedEvent event = createClusterChangedEvent( Collections.singletonMap(StackTemplateRegistry.LOGS_INDEX_TEMPLATE_NAME, null), nodes ); registry.clusterChanged(event); } public void testThatTemplatesAreNotDeprecated() { for (ComposableIndexTemplate it : registry.getComposableTemplateConfigs().values()) { assertFalse(it.isDeprecated()); } for (LifecyclePolicy ilm : registry.getLifecyclePolicies()) { assertFalse(ilm.isDeprecated()); } for (ComponentTemplate ct : registry.getComponentTemplateConfigs().values()) { assertFalse(ct.deprecated()); } registry.getIngestPipelines() .stream() .map(ipc -> new PipelineConfiguration(ipc.getId(), ipc.loadConfig(), XContentType.JSON)) .map(PipelineConfiguration::getConfig) .forEach(p -> assertFalse((Boolean) p.get("deprecated"))); } public void testRegistryIsUpToDate() throws Exception { assumeFalse("This test relies on text files checksum, which is inconsistent between Windows and Linux", Constants.WINDOWS); CRC32 crc32 = new CRC32(); for (IndexTemplateConfig config : StackTemplateRegistry.getComponentTemplateConfigsAsConfigs()) { crc32.update(loadTemplate(config.getFileName())); } for (LifecyclePolicyConfig config : StackTemplateRegistry.LIFECYCLE_POLICY_CONFIGS) { crc32.update(loadTemplate(config.getFileName())); } for (IndexTemplateConfig config : StackTemplateRegistry.getComposableTemplateConfigsAsConfigs()) { crc32.update(loadTemplate(config.getFileName())); } for (IngestPipelineConfig config : StackTemplateRegistry.INGEST_PIPELINE_CONFIGS) { crc32.update(loadTemplate(config.getFileName())); } String computedChecksum = Long.toHexString(crc32.getValue()); assertEquals( "The StackTemplateRegistry.REGISTRY_VERSION must be incremented when templates are changed. " + "Please update REGISTRY_VERSION to " + (StackTemplateRegistry.REGISTRY_VERSION + 1) + " and update COMPUTED_CHECKSUM to \"" + computedChecksum + "\"", StackTemplateRegistry.COMPUTED_CHECKSUM, computedChecksum ); } private byte[] loadTemplate(String name) throws IOException { try (InputStream is = StackTemplateRegistry.class.getResourceAsStream(name)) { if (is == null) { throw new IOException("Template [" + name + "] not found"); } return is.readAllBytes(); } } // ------------- /** * A client that delegates to a verifying function for action/request/listener */ public static
StackTemplateRegistryTests
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_containsSequence_Test.java
{ "start": 969, "end": 1340 }
class ____ extends ByteArrayAssertBaseTest { @Override protected ByteArrayAssert invoke_api_method() { return assertions.containsSequence((byte) 6, (byte) 8); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsSequence(getInfo(assertions), getActual(assertions), arrayOf(6, 8)); } }
ByteArrayAssert_containsSequence_Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/ActionRequestLazyBuilder.java
{ "start": 647, "end": 830 }
class ____ similar to ActionRequestBuilder, except that it does not build the request until the request() method is called. * @param <Request> * @param <Response> */ public abstract
is
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/net/ssl/StoreConfigurationException.java
{ "start": 869, "end": 1273 }
class ____ extends Exception { private static final long serialVersionUID = 1L; public StoreConfigurationException(final Exception e) { super(e); } public StoreConfigurationException(final String message) { super(message); } public StoreConfigurationException(final String message, final Exception e) { super(message, e); } }
StoreConfigurationException
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/stmt/OracleSelectTableReference.java
{ "start": 1096, "end": 5056 }
class ____ extends SQLExprTableSource implements OracleSelectTableSource { private boolean only; protected PartitionExtensionClause partition; protected SampleClause sampleClause; public OracleSelectTableReference() { } public OracleSelectTableReference(SQLExpr expr) { this.setExpr(expr); } public PartitionExtensionClause getPartition() { return partition; } public void setPartition(PartitionExtensionClause partition) { if (partition != null) { partition.setParent(this); } this.partition = partition; } public boolean isOnly() { return this.only; } public void setOnly(boolean only) { this.only = only; } public SampleClause getSampleClause() { return sampleClause; } public void setSampleClause(SampleClause sampleClause) { if (sampleClause != null) { sampleClause.setParent(this); } this.sampleClause = sampleClause; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor instanceof OracleASTVisitor) { this.accept0((OracleASTVisitor) visitor); } else { super.accept0(visitor); } } protected void accept0(OracleASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, this.expr); acceptChild(visitor, this.partition); acceptChild(visitor, this.sampleClause); acceptChild(visitor, this.pivot); acceptChild(visitor, this.unpivot); } visitor.endVisit(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } OracleSelectTableReference that = (OracleSelectTableReference) o; if (only != that.only) { return false; } if (pivot != null ? !pivot.equals(that.pivot) : that.pivot != null) { return false; } if (unpivot != null ? !unpivot.equals(that.unpivot) : that.unpivot != null) { return false; } if (partition != null ? !partition.equals(that.partition) : that.partition != null) { return false; } if (sampleClause != null ? !sampleClause.equals(that.sampleClause) : that.sampleClause != null) { return false; } return flashback != null ? flashback.equals(that.flashback) : that.flashback == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (only ? 1 : 0); result = 31 * result + (pivot != null ? pivot.hashCode() : 0); result = 31 * result + (unpivot != null ? unpivot.hashCode() : 0); result = 31 * result + (partition != null ? partition.hashCode() : 0); result = 31 * result + (sampleClause != null ? sampleClause.hashCode() : 0); result = 31 * result + (flashback != null ? flashback.hashCode() : 0); return result; } public String toString() { return SQLUtils.toOracleString(this); } public OracleSelectTableReference clone() { OracleSelectTableReference x = new OracleSelectTableReference(); cloneTo(x); x.only = only; if (pivot != null) { x.setPivot(pivot.clone()); } if (unpivot != null) { x.setUnpivot(unpivot.clone()); } if (partition != null) { x.setPartition(partition.clone()); } if (sampleClause != null) { x.setSampleClause(sampleClause.clone()); } if (flashback != null) { setFlashback(flashback.clone()); } return x; } }
OracleSelectTableReference
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/staticmethod/StaticMethodInjectionTest.java
{ "start": 1071, "end": 1398 }
class ____ { static Head head; // The parameter is injected CombineHarvester(Head head) { CombineHarvester.head = head; } // This one is ignored @Inject static void init(Head head) { CombineHarvester.head = head; } } }
CombineHarvester
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/basic/DetachedElementTest.java
{ "start": 3054, "end": 3296 }
class ____ { @Id long id; @OneToMany(mappedBy = "parent") List<ListElement> children = new ArrayList<>(); public EntityWithList(int id) { this.id = id; } protected EntityWithList() {} } @Entity public static
EntityWithList
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/BoundedOneInput.java
{ "start": 1236, "end": 2312 }
interface ____ { /** * It is notified that no more data will arrive from the input. * * <p>Stateful operators need to be aware that a restart with rescaling may occur after * receiving this notification. A changed source split assignment may imply that the same * subtask of this operator that received endInput, has its state after endInput snapshotted, * and will receive new data after restart. Hence, the state should not contain any finalization * that would make it impossible to process new data. * * <p><b>WARNING:</b> It is not safe to use this method to commit any transactions or other side * effects! You can use this method to flush any buffered data that can later on be committed * e.g. in a {@link StreamOperator#notifyCheckpointComplete(long)}. * * <p><b>NOTE:</b> Given it is semantically very similar to the {@link StreamOperator#finish()} * method. It might be dropped in favour of the other method at some point in time. */ void endInput() throws Exception; }
BoundedOneInput
java
google__guava
android/guava/src/com/google/common/util/concurrent/AbstractCatchingFuture.java
{ "start": 8569, "end": 9188 }
class ____<V extends @Nullable Object, X extends Throwable> extends AbstractCatchingFuture<V, X, Function<? super X, ? extends V>, V> { CatchingFuture( ListenableFuture<? extends V> input, Class<X> exceptionType, Function<? super X, ? extends V> fallback) { super(input, exceptionType, fallback); } @Override @ParametricNullness V doFallback(Function<? super X, ? extends V> fallback, X cause) throws Exception { return fallback.apply(cause); } @Override void setResult(@ParametricNullness V result) { set(result); } } }
CatchingFuture
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/classes/Classes_assertHasMethods_Test.java
{ "start": 5384, "end": 5493 }
class ____ implements InterfaceInheritingDefaultMethod { } private
ClassWithIndirectlyInheritedDefaultMethod
java
greenrobot__greendao
DaoCore/src/main/java/org/greenrobot/greendao/database/Database.java
{ "start": 828, "end": 1322 }
interface ____ { Cursor rawQuery(String sql, String[] selectionArgs); void execSQL(String sql) throws SQLException; void beginTransaction(); void endTransaction(); boolean inTransaction(); void setTransactionSuccessful(); void execSQL(String sql, Object[] bindArgs) throws SQLException; DatabaseStatement compileStatement(String sql); boolean isDbLockedByCurrentThread(); boolean isOpen(); void close(); Object getRawDatabase(); }
Database
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/watermarkstatus/StatusWatermarkValveTest.java
{ "start": 21856, "end": 23033 }
class ____ implements PushingAsyncDataInput.DataOutput { private BlockingQueue<StreamElement> allOutputs = new LinkedBlockingQueue<>(); @Override public void emitWatermark(Watermark watermark) { allOutputs.add(watermark); } @Override public void emitWatermarkStatus(WatermarkStatus watermarkStatus) { allOutputs.add(watermarkStatus); } @Override public void emitRecord(StreamRecord record) { throw new UnsupportedOperationException(); } @Override public void emitLatencyMarker(LatencyMarker latencyMarker) { throw new UnsupportedOperationException(); } @Override public void emitRecordAttributes(RecordAttributes recordAttributes) throws Exception { throw new UnsupportedOperationException(); } @Override public void emitWatermark(WatermarkEvent watermark) throws Exception { throw new UnsupportedOperationException(); } public StreamElement popLastSeenOutput() { return allOutputs.poll(); } } }
StatusWatermarkOutput
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/util/RyuFloatTest.java
{ "start": 146, "end": 3509 }
class ____ extends TestCase { public void test_for_ryu() throws Exception { Random random = new Random(); for (int i = 0; i < 1000 * 1000 * 10; ++i) { float value = random.nextFloat(); String str1 = Float.toString(value); String str2 = RyuFloat.toString(value); if (!str1.equals(str2)) { boolean cmp = (Float.parseFloat(str1) == Float.parseFloat(str2)); System.out.println(str1 + " -> " + str2 + " : " + cmp); assertTrue(cmp); // assertTrue(Float.parseFloat(str1) == Float.parseFloat(str2)); } } } public void test_0() throws Exception { float[] values = new float[] { Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.MIN_VALUE, Float.MAX_VALUE, 0, 0.0f, -0.0f, Integer.MAX_VALUE, Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, Float.intBitsToFloat(0x80000000), 1.0f, -1f, Float.intBitsToFloat(0x00800000), 1.0E7f, 9999999.0f, 0.001f, 0.0009999999f, Float.intBitsToFloat(0x7f7fffff), Float.intBitsToFloat(0x00000001), 3.3554448E7f, 8.999999E9f, 3.4366717E10f, 0.33007812f, Float.intBitsToFloat(0x5D1502F9), Float.intBitsToFloat(0x5D9502F9), Float.intBitsToFloat(0x5E1502F9), 4.7223665E21f, 8388608.0f, 1.6777216E7f, 3.3554436E7f, 6.7131496E7f, 1.9310392E-38f, -2.47E-43f, 1.993244E-38f, 4103.9003f, 5.3399997E9f, 6.0898E-39f, 0.0010310042f, 2.8823261E17f, 7.038531E-26f, 9.2234038E17f, 6.7108872E7f, 1.0E-44f, 2.816025E14f, 9.223372E18f, 1.5846085E29f, 1.1811161E19f, 5.368709E18f, 4.6143165E18f, 0.007812537f, 1.4E-45f, 1.18697724E20f, 1.00014165E-36f, 200f, 3.3554432E7f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 1.1f, 1.01f, 1.001f, 1.0001f, 1.00001f, 1.000001f, 1.0000001f, }; for (float value : values) { String str1 = Float.toString(value); String str2 = RyuFloat.toString(value); if (!str1.equals(str2)) { boolean cmp = (Float.parseFloat(str1) == Float.parseFloat(str2)); System.out.println(str1 + " -> " + str2 + " : " + cmp); assertTrue(cmp); } } } }
RyuFloatTest
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java
{ "start": 22703, "end": 23276 }
class ____ extends MappedDataSourceProperties<BasicDataSource> { MappedDbcp2DataSource() { add(DataSourceProperty.URL, BasicDataSource::getUrl, BasicDataSource::setUrl); add(DataSourceProperty.DRIVER_CLASS_NAME, BasicDataSource::getDriverClassName, BasicDataSource::setDriverClassName); add(DataSourceProperty.USERNAME, BasicDataSource::getUserName, BasicDataSource::setUsername); add(DataSourceProperty.PASSWORD, null, BasicDataSource::setPassword); } } /** * {@link DataSourceProperties} for Oracle Pool. */ private static
MappedDbcp2DataSource
java
google__guava
android/guava/src/com/google/common/base/FinalizableReferenceQueue.java
{ "start": 6084, "end": 6269 }
class ____ remain, the Finalizer * thread keeps an indirect strong reference to the queue in ReferenceMap, which keeps the * Finalizer running, and as a result, the application
loader
java
google__guice
extensions/dagger-adapter/src/com/google/inject/daggeradapter/DaggerMethodScanner.java
{ "start": 6510, "end": 9043 }
class ____<K> { final TypeLiteral<K> typeLiteral; final K key; MapKeyData(TypeLiteral<K> typeLiteral, K key) { this.typeLiteral = typeLiteral; this.key = key; } // We can't verify the compatibility of the type arguments here, but by definition they must be // aligned @SuppressWarnings({"unchecked", "rawtypes"}) static <K> MapKeyData<K> create(TypeLiteral<?> typeLiteral, Object key) { return new MapKeyData(typeLiteral, key); } } private static <T> Multibinder<T> newSetBinder( Binder binder, TypeLiteral<T> typeLiteral, Annotation possibleAnnotation) { return possibleAnnotation == null ? Multibinder.newSetBinder(binder, typeLiteral) : Multibinder.newSetBinder(binder, typeLiteral, possibleAnnotation); } private static <K, V> MapBinder<K, V> newMapBinder( Binder binder, TypeLiteral<K> keyType, TypeLiteral<V> valueType, Annotation possibleAnnotation) { return possibleAnnotation == null ? MapBinder.newMapBinder(binder, keyType, valueType) : MapBinder.newMapBinder(binder, keyType, valueType, possibleAnnotation); } private <T> void configureMultibindsKey(Binder binder, Method method, Key<T> key) { Class<?> rawReturnType = method.getReturnType(); ImmutableList<? extends TypeLiteral<?>> typeParameters = Arrays.stream(((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()) .map(TypeLiteral::get) .collect(toImmutableList()); if (rawReturnType.equals(Set.class)) { newSetBinder(binder, typeParameters.get(0), key.getAnnotation()); } else if (rawReturnType.equals(Map.class)) { newMapBinder(binder, typeParameters.get(0), typeParameters.get(1), key.getAnnotation()); } else { throw new AssertionError( "@dagger.Multibinds can only be used with Sets or Map, found: " + method.getGenericReturnType()); } } @Override public boolean equals(Object object) { if (object instanceof DaggerMethodScanner) { DaggerMethodScanner that = (DaggerMethodScanner) object; return this.predicate.equals(that.predicate); } return false; } @Override public int hashCode() { return predicate.hashCode(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("predicate", predicate).toString(); } private DaggerMethodScanner(Predicate<Method> predicate) { this.predicate = predicate; } }
MapKeyData
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/PathAssertBaseTest.java
{ "start": 990, "end": 1718 }
class ____ extends BaseTestTemplate<PathAssert, Path> { protected Paths paths; protected Charset defaultCharset; protected Charset otherCharset; @Override protected PathAssert create_assertions() { return new PathAssert(mock(Path.class)); } @Override protected void inject_internal_objects() { super.inject_internal_objects(); paths = mock(Paths.class); assertions.paths = paths; defaultCharset = defaultCharset(); otherCharset = getDifferentCharsetFrom(defaultCharset); } protected Charset getCharset(PathAssert someAssertions) { return someAssertions.charset; } protected Paths getPaths(PathAssert someAssertions) { return someAssertions.paths; } }
PathAssertBaseTest
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/ByteConsumer.java
{ "start": 1064, "end": 2279 }
interface ____ { /** NOP singleton */ ByteConsumer NOP = t -> { /* NOP */ }; /** * Gets the NOP singleton. * * @return The NOP singleton. */ static ByteConsumer nop() { return NOP; } /** * Accepts the given arguments. * * @param value the input argument */ void accept(byte value); /** * Returns a composed {@link ByteConsumer} that performs, in sequence, this operation followed by the {@code after} operation. If performing either * operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the {@code after} * operation will not be performed. * * @param after the operation to perform after this operation * @return a composed {@link ByteConsumer} that performs in sequence this operation followed by the {@code after} operation * @throws NullPointerException if {@code after} is null */ default ByteConsumer andThen(final ByteConsumer after) { Objects.requireNonNull(after); return (final byte t) -> { accept(t); after.accept(t); }; } }
ByteConsumer
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClass.java
{ "start": 5109, "end": 5864 }
class ____ been registered through a scan * @since 6.2 */ ConfigurationClass(AnnotationMetadata metadata, String beanName, boolean scanned) { Assert.notNull(beanName, "Bean name must not be null"); this.metadata = metadata; this.resource = new DescriptiveResource(metadata.getClassName()); this.beanName = beanName; this.scanned = scanned; } AnnotationMetadata getMetadata() { return this.metadata; } Resource getResource() { return this.resource; } String getSimpleName() { return ClassUtils.getShortName(getMetadata().getClassName()); } void setBeanName(@Nullable String beanName) { this.beanName = beanName; } @Nullable String getBeanName() { return this.beanName; } /** * Return whether this configuration
has
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-cos/src/main/java/org/apache/hadoop/fs/cosn/BufferPool.java
{ "start": 1497, "end": 8465 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(BufferPool.class); private static BufferPool ourInstance = new BufferPool(); /** * Use this method to get the instance of BufferPool. * * @return the instance of BufferPool */ public static BufferPool getInstance() { return ourInstance; } private BlockingQueue<ByteBuffer> bufferPool = null; private long singleBufferSize = 0; private File diskBufferDir = null; private AtomicBoolean isInitialize = new AtomicBoolean(false); private BufferPool() { } private File createDir(String dirPath) throws IOException { File dir = new File(dirPath); if (!dir.exists()) { LOG.debug("Buffer dir: [{}] does not exists. create it first.", dirPath); if (dir.mkdirs()) { if (!dir.setWritable(true) || !dir.setReadable(true) || !dir.setExecutable(true)) { LOG.warn("Set the buffer dir: [{}]'s permission [writable," + "readable, executable] failed.", dir.getAbsolutePath()); } LOG.debug("Buffer dir: [{}] is created successfully.", dir.getAbsolutePath()); } else { // Once again, check if it has been created successfully. // Prevent problems created by multiple processes at the same time. if (!dir.exists()) { throw new IOException("buffer dir:" + dir.getAbsolutePath() + " is created unsuccessfully"); } } } else { LOG.debug("buffer dir: {} already exists.", dirPath); } return dir; } /** * Create buffers correctly by reading the buffer file directory, * buffer pool size,and file block size in the configuration. * * @param conf Provides configurations for the Hadoop runtime * @throws IOException Configuration errors, * insufficient or no access for memory or * disk space may cause this exception */ public synchronized void initialize(Configuration conf) throws IOException { if (this.isInitialize.get()) { return; } this.singleBufferSize = conf.getLong(CosNConfigKeys.COSN_BLOCK_SIZE_KEY, CosNConfigKeys.DEFAULT_BLOCK_SIZE); // The block size of CosN can only support up to 2GB. if (this.singleBufferSize < Constants.MIN_PART_SIZE || this.singleBufferSize > Constants.MAX_PART_SIZE) { String exceptionMsg = String.format( "The block size of CosN is limited to %d to %d", Constants.MIN_PART_SIZE, Constants.MAX_PART_SIZE); throw new IOException(exceptionMsg); } long memoryBufferLimit = conf.getLong( CosNConfigKeys.COSN_UPLOAD_BUFFER_SIZE_KEY, CosNConfigKeys.DEFAULT_UPLOAD_BUFFER_SIZE); this.diskBufferDir = this.createDir(conf.get( CosNConfigKeys.COSN_BUFFER_DIR_KEY, CosNConfigKeys.DEFAULT_BUFFER_DIR)); int bufferPoolSize = (int) (memoryBufferLimit / this.singleBufferSize); if (0 == bufferPoolSize) { throw new IOException( String.format("The total size of the buffer [%d] is " + "smaller than a single block [%d]." + "please consider increase the buffer size " + "or decrease the block size", memoryBufferLimit, this.singleBufferSize)); } this.bufferPool = new LinkedBlockingQueue<>(bufferPoolSize); for (int i = 0; i < bufferPoolSize; i++) { this.bufferPool.add(ByteBuffer.allocateDirect( (int) this.singleBufferSize)); } this.isInitialize.set(true); } /** * Check if the buffer pool has been initialized. * * @throws IOException if the buffer pool is not initialized */ private void checkInitialize() throws IOException { if (!this.isInitialize.get()) { throw new IOException( "The buffer pool has not been initialized yet"); } } /** * Obtain a buffer from this buffer pool through the method. * * @param bufferSize expected buffer size to get * @return a buffer wrapper that satisfies the bufferSize. * @throws IOException if the buffer pool not initialized, * or the bufferSize parameter is not within * the range[1MB to the single buffer size] */ public ByteBufferWrapper getBuffer(int bufferSize) throws IOException { this.checkInitialize(); if (bufferSize > 0 && bufferSize <= this.singleBufferSize) { ByteBufferWrapper byteBufferWrapper = this.getByteBuffer(); if (null == byteBufferWrapper) { // Use a disk buffer when the memory buffer is not enough byteBufferWrapper = this.getMappedBuffer(); } return byteBufferWrapper; } else { String exceptionMsg = String.format( "Parameter buffer size out of range: 1048576 to %d", this.singleBufferSize ); throw new IOException(exceptionMsg); } } /** * Get a ByteBufferWrapper from the buffer pool. * * @return a new byte buffer wrapper * @throws IOException if the buffer pool is not initialized */ private ByteBufferWrapper getByteBuffer() throws IOException { this.checkInitialize(); ByteBuffer buffer = this.bufferPool.poll(); return buffer == null ? null : new ByteBufferWrapper(buffer); } /** * Get a mapped buffer from the buffer pool. * * @return a new mapped buffer * @throws IOException If the buffer pool is not initialized. * or some I/O error occurs */ private ByteBufferWrapper getMappedBuffer() throws IOException { this.checkInitialize(); File tmpFile = File.createTempFile(Constants.BLOCK_TMP_FILE_PREFIX, Constants.BLOCK_TMP_FILE_SUFFIX, this.diskBufferDir); tmpFile.deleteOnExit(); RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw"); raf.setLength(this.singleBufferSize); MappedByteBuffer buf = raf.getChannel().map( FileChannel.MapMode.READ_WRITE, 0, this.singleBufferSize); return new ByteBufferWrapper(buf, raf, tmpFile); } /** * return the byte buffer wrapper to the buffer pool. * * @param byteBufferWrapper the byte buffer wrapper getting from the pool * @throws InterruptedException if interrupted while waiting * @throws IOException some io error occurs */ public void returnBuffer(ByteBufferWrapper byteBufferWrapper) throws InterruptedException, IOException { if (null == this.bufferPool || null == byteBufferWrapper) { return; } if (byteBufferWrapper.isDiskBuffer()) { byteBufferWrapper.close(); } else { ByteBuffer byteBuffer = byteBufferWrapper.getByteBuffer(); if (null != byteBuffer) { byteBuffer.clear(); LOG.debug("Return the buffer to the buffer pool."); if (!this.bufferPool.offer(byteBuffer)) { LOG.error("Return the buffer to buffer pool failed."); } } } } }
BufferPool
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/interpolation/StringVisitorModelInterpolator.java
{ "start": 3607, "end": 5941 }
interface ____ { String interpolate(String value); } @Override public Model interpolateModel( Model model, File projectDir, ModelBuildingRequest config, ModelProblemCollector problems) { List<? extends ValueSource> valueSources = createValueSources(model, projectDir, config, problems); List<? extends InterpolationPostProcessor> postProcessors = createPostProcessors(model, projectDir, config); InnerInterpolator innerInterpolator = createInterpolator(valueSources, postProcessors, problems); new ModelVisitor(innerInterpolator).visit(model); return model; } private InnerInterpolator createInterpolator( List<? extends ValueSource> valueSources, List<? extends InterpolationPostProcessor> postProcessors, final ModelProblemCollector problems) { final Map<String, String> cache = new HashMap<>(); final StringSearchInterpolator interpolator = new StringSearchInterpolator(); interpolator.setCacheAnswers(true); for (ValueSource vs : valueSources) { interpolator.addValueSource(vs); } for (InterpolationPostProcessor postProcessor : postProcessors) { interpolator.addPostProcessor(postProcessor); } final RecursionInterceptor recursionInterceptor = createRecursionInterceptor(); return new InnerInterpolator() { @Override public String interpolate(String value) { if (value != null && value.contains("${")) { String c = cache.get(value); if (c == null) { try { c = interpolator.interpolate(value, recursionInterceptor); } catch (InterpolationException e) { problems.add(new ModelProblemCollectorRequest(Severity.ERROR, Version.BASE) .setMessage(e.getMessage()) .setException(e)); } cache.put(value, c); } return c; } return value; } }; } @SuppressWarnings("StringEquality") private static final
InnerInterpolator
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/MatchersTest.java
{ "start": 7575, "end": 8273 }
class ____ { // BUG: Diagnostic contains: public java.util.ArrayList<String> matches() { return null; } public java.util.HashSet<String> doesntMatch() { return null; } } """) .doTest(); } @Test public void methodReturnsType() { Matcher<MethodTree> matcher = methodReturns(typeFromString("java.lang.Number")); CompilationTestHelper.newInstance(methodTreeCheckerSupplier(matcher), getClass()) .addSourceLines( "test/MethodReturnsSubtypeTest.java", """ package test; public
MethodReturnsSubtypeTest
java
apache__maven
api/maven-api-plugin/src/test/java/org/apache/maven/api/plugin/descriptor/another/ExtendedPluginDescriptorTest.java
{ "start": 1632, "end": 2760 }
class ____ extends PluginDescriptor.Builder { protected String additionalField; Builder() { super(false); } public Builder additionalField(String additionalField) { this.additionalField = additionalField; return this; } @Override public ExtendedPluginDescriptor build() { return new ExtendedPluginDescriptor(this); } } } @Test void testExtendedPluginDescriptor() { ExtendedPluginDescriptor.Builder builder = new ExtendedPluginDescriptor.Builder(); // make sure to call the subclasses' builder methods first, otherwise fluent API would not work builder.additionalField("additional") .groupId("org.apache.maven") .artifactId("maven-plugin-api") .version("1.0.0"); ExtendedPluginDescriptor descriptor = builder.build(); assertEquals("additional", descriptor.getAdditionalField()); assertEquals("org.apache.maven", descriptor.getGroupId()); } }
Builder
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/arg_name_based_constructor_automapping/User.java
{ "start": 734, "end": 1127 }
class ____ { private final Integer id; private final String name; private Long team; public User(Integer id, String name) { this.id = id; this.name = name + "!"; } public Integer getId() { return id; } public String getName() { return name; } public void setTeam(Long team) { this.team = team; } public Long getTeam() { return team; } }
User
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/conditionaldeps/ExcludedDirectConditionalDependencyTest.java
{ "start": 229, "end": 1564 }
class ____ extends BootstrapFromOriginalJarTestBase { @Override protected TsArtifact composeApplication() { final TsQuarkusExt extA = new TsQuarkusExt("ext-a"); final TsQuarkusExt extB = new TsQuarkusExt("ext-b"); extB.setDependencyCondition(extA); install(extB); final TsQuarkusExt extD = new TsQuarkusExt("ext-d"); final TsQuarkusExt extE = new TsQuarkusExt("ext-e"); extE.setDependencyCondition(extD); install(extE); final TsQuarkusExt extC = new TsQuarkusExt("ext-c"); extC.setConditionalDeps(extB, extE); addToExpectedLib(extA.getRuntime()); addToExpectedLib(extC.getRuntime()); addToExpectedLib(extD.getRuntime()); addToExpectedLib(extE.getRuntime()); return TsArtifact.jar("app") .addManagedDependency(platformDescriptor()) .addManagedDependency(platformProperties()) .addDependency(extC, extB.getRuntime()) .addDependency(extA) .addDependency(extD); } @Override protected String[] expectedExtensionDependencies() { return new String[] { "ext-a", "ext-c", "ext-d", "ext-e" }; } }
ExcludedDirectConditionalDependencyTest
java
quarkusio__quarkus
extensions/reactive-db2-client/runtime/src/main/java/io/quarkus/reactive/db2/client/runtime/DB2PoolSupport.java
{ "start": 79, "end": 342 }
class ____ { private final Set<String> db2PoolNames; public DB2PoolSupport(Set<String> db2PoolNames) { this.db2PoolNames = Set.copyOf(db2PoolNames); } public Set<String> getDB2PoolNames() { return db2PoolNames; } }
DB2PoolSupport
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/util/HadoopCompressionCodec.java
{ "start": 1371, "end": 2283 }
enum ____ { NONE(null), UNCOMPRESSED(null), BZIP2(new BZip2Codec()), DEFLATE(new DeflateCodec()), GZIP(new GzipCodec()), LZ4(new Lz4Codec()), SNAPPY(new SnappyCodec()); // TODO supports ZStandardCodec private final CompressionCodec compressionCodec; HadoopCompressionCodec(CompressionCodec compressionCodec) { this.compressionCodec = compressionCodec; } public CompressionCodec getCompressionCodec() { return this.compressionCodec; } private static final EnumMap<HadoopCompressionCodec, String> codecNameMap = Arrays.stream(HadoopCompressionCodec.values()).collect( Collectors.toMap( codec -> codec, codec -> codec.name().toLowerCase(Locale.ROOT), (oldValue, newValue) -> oldValue, () -> new EnumMap<>(HadoopCompressionCodec.class))); public String lowerCaseName() { return codecNameMap.get(this); } }
HadoopCompressionCodec
java
spring-projects__spring-framework
spring-context-support/src/main/java/org/springframework/scheduling/quartz/SimpleThreadPoolTaskExecutor.java
{ "start": 1823, "end": 3077 }
class ____ extends SimpleThreadPool implements AsyncTaskExecutor, SchedulingTaskExecutor, InitializingBean, DisposableBean { private boolean waitForJobsToCompleteOnShutdown = false; /** * Set whether to wait for running jobs to complete on shutdown. * Default is "false". * @see org.quartz.simpl.SimpleThreadPool#shutdown(boolean) */ public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) { this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown; } @Override public void afterPropertiesSet() throws SchedulerConfigException { initialize(); } @Override public void execute(Runnable task) { Assert.notNull(task, "Runnable must not be null"); if (!runInThread(task)) { throw new SchedulingException("Quartz SimpleThreadPool already shut down"); } } @Override public Future<?> submit(Runnable task) { FutureTask<Object> future = new FutureTask<>(task, null); execute(future); return future; } @Override public <T> Future<T> submit(Callable<T> task) { FutureTask<T> future = new FutureTask<>(task); execute(future); return future; } @Override public void destroy() { shutdown(this.waitForJobsToCompleteOnShutdown); } }
SimpleThreadPoolTaskExecutor
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/clause/MySqlCaseStatement.java
{ "start": 2680, "end": 3527 }
class ____ extends MySqlObjectImpl { private SQLExpr condition; private List<SQLStatement> statements = new ArrayList<SQLStatement>(); @Override public void accept0(MySqlASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, condition); acceptChild(visitor, statements); } visitor.endVisit(this); } public SQLExpr getCondition() { return condition; } public void setCondition(SQLExpr condition) { this.condition = condition; } public List<SQLStatement> getStatements() { return statements; } public void setStatements(List<SQLStatement> statements) { this.statements = statements; } } }
MySqlWhenStatement
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLWhileStatement.java
{ "start": 851, "end": 2741 }
class ____ extends SQLStatementImpl implements SQLReplaceable { //while expr private SQLExpr condition; private List<SQLStatement> statements = new ArrayList<SQLStatement>(); //while label name private String labelName; public String getLabelName() { return labelName; } public void setLabelName(String labelName) { this.labelName = labelName; } public void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, condition); acceptChild(visitor, statements); } visitor.endVisit(this); } @Override public List<SQLObject> getChildren() { List<SQLObject> children = new ArrayList<SQLObject>(); children.add(condition); children.addAll(this.statements); return children; } public List<SQLStatement> getStatements() { return statements; } public void setStatements(List<SQLStatement> statements) { this.statements = statements; } public SQLExpr getCondition() { return condition; } public void setCondition(SQLExpr x) { if (x != null) { x.setParent(this); } this.condition = x; } public SQLWhileStatement clone() { SQLWhileStatement x = new SQLWhileStatement(); if (condition != null) { x.setCondition(condition.clone()); } for (SQLStatement stmt : statements) { SQLStatement stmt2 = stmt.clone(); stmt2.setParent(x); x.statements.add(stmt2); } x.labelName = labelName; return x; } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (condition == expr) { setCondition(target); return true; } return false; } }
SQLWhileStatement
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/metrics/ProxyMetricsManager.java
{ "start": 3277, "end": 11915 }
class ____ implements StartAndShutdown { private final static Logger log = LoggerFactory.getLogger(LoggerName.PROXY_LOGGER_NAME); private static ProxyConfig proxyConfig; private final static Map<String, String> LABEL_MAP = new HashMap<>(); public static Supplier<AttributesBuilder> attributesBuilderSupplier; private OtlpGrpcMetricExporter metricExporter; private PeriodicMetricReader periodicMetricReader; private PrometheusHttpServer prometheusHttpServer; private MetricExporter loggingMetricExporter; public static ObservableLongGauge proxyUp = null; public static void initLocalMode(BrokerMetricsManager brokerMetricsManager, ProxyConfig proxyConfig) { if (proxyConfig.getMetricsExporterType() == MetricsExporterType.DISABLE) { return; } ProxyMetricsManager.proxyConfig = proxyConfig; LABEL_MAP.put(LABEL_NODE_TYPE, NODE_TYPE_PROXY); LABEL_MAP.put(LABEL_CLUSTER_NAME, proxyConfig.getProxyClusterName()); LABEL_MAP.put(LABEL_NODE_ID, proxyConfig.getProxyName()); LABEL_MAP.put(LABEL_PROXY_MODE, proxyConfig.getProxyMode().toLowerCase()); initMetrics(brokerMetricsManager.getBrokerMeter(), brokerMetricsManager::newAttributesBuilder); } public static ProxyMetricsManager initClusterMode(ProxyConfig proxyConfig) { ProxyMetricsManager.proxyConfig = proxyConfig; return new ProxyMetricsManager(); } public static AttributesBuilder newAttributesBuilder() { AttributesBuilder attributesBuilder; if (attributesBuilderSupplier == null) { attributesBuilder = Attributes.builder(); LABEL_MAP.forEach(attributesBuilder::put); return attributesBuilder; } attributesBuilder = attributesBuilderSupplier.get(); LABEL_MAP.forEach(attributesBuilder::put); return attributesBuilder; } private static void initMetrics(Meter meter, Supplier<AttributesBuilder> attributesBuilderSupplier) { ProxyMetricsManager.attributesBuilderSupplier = attributesBuilderSupplier; proxyUp = meter.gaugeBuilder(GAUGE_PROXY_UP) .setDescription("proxy status") .ofLongs() .buildWithCallback(measurement -> measurement.record(1, newAttributesBuilder().build())); } public ProxyMetricsManager() { } private boolean checkConfig() { if (proxyConfig == null) { return false; } MetricsExporterType exporterType = proxyConfig.getMetricsExporterType(); if (!exporterType.isEnable()) { return false; } switch (exporterType) { case OTLP_GRPC: return StringUtils.isNotBlank(proxyConfig.getMetricsGrpcExporterTarget()); case PROM: return true; case LOG: return true; } return false; } @Override public void start() throws Exception { MetricsExporterType metricsExporterType = proxyConfig.getMetricsExporterType(); if (metricsExporterType == MetricsExporterType.DISABLE) { return; } if (!checkConfig()) { log.error("check metrics config failed, will not export metrics"); return; } String labels = proxyConfig.getMetricsLabel(); if (StringUtils.isNotBlank(labels)) { List<String> kvPairs = Splitter.on(',').omitEmptyStrings().splitToList(labels); for (String item : kvPairs) { String[] split = item.split(":"); if (split.length != 2) { log.warn("metricsLabel is not valid: {}", labels); continue; } LABEL_MAP.put(split[0], split[1]); } } if (proxyConfig.isMetricsInDelta()) { LABEL_MAP.put(LABEL_AGGREGATION, AGGREGATION_DELTA); } LABEL_MAP.put(LABEL_NODE_TYPE, NODE_TYPE_PROXY); LABEL_MAP.put(LABEL_CLUSTER_NAME, proxyConfig.getProxyClusterName()); LABEL_MAP.put(LABEL_NODE_ID, proxyConfig.getProxyName()); LABEL_MAP.put(LABEL_PROXY_MODE, proxyConfig.getProxyMode().toLowerCase()); SdkMeterProviderBuilder providerBuilder = SdkMeterProvider.builder() .setResource(Resource.empty()); if (metricsExporterType == MetricsExporterType.OTLP_GRPC) { String endpoint = proxyConfig.getMetricsGrpcExporterTarget(); if (!endpoint.startsWith("http")) { endpoint = "https://" + endpoint; } OtlpGrpcMetricExporterBuilder metricExporterBuilder = OtlpGrpcMetricExporter.builder() .setEndpoint(endpoint) .setTimeout(proxyConfig.getMetricGrpcExporterTimeOutInMills(), TimeUnit.MILLISECONDS) .setAggregationTemporalitySelector(type -> { if (proxyConfig.isMetricsInDelta() && (type == InstrumentType.COUNTER || type == InstrumentType.OBSERVABLE_COUNTER || type == InstrumentType.HISTOGRAM)) { return AggregationTemporality.DELTA; } return AggregationTemporality.CUMULATIVE; }); String headers = proxyConfig.getMetricsGrpcExporterHeader(); if (StringUtils.isNotBlank(headers)) { Map<String, String> headerMap = new HashMap<>(); List<String> kvPairs = Splitter.on(',').omitEmptyStrings().splitToList(headers); for (String item : kvPairs) { String[] split = item.split(":"); if (split.length != 2) { log.warn("metricsGrpcExporterHeader is not valid: {}", headers); continue; } headerMap.put(split[0], split[1]); } headerMap.forEach(metricExporterBuilder::addHeader); } metricExporter = metricExporterBuilder.build(); periodicMetricReader = PeriodicMetricReader.builder(metricExporter) .setInterval(proxyConfig.getMetricGrpcExporterIntervalInMills(), TimeUnit.MILLISECONDS) .build(); providerBuilder.registerMetricReader(periodicMetricReader); } if (metricsExporterType == MetricsExporterType.PROM) { String promExporterHost = proxyConfig.getMetricsPromExporterHost(); if (StringUtils.isBlank(promExporterHost)) { promExporterHost = "0.0.0.0"; } prometheusHttpServer = PrometheusHttpServer.builder() .setHost(promExporterHost) .setPort(proxyConfig.getMetricsPromExporterPort()) .build(); providerBuilder.registerMetricReader(prometheusHttpServer); } if (metricsExporterType == MetricsExporterType.LOG) { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); loggingMetricExporter = OtlpJsonLoggingMetricExporter.create(proxyConfig.isMetricsInDelta() ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE); java.util.logging.Logger.getLogger(OtlpJsonLoggingMetricExporter.class.getName()).setLevel(java.util.logging.Level.FINEST); periodicMetricReader = PeriodicMetricReader.builder(loggingMetricExporter) .setInterval(proxyConfig.getMetricLoggingExporterIntervalInMills(), TimeUnit.MILLISECONDS) .build(); providerBuilder.registerMetricReader(periodicMetricReader); } Meter proxyMeter = OpenTelemetrySdk.builder() .setMeterProvider(providerBuilder.build()) .build() .getMeter(OPEN_TELEMETRY_METER_NAME); initMetrics(proxyMeter, null); } @Override public void shutdown() throws Exception { if (proxyConfig.getMetricsExporterType() == MetricsExporterType.OTLP_GRPC) { periodicMetricReader.forceFlush(); periodicMetricReader.shutdown(); metricExporter.shutdown(); } if (proxyConfig.getMetricsExporterType() == MetricsExporterType.PROM) { prometheusHttpServer.forceFlush(); prometheusHttpServer.shutdown(); } if (proxyConfig.getMetricsExporterType() == MetricsExporterType.LOG) { periodicMetricReader.forceFlush(); periodicMetricReader.shutdown(); loggingMetricExporter.shutdown(); } } }
ProxyMetricsManager
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/graph/basic/CoercingResultAssembler.java
{ "start": 598, "end": 1222 }
class ____<J> extends BasicResultAssembler<J> { public CoercingResultAssembler( int valuesArrayPosition, JavaType<J> assembledJavaType, BasicValueConverter<J, ?> valueConverter, boolean nestedInAggregateComponent) { super( valuesArrayPosition, assembledJavaType, valueConverter, nestedInAggregateComponent ); } /** * Access to the row value, coerced to expected type */ @Override public Object extractRawValue(RowProcessingState rowProcessingState) { return assembledJavaType.coerce( super.extractRawValue( rowProcessingState ), rowProcessingState.getSession() ); } }
CoercingResultAssembler
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/org/mapstruct/ap/test/bugs/_2197/Issue2197MapperImpl.java
{ "start": 430, "end": 756 }
class ____ implements Issue2197Mapper { @Override public _0Target map(Source source) { if ( source == null ) { return null; } String value = null; value = source.getValue(); _0Target target = new _0Target( value ); return target; } }
Issue2197MapperImpl
java
apache__camel
core/camel-cloud/src/generated/java/org/apache/camel/impl/cloud/CombinedServiceDiscoveryFactoryConfigurer.java
{ "start": 721, "end": 2548 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.impl.cloud.CombinedServiceDiscoveryFactory target = (org.apache.camel.impl.cloud.CombinedServiceDiscoveryFactory) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "servicediscoverylist": case "serviceDiscoveryList": target.setServiceDiscoveryList(property(camelContext, java.util.List.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "servicediscoverylist": case "serviceDiscoveryList": return java.util.List.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.impl.cloud.CombinedServiceDiscoveryFactory target = (org.apache.camel.impl.cloud.CombinedServiceDiscoveryFactory) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "servicediscoverylist": case "serviceDiscoveryList": return target.getServiceDiscoveryList(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "servicediscoverylist": case "serviceDiscoveryList": return org.apache.camel.cloud.ServiceDiscovery.class; default: return null; } } }
CombinedServiceDiscoveryFactoryConfigurer
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationWithFactoryBeanAndAutowiringTests.java
{ "start": 3222, "end": 3721 }
class ____ implements FactoryBean<String>, InitializingBean { private boolean initialized = false; @Override public void afterPropertiesSet() { this.initialized = true; } @Override public String getObject() { return "foo"; } @Override public Class<String> getObjectType() { return String.class; } @Override public boolean isSingleton() { return true; } public String getString() { return Boolean.toString(this.initialized); } } static
MyFactoryBean
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/support/FinalConfigInnerClassTestCase.java
{ "start": 874, "end": 968 }
class ____ { // Intentionally FINAL. @Configuration static final
FinalConfigInnerClassTestCase
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/SystemUtils.java
{ "start": 3800, "end": 4412 }
class ____ loaded, the value will be out of sync with that System property. * </p> * * @see SystemProperties#getJavaAwtFonts() * @since 2.1 * @deprecated Deprecated without replacement. */ @Deprecated public static final String JAVA_AWT_FONTS = SystemProperties.getJavaAwtFonts(); /** * A constant for the System Property {@code java.awt.graphicsenv}. * * <p> * Defaults to {@code null} if the runtime does not have security access to read this property or the property does not exist. * </p> * <p> * This value is initialized when the
is
java
elastic__elasticsearch
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/FixedCapacityExponentialHistogram.java
{ "start": 1670, "end": 9146 }
class ____ extends AbstractExponentialHistogram implements ReleasableExponentialHistogram { static final long BASE_SIZE = RamUsageEstimator.shallowSizeOfInstance(FixedCapacityExponentialHistogram.class) + ZeroBucket.SHALLOW_SIZE + 2 * Buckets.SHALLOW_SIZE; // These arrays represent both the positive and the negative buckets. // To avoid confusion, we refer to positions within the array as "slots" instead of indices in this file // When we use term "index", we mean the exponential histogram bucket index. // They store all buckets for the negative range first, with the bucket indices in ascending order, // followed by all buckets for the positive range, also with their indices in ascending order. // This means we store all the negative buckets first, ordered by their boundaries in descending order (from 0 to -INF), // followed by all the positive buckets, ordered by their boundaries in ascending order (from 0 to +INF). private final long[] bucketIndices; private final long[] bucketCounts; private int bucketScale; private final Buckets negativeBuckets = new Buckets(false); private ZeroBucket zeroBucket; private final Buckets positiveBuckets = new Buckets(true); private double sum; private double min; private double max; private final ExponentialHistogramCircuitBreaker circuitBreaker; private boolean closed = false; static FixedCapacityExponentialHistogram create(int bucketCapacity, ExponentialHistogramCircuitBreaker circuitBreaker) { circuitBreaker.adjustBreaker(estimateSize(bucketCapacity)); return new FixedCapacityExponentialHistogram(bucketCapacity, circuitBreaker); } /** * Creates an empty histogram with the given capacity and a {@link ZeroBucket#minimalEmpty()} zero bucket. * The scale is initialized to the maximum possible precision ({@link #MAX_SCALE}). * * @param bucketCapacity the maximum total number of positive and negative buckets this histogram can hold. */ private FixedCapacityExponentialHistogram(int bucketCapacity, ExponentialHistogramCircuitBreaker circuitBreaker) { this.circuitBreaker = circuitBreaker; bucketIndices = new long[bucketCapacity]; bucketCounts = new long[bucketCapacity]; reset(); } int getCapacity() { return bucketIndices.length; } /** * Resets this histogram to the same state as a newly constructed one with the same capacity. */ void reset() { sum = 0; min = Double.NaN; max = Double.NaN; setZeroBucket(ZeroBucket.minimalEmpty()); resetBuckets(MAX_SCALE); } /** * Removes all positive and negative buckets from this histogram and sets the scale to the given value. * * @param scale the scale to set for this histogram */ void resetBuckets(int scale) { setScale(scale); negativeBuckets.reset(); positiveBuckets.reset(); } @Override public ZeroBucket zeroBucket() { return zeroBucket; } /** * Replaces the zero bucket of this histogram with the given one. * Callers must ensure that the given {@link ZeroBucket} does not * overlap with any of the positive or negative buckets of this histogram. * * @param zeroBucket the zero bucket to set */ void setZeroBucket(ZeroBucket zeroBucket) { this.zeroBucket = zeroBucket; } @Override public double sum() { return sum; } void setSum(double sum) { this.sum = sum; } @Override public double min() { return min; } void setMin(double min) { this.min = min; } @Override public double max() { return max; } void setMax(double max) { this.max = max; } /** * Attempts to add a bucket to the positive or negative range of this histogram. * <br> * Callers must adhere to the following rules: * <ul> * <li>All buckets for the negative values range must be provided before the first one from the positive values range.</li> * <li>For both the negative and positive ranges, buckets must be provided with their indices in ascending order.</li> * <li>It is not allowed to provide the same bucket more than once.</li> * <li>It is not allowed to add empty buckets ({@code count <= 0}).</li> * </ul> * * If any of these rules are violated, this call will fail with an exception. * If the bucket cannot be added because the maximum capacity has been reached, the call will not modify the state * of this histogram and will return {@code false}. * * @param index the index of the bucket to add * @param count the count to associate with the given bucket * @param isPositive {@code true} if the bucket belongs to the positive range, {@code false} if it belongs to the negative range * @return {@code true} if the bucket was added, {@code false} if it could not be added due to insufficient capacity */ boolean tryAddBucket(long index, long count, boolean isPositive) { assert index >= MIN_INDEX && index <= MAX_INDEX : "index must be in range [" + MIN_INDEX + ".." + MAX_INDEX + "]"; assert isPositive || positiveBuckets.numBuckets == 0 : "Cannot add negative buckets after a positive bucket has been added"; assert count > 0 : "Cannot add a bucket with empty or negative count"; if (isPositive) { return positiveBuckets.tryAddBucket(index, count); } else { return negativeBuckets.tryAddBucket(index, count); } } @Override public int scale() { return bucketScale; } void setScale(int scale) { assert scale >= MIN_SCALE && scale <= MAX_SCALE : "scale must be in range [" + MIN_SCALE + ".." + MAX_SCALE + "]"; bucketScale = scale; } @Override public ExponentialHistogram.Buckets negativeBuckets() { return negativeBuckets; } @Override public ExponentialHistogram.Buckets positiveBuckets() { return positiveBuckets; } /** * @return the index of the last bucket added successfully via {@link #tryAddBucket(long, long, boolean)}, * or {@link Long#MIN_VALUE} if no buckets have been added yet. */ long getLastAddedBucketIndex() { if (positiveBuckets.numBuckets + negativeBuckets.numBuckets > 0) { return bucketIndices[negativeBuckets.numBuckets + positiveBuckets.numBuckets - 1]; } else { return Long.MIN_VALUE; } } /** * @return true, if the last bucket added successfully via {@link #tryAddBucket(long, long, boolean)} was a positive one. */ boolean wasLastAddedBucketPositive() { return positiveBuckets.numBuckets > 0; } @Override public void close() { if (closed) { assert false : "FixedCapacityExponentialHistogram closed multiple times"; } else { closed = true; circuitBreaker.adjustBreaker(-ramBytesUsed()); } } static long estimateSize(int bucketCapacity) { return BASE_SIZE + 2 * RamEstimationUtil.estimateLongArray(bucketCapacity); } @Override public long ramBytesUsed() { return estimateSize(bucketIndices.length); } private
FixedCapacityExponentialHistogram
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithApplicationPropertiesTest.java
{ "start": 775, "end": 4898 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("openshift") .setApplicationVersion("0.1-SNAPSHOT") .withConfigurationResource("openshift-with-application.properties") .overrideConfigKey("quarkus.openshift.deployment-kind", "deployment-config"); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("openshift.yml")); List<HasMetadata> openshiftList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("openshift.yml")); assertThat(openshiftList).filteredOn(h -> "DeploymentConfig".equals(h.getKind())).singleElement().satisfies(h -> { assertThat(h.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("test-it"); assertThat(m.getLabels()).contains(entry("foo", "bar")) .containsKey("app.kubernetes.io/version"); // make sure the version was not removed from the labels assertThat(m.getNamespace()).isEqualTo("applications"); }); AbstractObjectAssert<?, ?> specAssert = assertThat(h).extracting("spec"); specAssert.extracting("replicas").isEqualTo(3); specAssert.extracting("template").extracting("spec").isInstanceOfSatisfying(PodSpec.class, podSpec -> { assertThat(podSpec.getContainers()).singleElement().satisfies(container -> { assertThat(container.getEnv()).extracting("name", "value") .contains(tuple("MY_ENV_VAR", "SOMEVALUE")); assertThat(container.getImagePullPolicy()).isEqualTo("IfNotPresent"); }); }); specAssert.extracting("selector").isInstanceOfSatisfying(Map.class, selectorsMap -> { assertThat(selectorsMap).containsOnly(entry("app.kubernetes.io/name", "test-it")); }); }); assertThat(openshiftList).filteredOn(h -> "Service".equals(h.getKind())).singleElement().satisfies(h -> { assertThat(h).isInstanceOfSatisfying(Service.class, s -> { assertThat(s.getMetadata()).satisfies(m -> { assertThat(m.getNamespace()).isEqualTo("applications"); }); assertThat(s.getSpec()).satisfies(spec -> { assertThat(spec.getSelector()).containsOnly(entry("app.kubernetes.io/name", "test-it")); assertThat(spec.getPorts()).hasSize(1).anySatisfy(p -> { assertThat(p.getPort()).isEqualTo(80); assertThat(p.getTargetPort().getIntVal()).isEqualTo(9090); }); }); }); }); assertThat(openshiftList).filteredOn(i -> "Route".equals(i.getKind())).singleElement().satisfies(i -> { assertThat(i).isInstanceOfSatisfying(Route.class, r -> { //Check that labels and annotations are also applied to Routes (#10260) assertThat(r.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("test-it"); assertThat(m.getLabels()).contains(entry("foo", "bar")); assertThat(m.getAnnotations()).contains(entry("bar", "baz")); assertThat(m.getNamespace()).isEqualTo("applications"); }); assertThat(r.getSpec().getPort().getTargetPort().getStrVal()).isEqualTo("http"); }); }); } }
OpenshiftWithApplicationPropertiesTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StaticMockMemberTest.java
{ "start": 2505, "end": 2987 }
class ____ { @Mock private String mockedPrivateString; @Mock String mockedString; } """) .doTest(); } @Test public void memberSuppression() { compilationHelper .addSourceLines( "in/Test.java", """ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; @RunWith(JUnit4.class) public
Test
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
{ "start": 2693, "end": 22566 }
class ____ implements UriBuilder, Cloneable { private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?"); private static final Object[] EMPTY_VALUES = new Object[0]; private @Nullable String scheme; private @Nullable String ssp; private @Nullable String userInfo; private @Nullable String host; private @Nullable String port; private CompositePathComponentBuilder pathBuilder; private final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(); private @Nullable String fragment; private final Map<String, Object> uriVariables = new HashMap<>(4); private boolean encodeTemplate; private Charset charset = StandardCharsets.UTF_8; /** * Default constructor. Protected to prevent direct instantiation. * @see #newInstance() * @see #fromPath(String) * @see #fromUri(URI) */ protected UriComponentsBuilder() { this.pathBuilder = new CompositePathComponentBuilder(); } /** * Create a deep copy of the given UriComponentsBuilder. * @param other the other builder to copy from * @since 4.1.3 */ protected UriComponentsBuilder(UriComponentsBuilder other) { this.scheme = other.scheme; this.ssp = other.ssp; this.userInfo = other.userInfo; this.host = other.host; this.port = other.port; this.pathBuilder = other.pathBuilder.cloneBuilder(); this.uriVariables.putAll(other.uriVariables); this.queryParams.addAll(other.queryParams); this.fragment = other.fragment; this.encodeTemplate = other.encodeTemplate; this.charset = other.charset; } // Factory methods /** * Create a new, empty builder. * @return the new {@code UriComponentsBuilder} */ public static UriComponentsBuilder newInstance() { return new UriComponentsBuilder(); } /** * Create a builder that is initialized with the given path. * @param path the path to initialize with * @return the new {@code UriComponentsBuilder} */ public static UriComponentsBuilder fromPath(String path) { UriComponentsBuilder builder = new UriComponentsBuilder(); builder.path(path); return builder; } /** * Create a builder that is initialized from the given {@code URI}. * <p><strong>Note:</strong> the components in the resulting builder will be * in fully encoded (raw) form and further changes must also supply values * that are fully encoded, for example via methods in {@link UriUtils}. * In addition please use {@link #build(boolean)} with a value of "true" to * build the {@link UriComponents} instance in order to indicate that the * components are encoded. * @param uri the URI to initialize with * @return the new {@code UriComponentsBuilder} */ public static UriComponentsBuilder fromUri(URI uri) { UriComponentsBuilder builder = new UriComponentsBuilder(); builder.uri(uri); return builder; } /** * Variant of {@link #fromUriString(String, ParserType)} that defaults to * the {@link ParserType#RFC} parsing. */ public static UriComponentsBuilder fromUriString(String uri) throws InvalidUrlException { Assert.notNull(uri, "URI must not be null"); if (uri.isEmpty()) { return new UriComponentsBuilder(); } return fromUriString(uri, ParserType.RFC); } /** * Create a builder that is initialized by parsing the given URI string. * <p><strong>Note:</strong> The presence of reserved characters can prevent * correct parsing of the URI string. For example if a query parameter * contains {@code '='} or {@code '&'} characters, the query string cannot * be parsed unambiguously. Such values should be substituted for URI * variables to enable correct parsing: * <pre class="code"> * String uriString = &quot;/hotels/42?filter={value}&quot;; * UriComponentsBuilder.fromUriString(uriString).buildAndExpand(&quot;hot&amp;cold&quot;); * </pre> * @param uri the URI string to initialize with * @param parserType the parsing algorithm to use * @return the new {@code UriComponentsBuilder} * @throws InvalidUrlException if {@code uri} cannot be parsed * @since 6.2 */ public static UriComponentsBuilder fromUriString(String uri, ParserType parserType) throws InvalidUrlException { Assert.notNull(uri, "URI must not be null"); if (uri.isEmpty()) { return new UriComponentsBuilder(); } UriComponentsBuilder builder = new UriComponentsBuilder(); return switch (parserType) { case RFC -> { RfcUriParser.UriRecord record = RfcUriParser.parse(uri); yield builder.rfcUriRecord(record); } case WHAT_WG -> { WhatWgUrlParser.UrlRecord record = WhatWgUrlParser.parse(uri, WhatWgUrlParser.EMPTY_RECORD, null, null); yield builder.whatWgUrlRecord(record); } }; } // Encode methods /** * Request to have the URI template pre-encoded at build time, and * URI variables encoded separately when expanded. * <p>In comparison to {@link UriComponents#encode()}, this method has the * same effect on the URI template, i.e. each URI component is encoded by * replacing non-ASCII and illegal (within the URI component type) characters * with escaped octets. However URI variables are encoded more strictly, by * also escaping characters with reserved meaning. * <p>For most cases, this method is more likely to give the expected result * because in treats URI variables as opaque data to be fully encoded, while * {@link UriComponents#encode()} is useful when intentionally expanding URI * variables that contain reserved characters. * <p>For example ';' is legal in a path but has reserved meaning. This * method replaces ";" with "%3B" in URI variables but not in the URI * template. By contrast, {@link UriComponents#encode()} never replaces ";" * since it is a legal character in a path. * <p>When not expanding URI variables at all, prefer use of * {@link UriComponents#encode()} since that will also encode anything that * incidentally looks like a URI variable. * @since 5.0.8 */ public final UriComponentsBuilder encode() { return encode(StandardCharsets.UTF_8); } /** * A variant of {@link #encode()} with a charset other than "UTF-8". * @param charset the charset to use for encoding * @since 5.0.8 */ public UriComponentsBuilder encode(Charset charset) { this.encodeTemplate = true; this.charset = charset; return this; } // Build methods /** * Build a {@code UriComponents} instance from the various components contained in this builder. * @return the URI components */ public UriComponents build() { return build(false); } /** * Variant of {@link #build()} to create a {@link UriComponents} instance * when components are already fully encoded. This is useful for example if * the builder was created via {@link UriComponentsBuilder#fromUri(URI)}. * @param encoded whether the components in this builder are already encoded * @return the URI components * @throws IllegalArgumentException if any of the components contain illegal * characters that should have been encoded. */ public UriComponents build(boolean encoded) { return buildInternal(encoded ? EncodingHint.FULLY_ENCODED : (this.encodeTemplate ? EncodingHint.ENCODE_TEMPLATE : EncodingHint.NONE)); } private UriComponents buildInternal(EncodingHint hint) { UriComponents result; if (this.ssp != null) { result = new OpaqueUriComponents(this.scheme, this.ssp, this.fragment); } else { MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(this.queryParams); HierarchicalUriComponents uric = new HierarchicalUriComponents(this.scheme, this.fragment, this.userInfo, this.host, this.port, this.pathBuilder.build(), queryParams, hint == EncodingHint.FULLY_ENCODED); result = (hint == EncodingHint.ENCODE_TEMPLATE ? uric.encodeTemplate(this.charset) : uric); } if (!this.uriVariables.isEmpty()) { result = result.expand(name -> this.uriVariables.getOrDefault(name, UriTemplateVariables.SKIP_VALUE)); } return result; } /** * Build a {@code UriComponents} instance and replaces URI template variables * with the values from a map. This is a shortcut method which combines * calls to {@link #build()} and then {@link UriComponents#expand(Map)}. * @param uriVariables the map of URI variables * @return the URI components with expanded values */ public UriComponents buildAndExpand(Map<String, ?> uriVariables) { return build().expand(uriVariables); } /** * Build a {@code UriComponents} instance and replaces URI template variables * with the values from an array. This is a shortcut method which combines * calls to {@link #build()} and then {@link UriComponents#expand(Object...)}. * @param uriVariableValues the URI variable values * @return the URI components with expanded values */ public UriComponents buildAndExpand(@Nullable Object... uriVariableValues) { return build().expand(uriVariableValues); } @Override public URI build(@Nullable Object... uriVariables) { return buildInternal(EncodingHint.ENCODE_TEMPLATE).expand(uriVariables).toUri(); } @Override public URI build(Map<String, ? extends @Nullable Object> uriVariables) { return buildInternal(EncodingHint.ENCODE_TEMPLATE).expand(uriVariables).toUri(); } /** * Build a URI String. * <p>Effectively, a shortcut for building, encoding, and returning the * String representation: * <pre class="code"> * String uri = builder.build().encode().toUriString() * </pre> * <p>However if {@link #uriVariables(Map) URI variables} have been provided * then the URI template is pre-encoded separately from URI variables (see * {@link #encode()} for details), i.e. equivalent to: * <pre> * String uri = builder.encode().build().toUriString() * </pre> * @since 4.1 * @see UriComponents#toUriString() */ @Override public String toUriString() { return (this.uriVariables.isEmpty() ? build().encode().toUriString() : buildInternal(EncodingHint.ENCODE_TEMPLATE).toUriString()); } // Instance methods /** * Initialize components of this builder from components of the given URI. * @param uri the URI * @return this UriComponentsBuilder */ public UriComponentsBuilder uri(URI uri) { Assert.notNull(uri, "URI must not be null"); this.scheme = uri.getScheme(); if (uri.isOpaque()) { this.ssp = uri.getRawSchemeSpecificPart(); resetHierarchicalComponents(); } else { if (uri.getRawUserInfo() != null) { this.userInfo = uri.getRawUserInfo(); } if (uri.getHost() != null) { this.host = uri.getHost(); } if (uri.getPort() != -1) { this.port = String.valueOf(uri.getPort()); } if (StringUtils.hasLength(uri.getRawPath())) { this.pathBuilder = new CompositePathComponentBuilder(); this.pathBuilder.addPath(uri.getRawPath()); } if (StringUtils.hasLength(uri.getRawQuery())) { this.queryParams.clear(); query(uri.getRawQuery()); } resetSchemeSpecificPart(); } if (uri.getRawFragment() != null) { this.fragment = uri.getRawFragment(); } return this; } /** * Set or append individual URI components of this builder from the values * of the given {@link UriComponents} instance. * <p>For the semantics of each component (i.e. set vs append) check the * builder methods on this class. For example {@link #host(String)} sets * while {@link #path(String)} appends. * @param uriComponents the UriComponents to copy from * @return this UriComponentsBuilder */ public UriComponentsBuilder uriComponents(UriComponents uriComponents) { Assert.notNull(uriComponents, "UriComponents must not be null"); uriComponents.copyToUriComponentsBuilder(this); return this; } /** * Internal method to initialize this builder from an RFC {@code UriRecord}. */ private UriComponentsBuilder rfcUriRecord(RfcUriParser.UriRecord record) { scheme(record.scheme()); if (record.isOpaque()) { if (record.path() != null) { schemeSpecificPart(record.path()); } } else { userInfo(record.user()); host(record.host()); port(record.port()); if (record.path() != null) { path(record.path()); } if (record.query() != null) { query(record.query()); } } fragment(record.fragment()); return this; } /** * Internal method to initialize this builder from a WhatWG {@code UrlRecord}. */ private UriComponentsBuilder whatWgUrlRecord(WhatWgUrlParser.UrlRecord record) { if (!record.scheme().isEmpty()) { scheme(record.scheme()); } if (record.path().isOpaque()) { String ssp = record.path() + record.search(); schemeSpecificPart(ssp); } else { userInfo(record.userInfo()); String hostname = record.hostname(); if (StringUtils.hasText(hostname)) { host(hostname); } if (record.port() != null) { port(record.portString()); } path(record.path().toString()); if (record.query() != null) { query(record.query()); } } if (StringUtils.hasText(record.fragment())) { fragment(record.fragment()); } return this; } @Override public UriComponentsBuilder scheme(@Nullable String scheme) { this.scheme = scheme; return this; } /** * Set the URI scheme-specific-part. When invoked, this method overwrites * {@linkplain #userInfo(String) user-info}, {@linkplain #host(String) host}, * {@linkplain #port(int) port}, {@linkplain #path(String) path}, and * {@link #query(String) query}. * @param ssp the URI scheme-specific-part, may contain URI template parameters * @return this UriComponentsBuilder */ public UriComponentsBuilder schemeSpecificPart(String ssp) { this.ssp = ssp; resetHierarchicalComponents(); return this; } @Override public UriComponentsBuilder userInfo(@Nullable String userInfo) { this.userInfo = userInfo; resetSchemeSpecificPart(); return this; } @Override public UriComponentsBuilder host(@Nullable String host) { this.host = host; if (host != null) { resetSchemeSpecificPart(); } return this; } @Override public UriComponentsBuilder port(int port) { Assert.isTrue(port >= -1, "Port must be >= -1"); this.port = String.valueOf(port); if (port > -1) { resetSchemeSpecificPart(); } return this; } @Override public UriComponentsBuilder port(@Nullable String port) { this.port = port; if (port != null) { resetSchemeSpecificPart(); } return this; } @Override public UriComponentsBuilder path(String path) { this.pathBuilder.addPath(path); resetSchemeSpecificPart(); return this; } @Override public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException { this.pathBuilder.addPathSegments(pathSegments); resetSchemeSpecificPart(); return this; } @Override public UriComponentsBuilder replacePath(@Nullable String path) { this.pathBuilder = new CompositePathComponentBuilder(); if (path != null) { this.pathBuilder.addPath(path); } resetSchemeSpecificPart(); return this; } @Override public UriComponentsBuilder query(String query) { if (StringUtils.hasText(query)) { Matcher matcher = QUERY_PARAM_PATTERN.matcher(query); while (matcher.find()) { String name = matcher.group(1); String eq = matcher.group(2); String value = matcher.group(3); queryParam(name, (value != null ? value : (StringUtils.hasLength(eq) ? "" : null))); } resetSchemeSpecificPart(); } return this; } @Override public UriComponentsBuilder replaceQuery(@Nullable String query) { this.queryParams.clear(); if (query != null) { query(query); resetSchemeSpecificPart(); } return this; } @Override public UriComponentsBuilder queryParam(String name, @Nullable Object... values) { Assert.notNull(name, "Name must not be null"); if (!ObjectUtils.isEmpty(values)) { for (Object value : values) { String valueAsString = getQueryParamValue(value); this.queryParams.add(name, valueAsString); } } else { this.queryParams.add(name, null); } resetSchemeSpecificPart(); return this; } private @Nullable String getQueryParamValue(@Nullable Object value) { if (value != null) { return (value instanceof Optional<?> optional ? optional.map(Object::toString).orElse(null) : value.toString()); } return null; } @Override public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) { return queryParam(name, (CollectionUtils.isEmpty(values) ? EMPTY_VALUES : values.toArray())); } @Override public UriComponentsBuilder queryParamIfPresent(String name, Optional<?> value) { value.ifPresent(v -> { if (v instanceof Collection<?> values) { queryParam(name, values); } else { queryParam(name, v); } }); return this; } /** * {@inheritDoc} * @since 4.0 */ @Override public UriComponentsBuilder queryParams(@Nullable MultiValueMap<String, String> params) { if (params != null) { this.queryParams.addAll(params); resetSchemeSpecificPart(); } return this; } @Override public UriComponentsBuilder replaceQueryParam(String name, Object... values) { Assert.notNull(name, "Name must not be null"); this.queryParams.remove(name); if (!ObjectUtils.isEmpty(values)) { queryParam(name, values); } resetSchemeSpecificPart(); return this; } @Override public UriComponentsBuilder replaceQueryParam(String name, @Nullable Collection<?> values) { return replaceQueryParam(name, (CollectionUtils.isEmpty(values) ? EMPTY_VALUES : values.toArray())); } /** * {@inheritDoc} * @since 4.2 */ @Override public UriComponentsBuilder replaceQueryParams(@Nullable MultiValueMap<String, String> params) { this.queryParams.clear(); if (params != null) { this.queryParams.putAll(params); } return this; } @Override public UriComponentsBuilder fragment(@Nullable String fragment) { if (fragment != null) { Assert.hasLength(fragment, "Fragment must not be empty"); this.fragment = fragment; } else { this.fragment = null; } return this; } /** * Configure URI variables to be expanded at build time. * <p>The provided variables may be a subset of all required ones. At build * time, the available ones are expanded, while unresolved URI placeholders * are left in place and can still be expanded later. * <p>In contrast to {@link UriComponents#expand(Map)} or * {@link #buildAndExpand(Map)}, this method is useful when you need to * supply URI variables without building the {@link UriComponents} instance * just yet, or perhaps pre-expand some shared default values such as host * and port. * @param uriVariables the URI variables to use * @return this UriComponentsBuilder * @since 5.0.8 */ public UriComponentsBuilder uriVariables(Map<String, Object> uriVariables) { this.uriVariables.putAll(uriVariables); return this; } private void resetHierarchicalComponents() { this.userInfo = null; this.host = null; this.port = null; this.pathBuilder = new CompositePathComponentBuilder(); this.queryParams.clear(); } private void resetSchemeSpecificPart() { this.ssp = null; } void resetPortIfDefaultForScheme() { if (this.scheme != null && (((this.scheme.equals("http") || this.scheme.equals("ws")) && "80".equals(this.port)) || ((this.scheme.equals("https") || this.scheme.equals("wss")) && "443".equals(this.port)))) { port(null); } } /** * Public declaration of Object's {@code clone()} method. * Delegates to {@link #cloneBuilder()}. */ @Override public Object clone() { return cloneBuilder(); } /** * Clone this {@code UriComponentsBuilder}. * @return the cloned {@code UriComponentsBuilder} object * @since 4.2.7 */ public UriComponentsBuilder cloneBuilder() { return new UriComponentsBuilder(this); } /** * Enum to provide a choice of URI parsers to use in {@link #fromUriString(String, ParserType)}. * @since 6.2 */ public
UriComponentsBuilder
java
jhy__jsoup
src/main/java/org/jsoup/select/Evaluator.java
{ "start": 10704, "end": 11617 }
class ____ extends Evaluator { final String key; final Regex pattern; public AttributeWithValueMatching(String key, Regex pattern) { this.key = normalize(key); this.pattern = pattern; } public AttributeWithValueMatching(String key, Pattern pattern) { this(key, Regex.fromPattern(pattern)); // api compat } @Override public boolean matches(Element root, Element element) { return element.hasAttr(key) && pattern.matcher(element.attr(key)).find(); } @Override protected int cost() { return 8; } @Override public String toString() { return String.format("[%s~=%s]", key, pattern.toString()); } } /** * Abstract evaluator for attribute name/value matching */ public abstract static
AttributeWithValueMatching
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/AbstractNestedConditionTests.java
{ "start": 3022, "end": 3148 }
class ____ { } } @Configuration(proxyBeanMethods = false) @Conditional(InvalidNestedCondition.class) static
MissingMyBean
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/test/java/io/quarkus/vertx/http/runtime/TrustedProxyCheckPartConverterTest.java
{ "start": 192, "end": 5424 }
class ____ { private static final TrustedProxyCheckPartConverter CONVERTER = new TrustedProxyCheckPartConverter(); @Test public void testCidrIPv4() throws UnknownHostException { var part = CONVERTER.convert("10.0.0.0/24"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertEquals(0, part.port); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("10.0.0.0"), 0)); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("10.0.0.255"), 0)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("100.100.100.100"), 0)); } @Test public void testCidrIPv6() throws UnknownHostException { var part = CONVERTER.convert("2001:4860:4860::8888/32"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertEquals(0, part.port); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("2001:4860:4860:0000:0000:0000:0000:8888"), 0)); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("2001:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 0)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2005:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 0)); } @Test public void testIPv4() throws UnknownHostException { var part = CONVERTER.convert("10.0.0.0"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertEquals(0, part.port); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("10.0.0.0"), 0)); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("10.0.0.0"), 99)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("10.0.0.255"), 0)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("100.100.100.100"), 0)); } @Test public void testIPv4AndPort() throws UnknownHostException { var part = CONVERTER.convert("10.0.0.0:8085"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("10.0.0.0"), 8085)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("10.0.0.0"), 8000)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("10.0.0.255"), 8085)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("100.100.100.100"), 8085)); } @Test public void testIPv6() throws UnknownHostException { var part = CONVERTER.convert("[2001:4860:4860:0000:0000:0000:0000:8888]"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertEquals(0, part.port); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("2001:4860:4860:0000:0000:0000:0000:8888"), 0)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2001:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 0)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2005:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 0)); // test short form part = CONVERTER.convert("[::]"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertEquals(0, part.port); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("0:0:0:0:0:0:0:0"), 0)); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("0:0:0:0:0:0:0:0"), 99)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2001:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 0)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2005:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 0)); } @Test public void testIPv6AndPort() throws UnknownHostException { var part = CONVERTER.convert("[2001:4860:4860:0000:0000:0000:0000:8888]:8085"); Assertions.assertNull(part.hostName); Assertions.assertNotNull(part.proxyCheck); Assertions.assertTrue(part.proxyCheck.test(InetAddress.getByName("2001:4860:4860:0000:0000:0000:0000:8888"), 8085)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2001:4860:4860:0000:0000:0000:0000:8888"), 8000)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2001:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 8085)); Assertions.assertFalse(part.proxyCheck.test(InetAddress.getByName("2005:4860:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"), 8085)); } @Test public void testHostName() { var part = CONVERTER.convert("quarkus.io"); Assertions.assertNull(part.proxyCheck); Assertions.assertNotNull(part.hostName); Assertions.assertEquals(0, part.port); } @Test public void testHostNameAndPort() { var part = CONVERTER.convert("quarkus.io:8085"); Assertions.assertNull(part.proxyCheck); Assertions.assertNotNull(part.hostName); Assertions.assertEquals(8085, part.port); } }
TrustedProxyCheckPartConverterTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/util/ByteArray.java
{ "start": 1028, "end": 1544 }
class ____ { private int hash = 0; // cache the hash code private final byte[] bytes; public ByteArray(byte[] bytes) { this.bytes = bytes; } public byte[] getBytes() { return bytes; } @Override public int hashCode() { if (hash == 0) { hash = Arrays.hashCode(bytes); } return hash; } @Override public boolean equals(Object o) { if (!(o instanceof ByteArray)) { return false; } return Arrays.equals(bytes, ((ByteArray)o).bytes); } }
ByteArray
java
spring-projects__spring-boot
module/spring-boot-servlet/src/test/java/org/springframework/boot/servlet/autoconfigure/MultipartAutoConfigurationTests.java
{ "start": 10921, "end": 11250 }
class ____ { @Bean ServerProperties serverProperties() { ServerProperties properties = new ServerProperties(); properties.setPort(0); return properties; } @Bean DispatcherServlet dispatcherServlet() { return new DispatcherServlet(); } } @Configuration(proxyBeanMethods = false) static
BaseConfiguration
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/test/core/AsyncTestBaseTest.java
{ "start": 980, "end": 6577 }
class ____ extends AsyncTestBase { private ExecutorService executor; public void setUp() throws Exception { super.setUp(); disableThreadChecks(); executor = Executors.newFixedThreadPool(10); } protected void tearDown() throws Exception { executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); super.tearDown(); } @Test public void testAssertionFailedFromOtherThread() { executor.execute(() -> { assertEquals("foo", "bar"); testComplete(); }); try { await(); } catch (ComparisonFailure error) { assertTrue(error.getMessage().startsWith("expected:")); } } @Test public void testAssertionFailedFromOtherThreadAwaitBeforeAssertAndTestComplete() { executor.execute(() -> { //Pause to make sure await() is called before assertion and testComplete try { Thread.sleep(1000); } catch (InterruptedException e) { fail(e.getMessage()); } assertEquals("foo", "bar"); testComplete(); }); try { await(); } catch (ComparisonFailure error) { assertTrue(error.getMessage().startsWith("expected:")); } } @Test public void testAssertionFailedFromOtherThreadForgotToCallAwait() throws Exception { executor.execute(() -> { assertEquals("foo", "bar"); testComplete(); }); Thread.sleep(500); try { super.afterAsyncTestBase(); fail("Should throw exception"); } catch (IllegalStateException e) { // OK } finally { // Cancel the error condition clearThrown(); } } @Test public void testAssertionFailedFromMainThread() { try { assertEquals("foo", "bar"); } catch (ComparisonFailure error) { assertTrue(error.getMessage().startsWith("expected:")); } testComplete(); } @Test public void testAssertionPassedFromOtherThread() { executor.execute(() -> { assertEquals("foo", "foo"); testComplete(); }); await(); } @Test public void testAssertionPassedFromMainThread() { assertEquals("foo", "foo"); testComplete(); await(); } @Test public void testTimeout() { long timeout = 5000; long start = System.currentTimeMillis(); try { await(timeout, TimeUnit.MILLISECONDS); } catch (IllegalStateException error) { long now = System.currentTimeMillis(); assertTrue(error.getMessage().startsWith("Timed out in waiting for test complete")); long delay = now - start; assertTrue(delay >= timeout); assertTrue(delay < timeout * 1.5); } } // Commented this test as default timeout is now too large // @Test // public void testTimeoutDefault() { // long start = System.currentTimeMillis(); // try { // await(); // } catch (IllegalStateException error) { // long now = System.currentTimeMillis(); // assertTrue(error.getMessage().startsWith("Timed out in waiting for test complete")); // long delay = now - start; // long defaultTimeout = 10000; // assertTrue(delay >= defaultTimeout); // assertTrue(delay < defaultTimeout * 1.5); // } // } @Test public void testFailFromOtherThread() { String msg = "too many aardvarks!"; executor.execute(() -> { fail(msg); testComplete(); }); try { await(); } catch (AssertionError error) { assertTrue(error.getMessage().equals(msg)); } } @Test public void testSuccessfulCompletion() { executor.execute(() -> { assertEquals("foo", "foo"); assertFalse(false); testComplete(); }); await(); } @Test public void testTestCompleteCalledMultipleTimes() { executor.execute(() -> { assertEquals("foo", "foo"); testComplete(); try { testComplete(); } catch (IllegalStateException e) { //OK } }); await(); } @Test public void testAwaitCalledMultipleTimes() { executor.execute(() -> { assertEquals("foo", "foo"); testComplete(); }); await(); try { await(); } catch (IllegalStateException e) { //OK } } @Test public void testNoAssertionsNoTestComplete() { // Deliberately empty test } @Test public void testNoAssertionsTestComplete() { testComplete(); } @Test public void testAssertionOKTestComplete() { assertEquals("foo", "foo"); testComplete(); } @Test public void testAssertionFailedFromMainThreadWithNoTestComplete() { try { assertEquals("foo", "bar"); } catch (AssertionError e) { // OK testComplete(); try { super.afterAsyncTestBase(); } catch (IllegalStateException e2) { fail("Should not throw exception"); } finally { // Cancel the error condition clearThrown(); } } } @Test public void waitForMultiple() { int toWaitFor = 10; waitFor(10); AtomicInteger cnt = new AtomicInteger(); for (int i = 0; i < toWaitFor; i++) { executor.execute(() -> { cnt.incrementAndGet(); complete(); }); } await(); assertEquals(toWaitFor, cnt.get()); } @Test public void increaseToWait() { int toWaitFor = 10; waitFor(3); complete(); complete(); waitForMore(9); AtomicInteger cnt = new AtomicInteger(); for (int i = 0; i < toWaitFor; i++) { executor.execute(() -> { cnt.incrementAndGet(); complete(); }); } await(); assertEquals(toWaitFor, cnt.get()); } public static
AsyncTestBaseTest
java
elastic__elasticsearch
x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/BaseSearchableSnapshotsIntegTestCase.java
{ "start": 17882, "end": 18203 }
class ____ extends SnapshotBasedRecoveriesPlugin { public LicensedSnapshotBasedRecoveriesPlugin(Settings settings) { super(settings); } @Override public boolean isLicenseEnabled() { return true; } } public static
LicensedSnapshotBasedRecoveriesPlugin
java
netty__netty
example/src/main/java/io/netty/example/http2/helloworld/frame/server/Http2Server.java
{ "start": 1948, "end": 4381 }
class ____ { static final boolean SSL = System.getProperty("ssl") != null; static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8080")); public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; X509Bundle ssc = new CertificateBuilder() .subject("cn=localhost") .setIsCertificateAuthority(true) .buildSelfSigned(); sslCtx = SslContextBuilder.forServer(ssc.toKeyManagerFactory()) .sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new Http2ServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your HTTP/2-enabled web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { group.shutdownGracefully(); } } }
Http2Server
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowRuntimeCredentialsProviderTest.java
{ "start": 4775, "end": 4933 }
class ____ { public RuntimeSecretProvider createRuntimeSecretProvider() { return new RuntimeSecretProvider(); } } }
TestRecorder
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/wrappedio/impl/DynamicWrappedIO.java
{ "start": 1858, "end": 6608 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(DynamicWrappedIO.class); /** * Classname of the wrapped IO class: {@value}. */ private static final String WRAPPED_IO_CLASSNAME = "org.apache.hadoop.io.wrappedio.WrappedIO"; /** * Method name for openFile: {@value}. */ private static final String FILESYSTEM_OPEN_FILE = "fileSystem_openFile"; /** * Method name for bulk delete: {@value}. */ private static final String BULKDELETE_DELETE = "bulkDelete_delete"; /** * Method name for bulk delete: {@value}. */ private static final String BULKDELETE_PAGESIZE = "bulkDelete_pageSize"; /** * Method name for {@code byteBufferPositionedReadable}: {@value}. */ private static final String BYTE_BUFFER_POSITIONED_READABLE_READ_FULLY_AVAILABLE = "byteBufferPositionedReadable_readFullyAvailable"; /** * Method name for {@code byteBufferPositionedReadable}: {@value}. */ private static final String BYTE_BUFFER_POSITIONED_READABLE_READ_FULLY = "byteBufferPositionedReadable_readFully"; /** * Method name for {@code PathCapabilities.hasPathCapability()}. * {@value} */ private static final String PATH_CAPABILITIES_HAS_PATH_CAPABILITY = "pathCapabilities_hasPathCapability"; /** * Method name for {@code StreamCapabilities.hasCapability()}. * {@value} */ private static final String STREAM_CAPABILITIES_HAS_CAPABILITY = "streamCapabilities_hasCapability"; /** * A singleton instance of the wrapper. */ private static final DynamicWrappedIO INSTANCE = new DynamicWrappedIO(); /** * Read policy for parquet files: {@value}. */ public static final String PARQUET_READ_POLICIES = "parquet, columnar, vector, random"; /** * Was wrapped IO loaded? * In the hadoop codebase, this is true. * But in other libraries it may not always be true...this * field is used to assist copy-and-paste adoption. */ private final boolean loaded; /** * Method binding. * {@code WrappedIO.bulkDelete_delete(FileSystem, Path, Collection)}. */ private final DynMethods.UnboundMethod bulkDeleteDeleteMethod; /** * Method binding. * {@code WrappedIO.bulkDelete_pageSize(FileSystem, Path)}. */ private final DynMethods.UnboundMethod bulkDeletePageSizeMethod; /** * Dynamic openFile() method. * {@code WrappedIO.fileSystem_openFile(FileSystem, Path, String, FileStatus, Long, Map)}. */ private final DynMethods.UnboundMethod fileSystemOpenFileMethod; private final DynMethods.UnboundMethod pathCapabilitiesHasPathCapabilityMethod; private final DynMethods.UnboundMethod streamCapabilitiesHasCapabilityMethod; private final DynMethods.UnboundMethod byteBufferPositionedReadableReadFullyAvailableMethod; private final DynMethods.UnboundMethod byteBufferPositionedReadableReadFullyMethod; public DynamicWrappedIO() { this(WRAPPED_IO_CLASSNAME); } public DynamicWrappedIO(String classname) { // Wrapped IO class. Class<?> wrappedClass = loadClass(classname); loaded = wrappedClass != null; // bulk delete APIs bulkDeleteDeleteMethod = loadStaticMethod( wrappedClass, List.class, BULKDELETE_DELETE, FileSystem.class, Path.class, Collection.class); bulkDeletePageSizeMethod = loadStaticMethod( wrappedClass, Integer.class, BULKDELETE_PAGESIZE, FileSystem.class, Path.class); // load the openFile method fileSystemOpenFileMethod = loadStaticMethod( wrappedClass, FSDataInputStream.class, FILESYSTEM_OPEN_FILE, FileSystem.class, Path.class, String.class, FileStatus.class, Long.class, Map.class); // path and stream capabilities pathCapabilitiesHasPathCapabilityMethod = loadStaticMethod(wrappedClass, boolean.class, PATH_CAPABILITIES_HAS_PATH_CAPABILITY, Object.class, Path.class, String.class); streamCapabilitiesHasCapabilityMethod = loadStaticMethod(wrappedClass, boolean.class, STREAM_CAPABILITIES_HAS_CAPABILITY, Object.class, String.class); // ByteBufferPositionedReadable byteBufferPositionedReadableReadFullyAvailableMethod = loadStaticMethod(wrappedClass, Void.class, BYTE_BUFFER_POSITIONED_READABLE_READ_FULLY_AVAILABLE, InputStream.class); byteBufferPositionedReadableReadFullyMethod = loadStaticMethod(wrappedClass, Void.class, BYTE_BUFFER_POSITIONED_READABLE_READ_FULLY, InputStream.class, long.class, ByteBuffer.class); } /** * Is the wrapped IO
DynamicWrappedIO
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/util/UriUtils.java
{ "start": 2041, "end": 15257 }
class ____ { /** * Encode the given URI scheme with the given encoding. * @param scheme the scheme to be encoded * @param encoding the character encoding to encode to * @return the encoded scheme */ public static String encodeScheme(String scheme, String encoding) { return encode(scheme, encoding, HierarchicalUriComponents.Type.SCHEME); } /** * Encode the given URI scheme with the given encoding. * @param scheme the scheme to be encoded * @param charset the character encoding to encode to * @return the encoded scheme * @since 5.0 */ public static String encodeScheme(String scheme, Charset charset) { return encode(scheme, charset, HierarchicalUriComponents.Type.SCHEME); } /** * Encode the given URI authority with the given encoding. * @param authority the authority to be encoded * @param encoding the character encoding to encode to * @return the encoded authority */ public static String encodeAuthority(String authority, String encoding) { return encode(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY); } /** * Encode the given URI authority with the given encoding. * @param authority the authority to be encoded * @param charset the character encoding to encode to * @return the encoded authority * @since 5.0 */ public static String encodeAuthority(String authority, Charset charset) { return encode(authority, charset, HierarchicalUriComponents.Type.AUTHORITY); } /** * Encode the given URI user info with the given encoding. * @param userInfo the user info to be encoded * @param encoding the character encoding to encode to * @return the encoded user info */ public static String encodeUserInfo(String userInfo, String encoding) { return encode(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO); } /** * Encode the given URI user info with the given encoding. * @param userInfo the user info to be encoded * @param charset the character encoding to encode to * @return the encoded user info * @since 5.0 */ public static String encodeUserInfo(String userInfo, Charset charset) { return encode(userInfo, charset, HierarchicalUriComponents.Type.USER_INFO); } /** * Encode the given URI host with the given encoding. * @param host the host to be encoded * @param encoding the character encoding to encode to * @return the encoded host */ public static String encodeHost(String host, String encoding) { return encode(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4); } /** * Encode the given URI host with the given encoding. * @param host the host to be encoded * @param charset the character encoding to encode to * @return the encoded host * @since 5.0 */ public static String encodeHost(String host, Charset charset) { return encode(host, charset, HierarchicalUriComponents.Type.HOST_IPV4); } /** * Encode the given URI port with the given encoding. * @param port the port to be encoded * @param encoding the character encoding to encode to * @return the encoded port */ public static String encodePort(String port, String encoding) { return encode(port, encoding, HierarchicalUriComponents.Type.PORT); } /** * Encode the given URI port with the given encoding. * @param port the port to be encoded * @param charset the character encoding to encode to * @return the encoded port * @since 5.0 */ public static String encodePort(String port, Charset charset) { return encode(port, charset, HierarchicalUriComponents.Type.PORT); } /** * Encode the given URI path with the given encoding. * @param path the path to be encoded * @param encoding the character encoding to encode to * @return the encoded path */ public static String encodePath(String path, String encoding) { return encode(path, encoding, HierarchicalUriComponents.Type.PATH); } /** * Encode the given URI path with the given encoding. * @param path the path to be encoded * @param charset the character encoding to encode to * @return the encoded path * @since 5.0 */ public static String encodePath(String path, Charset charset) { return encode(path, charset, HierarchicalUriComponents.Type.PATH); } /** * Encode the given URI path segment with the given encoding. * @param segment the segment to be encoded * @param encoding the character encoding to encode to * @return the encoded segment */ public static String encodePathSegment(String segment, String encoding) { return encode(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT); } /** * Encode the given URI path segment with the given encoding. * @param segment the segment to be encoded * @param charset the character encoding to encode to * @return the encoded segment * @since 5.0 */ public static String encodePathSegment(String segment, Charset charset) { return encode(segment, charset, HierarchicalUriComponents.Type.PATH_SEGMENT); } /** * Encode the given URI query with the given encoding. * @param query the query to be encoded * @param encoding the character encoding to encode to * @return the encoded query */ public static String encodeQuery(String query, String encoding) { return encode(query, encoding, HierarchicalUriComponents.Type.QUERY); } /** * Encode the given URI query with the given encoding. * @param query the query to be encoded * @param charset the character encoding to encode to * @return the encoded query * @since 5.0 */ public static String encodeQuery(String query, Charset charset) { return encode(query, charset, HierarchicalUriComponents.Type.QUERY); } /** * Encode the given URI query parameter with the given encoding. * @param queryParam the query parameter to be encoded * @param encoding the character encoding to encode to * @return the encoded query parameter */ public static String encodeQueryParam(String queryParam, String encoding) { return encode(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM); } /** * Encode the given URI query parameter with the given encoding. * @param queryParam the query parameter to be encoded * @param charset the character encoding to encode to * @return the encoded query parameter * @since 5.0 */ public static String encodeQueryParam(String queryParam, Charset charset) { return encode(queryParam, charset, HierarchicalUriComponents.Type.QUERY_PARAM); } /** * Encode the query parameters from the given {@code MultiValueMap} with UTF-8. * <p>This can be used with {@link UriComponentsBuilder#queryParams(MultiValueMap)} * when building a URI from an already encoded template. * <pre class="code">{@code * MultiValueMap<String, String> params = new LinkedMultiValueMap<>(2); * // add to params... * * ServletUriComponentsBuilder.fromCurrentRequest() * .queryParams(UriUtils.encodeQueryParams(params)) * .build(true) * .toUriString(); * }</pre> * @param params the parameters to encode * @return a new {@code MultiValueMap} with the encoded names and values * @since 5.2.3 */ public static MultiValueMap<String, String> encodeQueryParams(MultiValueMap<String, String> params) { Charset charset = StandardCharsets.UTF_8; MultiValueMap<String, String> result = new LinkedMultiValueMap<>(params.size()); for (Map.Entry<String, List<String>> entry : params.entrySet()) { for (String value : entry.getValue()) { result.add(encodeQueryParam(entry.getKey(), charset), encodeQueryParam(value, charset)); } } return result; } /** * Encode the given URI fragment with the given encoding. * @param fragment the fragment to be encoded * @param encoding the character encoding to encode to * @return the encoded fragment */ public static String encodeFragment(String fragment, String encoding) { return encode(fragment, encoding, HierarchicalUriComponents.Type.FRAGMENT); } /** * Encode the given URI fragment with the given encoding. * @param fragment the fragment to be encoded * @param charset the character encoding to encode to * @return the encoded fragment * @since 5.0 */ public static String encodeFragment(String fragment, Charset charset) { return encode(fragment, charset, HierarchicalUriComponents.Type.FRAGMENT); } /** * Variant of {@link #encode(String, Charset)} with a String charset. * @param source the String to be encoded * @param encoding the character encoding to encode to * @return the encoded String */ public static String encode(String source, String encoding) { return encode(source, encoding, HierarchicalUriComponents.Type.URI); } /** * Encode all characters that are either illegal, or have any reserved * meaning, anywhere within a URI, as defined in * <a href="https://tools.ietf.org/html/rfc3986">RFC 3986</a>. * This is useful to ensure that the given String will be preserved as-is * and will not have any impact on the structure or meaning of the URI. * @param source the String to be encoded * @param charset the character encoding to encode to * @return the encoded String * @since 5.0 */ public static String encode(String source, Charset charset) { return encode(source, charset, HierarchicalUriComponents.Type.URI); } /** * Convenience method to apply {@link #encode(String, Charset)} to all * given URI variable values. * @param uriVariables the URI variable values to be encoded * @return the encoded String * @since 5.0 */ public static Map<String, String> encodeUriVariables(Map<String, ? extends @Nullable Object> uriVariables) { Map<String, String> result = CollectionUtils.newLinkedHashMap(uriVariables.size()); uriVariables.forEach((key, value) -> { String stringValue = (value != null ? value.toString() : ""); result.put(key, encode(stringValue, StandardCharsets.UTF_8)); }); return result; } /** * Convenience method to apply {@link #encode(String, Charset)} to all * given URI variable values. * @param uriVariables the URI variable values to be encoded * @return the encoded String * @since 5.0 */ public static Object[] encodeUriVariables(@Nullable Object... uriVariables) { return Arrays.stream(uriVariables) .map(value -> { String stringValue = (value != null ? value.toString() : ""); return encode(stringValue, StandardCharsets.UTF_8); }) .toArray(); } private static String encode(String scheme, String encoding, HierarchicalUriComponents.Type type) { return HierarchicalUriComponents.encodeUriComponent(scheme, encoding, type); } private static String encode(String scheme, Charset charset, HierarchicalUriComponents.Type type) { return HierarchicalUriComponents.encodeUriComponent(scheme, charset, type); } /** * Decode the given encoded URI component value by replacing each * "<i>{@code %xy}</i>" sequence with a hexadecimal representation of the * character in the specified character encoding, leaving other characters * unmodified. * @param source the encoded URI component value * @param encoding the character encoding to use to decode the "<i>{@code %xy}</i>" * sequences * @return the decoded value * @throws IllegalArgumentException if the given source contains invalid encoded * sequences * @see StringUtils#uriDecode(String, Charset) * @see java.net.URLDecoder#decode(String, String) java.net.URLDecoder#decode * for HTML form decoding */ public static String decode(String source, String encoding) { return StringUtils.uriDecode(source, Charset.forName(encoding)); } /** * Decode the given encoded URI component value by replacing each * "<i>{@code %xy}</i>" sequence with a hexadecimal representation of the * character in the specified character encoding, leaving other characters * unmodified. * @param source the encoded URI component value * @param charset the character encoding to use to decode the "<i>{@code %xy}</i>" * sequences * @return the decoded value * @throws IllegalArgumentException if the given source contains invalid encoded * sequences * @since 5.0 * @see StringUtils#uriDecode(String, Charset) * @see java.net.URLDecoder#decode(String, String) java.net.URLDecoder#decode * for HTML form decoding */ public static String decode(String source, Charset charset) { return StringUtils.uriDecode(source, charset); } /** * Extract the file extension from the given URI path. * @param path the URI path (for example, "/products/index.html") * @return the extracted file extension (for example, "html") * @since 4.3.2 */ public static @Nullable String extractFileExtension(String path) { int end = path.indexOf('?'); int fragmentIndex = path.indexOf('#'); if (fragmentIndex != -1 && (end == -1 || fragmentIndex < end)) { end = fragmentIndex; } if (end == -1) { end = path.length(); } int begin = path.lastIndexOf('/', end) + 1; int paramIndex = path.indexOf(';', begin); end = (paramIndex != -1 && paramIndex < end ? paramIndex : end); int extIndex = path.lastIndexOf('.', end); if (extIndex != -1 && extIndex >= begin) { return path.substring(extIndex + 1, end); } return null; } }
UriUtils
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/schedulers/SchedulerWhen.java
{ "start": 9696, "end": 10078 }
class ____ implements Function<ScheduledAction, Completable> { final Worker actualWorker; CreateWorkerFunction(Worker actualWorker) { this.actualWorker = actualWorker; } @Override public Completable apply(final ScheduledAction action) { return new WorkerCompletable(action); } final
CreateWorkerFunction
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java
{ "start": 5694, "end": 5986 }
class ____ { @Around("execution(* setAge(*))") public Object doLog(ProceedingJoinPoint pjp) throws Throwable { LogFactory.getLog(LoggingAspectOnSetter.class).debug(Arrays.asList(pjp.getArgs())); return pjp.proceed(); } } } @Aspect @SuppressWarnings("serial")
LoggingAspectOnSetter
java
spring-projects__spring-framework
spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJEnableCachingIsolatedTests.java
{ "start": 6302, "end": 6484 }
class ____ { @Bean public CacheManager cm1() { return new NoOpCacheManager(); } } @Configuration @EnableCaching(mode = AdviceMode.ASPECTJ) static
SingleCacheManagerConfig
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/internal/NamedResultSetMappingMementoImpl.java
{ "start": 521, "end": 1295 }
class ____ implements NamedResultSetMappingMemento { private final String name; private final List<ResultMemento> resultMementos; public NamedResultSetMappingMementoImpl( String name, List<ResultMemento> resultMementos) { this.name = name; this.resultMementos = resultMementos; } @Override public String getName() { return name; } public List<ResultMemento> getResultMementos() { return unmodifiableList( resultMementos ); } @Override public void resolve( ResultSetMapping resultSetMapping, Consumer<String> querySpaceConsumer, ResultSetMappingResolutionContext context) { resultMementos.forEach( memento -> resultSetMapping.addResultBuilder( memento.resolve( querySpaceConsumer, context ) ) ); } }
NamedResultSetMappingMementoImpl
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/DisposablesTest.java
{ "start": 935, "end": 2066 }
class ____ { //==== PUBLIC API TESTS ==== @Test public void sequentialEmpty() { assertThat(Disposables.swap() .get()).isNull(); } @Test public void compositeEmpty() { Disposable.Composite cd = Disposables.composite(); assertThat(cd.size()).isZero(); assertThat(cd.isDisposed()).isFalse(); } @Test public void compositeFromArray() { Disposable d1 = new FakeDisposable(); Disposable d2 = new FakeDisposable(); Disposable.Composite cd = Disposables.composite(d1, d2); assertThat(cd.size()).isEqualTo(2); assertThat(cd.isDisposed()).isFalse(); } @Test public void compositeFromCollection() { Disposable d1 = new FakeDisposable(); Disposable d2 = new FakeDisposable(); Disposable.Composite cd = Disposables.composite(Arrays.asList(d1, d2)); assertThat(cd.size()).isEqualTo(2); assertThat(cd.isDisposed()).isFalse(); } //==== PRIVATE API TESTS ==== static final AtomicReferenceFieldUpdater<TestDisposable, Disposable> DISPOSABLE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(TestDisposable.class, Disposable.class, "disp"); private static
DisposablesTest
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/GetTypeStrategyTest.java
{ "start": 1312, "end": 7980 }
class ____ extends TypeStrategiesTestBase { @Override protected Stream<TestSpec> testData() { return Stream.of( TestSpec.forStrategy( "Access field of a row nullable type by name", SpecificTypeStrategies.GET) .inputTypes( DataTypes.ROW(DataTypes.FIELD("f0", DataTypes.BIGINT().notNull())), DataTypes.STRING().notNull()) .calledWithLiteralAt(1, "f0") .expectDataType(DataTypes.BIGINT().nullable()), TestSpec.forStrategy( "Access field of a row not null type by name", SpecificTypeStrategies.GET) .inputTypes( DataTypes.ROW(DataTypes.FIELD("f0", DataTypes.BIGINT().notNull())) .notNull(), DataTypes.STRING().notNull()) .calledWithLiteralAt(1, "f0") .expectDataType(DataTypes.BIGINT().notNull()), TestSpec.forStrategy( "Access field of a structured nullable type by name", SpecificTypeStrategies.GET) .inputTypes( new FieldsDataType( StructuredType.newBuilder( ObjectIdentifier.of( "cat", "db", "type")) .attributes( Collections.singletonList( new StructuredType .StructuredAttribute( "f0", new BigIntType( false)))) .build(), Collections.singletonList( DataTypes.BIGINT().notNull())) .nullable(), DataTypes.STRING().notNull()) .calledWithLiteralAt(1, "f0") .expectDataType(DataTypes.BIGINT().nullable()), TestSpec.forStrategy( "Access field of a structured not null type by name", SpecificTypeStrategies.GET) .inputTypes( new FieldsDataType( StructuredType.newBuilder( ObjectIdentifier.of( "cat", "db", "type")) .attributes( Collections.singletonList( new StructuredType .StructuredAttribute( "f0", new BigIntType( false)))) .build(), Collections.singletonList( DataTypes.BIGINT().notNull())) .notNull(), DataTypes.STRING().notNull()) .calledWithLiteralAt(1, "f0") .expectDataType(DataTypes.BIGINT().notNull()), TestSpec.forStrategy( "Access field of a row nullable type by index", SpecificTypeStrategies.GET) .inputTypes( DataTypes.ROW(DataTypes.FIELD("f0", DataTypes.BIGINT().notNull())), DataTypes.INT().notNull()) .calledWithLiteralAt(1, 0) .expectDataType(DataTypes.BIGINT().nullable()), TestSpec.forStrategy( "Access field of a row not null type by index", SpecificTypeStrategies.GET) .inputTypes( DataTypes.ROW(DataTypes.FIELD("f0", DataTypes.BIGINT().notNull())) .notNull(), DataTypes.INT().notNull()) .calledWithLiteralAt(1, 0) .expectDataType(DataTypes.BIGINT().notNull()), TestSpec.forStrategy( "Fields can be accessed only with a literal (name)", SpecificTypeStrategies.GET) .inputTypes( DataTypes.ROW(DataTypes.FIELD("f0", DataTypes.BIGINT().notNull())) .notNull(), DataTypes.STRING().notNull()) .expectErrorMessage( "Could not infer an output type for the given arguments."), TypeStrategiesTestBase.TestSpec.forStrategy( "Fields can be accessed only with a literal (index)", SpecificTypeStrategies.GET) .inputTypes( DataTypes.ROW(DataTypes.FIELD("f0", DataTypes.BIGINT().notNull())) .notNull(), DataTypes.INT().notNull()) .expectErrorMessage( "Could not infer an output type for the given arguments.")); } }
GetTypeStrategyTest
java
elastic__elasticsearch
x-pack/plugin/security/qa/smoke-test-all-realms/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/SecurityRealmSmokeTestCase.java
{ "start": 1744, "end": 12617 }
class ____ extends ESRestTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local() .distribution(DistributionType.DEFAULT) .nodes(2) .configFile("http-server.key", Resource.fromClasspath("ssl/http-server.key")) .configFile("http-server.crt", Resource.fromClasspath("ssl/http-server.crt")) .configFile("http-client-ca.crt", Resource.fromClasspath("ssl/http-client-ca.crt")) .configFile("saml-metadata.xml", Resource.fromClasspath("saml-metadata.xml")) .configFile("kerberos.keytab", Resource.fromClasspath("kerberos.keytab")) .configFile("oidc-jwkset.json", Resource.fromClasspath("oidc-jwkset.json")) .configFile("ldap_role_mapping.yml", Resource.fromClasspath("ldap_role_mapping.yml")) .configFile("pki_role_mapping.yml", Resource.fromClasspath("pki_role_mapping.yml")) .setting("xpack.ml.enabled", "false") .setting("xpack.security.enabled", "true") .setting("xpack.security.authc.token.enabled", "true") .setting("xpack.security.authc.api_key.enabled", "true") // Need a trial license (not basic) to enable all realms .setting("xpack.license.self_generated.type", "trial") // Need SSL to enable PKI realms .setting("xpack.security.http.ssl.enabled", "true") .setting("xpack.security.http.ssl.certificate", "http-server.crt") .setting("xpack.security.http.ssl.key", "http-server.key") .setting("xpack.security.http.ssl.key_passphrase", "http-password") .setting("xpack.security.http.ssl.client_authentication", "optional") .setting("xpack.security.http.ssl.certificate_authorities", "http-client-ca.crt") // Don't need transport SSL, so leave it out .setting("xpack.security.transport.ssl.enabled", "false") // Configure every realm type // - File .setting("xpack.security.authc.realms.file.file0.order", "0") // - Native .setting("xpack.security.authc.realms.native.native1.order", "1") // - LDAP (configured but won't work because we don't want external fixtures in this test suite) .setting("xpack.security.authc.realms.ldap.ldap2.order", "2") .setting("xpack.security.authc.realms.ldap.ldap2.url", "ldap://localhost:7777") .setting("xpack.security.authc.realms.ldap.ldap2.user_search.base_dn", "OU=users,DC=example,DC=com") .setting("xpack.security.authc.realms.ldap.ldap2.files.role_mapping", "ldap_role_mapping.yml") // - AD (configured but won't work because we don't want external fixtures in this test suite) .setting("xpack.security.authc.realms.active_directory.ad3.order", "3") .setting("xpack.security.authc.realms.active_directory.ad3.domain_name", "localhost") // role mappings don't matter, but we need to read the file as part of the test .setting("xpack.security.authc.realms.active_directory.ad3.files.role_mapping", "ldap_role_mapping.yml") // - PKI (works) .setting("xpack.security.authc.realms.pki.pki4.order", "4") // role mappings don't matter, but we need to read the file as part of the test .setting("xpack.security.authc.realms.pki.pki4.files.role_mapping", "pki_role_mapping.yml") // - SAML (configured but won't work because we don't want external fixtures in this test suite) .setting("xpack.security.authc.realms.saml.saml5.order", "5") .setting("xpack.security.authc.realms.saml.saml5.idp.metadata.path", "saml-metadata.xml") .setting("xpack.security.authc.realms.saml.saml5.idp.entity_id", "http://idp.example.com/") .setting("xpack.security.authc.realms.saml.saml5.sp.entity_id", "http://kibana.example.net/") .setting("xpack.security.authc.realms.saml.saml5.sp.acs", "http://kibana.example.net/api/security/saml/callback") .setting("xpack.security.authc.realms.saml.saml5.attributes.principal", "uid") // - Kerberos (configured but won't work because we don't want external fixtures in this test suite) .setting("xpack.security.authc.realms.kerberos.kerb6.order", "6") .setting("xpack.security.authc.realms.kerberos.kerb6.keytab.path", "kerberos.keytab") // - OIDC (configured but won't work because we don't want external fixtures in this test suite) .setting("xpack.security.authc.realms.oidc.openid7.order", "7") .setting("xpack.security.authc.realms.oidc.openid7.rp.client_id", "http://rp.example.net") .setting("xpack.security.authc.realms.oidc.openid7.rp.response_type", "id_token") .setting("xpack.security.authc.realms.oidc.openid7.rp.redirect_uri", "https://kibana.example.net/api/security/v1/oidc") .setting("xpack.security.authc.realms.oidc.openid7.op.issuer", "https://op.example.com/") .setting("xpack.security.authc.realms.oidc.openid7.op.authorization_endpoint", "https://op.example.com/auth") .setting("xpack.security.authc.realms.oidc.openid7.op.jwkset_path", "oidc-jwkset.json") .setting("xpack.security.authc.realms.oidc.openid7.claims.principal", "sub") .setting("xpack.security.authc.realms.oidc.openid7.http.connection_pool_ttl", "1m") .keystore("xpack.security.authc.realms.oidc.openid7.rp.client_secret", "this-is-my-secret") // - JWT (works) .setting("xpack.security.authc.realms.jwt.jwt8.order", "8") .setting("xpack.security.authc.realms.jwt.jwt8.allowed_issuer", "iss8") .setting("xpack.security.authc.realms.jwt.jwt8.allowed_signature_algorithms", "HS256") .setting("xpack.security.authc.realms.jwt.jwt8.allowed_audiences", "aud8") .setting("xpack.security.authc.realms.jwt.jwt8.claims.principal", "sub") .setting("xpack.security.authc.realms.jwt.jwt8.client_authentication.type", "shared_secret") .keystore("xpack.security.authc.realms.jwt.jwt8.client_authentication.shared_secret", "client-shared-secret-string") .keystore("xpack.security.authc.realms.jwt.jwt8.hmac_key", "hmac-oidc-key-string-for-hs256-algorithm") .rolesFile(Resource.fromClasspath("roles.yml")) .user("admin_user", "admin-password") .user("security_test_user", "security-test-password", "security_test_role", false) .user("index_and_app_user", "security-test-password", "all_index_privileges,all_application_privileges", false) .build(); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } private static Path httpCAPath; private TestSecurityClient securityClient; @BeforeClass public static void findHttpCertificateAuthority() throws Exception { final URL resource = SecurityRealmSmokeTestCase.class.getResource("/ssl/http-server-ca.crt"); if (resource == null) { throw new FileNotFoundException("Cannot find classpath resource /ssl/http-server-ca.crt"); } httpCAPath = PathUtils.get(resource.toURI()); } @Override protected Settings restAdminSettings() { String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray())); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).put(CERTIFICATE_AUTHORITIES, httpCAPath).build(); } @Override protected Settings restClientSettings() { String token = basicAuthHeaderValue("security_test_user", new SecureString("security-test-password".toCharArray())); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).put(CERTIFICATE_AUTHORITIES, httpCAPath).build(); } @Override protected String getProtocol() { // Because http.ssl.enabled = true return "https"; } protected Map<String, Object> authenticate(RequestOptions.Builder options) throws IOException { final Request request = new Request("GET", "_security/_authenticate"); request.setOptions(options); final Response response = client().performRequest(request); return entityAsMap(response); } protected void assertUsername(Map<String, Object> authenticateResponse, String username) { assertThat(authenticateResponse, hasEntry("username", username)); } protected void assertRealm(Map<String, Object> authenticateResponse, String realmType, String realmName) { assertThat(authenticateResponse, hasEntry(equalTo("authentication_realm"), instanceOf(Map.class))); Map<?, ?> realmObj = (Map<?, ?>) authenticateResponse.get("authentication_realm"); assertThat(realmObj, hasEntry("type", realmType)); assertThat(realmObj, hasEntry("name", realmName)); } protected void assertRoles(Map<String, Object> authenticateResponse, String... roles) { assertThat(authenticateResponse, hasEntry(equalTo("roles"), instanceOf(List.class))); String[] roleJson = ((List<?>) authenticateResponse.get("roles")).toArray(String[]::new); assertThat( "Server returned unexpected roles list [" + Strings.arrayToCommaDelimitedString(roleJson) + "]", roleJson, arrayContainingInAnyOrder(roles) ); } protected void assertNoApiKeyInfo(Map<String, Object> authenticateResponse, AuthenticationType type) { // If authentication type is API_KEY, authentication.api_key={"id":"abc123","name":"my-api-key"}. No encoded, api_key, or metadata. // If authentication type is other, authentication.api_key not present. assertThat(authenticateResponse, not(hasKey("api_key"))); } protected void createUser(String username, SecureString password, List<String> roles) throws IOException { getSecurityClient().putUser(new User(username, roles.toArray(String[]::new)), password); } protected void changePassword(String username, SecureString password) throws IOException { getSecurityClient().changePassword(username, password); } protected void createRole(String name, Collection<String> clusterPrivileges) throws IOException { final RoleDescriptor role = new RoleDescriptor( name, clusterPrivileges.toArray(String[]::new), new RoleDescriptor.IndicesPrivileges[0], new String[0] ); getSecurityClient().putRole(role); } protected void deleteUser(String username) throws IOException { getSecurityClient().deleteUser(username); } protected void deleteRole(String name) throws IOException { getSecurityClient().deleteRole(name); } protected TestSecurityClient getSecurityClient() { if (securityClient == null) { securityClient = new TestSecurityClient(adminClient()); } return securityClient; } }
SecurityRealmSmokeTestCase
java
junit-team__junit5
documentation/src/test/java/example/OrderedNestedTestClassesDemo.java
{ "start": 603, "end": 662 }
class ____ { @Nested @Order(1)
OrderedNestedTestClassesDemo
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/ContextLoader.java
{ "start": 4747, "end": 5783 }
class ____ use: {@value}. * @see #determineContextClass(ServletContext) */ public static final String CONTEXT_CLASS_PARAM = "contextClass"; /** * Config param for {@link ApplicationContextInitializer} classes to use * for initializing the root web application context: {@value}. * @see #customizeContext(ServletContext, ConfigurableWebApplicationContext) */ public static final String CONTEXT_INITIALIZER_CLASSES_PARAM = "contextInitializerClasses"; /** * Config param for global {@link ApplicationContextInitializer} classes to use * for initializing all web application contexts in the current application: {@value}. * @see #customizeContext(ServletContext, ConfigurableWebApplicationContext) */ public static final String GLOBAL_INITIALIZER_CLASSES_PARAM = "globalInitializerClasses"; /** * Any number of these characters are considered delimiters between * multiple values in a single init-param String value. */ private static final String INIT_PARAM_DELIMITERS = ",; \t\n"; /** * Name of the
to
java
apache__camel
components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathBeanStreamCachingTest.java
{ "start": 1108, "end": 1907 }
class ____ extends CamelTestSupport { @Test public void testFullName() throws Exception { String json = "{\"person\" : {\"firstname\" : \"foo\", \"middlename\" : \"foo2\", \"lastname\" : \"bar\"}}"; getMockEndpoint("mock:result").expectedBodiesReceived("foo foo2 bar"); template.sendBody("direct:start", new ByteArrayInputStream(json.getBytes())); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").streamCaching() .bean(FullNameBean.class).to("mock:result"); } }; } protected static
JsonPathBeanStreamCachingTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/store/records/TestMountTable.java
{ "start": 1906, "end": 10044 }
class ____ { private static final String SRC = "/test"; private static final String DST_NS_0 = "ns0"; private static final String DST_NS_1 = "ns1"; private static final String DST_PATH_0 = "/path1"; private static final String DST_PATH_1 = "/path/path2"; private static final List<RemoteLocation> DST = new LinkedList<>(); static { DST.add(new RemoteLocation(DST_NS_0, DST_PATH_0, SRC)); DST.add(new RemoteLocation(DST_NS_1, DST_PATH_1, SRC)); } private static final Map<String, String> DST_MAP = new LinkedHashMap<>(); static { DST_MAP.put(DST_NS_0, DST_PATH_0); DST_MAP.put(DST_NS_1, DST_PATH_1); } private static final long DATE_CREATED = 100; private static final long DATE_MOD = 200; private static final long NS_COUNT = 1; private static final long NS_QUOTA = 5; private static final long SS_COUNT = 10; private static final long SS_QUOTA = 100; private static final RouterQuotaUsage QUOTA = new RouterQuotaUsage.Builder() .fileAndDirectoryCount(NS_COUNT).quota(NS_QUOTA).spaceConsumed(SS_COUNT) .spaceQuota(SS_QUOTA).build(); @Test public void testGetterSetter() throws IOException { MountTable record = MountTable.newInstance(SRC, DST_MAP); validateDestinations(record); assertEquals(SRC, record.getSourcePath()); assertEquals(DST, record.getDestinations()); assertTrue(DATE_CREATED > 0); assertTrue(DATE_MOD > 0); RouterQuotaUsage quota = record.getQuota(); assertEquals(0, quota.getFileAndDirectoryCount()); assertEquals(HdfsConstants.QUOTA_RESET, quota.getQuota()); assertEquals(0, quota.getSpaceConsumed()); assertEquals(HdfsConstants.QUOTA_RESET, quota.getSpaceQuota()); MountTable record2 = MountTable.newInstance(SRC, DST_MAP, DATE_CREATED, DATE_MOD); validateDestinations(record2); assertEquals(SRC, record2.getSourcePath()); assertEquals(DST, record2.getDestinations()); assertEquals(DATE_CREATED, record2.getDateCreated()); assertEquals(DATE_MOD, record2.getDateModified()); assertFalse(record.isReadOnly()); assertEquals(DestinationOrder.HASH, record.getDestOrder()); } @Test public void testSerialization() throws IOException { testSerialization(DestinationOrder.RANDOM); testSerialization(DestinationOrder.HASH); testSerialization(DestinationOrder.LOCAL); } private void testSerialization(final DestinationOrder order) throws IOException { MountTable record = MountTable.newInstance( SRC, DST_MAP, DATE_CREATED, DATE_MOD); record.setReadOnly(true); record.setDestOrder(order); record.setQuota(QUOTA); StateStoreSerializer serializer = StateStoreSerializer.getSerializer(); String serializedString = serializer.serializeString(record); MountTable record2 = serializer.deserialize(serializedString, MountTable.class); validateDestinations(record2); assertEquals(SRC, record2.getSourcePath()); assertEquals(DST, record2.getDestinations()); assertEquals(DATE_CREATED, record2.getDateCreated()); assertEquals(DATE_MOD, record2.getDateModified()); assertTrue(record2.isReadOnly()); assertEquals(order, record2.getDestOrder()); RouterQuotaUsage quotaGet = record2.getQuota(); assertEquals(NS_COUNT, quotaGet.getFileAndDirectoryCount()); assertEquals(NS_QUOTA, quotaGet.getQuota()); assertEquals(SS_COUNT, quotaGet.getSpaceConsumed()); assertEquals(SS_QUOTA, quotaGet.getSpaceQuota()); } @Test public void testReadOnly() throws IOException { Map<String, String> dest = new LinkedHashMap<>(); dest.put(DST_NS_0, DST_PATH_0); dest.put(DST_NS_1, DST_PATH_1); MountTable record1 = MountTable.newInstance(SRC, dest); record1.setReadOnly(true); validateDestinations(record1); assertEquals(SRC, record1.getSourcePath()); assertEquals(DST, record1.getDestinations()); assertTrue(DATE_CREATED > 0); assertTrue(DATE_MOD > 0); assertTrue(record1.isReadOnly()); MountTable record2 = MountTable.newInstance( SRC, DST_MAP, DATE_CREATED, DATE_MOD); record2.setReadOnly(true); validateDestinations(record2); assertEquals(SRC, record2.getSourcePath()); assertEquals(DST, record2.getDestinations()); assertEquals(DATE_CREATED, record2.getDateCreated()); assertEquals(DATE_MOD, record2.getDateModified()); assertTrue(record2.isReadOnly()); } @Test public void testFaultTolerant() throws IOException { Map<String, String> dest = new LinkedHashMap<>(); dest.put(DST_NS_0, DST_PATH_0); dest.put(DST_NS_1, DST_PATH_1); MountTable record0 = MountTable.newInstance(SRC, dest); assertFalse(record0.isFaultTolerant()); MountTable record1 = MountTable.newInstance(SRC, dest); assertFalse(record1.isFaultTolerant()); assertEquals(record0, record1); record1.setFaultTolerant(true); assertTrue(record1.isFaultTolerant()); assertNotEquals(record0, record1); } @Test public void testOrder() throws IOException { testOrder(DestinationOrder.HASH); testOrder(DestinationOrder.LOCAL); testOrder(DestinationOrder.RANDOM); } private void testOrder(final DestinationOrder order) throws IOException { MountTable record = MountTable.newInstance( SRC, DST_MAP, DATE_CREATED, DATE_MOD); record.setDestOrder(order); validateDestinations(record); assertEquals(SRC, record.getSourcePath()); assertEquals(DST, record.getDestinations()); assertEquals(DATE_CREATED, record.getDateCreated()); assertEquals(DATE_MOD, record.getDateModified()); assertEquals(order, record.getDestOrder()); } private void validateDestinations(MountTable record) { assertEquals(SRC, record.getSourcePath()); assertEquals(2, record.getDestinations().size()); RemoteLocation location1 = record.getDestinations().get(0); assertEquals(DST_NS_0, location1.getNameserviceId()); assertEquals(DST_PATH_0, location1.getDest()); RemoteLocation location2 = record.getDestinations().get(1); assertEquals(DST_NS_1, location2.getNameserviceId()); assertEquals(DST_PATH_1, location2.getDest()); } @Test public void testQuota() throws IOException { MountTable record = MountTable.newInstance(SRC, DST_MAP); record.setQuota(QUOTA); validateDestinations(record); assertEquals(SRC, record.getSourcePath()); assertEquals(DST, record.getDestinations()); assertTrue(DATE_CREATED > 0); assertTrue(DATE_MOD > 0); RouterQuotaUsage quotaGet = record.getQuota(); assertEquals(NS_COUNT, quotaGet.getFileAndDirectoryCount()); assertEquals(NS_QUOTA, quotaGet.getQuota()); assertEquals(SS_COUNT, quotaGet.getSpaceConsumed()); assertEquals(SS_QUOTA, quotaGet.getSpaceQuota()); } @Test public void testValidation() throws IOException { Map<String, String> destinations = new HashMap<>(); destinations.put("ns0", "/testValidate-dest"); try { MountTable.newInstance("testValidate", destinations); fail("Mount table entry should be created failed."); } catch (Exception e) { GenericTestUtils.assertExceptionContains( MountTable.ERROR_MSG_MUST_START_WITH_BACK_SLASH, e); } destinations.clear(); destinations.put("ns0", "testValidate-dest"); try { MountTable.newInstance("/testValidate", destinations); fail("Mount table entry should be created failed."); } catch (Exception e) { GenericTestUtils.assertExceptionContains( MountTable.ERROR_MSG_ALL_DEST_MUST_START_WITH_BACK_SLASH, e); } destinations.clear(); destinations.put("", "/testValidate-dest"); try { MountTable.newInstance("/testValidate", destinations); fail("Mount table entry should be created failed."); } catch (Exception e) { GenericTestUtils.assertExceptionContains( MountTable.ERROR_MSG_INVALID_DEST_NS, e); } destinations.clear(); destinations.put("ns0", "/testValidate-dest"); MountTable record = MountTable.newInstance("/testValidate", destinations); assertNotNull(record); } }
TestMountTable
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/StartTrainedModelDeploymentAction.java
{ "start": 2111, "end": 4004 }
class ____ extends ActionType<CreateTrainedModelAssignmentAction.Response> { public static final StartTrainedModelDeploymentAction INSTANCE = new StartTrainedModelDeploymentAction(); public static final String NAME = "cluster:admin/xpack/ml/trained_models/deployment/start"; public static final TimeValue DEFAULT_TIMEOUT = new TimeValue(30, TimeUnit.SECONDS); /** * This has been found to be approximately 300MB on linux by manual testing. * 30MB of this is accounted for via the space set aside to load the code into memory * that we always add as overhead (see MachineLearning.NATIVE_EXECUTABLE_CODE_OVERHEAD). * That would result in 270MB here, although the problem with this is that it would * mean few models would fit on a 2GB ML node in Cloud with logging and metrics enabled. * Therefore we push the boundary a bit and require a 240MB per-model overhead. * TODO Check if it is substantially different in other platforms. */ private static final ByteSizeValue MEMORY_OVERHEAD = ByteSizeValue.ofMb(240); /** * The ELSER model turned out to use more memory than what we usually estimate. * We overwrite the estimate with this static value for ELSER v1 and v2 for now. * Soon to be replaced with a better estimate provided by the model. */ private static final ByteSizeValue ELSER_1_OR_2_MEMORY_USAGE = ByteSizeValue.ofMb(2004); public static final AllocationStatus.State DEFAULT_WAITFOR_STATE = AllocationStatus.State.STARTED; public static final int DEFAULT_NUM_ALLOCATIONS = 1; public static final int DEFAULT_NUM_THREADS = 1; public static final int DEFAULT_QUEUE_CAPACITY = 10_000; public static final Priority DEFAULT_PRIORITY = Priority.NORMAL; public StartTrainedModelDeploymentAction() { super(NAME); } public static
StartTrainedModelDeploymentAction
java
spring-projects__spring-boot
module/spring-boot-pulsar/src/test/java/org/springframework/boot/pulsar/autoconfigure/PulsarPropertiesTests.java
{ "start": 20012, "end": 20333 }
class ____ { @Test void bind() { Map<String, String> map = new HashMap<>(); map.put("spring.pulsar.template.observations-enabled", "true"); PulsarProperties.Template properties = bindProperties(map).getTemplate(); assertThat(properties.isObservationsEnabled()).isTrue(); } } @Nested
TemplateProperties
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AutoValueBoxedValuesTest.java
{ "start": 18457, "end": 19026 }
class ____ {", " public abstract Long longId();", " @SuppressWarnings(\"AutoValueBoxedValues\")", " public abstract Long longIdSuppressWarnings();"), linesWithoutBuilder( " static Test create(Long longId, Long longIdSuppressWarnings) {", " return new AutoValue_Test(longId, longIdSuppressWarnings);", " }"), linesWithBuilder( " @AutoValue.Builder", " abstract static
Test
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonCountDownLatchConcurrentTest.java
{ "start": 345, "end": 1648 }
class ____ extends RedisDockerTest { @Test public void testSingleCountDownAwait_SingleInstance() throws InterruptedException { int iterations = Runtime.getRuntime().availableProcessors()*3; RCountDownLatch latch = redisson.getCountDownLatch("latch"); latch.trySetCount(iterations); AtomicInteger counter = new AtomicInteger(); ExecutorService executor = Executors.newScheduledThreadPool(iterations); for (int i = 0; i < iterations; i++) { executor.execute(() -> { try { latch.await(); Assertions.assertEquals(0, latch.getCount()); Assertions.assertEquals(iterations, counter.get()); } catch (InterruptedException e) { Assertions.fail(); } }); } ExecutorService countDownExecutor = Executors.newFixedThreadPool(iterations); for (int i = 0; i < iterations; i++) { countDownExecutor.execute(() -> { latch.countDown(); counter.incrementAndGet(); }); } executor.shutdown(); Assertions.assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); } }
RedissonCountDownLatchConcurrentTest
java
apache__camel
components/camel-olingo4/camel-olingo4-component/src/generated/java/org/apache/camel/component/olingo4/Olingo4ConfigurationConfigurer.java
{ "start": 724, "end": 7760 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("ApiName", org.apache.camel.component.olingo4.internal.Olingo4ApiName.class); map.put("ConnectTimeout", int.class); map.put("ContentType", java.lang.String.class); map.put("FilterAlreadySeen", boolean.class); map.put("HttpAsyncClientBuilder", org.apache.http.impl.nio.client.HttpAsyncClientBuilder.class); map.put("HttpClientBuilder", org.apache.http.impl.client.HttpClientBuilder.class); map.put("HttpHeaders", java.util.Map.class); map.put("MethodName", java.lang.String.class); map.put("Proxy", org.apache.http.HttpHost.class); map.put("ServiceUri", java.lang.String.class); map.put("SocketTimeout", int.class); map.put("SplitResult", boolean.class); map.put("SslContextParameters", org.apache.camel.support.jsse.SSLContextParameters.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.olingo4.Olingo4Configuration target = (org.apache.camel.component.olingo4.Olingo4Configuration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.olingo4.internal.Olingo4ApiName.class, value)); return true; case "connecttimeout": case "connectTimeout": target.setConnectTimeout(property(camelContext, int.class, value)); return true; case "contenttype": case "contentType": target.setContentType(property(camelContext, java.lang.String.class, value)); return true; case "filteralreadyseen": case "filterAlreadySeen": target.setFilterAlreadySeen(property(camelContext, boolean.class, value)); return true; case "httpasyncclientbuilder": case "httpAsyncClientBuilder": target.setHttpAsyncClientBuilder(property(camelContext, org.apache.http.impl.nio.client.HttpAsyncClientBuilder.class, value)); return true; case "httpclientbuilder": case "httpClientBuilder": target.setHttpClientBuilder(property(camelContext, org.apache.http.impl.client.HttpClientBuilder.class, value)); return true; case "httpheaders": case "httpHeaders": target.setHttpHeaders(property(camelContext, java.util.Map.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "proxy": target.setProxy(property(camelContext, org.apache.http.HttpHost.class, value)); return true; case "serviceuri": case "serviceUri": target.setServiceUri(property(camelContext, java.lang.String.class, value)); return true; case "sockettimeout": case "socketTimeout": target.setSocketTimeout(property(camelContext, int.class, value)); return true; case "splitresult": case "splitResult": target.setSplitResult(property(camelContext, boolean.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": target.setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return org.apache.camel.component.olingo4.internal.Olingo4ApiName.class; case "connecttimeout": case "connectTimeout": return int.class; case "contenttype": case "contentType": return java.lang.String.class; case "filteralreadyseen": case "filterAlreadySeen": return boolean.class; case "httpasyncclientbuilder": case "httpAsyncClientBuilder": return org.apache.http.impl.nio.client.HttpAsyncClientBuilder.class; case "httpclientbuilder": case "httpClientBuilder": return org.apache.http.impl.client.HttpClientBuilder.class; case "httpheaders": case "httpHeaders": return java.util.Map.class; case "methodname": case "methodName": return java.lang.String.class; case "proxy": return org.apache.http.HttpHost.class; case "serviceuri": case "serviceUri": return java.lang.String.class; case "sockettimeout": case "socketTimeout": return int.class; case "splitresult": case "splitResult": return boolean.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.olingo4.Olingo4Configuration target = (org.apache.camel.component.olingo4.Olingo4Configuration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return target.getApiName(); case "connecttimeout": case "connectTimeout": return target.getConnectTimeout(); case "contenttype": case "contentType": return target.getContentType(); case "filteralreadyseen": case "filterAlreadySeen": return target.isFilterAlreadySeen(); case "httpasyncclientbuilder": case "httpAsyncClientBuilder": return target.getHttpAsyncClientBuilder(); case "httpclientbuilder": case "httpClientBuilder": return target.getHttpClientBuilder(); case "httpheaders": case "httpHeaders": return target.getHttpHeaders(); case "methodname": case "methodName": return target.getMethodName(); case "proxy": return target.getProxy(); case "serviceuri": case "serviceUri": return target.getServiceUri(); case "sockettimeout": case "socketTimeout": return target.getSocketTimeout(); case "splitresult": case "splitResult": return target.isSplitResult(); case "sslcontextparameters": case "sslContextParameters": return target.getSslContextParameters(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "httpheaders": case "httpHeaders": return java.lang.String.class; default: return null; } } }
Olingo4ConfigurationConfigurer
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterInfoIntegrationTests.java
{ "start": 1036, "end": 1521 }
class ____ extends AbstractJupiterTestEngineTests { @Test void storesParameterInfoInExtensionContextStoreOnDifferentLevels() { var results = executeTestsForClass(TestCase.class); results.allEvents().debug().assertStatistics(stats -> stats.started(7).succeeded(7)); } @ParameterizedClass @ValueSource(ints = 1) @ExtendWith(ParameterInfoConsumingExtension.class) record TestCase(int i) { @Nested @ParameterizedClass @ValueSource(ints = 2)
ParameterInfoIntegrationTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvtVO/DataTransaction2.java
{ "start": 2492, "end": 2684 }
class ____ { private Param param = new Param(); private DataSet dataset = new DataSet(); public Body() { } /** * 参数 * */
Body
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builtin/bean/JakartaJaxbElementListProperty.java
{ "start": 262, "end": 612 }
class ____ { // CHECKSTYLE:OFF public List<JAXBElement<String>> publicProp; // CHECKSTYLE:ON private List<JAXBElement<String>> prop; public List<JAXBElement<String>> getProp() { return prop; } public void setProp( List<JAXBElement<String>> prop ) { this.prop = prop; } }
JakartaJaxbElementListProperty
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3652/FooBarMapper.java
{ "start": 304, "end": 452 }
interface ____ { FooBarMapper INSTANCE = Mappers.getMapper( FooBarMapper.class ); Bar toBar(Foo foo); Foo toFoo(Bar bar); }
FooBarMapper
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/webapp/dao/ConfEntryInfo.java
{ "start": 1072, "end": 1609 }
class ____ { protected String name; protected String value; protected String[] source; public ConfEntryInfo() { } public ConfEntryInfo(String key, String value) { this(key, value, null); } public ConfEntryInfo(String key, String value, String[] source) { this.name = key; this.value = value; this.source = source; } public String getName() { return this.name; } public String getValue() { return this.value; } public String[] getSource() { return source; } }
ConfEntryInfo
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/short2darrays/Short2DArrays_assertNullOrEmpty_Test.java
{ "start": 785, "end": 1053 }
class ____ extends Short2DArraysBaseTest { @Test void should_delegate_to_Arrays2D() { // WHEN short2DArrays.assertNullOrEmpty(info, actual); // THEN verify(arrays2d).assertNullOrEmpty(info, failures, actual); } }
Short2DArrays_assertNullOrEmpty_Test
java
spring-projects__spring-boot
module/spring-boot-jackson2/src/test/java/org/springframework/boot/jackson2/JsonObjectSerializerTests.java
{ "start": 1101, "end": 1781 }
class ____ { @Test void serializeObjectShouldWriteJson() throws Exception { org.springframework.boot.jackson2.NameAndAgeJsonComponent.Serializer serializer = new org.springframework.boot.jackson2.NameAndAgeJsonComponent.Serializer(); SimpleModule module = new SimpleModule(); module.addSerializer(org.springframework.boot.jackson2.types.NameAndAge.class, serializer); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); String json = mapper.writeValueAsString(new org.springframework.boot.jackson2.types.NameAndAge("spring", 100)); assertThat(json).isEqualToIgnoringWhitespace("{\"name\":\"spring\",\"age\":100}"); } }
JsonObjectSerializerTests
java
apache__camel
components/camel-huawei/camel-huaweicloud-obs/src/test/java/org/apache/camel/component/huaweicloud/obs/ListObjectsJsonFunctionalTest.java
{ "start": 1360, "end": 3593 }
class ____ extends CamelTestSupport { private static final String ACCESS_KEY = "replace_this_with_access_key"; private static final String SECRET_KEY = "replace_this_with_secret_key"; private static final String REGION = "replace_this_with_region"; private static final String BUCKET_NAME = "replace_this_with_bucket_name"; @BindToRegistry("serviceKeys") ServiceKeys serviceKeys = new ServiceKeys(ACCESS_KEY, SECRET_KEY); protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:list_objects") .to("hwcloud-obs:listObjects?" + "serviceKeys=#serviceKeys" + "&region=" + REGION + "&ignoreSslVerification=true") .log("List objects successful") .to("log:LOG?showAll=true") .to("mock:list_objects_result"); } }; } /** * The following test cases should be manually enabled to perform test against the actual HuaweiCloud OBS server * with real user credentials. To perform this test, manually comment out the @Ignore annotation and enter relevant * service parameters in the placeholders above (static variables of this test class) * * @throws Exception */ @Disabled("Manually enable this once you configure the parameters in the placeholders above") @Test public void testListBuckets() throws Exception { MockEndpoint mock = getMockEndpoint("mock:list_objects_result"); mock.expectedMinimumMessageCount(1); // More parameters can be added to the Json string below. E.g. delimiter, marker, maxKeys, prefix String request = "{\"bucketName\":\"" + BUCKET_NAME + "\"}"; template.sendBody("direct:list_objects", request); Exchange responseExchange = mock.getExchanges().get(0); mock.assertIsSatisfied(); assertNotNull(responseExchange.getIn().getBody(String.class)); assertTrue(responseExchange.getIn().getBody(String.class).length() > 0); } }
ListObjectsJsonFunctionalTest
java
google__guava
guava-gwt/src-super/com/google/common/cache/super/com/google/common/cache/LocalCache.java
{ "start": 9925, "end": 10950 }
class ____<V> { private final V value; private final Ticker ticker; private long writeTimestamp; private long accessTimestamp; public Timestamped(V value, Ticker ticker) { this.value = checkNotNull(value); this.ticker = checkNotNull(ticker); this.writeTimestamp = ticker.read(); this.accessTimestamp = this.writeTimestamp; } public V getValue() { return value; } public void updateTimestamp() { accessTimestamp = ticker.read(); } public long getAccessTimestamp() { return accessTimestamp; } public long getWriteTimestamp() { return writeTimestamp; } @Override public boolean equals(Object o) { return value.equals(o); } @Override public int hashCode() { return value.hashCode(); } } /** * LocalManualCache is a wrapper around LocalCache for a cache without loading. * * @param <K> the base key type * @param <V> the base value type */ public static
Timestamped
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/message/ReusableMessageFactory.java
{ "start": 1560, "end": 8132 }
class ____ implements MessageFactory2, Serializable { /** * Instance of ReusableMessageFactory. */ public static final ReusableMessageFactory INSTANCE = new ReusableMessageFactory(); private static final long serialVersionUID = 1L; private final transient ThreadLocal<ReusableParameterizedMessage> threadLocalParameterized = new ThreadLocal<>(); private final transient ThreadLocal<ReusableSimpleMessage> threadLocalSimpleMessage = new ThreadLocal<>(); private final transient ThreadLocal<ReusableObjectMessage> threadLocalObjectMessage = new ThreadLocal<>(); /** * Constructs a message factory. */ public ReusableMessageFactory() {} private ReusableParameterizedMessage getParameterized() { ReusableParameterizedMessage result = threadLocalParameterized.get(); if (result == null) { result = new ReusableParameterizedMessage(); threadLocalParameterized.set(result); } return result.reserved ? new ReusableParameterizedMessage().reserve() : result.reserve(); } private ReusableSimpleMessage getSimple() { ReusableSimpleMessage result = threadLocalSimpleMessage.get(); if (result == null) { result = new ReusableSimpleMessage(); threadLocalSimpleMessage.set(result); } return result; } private ReusableObjectMessage getObject() { ReusableObjectMessage result = threadLocalObjectMessage.get(); if (result == null) { result = new ReusableObjectMessage(); threadLocalObjectMessage.set(result); } return result; } /** * Invokes {@link Clearable#clear()} when possible. * This flag is used internally to verify that a reusable message is no longer in use and * can be reused. * @param message the message to make available again * @since 2.7 */ public static void release(final Message message) { // LOG4J2-1583 if (message instanceof Clearable) { ((Clearable) message).clear(); } } @Override public Message newMessage(final CharSequence charSequence) { final ReusableSimpleMessage result = getSimple(); result.set(charSequence); return result; } /** * Creates {@link ReusableParameterizedMessage} instances. * * @param message The message pattern. * @param params The message parameters. * @return The Message. * * @see MessageFactory#newMessage(String, Object...) */ @Override public Message newMessage(final String message, final Object... params) { return getParameterized().set(message, params); } @Override public Message newMessage(final String message, final Object p0) { return getParameterized().set(message, p0); } @Override public Message newMessage(final String message, final Object p0, final Object p1) { return getParameterized().set(message, p0, p1); } @Override public Message newMessage(final String message, final Object p0, final Object p1, final Object p2) { return getParameterized().set(message, p0, p1, p2); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3) { return getParameterized().set(message, p0, p1, p2, p3); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4) { return getParameterized().set(message, p0, p1, p2, p3, p4); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5) { return getParameterized().set(message, p0, p1, p2, p3, p4, p5); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6) { return getParameterized().set(message, p0, p1, p2, p3, p4, p5, p6); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7) { return getParameterized().set(message, p0, p1, p2, p3, p4, p5, p6, p7); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7, final Object p8) { return getParameterized().set(message, p0, p1, p2, p3, p4, p5, p6, p7, p8); } @Override public Message newMessage( final String message, final Object p0, final Object p1, final Object p2, final Object p3, final Object p4, final Object p5, final Object p6, final Object p7, final Object p8, final Object p9) { return getParameterized().set(message, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } /** * Creates {@link ReusableSimpleMessage} instances. * * @param message The message String. * @return The Message. * * @see MessageFactory#newMessage(String) */ @Override public Message newMessage(final String message) { final ReusableSimpleMessage result = getSimple(); result.set(message); return result; } /** * Creates {@link ReusableObjectMessage} instances. * * @param message The message Object. * @return The Message. * * @see MessageFactory#newMessage(Object) */ @Override public Message newMessage(final Object message) { final ReusableObjectMessage result = getObject(); result.set(message); return result; } private Object writeReplace() { return new SerializationProxy(); } private static
ReusableMessageFactory
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/support/DirtiesContextTestExecutionListenerTests.java
{ "start": 3008, "end": 8190 }
class ____ { @Test void declaredLocallyOnMethodWithBeforeMethodMode() throws Exception { Class<?> clazz = getClass().getEnclosingClass(); BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn( clazz.getDeclaredMethod("dirtiesContextDeclaredLocallyWithBeforeMethodMode")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); verify(testContext, times(1)).markApplicationContextDirty(EXHAUSTIVE); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(1)).markApplicationContextDirty(EXHAUSTIVE); } @Test void declaredLocallyOnMethodWithAfterMethodMode() throws Exception { Class<?> clazz = getClass().getEnclosingClass(); BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn( clazz.getDeclaredMethod("dirtiesContextDeclaredLocallyWithAfterMethodMode")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class)); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(1)).markApplicationContextDirty(EXHAUSTIVE); } @Test void declaredOnMethodViaMetaAnnotationWithAfterMethodMode() throws Exception { Class<?> clazz = getClass().getEnclosingClass(); BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn( clazz.getDeclaredMethod("dirtiesContextDeclaredViaMetaAnnotationWithAfterMethodMode")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class)); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(1)).markApplicationContextDirty(EXHAUSTIVE); } @Test void declaredLocallyOnClassBeforeEachTestMethod() throws Exception { assertBeforeMethod(DirtiesContextDeclaredLocallyBeforeEachTestMethod.class); } @Test void declaredLocallyOnClassAfterEachTestMethod() throws Exception { assertAfterMethod(DirtiesContextDeclaredLocallyAfterEachTestMethod.class); } @Test void declaredViaMetaAnnotationOnClassAfterEachTestMethod() throws Exception { assertAfterMethod(DirtiesContextDeclaredViaMetaAnnotationAfterEachTestMethod.class); } @Test void declaredLocallyOnClassBeforeClass() throws Exception { Class<?> clazz = DirtiesContextDeclaredLocallyBeforeClass.class; BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("test")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class)); } @Test void declaredLocallyOnClassAfterClass() throws Exception { Class<?> clazz = DirtiesContextDeclaredLocallyAfterClass.class; BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("test")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class)); } @Test void declaredViaMetaAnnotationOnClassAfterClass() throws Exception { Class<?> clazz = DirtiesContextDeclaredViaMetaAnnotationAfterClass.class; BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("test")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class)); } @Test void beforeAndAfterTestMethodForDirtiesContextViaMetaAnnotationWithOverrides() throws Exception { Class<?> clazz = DirtiesContextViaMetaAnnotationWithOverrides.class; BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("test")); beforeListener.beforeTestMethod(testContext); afterListener.beforeTestMethod(testContext); verify(testContext, times(0)).markApplicationContextDirty(any(HierarchyMode.class)); afterListener.afterTestMethod(testContext); beforeListener.afterTestMethod(testContext); verify(testContext, times(1)).markApplicationContextDirty(CURRENT_LEVEL); } } @Nested @DisplayName("Before and after test class")
BeforeAndAfterTestMethodTests
java
netty__netty
microbench/src/main/java/io/netty/microbench/http/HttpPipelinedRequestDecoderBenchmark.java
{ "start": 2252, "end": 4438 }
class ____ extends AbstractMicrobenchmark { @Param({ "false", "true" }) public boolean direct; @Param({ "1", "16" }) public int pipeline; @Param({ "false", "true" }) public boolean pooled; @Param({ "true", "false" }) public boolean validateHeaders; private EmbeddedChannel channel; private ByteBuf pipelinedRequest; @Setup public void initPipeline() { final ByteBufAllocator allocator = pooled? PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT; pipelinedRequest = pipelined(allocator, CONTENT_MIXED_DELIMITERS, pipeline, direct); channel = new EmbeddedChannel( new HttpRequestDecoder(DEFAULT_MAX_INITIAL_LINE_LENGTH, DEFAULT_MAX_HEADER_SIZE, DEFAULT_MAX_CHUNK_SIZE, validateHeaders, DEFAULT_INITIAL_BUFFER_SIZE)); // this is a trick to save doing it each time pipelinedRequest.retain((Integer.MAX_VALUE / 2 - 1) - pipeline); } private static ByteBuf pipelined(ByteBufAllocator alloc, byte[] content, int pipeline, boolean direct) { final int totalSize = pipeline * content.length; final ByteBuf buf = direct? alloc.directBuffer(totalSize, totalSize) : alloc.heapBuffer(totalSize, totalSize); for (int i = 0; i < pipeline; i++) { buf.writeBytes(content); } return buf; } @Benchmark @CompilerControl(Mode.DONT_INLINE) public void testDecodeWholePipelinedRequestMixedDelimiters() { final EmbeddedChannel channel = this.channel; final ByteBuf batch = this.pipelinedRequest; final int refCnt = batch.refCnt(); if (refCnt == 1) { batch.retain((Integer.MAX_VALUE / 2 - 1) - pipeline); } batch.resetReaderIndex(); channel.writeInbound(batch); final Queue<Object> decoded = channel.inboundMessages(); Object o; while ((o = decoded.poll()) != null) { ReferenceCountUtil.release(o); } } @TearDown public void release() { this.pipelinedRequest.release(pipelinedRequest.refCnt()); } }
HttpPipelinedRequestDecoderBenchmark
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/CloserTest.java
{ "start": 4396, "end": 4889 }
class ____ implements Closeable { private final Counter counter; public SingletonResource(Counter counter) { this.counter = counter; } @GET public int get(@Context Closer closer) { closer.add(this); return counter.singleton.get(); } @Override public void close() { counter.singleton.incrementAndGet(); } } @Path("uni-singleton") public static
SingletonResource
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/objects/Objects_assertIsInstanceOfAny_Test.java
{ "start": 1694, "end": 3793 }
class ____ extends ObjectsBaseTest { private static Person actual; @BeforeAll static void setUpOnce() { actual = new Person("Yoda"); } @Test void should_pass_if_actual_is_instance_of_any_type() { Class<?>[] types = { String.class, Person.class }; objects.assertIsInstanceOfAny(someInfo(), actual, types); } @Test void should_throw_error_if_array_of_types_is_null() { assertThatNullPointerException().isThrownBy(() -> objects.assertIsInstanceOfAny(someInfo(), actual, null)) .withMessage("The given array of types should not be null"); } @Test void should_throw_error_if_array_of_types_is_empty() { assertThatIllegalArgumentException().isThrownBy(() -> objects.assertIsInstanceOfAny(someInfo(), actual, new Class<?>[0])) .withMessage("The given array of types should not be empty"); } @Test void should_throw_error_if_array_of_types_has_null_elements() { Class<?>[] types = { null, String.class }; assertThatNullPointerException().isThrownBy(() -> objects.assertIsInstanceOfAny(someInfo(), actual, types)) .withMessage("The given array of types:<[null, java.lang.String]> should not have null elements"); } @Test void should_fail_if_actual_is_null() { Class<?>[] types = { Object.class }; assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> objects.assertIsInstanceOfAny(someInfo(), null, types)) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_is_not_instance_of_any_type() { AssertionInfo info = someInfo(); Class<?>[] types = { String.class, File.class }; Throwable error = catchThrowable(() -> objects.assertIsInstanceOfAny(info, actual, types)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeInstanceOfAny(actual, types)); } }
Objects_assertIsInstanceOfAny_Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/VariableWidthHistogramAggregator.java
{ "start": 6796, "end": 8230 }
class ____ extends CollectionPhase { /** * "Cluster" refers to intermediate buckets during collection * They are kept sorted by centroid. The i'th index in all these arrays always refers to the i'th cluster */ public DoubleArray clusterMaxes; public DoubleArray clusterMins; public DoubleArray clusterCentroids; public DoubleArray clusterSizes; // clusterSizes != bucketDocCounts when clusters are in the middle of a merge public int numClusters; private double avgBucketDistance; MergeBucketsPhase(DoubleArray buffer, int bufferSize) { // Cluster the documents to reduce the number of buckets boolean success = false; try { bucketBufferedDocs(buffer, bufferSize, mergePhaseInitialBucketCount(shardSize)); success = true; } finally { if (success == false) { close(); clusterMaxes = clusterMins = clusterCentroids = clusterSizes = null; } } if (bufferSize > 1) { updateAvgBucketDistance(); } } /** * Sorts the <b>indices</b> of <code>values</code> by their underlying value * This will produce a merge map whose application will sort <code>values</code> */ private static
MergeBucketsPhase
java
netty__netty
codec-memcache/src/main/java/io/netty/handler/codec/memcache/binary/BinaryMemcacheResponseDecoder.java
{ "start": 888, "end": 1930 }
class ____ extends AbstractBinaryMemcacheDecoder<BinaryMemcacheResponse> { public BinaryMemcacheResponseDecoder() { this(DEFAULT_MAX_CHUNK_SIZE); } public BinaryMemcacheResponseDecoder(int chunkSize) { super(chunkSize); } @Override protected BinaryMemcacheResponse decodeHeader(ByteBuf in) { DefaultBinaryMemcacheResponse header = new DefaultBinaryMemcacheResponse(); header.setMagic(in.readByte()); header.setOpcode(in.readByte()); header.setKeyLength(in.readShort()); header.setExtrasLength(in.readByte()); header.setDataType(in.readByte()); header.setStatus(in.readShort()); header.setTotalBodyLength(in.readInt()); header.setOpaque(in.readInt()); header.setCas(in.readLong()); return header; } @Override protected BinaryMemcacheResponse buildInvalidMessage() { return new DefaultBinaryMemcacheResponse(Unpooled.EMPTY_BUFFER, Unpooled.EMPTY_BUFFER); } }
BinaryMemcacheResponseDecoder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/tasks/mailbox/TaskMailboxProcessorTest.java
{ "start": 16352, "end": 17789 }
class ____ extends Thread implements MailboxDefaultAction { MailboxProcessor mailboxProcessor; OneShotLatch mailboxCreatedLatch = new OneShotLatch(); OneShotLatch canRun = new OneShotLatch(); private Throwable caughtException; @Override public final void run() { mailboxProcessor = new MailboxProcessor(this); mailboxCreatedLatch.trigger(); try { canRun.await(); mailboxProcessor.runMailboxLoop(); } catch (Throwable t) { this.caughtException = t; } } @Override public void runDefaultAction(Controller controller) throws Exception { controller.allActionsCompleted(); } final MailboxProcessor getMailboxProcessor() { try { mailboxCreatedLatch.await(); return mailboxProcessor; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } final void signalStart() { if (mailboxCreatedLatch.isTriggered()) { canRun.trigger(); } } void checkException() throws Exception { if (caughtException != null) { throw new Exception(caughtException); } } } }
MailboxThread
java
elastic__elasticsearch
x-pack/plugin/wildcard/src/test/java/org/elasticsearch/xpack/wildcard/mapper/WildcardFieldBlockLoaderTests.java
{ "start": 684, "end": 2214 }
class ____ extends BlockLoaderTestCase { public WildcardFieldBlockLoaderTests(Params params) { super(FieldType.WILDCARD.toString(), params); } @Override @SuppressWarnings("unchecked") protected Object expected(Map<String, Object> fieldMapping, Object value, TestContext testContext) { var nullValue = (String) fieldMapping.get("null_value"); var ignoreAbove = fieldMapping.get("ignore_above") == null ? Integer.MAX_VALUE : ((Number) fieldMapping.get("ignore_above")).intValue(); if (value == null) { return convert(null, nullValue, ignoreAbove); } if (value instanceof String s) { return convert(s, nullValue, ignoreAbove); } var resultList = ((List<String>) value).stream() .map(s -> convert(s, nullValue, ignoreAbove)) .filter(Objects::nonNull) .distinct() .sorted() .toList(); return maybeFoldList(resultList); } private static BytesRef convert(String value, String nullValue, int ignoreAbove) { if (value == null) { if (nullValue != null) { value = nullValue; } else { return null; } } return value.length() <= ignoreAbove ? new BytesRef(value) : null; } @Override protected Collection<? extends Plugin> getPlugins() { return Collections.singleton(new Wildcard()); } }
WildcardFieldBlockLoaderTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/OperatorSubtaskState.java
{ "start": 16114, "end": 20357 }
class ____ { private StateObjectCollection<OperatorStateHandle> managedOperatorState = StateObjectCollection.empty(); private StateObjectCollection<OperatorStateHandle> rawOperatorState = StateObjectCollection.empty(); private StateObjectCollection<KeyedStateHandle> managedKeyedState = StateObjectCollection.empty(); private StateObjectCollection<KeyedStateHandle> rawKeyedState = StateObjectCollection.empty(); private StateObjectCollection<InputStateHandle> inputChannelState = StateObjectCollection.empty(); private StateObjectCollection<OutputStateHandle> resultSubpartitionState = StateObjectCollection.empty(); private InflightDataRescalingDescriptor inputRescalingDescriptor = InflightDataRescalingDescriptor.NO_RESCALE; private InflightDataRescalingDescriptor outputRescalingDescriptor = InflightDataRescalingDescriptor.NO_RESCALE; private Builder() {} public Builder setManagedOperatorState( StateObjectCollection<OperatorStateHandle> managedOperatorState) { this.managedOperatorState = checkNotNull(managedOperatorState); return this; } public Builder setManagedOperatorState(OperatorStateHandle managedOperatorState) { return setManagedOperatorState( StateObjectCollection.singleton(checkNotNull(managedOperatorState))); } public Builder setRawOperatorState( StateObjectCollection<OperatorStateHandle> rawOperatorState) { this.rawOperatorState = checkNotNull(rawOperatorState); return this; } public Builder setRawOperatorState(OperatorStateHandle rawOperatorState) { return setRawOperatorState( StateObjectCollection.singleton(checkNotNull(rawOperatorState))); } public Builder setManagedKeyedState( StateObjectCollection<KeyedStateHandle> managedKeyedState) { this.managedKeyedState = checkNotNull(managedKeyedState); return this; } public Builder setManagedKeyedState(KeyedStateHandle managedKeyedState) { return setManagedKeyedState( StateObjectCollection.singleton(checkNotNull(managedKeyedState))); } public Builder setRawKeyedState(StateObjectCollection<KeyedStateHandle> rawKeyedState) { this.rawKeyedState = checkNotNull(rawKeyedState); return this; } public Builder setRawKeyedState(KeyedStateHandle rawKeyedState) { return setRawKeyedState(StateObjectCollection.singleton(checkNotNull(rawKeyedState))); } public Builder setInputChannelState( StateObjectCollection<InputStateHandle> inputChannelState) { this.inputChannelState = checkNotNull(inputChannelState); return this; } public Builder setResultSubpartitionState( StateObjectCollection<OutputStateHandle> resultSubpartitionState) { this.resultSubpartitionState = checkNotNull(resultSubpartitionState); return this; } public Builder setInputRescalingDescriptor( InflightDataRescalingDescriptor inputRescalingDescriptor) { this.inputRescalingDescriptor = checkNotNull(inputRescalingDescriptor); return this; } public Builder setOutputRescalingDescriptor( InflightDataRescalingDescriptor outputRescalingDescriptor) { this.outputRescalingDescriptor = checkNotNull(outputRescalingDescriptor); return this; } public OperatorSubtaskState build() { return new OperatorSubtaskState( managedOperatorState, rawOperatorState, managedKeyedState, rawKeyedState, inputChannelState, resultSubpartitionState, inputRescalingDescriptor, outputRescalingDescriptor); } } }
Builder
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/RestFilter.java
{ "start": 1516, "end": 1728 }
interface ____ { void doFilter(HttpRequest request, HttpResponse response) throws Exception; CompletableFuture<Boolean> doFilterAsync(HttpRequest request, HttpResponse response); } }
FilterChain
java
google__guava
guava-testlib/test/com/google/common/testing/ClassSanityTesterTest.java
{ "start": 5525, "end": 6008 }
class ____ { public static Object good(Runnable r) { return r; } public static Object good(AnInterface i) { return i; } private GoodSerializableFactory() {} } public void testSerializableOnReturnValues_bad() throws Exception { try { tester.forAllPublicStaticMethods(BadSerializableFactory.class).testSerializable(); } catch (AssertionError expected) { return; } fail(); } public static final
GoodSerializableFactory