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
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
{ "start": 162294, "end": 162940 }
class ____ { int[] x; public Test(int foo) { x = null; } public static <T extends CharSequence & Comparable<String>> int[] foo() { int z = 1; switch (z) { case 1: T foo = null; break; case 2: System.out.println("Somehow, z was 2."); foo = null; } return new int[0]; } } """) .addOutputLines( "Test.java", """
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/executiongraph/utils/NotCancelAckingTaskGateway.java
{ "start": 1067, "end": 1331 }
class ____ extends SimpleAckingTaskManagerGateway { @Override public CompletableFuture<Acknowledge> cancelTask( ExecutionAttemptID executionAttemptID, Duration timeout) { return new CompletableFuture<>(); } }
NotCancelAckingTaskGateway
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/token/TransportRefreshTokenAction.java
{ "start": 1090, "end": 2288 }
class ____ extends HandledTransportAction<CreateTokenRequest, CreateTokenResponse> { private final TokenService tokenService; @Inject public TransportRefreshTokenAction(TransportService transportService, ActionFilters actionFilters, TokenService tokenService) { super(RefreshTokenAction.NAME, transportService, actionFilters, CreateTokenRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE); this.tokenService = tokenService; } @Override protected void doExecute(Task task, CreateTokenRequest request, ActionListener<CreateTokenResponse> listener) { tokenService.refreshToken(request.getRefreshToken(), ActionListener.wrap(tokenResult -> { final String scope = getResponseScopeValue(request.getScope()); final CreateTokenResponse response = new CreateTokenResponse( tokenResult.getAccessToken(), tokenService.getExpirationDelay(), scope, tokenResult.getRefreshToken(), null, tokenResult.getAuthentication() ); listener.onResponse(response); }, listener::onFailure)); } }
TransportRefreshTokenAction
java
apache__flink
flink-metrics/flink-metrics-dropwizard/src/main/java/org/apache/flink/dropwizard/metrics/FlinkHistogramWrapper.java
{ "start": 1162, "end": 1702 }
class ____ extends com.codahale.metrics.Histogram { private final Histogram histogram; public FlinkHistogramWrapper(Histogram histogram) { super(null); this.histogram = histogram; } @Override public void update(long value) { histogram.update(value); } @Override public long getCount() { return histogram.getCount(); } @Override public Snapshot getSnapshot() { return new HistogramStatisticsWrapper(histogram.getStatistics()); } }
FlinkHistogramWrapper
java
apache__camel
tooling/maven/camel-restdsl-openapi-plugin/src/main/java/org/apache/camel/maven/generator/openapi/GenerateYamlWithDtoMojo.java
{ "start": 1336, "end": 1704 }
class ____ extends GenerateYamlMojo { @Inject public GenerateYamlWithDtoMojo(BuildPluginManager pluginManager) { super(pluginManager); } @Override public void execute() throws MojoExecutionException { if (skip) { return; } super.execute(true); generateDto("java"); } }
GenerateYamlWithDtoMojo
java
apache__camel
components/camel-twilio/src/generated/java/org/apache/camel/component/twilio/TranscriptionEndpointConfigurationConfigurer.java
{ "start": 736, "end": 3736 }
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.twilio.internal.TwilioApiName.class); map.put("MethodName", java.lang.String.class); map.put("PathAccountSid", java.lang.String.class); map.put("PathSid", java.lang.String.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.twilio.TranscriptionEndpointConfiguration target = (org.apache.camel.component.twilio.TranscriptionEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.twilio.internal.TwilioApiName.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "pathaccountsid": case "pathAccountSid": target.setPathAccountSid(property(camelContext, java.lang.String.class, value)); return true; case "pathsid": case "pathSid": target.setPathSid(property(camelContext, java.lang.String.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.twilio.internal.TwilioApiName.class; case "methodname": case "methodName": return java.lang.String.class; case "pathaccountsid": case "pathAccountSid": return java.lang.String.class; case "pathsid": case "pathSid": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.twilio.TranscriptionEndpointConfiguration target = (org.apache.camel.component.twilio.TranscriptionEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "apiname": case "apiName": return target.getApiName(); case "methodname": case "methodName": return target.getMethodName(); case "pathaccountsid": case "pathAccountSid": return target.getPathAccountSid(); case "pathsid": case "pathSid": return target.getPathSid(); default: return null; } } }
TranscriptionEndpointConfigurationConfigurer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/support/ValuesSourceType.java
{ "start": 2386, "end": 2813 }
interface ____ { /** * Called when an aggregation is operating over a known empty set (usually because the field isn't specified), this method allows for * returning a no-op implementation. All {@link ValuesSource}s should implement this method. * @return - Empty specialization of the base {@link ValuesSource} */ ValuesSource getEmpty(); /** * Returns the type-specific sub
ValuesSourceType
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java
{ "start": 988, "end": 12058 }
class ____ { private final MockHttpServletRequest request = new MockHttpServletRequest(); @Test void testIntParameter() throws ServletRequestBindingException { request.addParameter("param1", "5"); request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getIntParameter(request, "param1")).isEqualTo(5); assertThat(ServletRequestUtils.getIntParameter(request, "param1", 6)).isEqualTo(5); assertThat(ServletRequestUtils.getRequiredIntParameter(request, "param1")).isEqualTo(5); assertThat(ServletRequestUtils.getIntParameter(request, "param2", 6)).isEqualTo(6); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "param2")); assertThat(ServletRequestUtils.getIntParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getIntParameter(request, "param3", 6)).isEqualTo(6); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "param3")); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameter(request, "paramEmpty")); } @Test void testIntParameters() throws ServletRequestBindingException { request.addParameter("param", "1", "2", "3"); request.addParameter("param2", "1"); request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); int[] array = new int[] {1, 2, 3}; int[] values = ServletRequestUtils.getRequiredIntParameters(request, "param"); assertThat(values).hasSize(3); for (int i = 0; i < array.length; i++) { assertThat(array[i]).isEqualTo(values[i]); } assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredIntParameters(request, "param2")); } @Test void testLongParameter() throws ServletRequestBindingException { request.addParameter("param1", "5"); request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getLongParameter(request, "param1")).isEqualTo(Long.valueOf(5L)); assertThat(ServletRequestUtils.getLongParameter(request, "param1", 6L)).isEqualTo(5L); assertThat(ServletRequestUtils.getRequiredIntParameter(request, "param1")).isEqualTo(5L); assertThat(ServletRequestUtils.getLongParameter(request, "param2", 6L)).isEqualTo(6L); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "param2")); assertThat(ServletRequestUtils.getLongParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getLongParameter(request, "param3", 6L)).isEqualTo(6L); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "param3")); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameter(request, "paramEmpty")); } @Test void testLongParameters() throws ServletRequestBindingException { request.setParameter("param", "1", "2", "3"); request.setParameter("param2", "0"); request.setParameter("param2", "1"); request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); long[] values = ServletRequestUtils.getRequiredLongParameters(request, "param"); assertThat(values).containsExactly(1, 2, 3); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameters(request, "param2")); request.setParameter("param2", "1", "2"); values = ServletRequestUtils.getRequiredLongParameters(request, "param2"); assertThat(values).containsExactly(1, 2); request.removeParameter("param2"); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredLongParameters(request, "param2")); } @Test void testFloatParameter() throws ServletRequestBindingException { request.addParameter("param1", "5.5"); request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getFloatParameter(request, "param1")).isEqualTo(Float.valueOf(5.5f)); assertThat(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f)).isEqualTo(5.5f); assertThat(ServletRequestUtils.getRequiredFloatParameter(request, "param1")).isEqualTo(5.5f); assertThat(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f)).isEqualTo(6.5f); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param2")); assertThat(ServletRequestUtils.getFloatParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f)).isEqualTo(6.5f); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "param3")); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameter(request, "paramEmpty")); } @Test void testFloatParameters() throws ServletRequestBindingException { request.addParameter("param", "1.5", "2.5", "3"); request.addParameter("param2", "1.5"); request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); float[] values = ServletRequestUtils.getRequiredFloatParameters(request, "param"); assertThat(values).containsExactly(1.5F, 2.5F, 3F); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredFloatParameters(request, "param2")); } @Test void testDoubleParameter() throws ServletRequestBindingException { request.addParameter("param1", "5.5"); request.addParameter("param2", "e"); request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getDoubleParameter(request, "param1")).isEqualTo(Double.valueOf(5.5)); assertThat(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5)).isEqualTo(5.5); assertThat(ServletRequestUtils.getRequiredDoubleParameter(request, "param1")).isEqualTo(5.5); assertThat(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5)).isEqualTo(6.5); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param2")); assertThat(ServletRequestUtils.getDoubleParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5)).isEqualTo(6.5); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "param3")); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty")); } @Test void testDoubleParameters() throws ServletRequestBindingException { request.addParameter("param", "1.5", "2.5", "3"); request.addParameter("param2", "1.5"); request.addParameter("param2", "2"); request.addParameter("param2", "bogus"); double[] values = ServletRequestUtils.getRequiredDoubleParameters(request, "param"); assertThat(values).containsExactly(1.5, 2.5, 3); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredDoubleParameters(request, "param2")); } @Test void testBooleanParameter() throws ServletRequestBindingException { request.addParameter("param1", "true"); request.addParameter("param2", "e"); request.addParameter("param4", "yes"); request.addParameter("param5", "1"); request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE)).isTrue(); assertThat(ServletRequestUtils.getBooleanParameter(request, "param1", false)).isTrue(); assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param1")).isTrue(); assertThat(ServletRequestUtils.getBooleanParameter(request, "param2", true)).isFalse(); assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param2")).isFalse(); assertThat(ServletRequestUtils.getBooleanParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getBooleanParameter(request, "param3", true)).isTrue(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredBooleanParameter(request, "param3")); assertThat(ServletRequestUtils.getBooleanParameter(request, "param4", false)).isTrue(); assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param4")).isTrue(); assertThat(ServletRequestUtils.getBooleanParameter(request, "param5", false)).isTrue(); assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "param5")).isTrue(); assertThat(ServletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty")).isFalse(); } @Test void testBooleanParameters() throws ServletRequestBindingException { request.addParameter("param", "true", "yes", "off", "1", "bogus"); request.addParameter("param2", "false"); request.addParameter("param2", "true"); request.addParameter("param2", ""); boolean[] array = new boolean[] {true, true, false, true, false}; boolean[] values = ServletRequestUtils.getRequiredBooleanParameters(request, "param"); assertThat(array).hasSameSizeAs(values); for (int i = 0; i < array.length; i++) { assertThat(array[i]).isEqualTo(values[i]); } array = new boolean[] {false, true, false}; values = ServletRequestUtils.getRequiredBooleanParameters(request, "param2"); assertThat(array).hasSameSizeAs(values); for (int i = 0; i < array.length; i++) { assertThat(array[i]).isEqualTo(values[i]); } } @Test void testStringParameter() throws ServletRequestBindingException { request.addParameter("param1", "str"); request.addParameter("paramEmpty", ""); assertThat(ServletRequestUtils.getStringParameter(request, "param1")).isEqualTo("str"); assertThat(ServletRequestUtils.getStringParameter(request, "param1", "string")).isEqualTo("str"); assertThat(ServletRequestUtils.getRequiredStringParameter(request, "param1")).isEqualTo("str"); assertThat(ServletRequestUtils.getStringParameter(request, "param3")).isNull(); assertThat(ServletRequestUtils.getStringParameter(request, "param3", "string")).isEqualTo("string"); assertThat(ServletRequestUtils.getStringParameter(request, "param3", null)).isNull(); assertThatExceptionOfType(ServletRequestBindingException.class).isThrownBy(() -> ServletRequestUtils.getRequiredStringParameter(request, "param3")); assertThat(ServletRequestUtils.getStringParameter(request, "paramEmpty")).isEmpty(); assertThat(ServletRequestUtils.getRequiredStringParameter(request, "paramEmpty")).isEmpty(); } }
ServletRequestUtilsTests
java
quarkusio__quarkus
independent-projects/bootstrap/maven-resolver/src/test/java/io/quarkus/bootstrap/resolver/maven/OrderedDependencyVisitorTest.java
{ "start": 352, "end": 5905 }
class ____ { private static final String ORG_ACME = "org.acme"; private static final String JAR = "jar"; private static final String VERSION = "1.0"; @Test public void main() { var root = newNode("root"); // direct dependencies var colors = newNode("colors"); var pets = newNode("pets"); var trees = newNode("trees"); root.setChildren(List.of(colors, pets, trees)); // colors var red = newNode("red"); var green = newNode("green"); var blue = newNode("blue"); colors.setChildren(List.of(red, green, blue)); // pets var dog = newNode("dog"); var cat = newNode("cat"); pets.setChildren(List.of(dog, cat)); // pets, puppy var puppy = newNode("puppy"); dog.setChildren(List.of(puppy)); // trees var pine = newNode("pine"); trees.setChildren(Arrays.asList(pine)); // List.of() can't be used for replace var oak = newNode("oak"); // oak, acorn var acorn = newNode("acorn"); oak.setChildren(List.of(acorn)); // create a visitor var visitor = new OrderedDependencyVisitor(root); // assertions assertThat(visitor.hasNext()).isTrue(); // distance 0 assertThat(visitor.next()).isSameAs(root); assertThat(visitor.getCurrent()).isSameAs(root); assertThat(visitor.getCurrentDistance()).isEqualTo(0); assertThat(visitor.getSubtreeIndex()).isEqualTo(0); assertThat(visitor.hasNext()).isTrue(); // distance 1, colors assertThat(visitor.next()).isSameAs(colors); assertThat(visitor.getCurrent()).isSameAs(colors); assertThat(visitor.getCurrentDistance()).isEqualTo(1); assertThat(visitor.getSubtreeIndex()).isEqualTo(1); assertThat(visitor.hasNext()).isTrue(); // distance 1, pets assertThat(visitor.next()).isSameAs(pets); assertThat(visitor.getCurrent()).isSameAs(pets); assertThat(visitor.getCurrentDistance()).isEqualTo(1); assertThat(visitor.getSubtreeIndex()).isEqualTo(2); assertThat(visitor.hasNext()).isTrue(); // distance 1, trees assertThat(visitor.next()).isSameAs(trees); assertThat(visitor.getCurrent()).isSameAs(trees); assertThat(visitor.getCurrentDistance()).isEqualTo(1); assertThat(visitor.getSubtreeIndex()).isEqualTo(3); assertThat(visitor.hasNext()).isTrue(); // distance 2, colors, red assertThat(visitor.next()).isSameAs(red); assertThat(visitor.getCurrent()).isSameAs(red); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(1); assertThat(visitor.hasNext()).isTrue(); // distance 2, colors, green assertThat(visitor.next()).isSameAs(green); assertThat(visitor.getCurrent()).isSameAs(green); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(1); assertThat(visitor.hasNext()).isTrue(); // distance 2, colors, blue assertThat(visitor.next()).isSameAs(blue); assertThat(visitor.getCurrent()).isSameAs(blue); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(1); assertThat(visitor.hasNext()).isTrue(); // distance 2, pets, dog assertThat(visitor.next()).isSameAs(dog); assertThat(visitor.getCurrent()).isSameAs(dog); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(2); assertThat(visitor.hasNext()).isTrue(); // distance 2, pets, cat assertThat(visitor.next()).isSameAs(cat); assertThat(visitor.getCurrent()).isSameAs(cat); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(2); assertThat(visitor.hasNext()).isTrue(); // distance 2, trees, pine assertThat(visitor.next()).isSameAs(pine); assertThat(visitor.getCurrent()).isSameAs(pine); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(3); assertThat(visitor.hasNext()).isTrue(); // replace the current node visitor.replaceCurrent(oak); assertThat(visitor.getCurrent()).isSameAs(oak); assertThat(visitor.getCurrentDistance()).isEqualTo(2); assertThat(visitor.getSubtreeIndex()).isEqualTo(3); assertThat(visitor.hasNext()).isTrue(); // distance 3, pets, dog, puppy assertThat(visitor.next()).isSameAs(puppy); assertThat(visitor.getCurrent()).isSameAs(puppy); assertThat(visitor.getCurrentDistance()).isEqualTo(3); assertThat(visitor.getSubtreeIndex()).isEqualTo(2); assertThat(visitor.hasNext()).isTrue(); // distance 3, trees, oak, acorn assertThat(visitor.next()).isSameAs(acorn); assertThat(visitor.getCurrent()).isSameAs(acorn); assertThat(visitor.getCurrentDistance()).isEqualTo(3); assertThat(visitor.getSubtreeIndex()).isEqualTo(3); assertThat(visitor.hasNext()).isFalse(); } private static DependencyNode newNode(String artifactId) { return new DefaultDependencyNode(new DefaultArtifact(ORG_ACME, artifactId, JAR, VERSION)); } }
OrderedDependencyVisitorTest
java
google__dagger
hilt-android/main/java/dagger/hilt/android/internal/managers/FragmentComponentManager.java
{ "start": 1802, "end": 3993 }
interface ____ { FragmentComponentBuilder fragmentComponentBuilder(); } private volatile Object component; private final Object componentLock = new Object(); private final Fragment fragment; public FragmentComponentManager(Fragment fragment) { this.fragment = fragment; } @Override public Object generatedComponent() { if (component == null) { synchronized (componentLock) { if (component == null) { component = createComponent(); } } } return component; } private Object createComponent() { Preconditions.checkNotNull( fragment.getHost(), "Hilt Fragments must be attached before creating the component."); Preconditions.checkState( fragment.getHost() instanceof GeneratedComponentManager, "Hilt Fragments must be attached to an @AndroidEntryPoint Activity. Found: %s", fragment.getHost().getClass()); validate(fragment); return EntryPoints.get(fragment.getHost(), FragmentComponentBuilderEntryPoint.class) .fragmentComponentBuilder() .fragment(fragment) .build(); } /** Returns the fragments bundle, creating a new one if none exists. */ public static final void initializeArguments(Fragment fragment) { Preconditions.checkNotNull(fragment); if (fragment.getArguments() == null) { fragment.setArguments(new Bundle()); } } public static final Context findActivity(Context context) { while (context instanceof ContextWrapper && !(context instanceof Activity)) { context = ((ContextWrapper) context).getBaseContext(); } return context; } public static ContextWrapper createContextWrapper(Context base, Fragment fragment) { return new ViewComponentManager.FragmentContextWrapper(base, fragment); } public static ContextWrapper createContextWrapper( LayoutInflater baseInflater, Fragment fragment) { return new ViewComponentManager.FragmentContextWrapper(baseInflater, fragment); } /** Called immediately before component creation to allow validation on the Fragment. */ protected void validate(Fragment fragment) { } }
FragmentComponentBuilderEntryPoint
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/timeline/TimelineEvents.java
{ "start": 2894, "end": 4692 }
class ____ { private String entityId; private String entityType; private List<TimelineEvent> events = new ArrayList<>(); public EventsOfOneEntity() { } /** * Get the entity Id * * @return the entity Id */ @XmlElement(name = "entity") public String getEntityId() { return entityId; } /** * Set the entity Id * * @param entityId * the entity Id */ public void setEntityId(String entityId) { this.entityId = entityId; } /** * Get the entity type * * @return the entity type */ @XmlElement(name = "entitytype") public String getEntityType() { return entityType; } /** * Set the entity type * * @param entityType * the entity type */ public void setEntityType(String entityType) { this.entityType = entityType; } /** * Get a list of events * * @return a list of events */ @XmlElement(name = "events") public List<TimelineEvent> getEvents() { return events; } /** * Add a single event to the existing event list * * @param event * a single event */ public void addEvent(TimelineEvent event) { events.add(event); } /** * Add a list of event to the existing event list * * @param events * a list of events */ public void addEvents(List<TimelineEvent> events) { this.events.addAll(events); } /** * Set the event list to the given list of events * * @param events * a list of events */ public void setEvents(List<TimelineEvent> events) { this.events = events; } } }
EventsOfOneEntity
java
alibaba__nacos
common/src/test/java/com/alibaba/nacos/common/utils/JacksonUtilsTest.java
{ "start": 24457, "end": 25248 }
class ____ { public Date date = new Date(1626192000000L); @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TestOfDate that = (TestOfDate) o; return date != null ? date.equals(that.date) : that.date == null; } @Override public int hashCode() { return date != null ? date.hashCode() : 0; } } @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) @JsonSubTypes({@JsonSubTypes.Type(TestOfAnnotationSub.class)}) static
TestOfDate
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/internal/InjectionHelper.java
{ "start": 702, "end": 3491 }
class ____ { public static void injectEntityGraph( NamedEntityGraphDefinition definition, Class<?> metamodelClass, JpaMetamodelImplementor jpaMetamodel) { if ( metamodelClass != null ) { final String name = definition.name(); final String fieldName = '_' + javaIdentifier( name ); final var graph = jpaMetamodel.findEntityGraphByName( name ); try { injectField( metamodelClass, fieldName, graph, false ); } catch ( NoSuchFieldException e ) { // ignore } } } public static void injectTypedQueryReference(NamedQueryDefinition<?> definition, Class<?> metamodelClass) { if ( metamodelClass != null ) { final String fieldName = '_' + javaIdentifier( definition.getRegistrationName() ) + '_'; try { injectField( metamodelClass, fieldName, definition, false ); } catch ( NoSuchFieldException e ) { // ignore } } } public static String javaIdentifier(String name) { final var result = new StringBuilder(); int position = 0; while ( position < name.length() ) { final int codePoint = name.codePointAt( position ); result.appendCodePoint( isJavaIdentifierPart( codePoint ) ? codePoint : '_' ); position += charCount( codePoint ); } return result.toString(); } public static void injectField( Class<?> metamodelClass, String name, Object model, boolean allowNonDeclaredFieldReference) throws NoSuchFieldException { final Field field = allowNonDeclaredFieldReference ? metamodelClass.getField( name ) : metamodelClass.getDeclaredField( name ); try { if ( !isPublic( metamodelClass.getModifiers() ) ) { ensureAccessibility( field ); } field.set( null, model); } catch (IllegalAccessException e) { // todo : exception type? throw new AssertionFailure( "Unable to inject attribute '" + name + "' of static metamodel class '" + metamodelClass.getName() + "'", e ); } catch (IllegalArgumentException e) { // most likely a mismatch in the type we are injecting and the defined field; this represents a // mismatch in how the annotation processor interpreted the attribute and how our metamodel // and/or annotation binder did. // This is particularly the case as arrays are not handled properly by the StaticMetamodel generator // throw new AssertionFailure( // "Illegal argument on static metamodel field injection : " + metamodelClass.getName() + '#' + name // + "; expected type : " + attribute.getClass().getName() // + "; encountered type : " + field.getType().getName() // ); CORE_LOGGER.illegalArgumentOnStaticMetamodelFieldInjection( metamodelClass.getName(), name, model.getClass().getName(), field.getType().getName() ); } } }
InjectionHelper
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/protocol/CommandWrapper.java
{ "start": 7762, "end": 8154 }
interface ____ the result is the wrapped object or a proxy for the * wrapped object. Otherwise return the result of calling <code>unwrap</code> recursively on the wrapped object or a proxy * for that result. If the receiver is not a wrapper and does not implement the interface, then an {@code null} is returned. * * @param wrapped * @param iface A Class defining an
then
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/create/MySQLCreateMaterializedViewTest1.java
{ "start": 1003, "end": 2949 }
class ____ extends MysqlTest { public void test_types() throws Exception { String sql = // "CREATE MATERIALIZED VIEW mymv (\n" + " PRIMARY KEY(id)\n" + ")\n" + "DISTRIBUTED BY HASH (id)\n" + "REFRESH COMPLETE ON DEMAND\n" + "START WITH now()\n" + "NEXT DATE_ADD(now(), INTERVAL 1 MINUTE)\n" + "ENABLE QUERY REWRITE\n" + "AS SELECT id FROM base;"; SQLStatement stmt = SQLUtils.parseSingleMysqlStatement(sql); assertEquals("CREATE MATERIALIZED VIEW mymv (\n" + "\tPRIMARY KEY (id)\n" + ")\n" + "DISTRIBUTED BY HASH(id)\n" + "REFRESH COMPLETE ON DEMAND\n" + "START WITH now() NEXT DATE_ADD(now(), INTERVAL 1 MINUTE)\n" + "ENABLE QUERY REWRITE\n" + "AS\n" + "SELECT id\n" + "FROM base;", SQLUtils.toSQLString(stmt, DbType.mysql, null, VisitorFeature.OutputDistributedLiteralInCreateTableStmt)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(1, visitor.getColumns().size()); assertTrue(visitor.getColumns().contains(new TableStat.Column("base", "id"))); } }
MySQLCreateMaterializedViewTest1
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/simple/cookies/SimpleCookie.java
{ "start": 939, "end": 5541 }
class ____ implements Cookie { private final String name; private String value; private String domain; private String path; private boolean httpOnly; private boolean secure; private long maxAge; private SameSite sameSite; /** * Constructor. * * @param name The name * @param value The value */ public SimpleCookie(String name, String value) { this.name = name; this.value = value; } @Override public @NonNull String getName() { return name; } @Override public @NonNull String getValue() { return value; } @Override public String getDomain() { return domain; } @Override public String getPath() { return path; } @Override public boolean isHttpOnly() { return httpOnly; } @Override public boolean isSecure() { return secure; } @Override public long getMaxAge() { return maxAge; } @Override public Optional<SameSite> getSameSite() { return Optional.ofNullable(sameSite); } @Override public @NonNull Cookie sameSite(SameSite sameSite) { this.sameSite = sameSite; return this; } @Override public @NonNull Cookie maxAge(long maxAge) { this.maxAge = maxAge; return this; } @Override public @NonNull Cookie value(@NonNull String value) { this.value = value; return this; } @Override public @NonNull Cookie domain(String domain) { this.domain = domain; return this; } @Override public @NonNull Cookie path(String path) { this.path = path; return this; } @Override public @NonNull Cookie secure(boolean secure) { this.secure = secure; return this; } @Override public @NonNull Cookie httpOnly(boolean httpOnly) { this.httpOnly = httpOnly; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Cookie)) { return false; } Cookie that = (Cookie) o; if (!getName().equals(that.getName())) { return false; } if (getPath() == null) { if (that.getPath() != null) { return false; } } else if (that.getPath() == null) { return false; } else if (!getPath().equals(that.getPath())) { return false; } if (getDomain() == null) { return that.getDomain() == null; } else { return getDomain().equalsIgnoreCase(that.getDomain()); } } @Override public int compareTo(Cookie c) { int v = getName().compareTo(c.getName()); if (v != 0) { return v; } if (getPath() == null) { if (c.getPath() != null) { return -1; } } else if (c.getPath() == null) { return 1; } else { v = getPath().compareTo(c.getPath()); if (v != 0) { return v; } } if (getDomain() == null) { if (c.getDomain() != null) { return -1; } } else if (c.getDomain() == null) { return 1; } else { v = getDomain().compareToIgnoreCase(c.getDomain()); return v; } return 0; } @Override public int hashCode() { return ObjectUtils.hash(name, domain, path); } @Override public String toString() { StringBuilder buf = new StringBuilder() .append(getName()) .append('=') .append(getValue()); if (getDomain() != null) { buf.append(", domain=") .append(getDomain()); } if (getPath() != null) { buf.append(", path=") .append(getPath()); } if (getMaxAge() >= 0) { buf.append(", maxAge=") .append(getMaxAge()) .append('s'); } if (isSecure()) { buf.append(", secure"); } if (isHttpOnly()) { buf.append(", HTTPOnly"); } Optional<SameSite> ss = getSameSite(); if (ss.isPresent()) { buf.append(", SameSite=").append(ss.get()); } return buf.toString(); } }
SimpleCookie
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/reactive/server/CookieAssertions.java
{ "start": 1094, "end": 3573 }
class ____ extends AbstractCookieAssertions<ExchangeResult, WebTestClient.ResponseSpec> { CookieAssertions(ExchangeResult exchangeResult, WebTestClient.ResponseSpec responseSpec) { super(exchangeResult, responseSpec); } @Override protected MultiValueMap<String, ResponseCookie> getResponseCookies() { return getExchangeResult().getResponseCookies(); } @Override protected void assertWithDiagnostics(Runnable assertion) { getExchangeResult().assertWithDiagnostics(assertion); } /** * Assert the value of the response cookie with the given name with a Hamcrest * {@link Matcher}. * @deprecated in favor of {@link Consumer}-based variants */ @Deprecated(since = "7.0", forRemoval = true) public WebTestClient.ResponseSpec value(String name, Matcher<? super String> matcher) { String value = getCookie(name).getValue(); assertWithDiagnostics(() -> { String message = getMessage(name); assertThat(message, value, matcher); }); return getResponseSpec(); } /** * Assert a cookie's "Max-Age" attribute with a Hamcrest {@link Matcher}. * @deprecated in favor of {@link Consumer}-based variants */ @Deprecated(since = "7.0", forRemoval = true) public WebTestClient.ResponseSpec maxAge(String name, Matcher<? super Long> matcher) { long maxAge = getCookie(name).getMaxAge().getSeconds(); assertWithDiagnostics(() -> { String message = getMessage(name) + " maxAge"; assertThat(message, maxAge, matcher); }); return getResponseSpec(); } /** * Assert a cookie's "Path" attribute with a Hamcrest {@link Matcher}. * @deprecated in favor of {@link Consumer}-based variants */ @Deprecated(since = "7.0", forRemoval = true) public WebTestClient.ResponseSpec path(String name, Matcher<? super String> matcher) { String path = getCookie(name).getPath(); assertWithDiagnostics(() -> { String message = getMessage(name) + " path"; assertThat(message, path, matcher); }); return getResponseSpec(); } /** * Assert a cookie's "Domain" attribute with a Hamcrest {@link Matcher}. * @deprecated in favor of {@link Consumer}-based variants */ @Deprecated(since = "7.0", forRemoval = true) public WebTestClient.ResponseSpec domain(String name, Matcher<? super String> matcher) { String domain = getCookie(name).getDomain(); assertWithDiagnostics(() -> { String message = getMessage(name) + " domain"; assertThat(message, domain, matcher); }); return getResponseSpec(); } }
CookieAssertions
java
elastic__elasticsearch
modules/reindex/src/internalClusterTest/java/org/elasticsearch/index/reindex/RetryFailedReindexIT.java
{ "start": 4475, "end": 4634 }
class ____ extends ElasticsearchException { TestException() { super("Injected index failure"); } } public static
TestException
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/BeanDefinition.java
{ "start": 14550, "end": 14866 }
interface ____ * @return The type arguments */ default @NonNull List<Argument<?>> getTypeArguments(Class<?> type) { if (type == null) { return Collections.emptyList(); } return getTypeArguments(type.getName()); } /** * Returns the type parameters as a
type
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AbstractMetricsHandlerTest.java
{ "start": 9334, "end": 9819 }
class ____ extends MessageParameters { private final MetricsFilterParameter metricsFilterParameter = new MetricsFilterParameter(); @Override public Collection<MessagePathParameter<?>> getPathParameters() { return Collections.emptyList(); } @Override public Collection<MessageQueryParameter<?>> getQueryParameters() { return Collections.singletonList(metricsFilterParameter); } } }
TestMessageParameters
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/ClusterStateWaitUntilThresholdStepTests.java
{ "start": 1421, "end": 14658 }
class ____ extends AbstractStepTestCase<ClusterStateWaitUntilThresholdStep> { @Override public ClusterStateWaitUntilThresholdStep createRandomInstance() { ClusterStateWaitStep stepToExecute = new WaitForActiveShardsStep(randomStepKey(), randomStepKey()); return new ClusterStateWaitUntilThresholdStep(stepToExecute, randomStepKey()); } @Override public ClusterStateWaitUntilThresholdStep mutateInstance(ClusterStateWaitUntilThresholdStep instance) { ClusterStateWaitStep stepToExecute = instance.getStepToExecute(); StepKey nextKeyOnThreshold = instance.getNextKeyOnThreshold(); switch (between(0, 1)) { case 0 -> stepToExecute = randomValueOtherThan( stepToExecute, () -> new WaitForActiveShardsStep(randomStepKey(), randomStepKey()) ); case 1 -> nextKeyOnThreshold = randomValueOtherThan(nextKeyOnThreshold, AbstractStepTestCase::randomStepKey); default -> throw new AssertionError("Illegal randomisation branch"); } return new ClusterStateWaitUntilThresholdStep(stepToExecute, nextKeyOnThreshold); } @Override public ClusterStateWaitUntilThresholdStep copyInstance(ClusterStateWaitUntilThresholdStep instance) { return new ClusterStateWaitUntilThresholdStep(instance.getStepToExecute(), instance.getNextKeyOnThreshold()); } public void testIndexIsMissingReturnsIncompleteResult() { WaitForIndexingCompleteStep stepToExecute = new WaitForIndexingCompleteStep(randomStepKey(), randomStepKey()); ClusterStateWaitUntilThresholdStep underTest = new ClusterStateWaitUntilThresholdStep(stepToExecute, randomStepKey()); ClusterStateWaitStep.Result result = underTest.isConditionMet( new Index("testName", UUID.randomUUID().toString()), projectStateFromProject(ProjectMetadata.builder(randomUniqueProjectId())) ); assertThat(result.complete(), is(false)); assertThat(result.informationContext(), nullValue()); } public void testIsConditionMetForUnderlyingStep() { { // threshold is not breached and the underlying step condition is met IndexMetadata indexMetadata = IndexMetadata.builder("follower-index") .settings( settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE, "true") .put(LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD, "480h") ) .putCustom(ILM_CUSTOM_METADATA_KEY, Map.of("step_time", String.valueOf(System.currentTimeMillis()))) .putCustom(CCR_METADATA_KEY, Map.of()) .numberOfShards(1) .numberOfReplicas(0) .build(); ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomUniqueProjectId()).put(indexMetadata, true)); WaitForIndexingCompleteStep stepToExecute = new WaitForIndexingCompleteStep(randomStepKey(), randomStepKey()); ClusterStateWaitUntilThresholdStep underTest = new ClusterStateWaitUntilThresholdStep(stepToExecute, randomStepKey()); ClusterStateWaitStep.Result result = underTest.isConditionMet(indexMetadata.getIndex(), state); assertThat(result.complete(), is(true)); assertThat(result.informationContext(), nullValue()); } { // threshold is not breached and the underlying step condition is NOT met IndexMetadata indexMetadata = IndexMetadata.builder("follower-index") .settings( settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE, "false") .put(LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD, "48h") ) .putCustom(ILM_CUSTOM_METADATA_KEY, Map.of("step_time", String.valueOf(System.currentTimeMillis()))) .putCustom(CCR_METADATA_KEY, Map.of()) .numberOfShards(1) .numberOfReplicas(0) .build(); ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomUniqueProjectId()).put(indexMetadata, true)); WaitForIndexingCompleteStep stepToExecute = new WaitForIndexingCompleteStep(randomStepKey(), randomStepKey()); ClusterStateWaitUntilThresholdStep underTest = new ClusterStateWaitUntilThresholdStep(stepToExecute, randomStepKey()); ClusterStateWaitStep.Result result = underTest.isConditionMet(indexMetadata.getIndex(), state); assertThat(result.complete(), is(false)); assertThat(result.informationContext(), notNullValue()); WaitForIndexingCompleteStep.IndexingNotCompleteInfo info = (WaitForIndexingCompleteStep.IndexingNotCompleteInfo) result .informationContext(); assertThat( info.getMessage(), equalTo( "waiting for the [index.lifecycle.indexing_complete] setting to be set to " + "true on the leader index, it is currently [false]" ) ); } { // underlying step is executed once even if the threshold is breached and the underlying complete result is returned IndexMetadata indexMetadata = IndexMetadata.builder("follower-index") .settings( settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE, "true") .put(LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD, "1s") ) .putCustom(CCR_METADATA_KEY, Map.of()) .putCustom(ILM_CUSTOM_METADATA_KEY, Map.of("step_time", String.valueOf(1234L))) .numberOfShards(1) .numberOfReplicas(0) .build(); ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomUniqueProjectId()).put(indexMetadata, true)); WaitForIndexingCompleteStep stepToExecute = new WaitForIndexingCompleteStep(randomStepKey(), randomStepKey()); StepKey nextKeyOnThresholdBreach = randomStepKey(); ClusterStateWaitUntilThresholdStep underTest = new ClusterStateWaitUntilThresholdStep(stepToExecute, nextKeyOnThresholdBreach); ClusterStateWaitStep.Result result = underTest.isConditionMet(indexMetadata.getIndex(), state); assertThat(result.complete(), is(true)); assertThat(result.informationContext(), nullValue()); assertThat(underTest.getNextStepKey(), is(not(nextKeyOnThresholdBreach))); assertThat(underTest.getNextStepKey(), is(stepToExecute.getNextStepKey())); } { // underlying step is executed once even if the threshold is breached, but because the underlying step result is false the // step under test will return `complete` (becuase the threshold is breached and we don't want to wait anymore) IndexMetadata indexMetadata = IndexMetadata.builder("follower-index") .settings( settings(IndexVersion.current()).put(LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE, "false") .put(LifecycleSettings.LIFECYCLE_STEP_WAIT_TIME_THRESHOLD, "1h") ) .putCustom(CCR_METADATA_KEY, Map.of()) .putCustom(ILM_CUSTOM_METADATA_KEY, Map.of("step_time", String.valueOf(1234L))) .numberOfShards(1) .numberOfReplicas(0) .build(); ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomUniqueProjectId()).put(indexMetadata, true)); StepKey currentStepKey = randomStepKey(); WaitForIndexingCompleteStep stepToExecute = new WaitForIndexingCompleteStep(currentStepKey, randomStepKey()); StepKey nextKeyOnThresholdBreach = randomStepKey(); ClusterStateWaitUntilThresholdStep underTest = new ClusterStateWaitUntilThresholdStep(stepToExecute, nextKeyOnThresholdBreach); ClusterStateWaitStep.Result result = underTest.isConditionMet(indexMetadata.getIndex(), state); assertThat(result.complete(), is(true)); assertThat(result.informationContext(), notNullValue()); SingleMessageFieldInfo info = (SingleMessageFieldInfo) result.informationContext(); assertThat( info.message(), equalTo( "[" + currentStepKey.name() + "] lifecycle step, as part of [" + currentStepKey.action() + "] " + "action, for index [follower-index] executed for more than [1h]. Abandoning execution and moving to the next " + "fallback step [" + nextKeyOnThresholdBreach + "]" ) ); // the next step must change to the provided one when the threshold is breached assertThat(underTest.getNextStepKey(), is(nextKeyOnThresholdBreach)); } } public void testWaitedMoreThanThresholdLevelMath() { long epochMillis = 1552684146542L; // Friday, 15 March 2019 21:09:06.542 Clock clock = Clock.fixed(Instant.ofEpochMilli(epochMillis), ZoneId.systemDefault()); TimeValue retryThreshold = TimeValue.timeValueHours(1); { // step time is "2 hours ago" with a threshold of 1 hour - the threshold level is breached LifecycleExecutionState executionState = new LifecycleExecutionState.Builder().setStepTime( epochMillis - TimeValue.timeValueHours(2).millis() ).build(); boolean thresholdBreached = waitedMoreThanThresholdLevel(retryThreshold, executionState, clock); assertThat(thresholdBreached, is(true)); } { // step time is "10 minutes ago" with a threshold of 1 hour - the threshold level is NOT breached LifecycleExecutionState executionState = new LifecycleExecutionState.Builder().setStepTime( epochMillis - TimeValue.timeValueMinutes(10).millis() ).build(); boolean thresholdBreached = waitedMoreThanThresholdLevel(retryThreshold, executionState, clock); assertThat(thresholdBreached, is(false)); } { // if no threshold is configured we'll never report the threshold is breached LifecycleExecutionState executionState = new LifecycleExecutionState.Builder().setStepTime( epochMillis - TimeValue.timeValueHours(2).millis() ).build(); boolean thresholdBreached = waitedMoreThanThresholdLevel(null, executionState, clock); assertThat(thresholdBreached, is(false)); } } public void testIsCompletableBreaches() { IndexMetadata indexMetadata = IndexMetadata.builder("index") .settings(settings(IndexVersion.current())) .numberOfShards(1) .numberOfReplicas(0) .putCustom(ILM_CUSTOM_METADATA_KEY, Map.of("step_time", String.valueOf(Clock.systemUTC().millis()))) .build(); ProjectState state = projectStateFromProject(ProjectMetadata.builder(randomUniqueProjectId()).put(indexMetadata, true)); ClusterStateWaitUntilThresholdStep step = new ClusterStateWaitUntilThresholdStep( new ClusterStateWaitStep(new StepKey("phase", "action", "key"), new StepKey("phase", "action", "next-key")) { @Override public Result isConditionMet(Index index, ProjectState currentState) { return new Result(false, new SingleMessageFieldInfo("")); } @Override public boolean isRetryable() { return true; } }, new StepKey("phase", "action", "breached") ); assertFalse(step.isConditionMet(indexMetadata.getIndex(), state).complete()); assertThat(step.getNextStepKey().name(), equalTo("next-key")); step = new ClusterStateWaitUntilThresholdStep( new ClusterStateWaitStep(new StepKey("phase", "action", "key"), new StepKey("phase", "action", "next-key")) { @Override public Result isConditionMet(Index index, ProjectState currentState) { return new Result(false, new SingleMessageFieldInfo("")); } @Override public boolean isCompletable() { return false; } @Override public boolean isRetryable() { return true; } }, new StepKey("phase", "action", "breached") ); assertTrue(step.isConditionMet(indexMetadata.getIndex(), state).complete()); assertThat(step.getNextStepKey().name(), equalTo("breached")); } }
ClusterStateWaitUntilThresholdStepTests
java
apache__flink
flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/hybrid/HybridSource.java
{ "start": 6636, "end": 7686 }
interface ____<EnumT> { EnumT getPreviousEnumerator(); } /** * Factory for underlying sources of {@link HybridSource}. * * <p>This factory permits building of a source at graph construction time or deferred at switch * time. Provides the ability to set a start position in any way a specific source allows. * Future convenience could be built on top of it, for example a default implementation that * recognizes optional interfaces to transfer position in a universal format. * * <p>Called when the current enumerator has finished. The previous source's final state can * thus be used to construct the next source, as required for dynamic position transfer at time * of switching. * * <p>If start position is known at job submission time, the source can be constructed in the * entry point and simply wrapped into the factory, providing the benefit of validation during * submission. */ @PublicEvolving @FunctionalInterface public
SourceSwitchContext
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/io/checkpointing/UnalignedCheckpointsTest.java
{ "start": 3509, "end": 43957 }
class ____ { private static final long DEFAULT_CHECKPOINT_ID = 0L; private int sizeCounter = 1; private CheckpointedInputGate inputGate; private RecordingChannelStateWriter channelStateWriter; private int[] sequenceNumbers; private List<BufferOrEvent> output; @BeforeEach void setUp() { channelStateWriter = new RecordingChannelStateWriter(); } @AfterEach void ensureEmpty() throws Exception { if (inputGate != null) { assertThat(inputGate.pollNext()).isNotPresent(); assertThat(inputGate.isFinished()).isTrue(); inputGate.close(); } if (channelStateWriter != null) { channelStateWriter.close(); } } // ------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------ /** * Validates that the buffer behaves correctly if no checkpoint barriers come, for a single * input channel. */ @Test void testSingleChannelNoBarriers() throws Exception { inputGate = createInputGate(1, new ValidatingCheckpointHandler(1)); final BufferOrEvent[] sequence = addSequence( inputGate, createBuffer(0), createBuffer(0), createBuffer(0), createEndOfPartition(0)); assertOutput(sequence); assertInflightData(); } /** * Validates that the buffer behaves correctly if no checkpoint barriers come, for an input with * multiple input channels. */ @Test void testMultiChannelNoBarriers() throws Exception { inputGate = createInputGate(4, new ValidatingCheckpointHandler(1)); final BufferOrEvent[] sequence = addSequence( inputGate, createBuffer(2), createBuffer(2), createBuffer(0), createBuffer(1), createBuffer(0), createEndOfPartition(0), createBuffer(3), createBuffer(1), createEndOfPartition(3), createBuffer(1), createEndOfPartition(1), createBuffer(2), createEndOfPartition(2)); assertOutput(sequence); assertInflightData(); } /** * Validates that the buffer preserved the order of elements for a input with a single input * channel, and checkpoint events. */ @Test void testSingleChannelWithBarriers() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(1, handler); final BufferOrEvent[] sequence = addSequence( inputGate, createBuffer(0), createBuffer(0), createBuffer(0), createBarrier(1, 0), createBuffer(0), createBuffer(0), createBuffer(0), createBuffer(0), createBarrier(2, 0), createBarrier(3, 0), createBuffer(0), createBuffer(0), createBarrier(4, 0), createBarrier(5, 0), createBarrier(6, 0), createBuffer(0), createEndOfPartition(0)); assertOutput(sequence); } /** * Validates that the buffer correctly aligns the streams for inputs with multiple input * channels, by buffering and blocking certain inputs. */ @Test void testMultiChannelWithBarriers() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(3, handler); // checkpoint with in-flight data BufferOrEvent[] sequence1 = addSequence( inputGate, createBuffer(0), createBuffer(2), createBuffer(0), createBarrier(1, 1), createBarrier(1, 2), createBuffer(2), createBuffer(1), createBuffer(0), // last buffer = in-flight createBarrier(1, 0)); // checkpoint 1 triggered unaligned assertOutput(sequence1); assertThat(channelStateWriter.getLastStartedCheckpointId()).isOne(); assertInflightData(sequence1[7]); // checkpoint without in-flight data BufferOrEvent[] sequence2 = addSequence( inputGate, createBuffer(0), createBuffer(0), createBuffer(1), createBuffer(1), createBuffer(2), createBarrier(2, 0), createBarrier(2, 1), createBarrier(2, 2)); assertOutput(sequence2); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); assertInflightData(); // checkpoint with data only from one channel BufferOrEvent[] sequence3 = addSequence( inputGate, createBuffer(2), createBuffer(2), createBarrier(3, 2), createBuffer(2), createBuffer(2), createBarrier(3, 0), createBarrier(3, 1)); assertOutput(sequence3); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(3L); assertInflightData(); // empty checkpoint addSequence(inputGate, createBarrier(4, 1), createBarrier(4, 2), createBarrier(4, 0)); assertOutput(); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(4L); assertInflightData(); // checkpoint with in-flight data in mixed order BufferOrEvent[] sequence5 = addSequence( inputGate, createBuffer(0), createBuffer(2), createBuffer(0), createBarrier(5, 1), createBuffer(2), createBuffer(0), createBuffer(2), createBuffer(1), createBarrier(5, 2), createBuffer(1), createBuffer(0), createBuffer(2), createBuffer(1), createBarrier(5, 0)); assertOutput(sequence5); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(5L); assertInflightData(sequence5[4], sequence5[5], sequence5[6], sequence5[10]); // some trailing data BufferOrEvent[] sequence6 = addSequence( inputGate, createBuffer(0), createEndOfPartition(0), createEndOfPartition(1), createEndOfPartition(2)); assertOutput(sequence6); assertInflightData(); } @Test void testMetrics() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(3, handler); int bufferSize = 100; long checkpointId = 1; long sleepTime = 10; long checkpointBarrierCreation = System.currentTimeMillis(); Thread.sleep(sleepTime); long alignmentStartNanos = System.nanoTime(); addSequence( inputGate, createBuffer(0, bufferSize), createBuffer(1, bufferSize), createBuffer(2, bufferSize), createBarrier(checkpointId, 1, checkpointBarrierCreation), createBuffer(0, bufferSize), createBuffer(1, bufferSize), createBuffer(2, bufferSize), createBarrier(checkpointId, 0), createBuffer(0, bufferSize), createBuffer(1, bufferSize), createBuffer(2, bufferSize)); long startDelay = System.currentTimeMillis() - checkpointBarrierCreation; Thread.sleep(sleepTime); addSequence( inputGate, createBarrier(checkpointId, 2), createBuffer(0, bufferSize), createBuffer(1, bufferSize), createBuffer(2, bufferSize), createEndOfPartition(0), createEndOfPartition(1), createEndOfPartition(2)); long alignmentDuration = System.nanoTime() - alignmentStartNanos; assertThat(inputGate.getCheckpointBarrierHandler().getLatestCheckpointId()) .isEqualTo(checkpointId); assertThat(inputGate.getCheckpointStartDelayNanos() / 1_000_000) .isBetween(sleepTime, startDelay); assertThat(handler.getLastAlignmentDurationNanos()).isDone(); assertThat(handler.getLastAlignmentDurationNanos().get() / 1_000_000) .isBetween(sleepTime, alignmentDuration); assertThat(handler.getLastBytesProcessedDuringAlignment()) .isCompletedWithValue(6L * bufferSize); } @Test void testMultiChannelTrailingInflightData() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(3, handler, false); BufferOrEvent[] sequence = addSequence( inputGate, createBuffer(0), createBuffer(1), createBuffer(2), createBarrier(1, 1), createBarrier(1, 2), createBarrier(1, 0), createBuffer(2), createBuffer(1), createBuffer(0), createBarrier(2, 1), createBuffer(1), createBuffer(1), createEndOfPartition(1), createBuffer(0), createBuffer(2), createBarrier(2, 2), createBuffer(2), createEndOfPartition(2), createBuffer(0), createEndOfPartition(0)); assertOutput(sequence); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); // TODO: treat EndOfPartitionEvent as a special CheckpointBarrier? assertInflightData(); } @Test void testMissingCancellationBarriers() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(2, handler); final BufferOrEvent[] sequence = addSequence( inputGate, createBarrier(1L, 0), createCancellationBarrier(2L, 0), createCancellationBarrier(3L, 0), createCancellationBarrier(3L, 1), createBuffer(0), createEndOfPartition(0), createEndOfPartition(1)); assertOutput(sequence); assertThat(channelStateWriter.getLastStartedCheckpointId()).isOne(); assertThat(handler.getLastCanceledCheckpointId()).isEqualTo(3L); assertInflightData(); } @Test void testEarlyCleanup() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(3, handler, false); // checkpoint 1 final BufferOrEvent[] sequence1 = addSequence( inputGate, createBuffer(0), createBuffer(1), createBuffer(2), createBarrier(1, 1), createBarrier(1, 2), createBarrier(1, 0)); assertOutput(sequence1); assertThat(channelStateWriter.getLastStartedCheckpointId()).isOne(); assertInflightData(); // checkpoint 2 final BufferOrEvent[] sequence2 = addSequence( inputGate, createBuffer(2), createBuffer(1), createBuffer(0), createBarrier(2, 1), createBuffer(1), createBuffer(1), createEndOfPartition(1), createBuffer(0), createBuffer(2), createBarrier(2, 2), createBuffer(2), createEndOfPartition(2), createBuffer(0), createEndOfPartition(0)); assertOutput(sequence2); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); assertInflightData(); } @Test void testStartAlignmentWithClosedChannels() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(2); inputGate = createInputGate(4, handler); final BufferOrEvent[] sequence1 = addSequence( inputGate, // close some channels immediately createEndOfPartition(2), createEndOfPartition(1), // checkpoint without in-flight data createBuffer(0), createBuffer(0), createBuffer(3), createBarrier(2, 3), createBarrier(2, 0)); assertOutput(sequence1); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); assertInflightData(); // checkpoint with in-flight data final BufferOrEvent[] sequence2 = addSequence( inputGate, createBuffer(3), createBuffer(0), createBarrier(3, 3), createBuffer(3), createBuffer(0), createBarrier(3, 0)); assertOutput(sequence2); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(3L); assertInflightData(sequence2[4]); // empty checkpoint final BufferOrEvent[] sequence3 = addSequence(inputGate, createBarrier(4, 0), createBarrier(4, 3)); assertOutput(sequence3); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(4L); assertInflightData(); // some data, one channel closes final BufferOrEvent[] sequence4 = addSequence( inputGate, createBuffer(0), createBuffer(0), createBuffer(3), createEndOfPartition(0)); assertOutput(sequence4); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(-1L); assertInflightData(); // checkpoint on last remaining channel final BufferOrEvent[] sequence5 = addSequence( inputGate, createBuffer(3), createBarrier(5, 3), createBuffer(3), createEndOfPartition(3)); assertOutput(sequence5); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(5L); assertInflightData(); } @Test void testEndOfStreamWhileCheckpoint() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(3, handler); // one checkpoint final BufferOrEvent[] sequence1 = addSequence( inputGate, createBarrier(1, 0), createBarrier(1, 1), createBarrier(1, 2)); assertOutput(sequence1); assertThat(channelStateWriter.getLastStartedCheckpointId()).isOne(); assertInflightData(); final BufferOrEvent[] sequence2 = addSequence( inputGate, // some buffers createBuffer(0), createBuffer(0), createBuffer(2), // start the checkpoint that will be incomplete createBarrier(2, 2), createBarrier(2, 0), createBuffer(0), createBuffer(2), createBuffer(1), // close one after the barrier one before the barrier createEndOfPartition(2), createEndOfPartition(1), createBuffer(0), // final end of stream createEndOfPartition(0)); assertOutput(sequence2); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); assertInflightData(sequence2[7]); } @Test public void testNotifyAbortCheckpointBeforeCancellingAsyncCheckpoint() throws Exception { ValidateAsyncFutureNotCompleted handler = new ValidateAsyncFutureNotCompleted(1); inputGate = createInputGate(2, handler); handler.setInputGate(inputGate); addSequence(inputGate, createBarrier(1, 0), createCancellationBarrier(1, 1)); addSequence(inputGate, createEndOfPartition(0), createEndOfPartition(1)); } @Test void testSingleChannelAbortCheckpoint() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(1, handler); final BufferOrEvent[] sequence1 = addSequence( inputGate, createBuffer(0), createBarrier(1, 0), createBuffer(0), createBarrier(2, 0), createCancellationBarrier(4, 0)); assertOutput(sequence1); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); assertThat(handler.getLastCanceledCheckpointId()).isEqualTo(4L); assertInflightData(); final BufferOrEvent[] sequence2 = addSequence( inputGate, createBarrier(5, 0), createBuffer(0), createCancellationBarrier(6, 0), createBuffer(0), createEndOfPartition(0)); assertOutput(sequence2); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(5L); assertThat(handler.getLastCanceledCheckpointId()).isEqualTo(6L); assertInflightData(); } @Test void testMultiChannelAbortCheckpoint() throws Exception { ValidatingCheckpointHandler handler = new ValidatingCheckpointHandler(1); inputGate = createInputGate(3, handler); // some buffers and a successful checkpoint final BufferOrEvent[] sequence1 = addSequence( inputGate, createBuffer(0), createBuffer(2), createBuffer(0), createBarrier(1, 1), createBarrier(1, 2), createBuffer(2), createBuffer(1), createBarrier(1, 0), createBuffer(0), createBuffer(2)); assertOutput(sequence1); assertThat(channelStateWriter.getLastStartedCheckpointId()).isOne(); assertInflightData(); // canceled checkpoint on last barrier final BufferOrEvent[] sequence2 = addSequence( inputGate, createBarrier(2, 0), createBarrier(2, 2), createBuffer(0), createBuffer(2), createCancellationBarrier(2, 1)); assertOutput(sequence2); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(2L); assertThat(handler.getLastCanceledCheckpointId()).isEqualTo(2L); assertInflightData(); // one more successful checkpoint final BufferOrEvent[] sequence3 = addSequence( inputGate, createBuffer(2), createBuffer(1), createBarrier(3, 1), createBarrier(3, 2), createBarrier(3, 0)); assertOutput(sequence3); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(3L); assertInflightData(); // this checkpoint gets immediately canceled, don't start a checkpoint at all final BufferOrEvent[] sequence4 = addSequence( inputGate, createBuffer(0), createBuffer(1), createCancellationBarrier(4, 1), createBarrier(4, 2), createBuffer(0), createBarrier(4, 0)); assertOutput(sequence4); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(-1L); assertThat(handler.getLastCanceledCheckpointId()).isEqualTo(4L); assertInflightData(); // a simple successful checkpoint // another successful checkpoint final BufferOrEvent[] sequence5 = addSequence( inputGate, createBuffer(0), createBuffer(1), createBuffer(2), createBarrier(5, 2), createBarrier(5, 1), createBarrier(5, 0), createBuffer(0), createBuffer(1)); assertOutput(sequence5); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(5L); assertInflightData(); // abort multiple cancellations and a barrier after the cancellations, don't start a // checkpoint at all final BufferOrEvent[] sequence6 = addSequence( inputGate, createCancellationBarrier(6, 1), createCancellationBarrier(6, 2), createBarrier(6, 0), createBuffer(0), createEndOfPartition(0), createEndOfPartition(1), createEndOfPartition(2)); assertOutput(sequence6); assertThat(channelStateWriter.getLastStartedCheckpointId()).isEqualTo(-1L); assertThat(handler.getLastCanceledCheckpointId()).isEqualTo(6L); assertInflightData(); } /** * Tests {@link * SingleCheckpointBarrierHandler#processCancellationBarrier(CancelCheckpointMarker, * InputChannelInfo)} abort the current pending checkpoint triggered by {@link * CheckpointBarrierHandler#processBarrier(CheckpointBarrier, InputChannelInfo, boolean)}. */ @Test void testProcessCancellationBarrierAfterProcessBarrier() throws Exception { final ValidatingCheckpointInvokable invokable = new ValidatingCheckpointInvokable(); final SingleInputGate inputGate = new SingleInputGateBuilder() .setNumberOfChannels(2) .setChannelFactory(InputChannelBuilder::buildLocalChannel) .build(); final SingleCheckpointBarrierHandler handler = SingleCheckpointBarrierHandler.createUnalignedCheckpointBarrierHandler( TestSubtaskCheckpointCoordinator.INSTANCE, "test", invokable, SystemClock.getInstance(), true, inputGate); // should trigger respective checkpoint handler.processBarrier( buildCheckpointBarrier(DEFAULT_CHECKPOINT_ID), new InputChannelInfo(0, 0), false); assertThat(handler.isCheckpointPending()).isTrue(); assertThat(handler.getLatestCheckpointId()).isEqualTo(DEFAULT_CHECKPOINT_ID); testProcessCancellationBarrier(handler, invokable); } @Test void testProcessCancellationBarrierBeforeProcessAndReceiveBarrier() throws Exception { final ValidatingCheckpointInvokable invokable = new ValidatingCheckpointInvokable(); final SingleInputGate inputGate = new SingleInputGateBuilder() .setChannelFactory(InputChannelBuilder::buildLocalChannel) .build(); final SingleCheckpointBarrierHandler handler = SingleCheckpointBarrierHandler.createUnalignedCheckpointBarrierHandler( TestSubtaskCheckpointCoordinator.INSTANCE, "test", invokable, SystemClock.getInstance(), true, inputGate); handler.processCancellationBarrier( new CancelCheckpointMarker(DEFAULT_CHECKPOINT_ID), new InputChannelInfo(0, 0)); verifyTriggeredCheckpoint(handler, invokable, DEFAULT_CHECKPOINT_ID); // it would not trigger checkpoint since the respective cancellation barrier already // happened before handler.processBarrier( buildCheckpointBarrier(DEFAULT_CHECKPOINT_ID), new InputChannelInfo(0, 0), false); verifyTriggeredCheckpoint(handler, invokable, DEFAULT_CHECKPOINT_ID); } private void testProcessCancellationBarrier( SingleCheckpointBarrierHandler handler, ValidatingCheckpointInvokable invokable) throws Exception { final long cancelledCheckpointId = new Random().nextBoolean() ? DEFAULT_CHECKPOINT_ID : DEFAULT_CHECKPOINT_ID + 1L; // should abort current checkpoint while processing CancelCheckpointMarker handler.processCancellationBarrier( new CancelCheckpointMarker(cancelledCheckpointId), new InputChannelInfo(0, 0)); verifyTriggeredCheckpoint(handler, invokable, cancelledCheckpointId); final long nextCancelledCheckpointId = cancelledCheckpointId + 1L; // should update current checkpoint id and abort notification while processing // CancelCheckpointMarker handler.processCancellationBarrier( new CancelCheckpointMarker(nextCancelledCheckpointId), new InputChannelInfo(0, 0)); verifyTriggeredCheckpoint(handler, invokable, nextCancelledCheckpointId); } private void verifyTriggeredCheckpoint( SingleCheckpointBarrierHandler handler, ValidatingCheckpointInvokable invokable, long currentCheckpointId) { assertThat(handler.isCheckpointPending()).isFalse(); assertThat(handler.getLatestCheckpointId()).isEqualTo(currentCheckpointId); assertThat(invokable.getAbortedCheckpointId()).isEqualTo(currentCheckpointId); } @Test void testEndOfStreamWithPendingCheckpoint() throws Exception { final int numberOfChannels = 2; final ValidatingCheckpointInvokable invokable = new ValidatingCheckpointInvokable(); final SingleInputGate inputGate = new SingleInputGateBuilder() .setChannelFactory(InputChannelBuilder::buildLocalChannel) .setNumberOfChannels(numberOfChannels) .build(); final SingleCheckpointBarrierHandler handler = SingleCheckpointBarrierHandler.createUnalignedCheckpointBarrierHandler( TestSubtaskCheckpointCoordinator.INSTANCE, "test", invokable, SystemClock.getInstance(), false, inputGate); // should trigger respective checkpoint handler.processBarrier( buildCheckpointBarrier(DEFAULT_CHECKPOINT_ID), new InputChannelInfo(0, 0), false); assertThat(handler.isCheckpointPending()).isTrue(); assertThat(handler.getLatestCheckpointId()).isEqualTo(DEFAULT_CHECKPOINT_ID); assertThat(handler.getNumOpenChannels()).isEqualTo(numberOfChannels); // should abort current checkpoint while processing eof handler.processEndOfPartition(new InputChannelInfo(0, 0)); assertThat(handler.isCheckpointPending()).isFalse(); assertThat(handler.getLatestCheckpointId()).isEqualTo(DEFAULT_CHECKPOINT_ID); assertThat(handler.getNumOpenChannels()).isEqualTo(numberOfChannels - 1); assertThat(invokable.getAbortedCheckpointId()).isEqualTo(DEFAULT_CHECKPOINT_ID); } @Test void testTriggerCheckpointsWithEndOfPartition() throws Exception { ValidatingCheckpointHandler validator = new ValidatingCheckpointHandler(-1); inputGate = createInputGate(3, validator); BufferOrEvent[] sequence = addSequence( inputGate, /* 0 */ createBarrier(1, 1), /* 1 */ createBuffer(0), /* 2 */ createBarrier(1, 0), /* 3 */ createBuffer(1), /* 4 */ createEndOfPartition(2), /* 5 */ createEndOfPartition(0), /* 6 */ createEndOfPartition(1)); assertOutput(sequence); assertThat(validator.triggeredCheckpoints).containsExactly(1L); assertThat(validator.getAbortedCheckpointCounter()).isZero(); assertInflightData(sequence[1]); } @Test void testTriggerCheckpointsAfterReceivedEndOfPartition() throws Exception { ValidatingCheckpointHandler validator = new ValidatingCheckpointHandler(-1); inputGate = createInputGate(3, validator); BufferOrEvent[] sequence1 = addSequence( inputGate, /* 0 */ createEndOfPartition(0), /* 1 */ createBarrier(3, 1), /* 2 */ createBuffer(1), /* 3 */ createBuffer(2), /* 4 */ createEndOfPartition(1), /* 5 */ createBarrier(3, 2)); assertOutput(sequence1); assertInflightData(sequence1[3]); assertThat(validator.triggeredCheckpoints).containsExactly(3L); assertThat(validator.getAbortedCheckpointCounter()).isZero(); BufferOrEvent[] sequence2 = addSequence( inputGate, /* 0 */ createBuffer(2), /* 1 */ createBarrier(4, 2), /* 2 */ createEndOfPartition(2)); assertOutput(sequence2); assertInflightData(); assertThat(validator.triggeredCheckpoints).containsExactly(3L, 4L); assertThat(validator.getAbortedCheckpointCounter()).isZero(); } // ------------------------------------------------------------------------ // Utils // ------------------------------------------------------------------------ private BufferOrEvent createBarrier(long checkpointId, int channel) { return createBarrier(checkpointId, channel, System.currentTimeMillis()); } private BufferOrEvent createBarrier(long checkpointId, int channel, long timestamp) { sizeCounter++; return new BufferOrEvent( new CheckpointBarrier( checkpointId, timestamp, CheckpointOptions.unaligned(CheckpointType.CHECKPOINT, getDefault())), new InputChannelInfo(0, channel)); } private BufferOrEvent createCancellationBarrier(long checkpointId, int channel) { sizeCounter++; return new BufferOrEvent( new CancelCheckpointMarker(checkpointId), new InputChannelInfo(0, channel)); } private BufferOrEvent createBuffer(int channel, int size) { return new BufferOrEvent( TestBufferFactory.createBuffer(size), new InputChannelInfo(0, channel)); } private BufferOrEvent createBuffer(int channel) { final int size = sizeCounter++; return new BufferOrEvent( TestBufferFactory.createBuffer(size), new InputChannelInfo(0, channel)); } private static BufferOrEvent createEndOfPartition(int channel) { return new BufferOrEvent(EndOfPartitionEvent.INSTANCE, new InputChannelInfo(0, channel)); } private CheckpointedInputGate createInputGate(int numberOfChannels, AbstractInvokable toNotify) throws IOException { return createInputGate(numberOfChannels, toNotify, true); } private CheckpointedInputGate createInputGate( int numberOfChannels, AbstractInvokable toNotify, boolean enableCheckpointsAfterTasksFinished) throws IOException { final NettyShuffleEnvironment environment = new NettyShuffleEnvironmentBuilder().build(); SingleInputGate gate = new SingleInputGateBuilder() .setNumberOfChannels(numberOfChannels) .setupBufferPoolFactory(environment) .build(); gate.setInputChannels( IntStream.range(0, numberOfChannels) .mapToObj( channelIndex -> InputChannelBuilder.newBuilder() .setChannelIndex(channelIndex) .setStateWriter(channelStateWriter) .setupFromNettyShuffleEnvironment(environment) .setConnectionManager( new TestingConnectionManager()) .buildRemoteChannel(gate)) .toArray(RemoteInputChannel[]::new)); sequenceNumbers = new int[numberOfChannels]; gate.setup(); gate.requestPartitions(); return createCheckpointedInputGate(gate, toNotify, enableCheckpointsAfterTasksFinished); } private BufferOrEvent[] addSequence(CheckpointedInputGate inputGate, BufferOrEvent... sequence) throws Exception { output = new ArrayList<>(); addSequence(inputGate, output, sequenceNumbers, sequence); sizeCounter = 1; return sequence; } static BufferOrEvent[] addSequence( CheckpointedInputGate inputGate, List<BufferOrEvent> output, int[] sequenceNumbers, BufferOrEvent... sequence) throws Exception { for (BufferOrEvent bufferOrEvent : sequence) { if (bufferOrEvent.isEvent()) { bufferOrEvent = new BufferOrEvent( EventSerializer.toBuffer( bufferOrEvent.getEvent(), bufferOrEvent.getEvent() instanceof CheckpointBarrier), bufferOrEvent.getChannelInfo(), bufferOrEvent.moreAvailable(), bufferOrEvent.morePriorityEvents()); } ((RemoteInputChannel) inputGate.getChannel( bufferOrEvent.getChannelInfo().getInputChannelIdx())) .onBuffer( bufferOrEvent.getBuffer(), sequenceNumbers[bufferOrEvent.getChannelInfo().getInputChannelIdx()]++, 0, 0); while (inputGate.pollNext().map(output::add).isPresent()) {} } return sequence; } private CheckpointedInputGate createCheckpointedInputGate( IndexedInputGate gate, AbstractInvokable toNotify) { return createCheckpointedInputGate(gate, toNotify, true); } private CheckpointedInputGate createCheckpointedInputGate( IndexedInputGate gate, AbstractInvokable toNotify, boolean enableCheckpointsAfterTasksFinished) { final SingleCheckpointBarrierHandler barrierHandler = SingleCheckpointBarrierHandler.createUnalignedCheckpointBarrierHandler( new TestSubtaskCheckpointCoordinator(channelStateWriter), "Test", toNotify, SystemClock.getInstance(), enableCheckpointsAfterTasksFinished, gate); return new CheckpointedInputGate(gate, barrierHandler, new SyncMailboxExecutor()); } private void assertInflightData(BufferOrEvent... expected) { Collection<BufferOrEvent> andResetInflightData = getAndResetInflightData(); assertThat(getIds(andResetInflightData)) .as("Unexpected in-flight sequence: " + andResetInflightData) .isEqualTo(getIds(Arrays.asList(expected))); } private Collection<BufferOrEvent> getAndResetInflightData() { final List<BufferOrEvent> inflightData = channelStateWriter.getAddedInput().entries().stream() .map(entry -> new BufferOrEvent(entry.getValue(), entry.getKey())) .collect(Collectors.toList()); channelStateWriter.reset(); return inflightData; } private void assertOutput(BufferOrEvent... expectedSequence) { assertThat(getIds(output)) .as("Unexpected output sequence") .isEqualTo(getIds(Arrays.asList(expectedSequence))); } private List<Object> getIds(Collection<BufferOrEvent> buffers) { return buffers.stream() .filter( boe -> !boe.isEvent() || !(boe.getEvent() instanceof CheckpointBarrier || boe.getEvent() instanceof CancelCheckpointMarker)) .map(boe -> boe.isBuffer() ? boe.getSize() - 1 : boe.getEvent()) .collect(Collectors.toList()); } private CheckpointBarrier buildCheckpointBarrier(long id) { return new CheckpointBarrier( id, 0, CheckpointOptions.unaligned(CheckpointType.CHECKPOINT, getDefault())); } // ------------------------------------------------------------------------ // Testing Mocks // ------------------------------------------------------------------------ /** The invokable handler used for triggering checkpoint and validation. */ static
UnalignedCheckpointsTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/util/Int3Hash.java
{ "start": 901, "end": 1019 }
class ____ not thread-safe. */ // IDs are internally stored as id + 1 so that 0 encodes for an empty slot public final
is
java
mockito__mockito
mockito-core/src/main/java/org/mockito/Mockito.java
{ "start": 120511, "end": 120904 }
interface ____ * want to mock. * @return mock controller * @since 5.21.0 */ @SafeVarargs public static <T> MockedStatic<T> mockStatic(MockSettings mockSettings, T... reified) { if (reified == null || reified.length > 0) { throw new IllegalArgumentException( "Please don't pass any values here. Java will detect
you
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/DiscriminatorConverter.java
{ "start": 457, "end": 3041 }
class ____<O,R> implements BasicValueConverter<O,R> { private final String discriminatorName; private final JavaType<O> domainJavaType; private final JavaType<R> relationalJavaType; public DiscriminatorConverter( String discriminatorName, JavaType<O> domainJavaType, JavaType<R> relationalJavaType) { this.discriminatorName = discriminatorName; this.domainJavaType = domainJavaType; this.relationalJavaType = relationalJavaType; } public String getDiscriminatorName() { return discriminatorName; } @Override public JavaType<O> getDomainJavaType() { return domainJavaType; } @Override public JavaType<R> getRelationalJavaType() { return relationalJavaType; } public DiscriminatorValueDetails getDetailsForRelationalForm(R relationalForm) { return getDetailsForDiscriminatorValue( relationalForm ); } @Override public O toDomainValue(R relationalForm) { assert relationalForm == null || relationalJavaType.isInstance( relationalForm ); final var matchingValueDetails = getDetailsForRelationalForm( relationalForm ); if ( matchingValueDetails == null ) { throw new IllegalStateException( "Could not resolve discriminator value" ); } final var indicatedEntity = matchingValueDetails.getIndicatedEntity(); //noinspection unchecked return indicatedEntity.getRepresentationStrategy().getMode() == RepresentationMode.POJO && indicatedEntity.getEntityName().equals( indicatedEntity.getJavaType().getJavaTypeClass().getName() ) ? (O) indicatedEntity.getJavaType().getJavaTypeClass() : (O) indicatedEntity.getEntityName(); } @Override public R toRelationalValue(O domainForm) { final String entityName = getEntityName( domainForm ); if ( entityName == null ) { return null; } else { final var discriminatorValueDetails = getDetailsForEntityName( entityName ); //noinspection unchecked return (R) discriminatorValueDetails.getValue(); } } protected abstract String getEntityName(O domainForm); public abstract DiscriminatorValueDetails getDetailsForDiscriminatorValue(Object relationalValue); public abstract DiscriminatorValueDetails getDetailsForEntityName(String entityName); @Override public String toString() { return "DiscriminatorConverter(" + discriminatorName + ")"; } public abstract void forEachValueDetail(Consumer<DiscriminatorValueDetails> consumer); /** * Find and return the first DiscriminatorValueDetails which matches the given {@code handler} */ public abstract <X> X fromValueDetails(Function<DiscriminatorValueDetails,X> handler); }
DiscriminatorConverter
java
quarkusio__quarkus
test-framework/junit5-internal/src/test/java/io/quarkus/test/QuarkusProdModeTestExpectExitTest.java
{ "start": 670, "end": 2469 }
class ____ { @RegisterExtension static final QuarkusProdModeTest simpleApp = new QuarkusProdModeTest() .withApplicationRoot(jar -> jar.addClass(Main.class)) .setApplicationName("simple-app") .setApplicationVersion("0.1-SNAPSHOT") .setExpectExit(true) .setRun(true); private static String startupConsoleOutput; @BeforeAll static void captureStartupConsoleLog() { startupConsoleOutput = simpleApp.getStartupConsoleOutput(); assertNotNull(startupConsoleOutput, "Missing startupConsoleOutput"); } @Test @Order(1) public void shouldStartManually() { thenAppIsNotRunning(); thenAppWasNotRestarted(); try (var urlMgrMock = Mockito.mockStatic(RestAssuredURLManager.class)) { whenStartApp(); thenAppIsNotRunning(); thenAppWasRestarted(); urlMgrMock.verifyNoInteractions(); } } @Test @Order(2) public void shouldNotBeRestartedInSubsequentTest() { thenAppIsNotRunning(); thenAppWasNotRestarted(); } private void whenStartApp() { simpleApp.start(); } private void thenAppIsNotRunning() { assertNotNull(simpleApp.getExitCode(), "App is running"); } private void thenAppWasNotRestarted() { assertEquals(startupConsoleOutput, simpleApp.getStartupConsoleOutput(), "App was restarted"); } private void thenAppWasRestarted() { var newStartupConsoleOutput = simpleApp.getStartupConsoleOutput(); assertNotEquals(startupConsoleOutput, newStartupConsoleOutput, "App was not restarted"); startupConsoleOutput = newStartupConsoleOutput; } @QuarkusMain public static
QuarkusProdModeTestExpectExitTest
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/NoFactoryAvailableException.java
{ "start": 1114, "end": 1354 }
class ____ resource: " + uri); this.uri = uri; } public NoFactoryAvailableException(String uri, Throwable cause) { this(uri); initCause(cause); } public String getUri() { return uri; } }
for
java
apache__maven
impl/maven-cli/src/test/java/org/apache/maven/cling/transfer/ConsoleMavenTransferListenerTest.java
{ "start": 1528, "end": 5772 }
class ____ { private CountDownLatch startLatch; private CountDownLatch endLatch; @Test void testTransferProgressedWithPrintResourceNames() throws Exception { int size = 1000; ExecutorService service = Executors.newFixedThreadPool(size * 2); try { startLatch = new CountDownLatch(size); endLatch = new CountDownLatch(size); Map<String, String> output = new ConcurrentHashMap<String, String>(); try (SimplexTransferListener listener = new SimplexTransferListener(new ConsoleMavenTransferListener( new JLineMessageBuilderFactory(), new PrintWriter(System.out) { @Override public void print(Object o) { String string = o.toString(); int i = string.length() - 1; while (i >= 0) { char c = string.charAt(i); if (c == '\n' || c == '\r' || c == ' ') { i--; } else { break; } } string = string.substring(0, i + 1).trim(); output.put(string, string); System.out.print(o); } }, true))) { TransferResource resource = new TransferResource(null, null, "http://maven.org/test/test-resource", new File(""), null); resource.setContentLength(size - 1); DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(h -> false); // no close handle // warm up test(listener, session, resource, 0); for (int i = 1; i < size; i++) { final int bytes = i; service.execute(() -> { test(listener, session, resource, bytes); }); } // start all threads at once try { startLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } // wait for all thread to end try { endLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } // despite all are back, we need to make sure all the events are processed (are async) // this one should block until all processed listener.transferSucceeded(new TransferEvent.Builder(session, resource) .setType(TransferEvent.EventType.SUCCEEDED) .build()); StringBuilder message = new StringBuilder("Messages ["); boolean test = true; for (int i = 0; i < 999; i++) { boolean ok = output.containsKey("Progress (1): test-resource (" + i + "/999 B)"); if (!ok) { System.out.println("false : " + i); message.append(i + ","); } test = test & ok; } assertTrue(test, message + "] are missing in " + output); } } finally { service.shutdown(); } } private void test( TransferListener listener, DefaultRepositorySystemSession session, TransferResource resource, final int bytes) { TransferEvent event = new TransferEvent.Builder(session, resource) .setType(TransferEvent.EventType.PROGRESSED) .setTransferredBytes(bytes) .build(); startLatch.countDown(); try { listener.transferProgressed(event); } catch (TransferCancelledException e) { } endLatch.countDown(); } }
ConsoleMavenTransferListenerTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/util/MBeanTestUtils.java
{ "start": 838, "end": 1717 }
class ____ { /** * Reset the {@link MBeanServerFactory} to a known consistent state. This involves * {@linkplain #releaseMBeanServer(MBeanServer) releasing} all currently registered * MBeanServers. */ public static synchronized void resetMBeanServers() { for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) { releaseMBeanServer(server); } } /** * Attempt to release the supplied {@link MBeanServer}. * <p>Ignores any {@link IllegalArgumentException} thrown by * {@link MBeanServerFactory#releaseMBeanServer(MBeanServer)} whose error * message contains the text "not in list". */ public static void releaseMBeanServer(MBeanServer server) { try { MBeanServerFactory.releaseMBeanServer(server); } catch (IllegalArgumentException ex) { if (!ex.getMessage().contains("not in list")) { throw ex; } } } }
MBeanTestUtils
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/CallableStatementCreatorFactory.java
{ "start": 4111, "end": 7584 }
class ____ implements CallableStatementCreator, SqlProvider, ParameterDisposer { private @Nullable ParameterMapper inParameterMapper; private @Nullable Map<String, ?> inParameters; /** * Create a new CallableStatementCreatorImpl. * @param inParamMapper the ParameterMapper implementation for mapping input parameters */ public CallableStatementCreatorImpl(ParameterMapper inParamMapper) { this.inParameterMapper = inParamMapper; } /** * Create a new CallableStatementCreatorImpl. * @param inParams list of SqlParameter objects */ public CallableStatementCreatorImpl(Map<String, ?> inParams) { this.inParameters = inParams; } @Override public CallableStatement createCallableStatement(Connection con) throws SQLException { // If we were given a ParameterMapper, we must let the mapper do its thing to create the Map. if (this.inParameterMapper != null) { this.inParameters = this.inParameterMapper.createMap(con); } else { if (this.inParameters == null) { throw new InvalidDataAccessApiUsageException( "A ParameterMapper or a Map of parameters must be provided"); } } CallableStatement cs = null; if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) { cs = con.prepareCall(callString); } else { cs = con.prepareCall(callString, resultSetType, updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY); } int sqlColIndx = 1; for (SqlParameter declaredParam : declaredParameters) { if (!declaredParam.isResultsParameter()) { // So, it's a call parameter - part of the call string. // Get the value - it may still be null. Object inValue = this.inParameters.get(declaredParam.getName()); if (declaredParam instanceof ResultSetSupportingSqlParameter) { // It's an output parameter: SqlReturnResultSet parameters already excluded. // It need not (but may be) supplied by the caller. if (declaredParam instanceof SqlOutParameter) { if (declaredParam.getTypeName() != null) { cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getTypeName()); } else { if (declaredParam.getScale() != null) { cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getScale()); } else { cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType()); } } if (declaredParam.isInputValueProvided()) { StatementCreatorUtils.setParameterValue(cs, sqlColIndx, declaredParam, inValue); } } } else { // It's an input parameter; must be supplied by the caller. if (!this.inParameters.containsKey(declaredParam.getName())) { throw new InvalidDataAccessApiUsageException( "Required input parameter '" + declaredParam.getName() + "' is missing"); } StatementCreatorUtils.setParameterValue(cs, sqlColIndx, declaredParam, inValue); } sqlColIndx++; } } return cs; } @Override public String getSql() { return callString; } @Override public void cleanupParameters() { if (this.inParameters != null) { StatementCreatorUtils.cleanupParameters(this.inParameters.values()); } } @Override public String toString() { return "CallableStatementCreator: sql=[" + callString + "]; parameters=" + this.inParameters; } } }
CallableStatementCreatorImpl
java
apache__camel
components/camel-thymeleaf/src/test/java/org/apache/camel/component/thymeleaf/ThymeleafAbstractBaseTest.java
{ "start": 7007, "end": 7508 }
class ____ implements Processor { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(ThymeleafConstants.THYMELEAF_RESOURCE_URI, resourceUri()); exchange.getIn().setHeader(LAST_NAME, "Doe"); exchange.getIn().setHeader(FIRST_NAME, JANE); exchange.getIn().setHeader(ITEM, "Widgets for Dummies"); exchange.setProperty(ORDER_NUMBER, "7"); } } protected static
ResourceUriHeaderProcessor
java
elastic__elasticsearch
x-pack/plugin/slm/src/main/java/org/elasticsearch/xpack/slm/UpdateSnapshotLifecycleStatsTask.java
{ "start": 1062, "end": 2586 }
class ____ extends ClusterStateUpdateTask { private static final Logger logger = LogManager.getLogger(SnapshotRetentionTask.class); private final SnapshotLifecycleStats runStats; static final String TASK_SOURCE = "update_slm_stats"; UpdateSnapshotLifecycleStatsTask(SnapshotLifecycleStats runStats) { this.runStats = runStats; } @Override public ClusterState execute(ClusterState currentState) { final Metadata currentMeta = currentState.metadata(); final var project = currentMeta.getProject(); final SnapshotLifecycleMetadata currentSlmMeta = project.custom(SnapshotLifecycleMetadata.TYPE); if (currentSlmMeta == null) { return currentState; } SnapshotLifecycleStats newMetrics = currentSlmMeta.getStats().merge(runStats); SnapshotLifecycleMetadata newSlmMeta = new SnapshotLifecycleMetadata( currentSlmMeta.getSnapshotConfigurations(), currentSLMMode(currentState), newMetrics ); return currentState.copyAndUpdateProject(project.id(), builder -> builder.putCustom(SnapshotLifecycleMetadata.TYPE, newSlmMeta)); } @Override public void onFailure(Exception e) { logger.error( () -> format( "failed to update cluster state with snapshot lifecycle stats, " + "source: [" + TASK_SOURCE + "], missing stats: [%s]", runStats ), e ); } }
UpdateSnapshotLifecycleStatsTask
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.java
{ "start": 37127, "end": 37745 }
class ____ { private int age = 10; private boolean isHealthy; private String name; } @Test void testLombokPojo() { TypeInformation<TestLombok> ti = TypeExtractor.getForClass(TestLombok.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<TestLombok> pti = (PojoTypeInfo<TestLombok>) ti; assertThat(pti.getTypeAt(0)).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); assertThat(pti.getTypeAt(1)).isEqualTo(BasicTypeInfo.BOOLEAN_TYPE_INFO); assertThat(pti.getTypeAt(2)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } }
TestLombok
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvPercentileDoubleEvaluator.java
{ "start": 1083, "end": 4325 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(MvPercentileDoubleEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator values; private final EvalOperator.ExpressionEvaluator percentile; private final MvPercentile.DoubleSortingScratch scratch; private final DriverContext driverContext; private Warnings warnings; public MvPercentileDoubleEvaluator(Source source, EvalOperator.ExpressionEvaluator values, EvalOperator.ExpressionEvaluator percentile, MvPercentile.DoubleSortingScratch scratch, DriverContext driverContext) { this.source = source; this.values = values; this.percentile = percentile; this.scratch = scratch; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (DoubleBlock valuesBlock = (DoubleBlock) values.eval(page)) { try (DoubleBlock percentileBlock = (DoubleBlock) percentile.eval(page)) { return eval(page.getPositionCount(), valuesBlock, percentileBlock); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += values.baseRamBytesUsed(); baseRamBytesUsed += percentile.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, DoubleBlock valuesBlock, DoubleBlock percentileBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { boolean allBlocksAreNulls = true; if (!valuesBlock.isNull(p)) { allBlocksAreNulls = false; } switch (percentileBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } if (allBlocksAreNulls) { result.appendNull(); continue position; } double percentile = percentileBlock.getDouble(percentileBlock.getFirstValueIndex(p)); try { MvPercentile.process(result, p, valuesBlock, percentile, this.scratch); } catch (IllegalArgumentException e) { warnings().registerException(e); result.appendNull(); } } return result.build(); } } @Override public String toString() { return "MvPercentileDoubleEvaluator[" + "values=" + values + ", percentile=" + percentile + "]"; } @Override public void close() { Releasables.closeExpectNoException(values, percentile); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
MvPercentileDoubleEvaluator
java
apache__camel
components/camel-tracing/src/test/java/org/apache/camel/tracing/propagation/CamelMessagingHeadersInjectAdapterTest.java
{ "start": 1200, "end": 2312 }
class ____ { private Map<String, Object> map; @BeforeEach public void before() { map = new HashMap<>(); } @Test public void putProperties() { CamelMessagingHeadersInjectAdapter adapter = new CamelMessagingHeadersInjectAdapter(map, true); adapter.put("key1", "value1"); adapter.put("key2", "value2"); adapter.put("key1", "value3"); assertEquals("value3", map.get("key1")); assertEquals("value2", map.get("key2")); } @Test public void propertyWithDash() { CamelMessagingHeadersInjectAdapter adapter = new CamelMessagingHeadersInjectAdapter(map, true); adapter.put("-key-1-", "value1"); assertEquals("value1", map.get(JMS_DASH + "key" + JMS_DASH + "1" + JMS_DASH)); } @Test public void propertyWithoutDashEncoding() { CamelMessagingHeadersInjectAdapter adapter = new CamelMessagingHeadersInjectAdapter(map, false); adapter.put("-key-1-", "value1"); assertNull(map.get(JMS_DASH + "key" + JMS_DASH + "1" + JMS_DASH)); } }
CamelMessagingHeadersInjectAdapterTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/OffsetSpec.java
{ "start": 1426, "end": 3635 }
class ____ extends OffsetSpec { private final long timestamp; TimestampSpec(long timestamp) { this.timestamp = timestamp; } long timestamp() { return timestamp; } } /** * Used to retrieve the latest offset of a partition */ public static OffsetSpec latest() { return new LatestSpec(); } /** * Used to retrieve the earliest offset of a partition */ public static OffsetSpec earliest() { return new EarliestSpec(); } /** * Used to retrieve the earliest offset whose timestamp is greater than * or equal to the given timestamp in the corresponding partition * @param timestamp in milliseconds */ public static OffsetSpec forTimestamp(long timestamp) { return new TimestampSpec(timestamp); } /** * Used to retrieve the offset with the largest timestamp of a partition * as message timestamps can be specified client side this may not match * the log end offset returned by LatestSpec */ public static OffsetSpec maxTimestamp() { return new MaxTimestampSpec(); } /** * Used to retrieve the local log start offset. * Local log start offset is the offset of a log above which reads * are guaranteed to be served from the disk of the leader broker. * <br/> * Note: When tiered Storage is not enabled, it behaves the same as retrieving the earliest timestamp offset. */ public static OffsetSpec earliestLocal() { return new EarliestLocalSpec(); } /** * Used to retrieve the highest offset of data stored in remote storage. * <br/> * Note: When tiered storage is not enabled, we will return unknown offset. */ public static OffsetSpec latestTiered() { return new LatestTieredSpec(); } /** * Used to retrieve the earliest offset of records that are pending upload to remote storage. * <br/> * Note: When tiered storage is not enabled, we will return unknown offset. */ public static OffsetSpec earliestPendingUpload() { return new EarliestPendingUploadSpec(); } }
TimestampSpec
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/handler/predicate/ReadBodyRoutePredicateFactoryTests.java
{ "start": 4932, "end": 5305 }
class ____ { private String foo; private String bar; Event() { } Event(String foo, String bar) { this.foo = foo; this.bar = bar; } public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } } }
Event
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/jsontype/impl/StdSubtypeResolver.java
{ "start": 463, "end": 9679 }
class ____ extends SubtypeResolver implements java.io.Serializable { private static final long serialVersionUID = 1L; protected Set<NamedType> _registeredSubtypes; public StdSubtypeResolver() { } protected StdSubtypeResolver(Set<NamedType> reg) { _registeredSubtypes = reg; } @Override public SubtypeResolver snapshot() { if (_registeredSubtypes == null) { return new StdSubtypeResolver(); } return new StdSubtypeResolver(new LinkedHashSet<>(_registeredSubtypes)); } /* /********************************************************** /* Subtype registration /********************************************************** */ @Override public StdSubtypeResolver registerSubtypes(NamedType... types) { if (_registeredSubtypes == null) { _registeredSubtypes = new LinkedHashSet<>(); } for (NamedType type : types) { _registeredSubtypes.add(type); } return this; } @Override public StdSubtypeResolver registerSubtypes(Class<?>... classes) { NamedType[] types = new NamedType[classes.length]; for (int i = 0, len = classes.length; i < len; ++i) { types[i] = new NamedType(classes[i]); } registerSubtypes(types); return this; } @Override public StdSubtypeResolver registerSubtypes(Collection<Class<?>> subtypes) { int len = subtypes.size(); NamedType[] types = new NamedType[len]; int i = 0; for (Class<?> subtype : subtypes) { types[i++] = new NamedType(subtype); } registerSubtypes(types); return this; } /* /********************************************************** /* Resolution by class (serialization) /********************************************************** */ @Override public Collection<NamedType> collectAndResolveSubtypesByClass(MapperConfig<?> config, AnnotatedMember property, JavaType baseType) { final AnnotationIntrospector ai = config.getAnnotationIntrospector(); // for backwards compatibility, must allow null here: final Class<?> rawBase; if (baseType != null) { rawBase = baseType.getRawClass(); } else if (property != null) { rawBase = property.getRawType(); } else { throw new IllegalArgumentException("Both property and base type are nulls"); } HashMap<NamedType, NamedType> collected = new HashMap<>(); // start with registered subtypes (which have precedence) if (_registeredSubtypes != null) { for (NamedType subtype : _registeredSubtypes) { // is it a subtype of root type? if (rawBase.isAssignableFrom(subtype.getType())) { // yes AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config, subtype.getType()); _collectAndResolve(config, curr, subtype, ai, collected); } } } // then annotated types for property itself if (property != null) { Collection<NamedType> st = ai.findSubtypes(config, property); if (st != null) { for (NamedType nt : st) { AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config, nt.getType()); _collectAndResolve(config, ac, nt, ai, collected); } } } NamedType rootType = new NamedType(rawBase, null); AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config, rawBase); // and finally subtypes via annotations from base type (recursively) _collectAndResolve(config, ac, rootType, ai, collected); return new ArrayList<NamedType>(collected.values()); } @Override public Collection<NamedType> collectAndResolveSubtypesByClass(MapperConfig<?> config, AnnotatedClass type) { final AnnotationIntrospector ai = config.getAnnotationIntrospector(); HashMap<NamedType, NamedType> subtypes = new HashMap<>(); // then consider registered subtypes (which have precedence over annotations) if (_registeredSubtypes != null) { Class<?> rawBase = type.getRawType(); for (NamedType subtype : _registeredSubtypes) { // is it a subtype of root type? if (rawBase.isAssignableFrom(subtype.getType())) { // yes AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config, subtype.getType()); _collectAndResolve(config, curr, subtype, ai, subtypes); } } } // and then check subtypes via annotations from base type (recursively) NamedType rootType = new NamedType(type.getRawType(), null); _collectAndResolve(config, type, rootType, ai, subtypes); return new ArrayList<>(subtypes.values()); } /* /********************************************************** /* Resolution by class (deserialization) /********************************************************** */ @Override public Collection<NamedType> collectAndResolveSubtypesByTypeId(MapperConfig<?> config, AnnotatedMember property, JavaType baseType) { final AnnotationIntrospector ai = config.getAnnotationIntrospector(); Class<?> rawBase = baseType.getRawClass(); // Need to keep track of classes that have been handled already Set<Class<?>> typesHandled = new LinkedHashSet<>(); Map<String,NamedType> byName = new LinkedHashMap<>(); // start with lowest-precedence, which is from type hierarchy NamedType rootType = new NamedType(rawBase, null); AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config, rawBase); _collectAndResolveByTypeId(config, ac, rootType, typesHandled, byName); // then with definitions from property if (property != null) { Collection<NamedType> st = ai.findSubtypes(config, property); if (st != null) { for (NamedType nt : st) { ac = AnnotatedClassResolver.resolveWithoutSuperTypes(config, nt.getType()); _collectAndResolveByTypeId(config, ac, nt, typesHandled, byName); } } } // and finally explicit type registrations (highest precedence) if (_registeredSubtypes != null) { for (NamedType subtype : _registeredSubtypes) { // is it a subtype of root type? if (rawBase.isAssignableFrom(subtype.getType())) { // yes AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config, subtype.getType()); _collectAndResolveByTypeId(config, curr, subtype, typesHandled, byName); } } } return _combineNamedAndUnnamed(rawBase, typesHandled, byName); } @Override public Collection<NamedType> collectAndResolveSubtypesByTypeId(MapperConfig<?> config, AnnotatedClass baseType) { final Class<?> rawBase = baseType.getRawType(); Set<Class<?>> typesHandled = new LinkedHashSet<>(); Map<String,NamedType> byName = new LinkedHashMap<>(); NamedType rootType = new NamedType(rawBase, null); _collectAndResolveByTypeId(config, baseType, rootType, typesHandled, byName); if (_registeredSubtypes != null) { for (NamedType subtype : _registeredSubtypes) { // is it a subtype of root type? if (rawBase.isAssignableFrom(subtype.getType())) { // yes AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config, subtype.getType()); _collectAndResolveByTypeId(config, curr, subtype, typesHandled, byName); } } } return _combineNamedAndUnnamed(rawBase, typesHandled, byName); } /* /********************************************************** /* Internal methods /********************************************************** */ /** * Method called to find subtypes for a specific type (class), using * type (class) as the unique key (in case of conflicts). */ protected void _collectAndResolve(MapperConfig<?> config, AnnotatedClass annotatedType, NamedType namedType, AnnotationIntrospector ai, HashMap<NamedType, NamedType> collectedSubtypes) { if (!namedType.hasName()) { String name = ai.findTypeName(config, annotatedType); if (name != null) { namedType = new NamedType(namedType.getType(), name); } } //For Serialization we only want to return a single NamedType per
StdSubtypeResolver
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/converters/IntegerConverterTest.java
{ "start": 1019, "end": 1534 }
class ____ extends NumberConverterTest<Integer> { public Integer[] samples() { return new Integer[]{Integer.MIN_VALUE, 1234, Integer.MAX_VALUE}; } @Override protected Schema schema() { return Schema.OPTIONAL_INT32_SCHEMA; } @Override protected NumberConverter<Integer> createConverter() { return new IntegerConverter(); } @Override protected Serializer<Integer> createSerializer() { return new IntegerSerializer(); } }
IntegerConverterTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeFinalTest.java
{ "start": 3896, "end": 4302 }
class ____ { @SuppressWarnings("FieldCanBeFinal") private int x; Test() { x = 42; } } """) .doTest(); } @Test public void suppressionOnClass() { compilationHelper .addSourceLines( "Test.java", """ @SuppressWarnings("FieldCanBeFinal")
Test
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/memory/MemoryUtils.java
{ "start": 1109, "end": 7216 }
class ____ { /** The "unsafe", which can be used to perform native memory accesses. */ @SuppressWarnings({"restriction", "UseOfSunClasses"}) public static final sun.misc.Unsafe UNSAFE = getUnsafe(); /** The native byte order of the platform on which the system currently runs. */ public static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder(); private static final long BUFFER_ADDRESS_FIELD_OFFSET = getClassFieldOffset(Buffer.class, "address"); private static final long BUFFER_CAPACITY_FIELD_OFFSET = getClassFieldOffset(Buffer.class, "capacity"); private static final Class<?> DIRECT_BYTE_BUFFER_CLASS = getClassByName("java.nio.DirectByteBuffer"); @SuppressWarnings("restriction") private static sun.misc.Unsafe getUnsafe() { try { Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); unsafeField.setAccessible(true); return (sun.misc.Unsafe) unsafeField.get(null); } catch (SecurityException e) { throw new Error( "Could not access the sun.misc.Unsafe handle, permission denied by security manager.", e); } catch (NoSuchFieldException e) { throw new Error("The static handle field in sun.misc.Unsafe was not found.", e); } catch (IllegalArgumentException e) { throw new Error("Bug: Illegal argument reflection access for static field.", e); } catch (IllegalAccessException e) { throw new Error("Access to sun.misc.Unsafe is forbidden by the runtime.", e); } catch (Throwable t) { throw new Error( "Unclassified error while trying to access the sun.misc.Unsafe handle.", t); } } private static long getClassFieldOffset( @SuppressWarnings("SameParameterValue") Class<?> cl, String fieldName) { try { return UNSAFE.objectFieldOffset(cl.getDeclaredField(fieldName)); } catch (SecurityException e) { throw new Error( getClassFieldOffsetErrorMessage(cl, fieldName) + ", permission denied by security manager.", e); } catch (NoSuchFieldException e) { throw new Error(getClassFieldOffsetErrorMessage(cl, fieldName), e); } catch (Throwable t) { throw new Error( getClassFieldOffsetErrorMessage(cl, fieldName) + ", unclassified error", t); } } private static String getClassFieldOffsetErrorMessage(Class<?> cl, String fieldName) { return "Could not get field '" + fieldName + "' offset in class '" + cl + "' for unsafe operations"; } private static Class<?> getClassByName( @SuppressWarnings("SameParameterValue") String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new Error("Could not find class '" + className + "' for unsafe operations.", e); } } /** * Allocates unsafe native memory. * * @param size size of the unsafe memory to allocate. * @return address of the allocated unsafe memory */ static long allocateUnsafe(long size) { return UNSAFE.allocateMemory(Math.max(1L, size)); } /** * Creates a cleaner to release the unsafe memory. * * @param address address of the unsafe memory to release * @param customCleanup A custom action to clean up GC * @return action to run to release the unsafe memory manually */ static Runnable createMemoryCleaner(long address, Runnable customCleanup) { return () -> { releaseUnsafe(address); customCleanup.run(); }; } private static void releaseUnsafe(long address) { UNSAFE.freeMemory(address); } /** * Wraps the unsafe native memory with a {@link ByteBuffer}. * * @param address address of the unsafe memory to wrap * @param size size of the unsafe memory to wrap * @return a {@link ByteBuffer} which is a view of the given unsafe memory */ static ByteBuffer wrapUnsafeMemoryWithByteBuffer(long address, int size) { //noinspection OverlyBroadCatchBlock try { ByteBuffer buffer = (ByteBuffer) UNSAFE.allocateInstance(DIRECT_BYTE_BUFFER_CLASS); UNSAFE.putLong(buffer, BUFFER_ADDRESS_FIELD_OFFSET, address); UNSAFE.putInt(buffer, BUFFER_CAPACITY_FIELD_OFFSET, size); buffer.clear(); return buffer; } catch (Throwable t) { throw new Error("Failed to wrap unsafe off-heap memory with ByteBuffer", t); } } /** * Get native memory address wrapped by the given {@link ByteBuffer}. * * @param buffer {@link ByteBuffer} which wraps the native memory address to get * @return native memory address wrapped by the given {@link ByteBuffer} */ public static long getByteBufferAddress(ByteBuffer buffer) { Preconditions.checkNotNull(buffer, "buffer is null"); Preconditions.checkArgument( buffer.isDirect(), "Can't get address of a non-direct ByteBuffer."); long offHeapAddress; try { offHeapAddress = UNSAFE.getLong(buffer, BUFFER_ADDRESS_FIELD_OFFSET); } catch (Throwable t) { throw new Error("Could not access direct byte buffer address field.", t); } Preconditions.checkState(offHeapAddress > 0, "negative pointer or size"); Preconditions.checkState( offHeapAddress < Long.MAX_VALUE - Integer.MAX_VALUE, "Segment initialized with too large address: %s ; Max allowed address is %d", offHeapAddress, (Long.MAX_VALUE - Integer.MAX_VALUE - 1)); return offHeapAddress; } /** Should not be instantiated. */ private MemoryUtils() {} }
MemoryUtils
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleMapKeyEnumeratedComponentMapper.java
{ "start": 613, "end": 1512 }
class ____ implements MiddleComponentMapper { private final String propertyName; public MiddleMapKeyEnumeratedComponentMapper(String propertyPrefix) { this.propertyName = propertyPrefix + "_KEY"; } @Override public Object mapToObjectFromFullMap( EntityInstantiator entityInstantiator, Map<String, Object> data, Object dataObject, Number revision) { return data.get( propertyName ); } @Override public void mapToMapFromObject( SharedSessionContractImplementor session, Map<String, Object> idData, Map<String, Object> data, Object obj) { idData.put( propertyName, obj ); } @Override public void addMiddleEqualToQuery( Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { throw new UnsupportedOperationException( "Cannot use this mapper with a middle table!" ); } }
MiddleMapKeyEnumeratedComponentMapper
java
square__javapoet
src/test/java/com/squareup/javapoet/JavaFileTest.java
{ "start": 32515, "end": 33274 }
class ____ extends JavaFileTest.Parent {\n" + " java.util.Optional<String> optionalString() {\n" + " return java.util.Optional.empty();\n" + " }\n" + "\n" + " java.util.regex.Pattern pattern() {\n" + " return null;\n" + " }\n" + "}\n"); } @Test public void avoidClashes_parentChild_superinterface_type() { String source = JavaFile.builder("com.squareup.javapoet", childTypeBuilder().addSuperinterface(ParentInterface.class).build()) .build() .toString(); assertThat(source).isEqualTo("package com.squareup.javapoet;\n" + "\n" + "import java.lang.String;\n" + "import java.util.regex.Pattern;\n" + "\n" + "
Child
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/HourOfDay.java
{ "start": 688, "end": 1151 }
class ____ extends TimeFunction { public HourOfDay(Source source, Expression field, ZoneId zoneId) { super(source, field, zoneId, DateTimeExtractor.HOUR_OF_DAY); } @Override protected NodeCtor2<Expression, ZoneId, BaseDateTimeFunction> ctorForInfo() { return HourOfDay::new; } @Override protected HourOfDay replaceChild(Expression newChild) { return new HourOfDay(source(), newChild, zoneId()); } }
HourOfDay
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/flush/AutoFlushOnUpdateQueryTest.java
{ "start": 3065, "end": 3482 }
class ____ { @Id @GeneratedValue private Long id; private String name; @OneToOne private FruitLogEntry logEntry; public Fruit() { } public Fruit(String name) { this.name = name; } public Long getId() { return id; } public String getName() { return name; } public FruitLogEntry getLogEntry() { return logEntry; } } @Entity(name = "FruitLogEntry") public static
Fruit
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/JavaTypeRegistrationsAnnotation.java
{ "start": 746, "end": 1946 }
class ____ implements JavaTypeRegistrations, RepeatableContainer<JavaTypeRegistration> { private org.hibernate.annotations.JavaTypeRegistration[] value; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public JavaTypeRegistrationsAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public JavaTypeRegistrationsAnnotation(JavaTypeRegistrations annotation, ModelsContext modelContext) { this.value = extractJdkValue( annotation, HibernateAnnotations.JAVA_TYPE_REGISTRATIONS, "value", modelContext ); } /** * Used in creating annotation instances from Jandex variant */ public JavaTypeRegistrationsAnnotation( Map<String, Object> attributeValues, ModelsContext modelContext) { this.value = (JavaTypeRegistration[]) attributeValues.get( "value" ); } @Override public Class<? extends Annotation> annotationType() { return JavaTypeRegistrations.class; } @Override public org.hibernate.annotations.JavaTypeRegistration[] value() { return value; } public void value(org.hibernate.annotations.JavaTypeRegistration[] value) { this.value = value; } }
JavaTypeRegistrationsAnnotation
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/RemoteSpringApplication.java
{ "start": 1931, "end": 2243 }
class ____ be launched from within your IDE * and should have the same classpath configuration as the locally developed application. * The remote URL of the application should be provided as a non-option argument. * * @author Phillip Webb * @since 1.3.0 * @see RemoteClientConfiguration */ public final
should
java
apache__camel
components/camel-openapi-java/src/test/java/org/apache/camel/openapi/model/AnyOfFormWrapper.java
{ "start": 906, "end": 1171 }
class ____ { @JsonProperty("formElements") AnyOfForm formPeices; public AnyOfForm getFormPeices() { return this.formPeices; } public void setFormPeices(AnyOfForm formPeices) { this.formPeices = formPeices; } }
AnyOfFormWrapper
java
apache__camel
components/camel-plc4x/src/test/java/org/apache/camel/component/plc4x/Plc4XProducerTest.java
{ "start": 1122, "end": 2941 }
class ____ { private Plc4XProducer sut; private Exchange testExchange; @BeforeEach public void setUp() throws Exception { Plc4XEndpoint endpointMock = mock(Plc4XEndpoint.class, RETURNS_DEEP_STUBS); when(endpointMock.getEndpointUri()).thenReturn("plc4x:mock:10.10.10.1/1/1"); when(endpointMock.canWrite()).thenReturn(true); sut = new Plc4XProducer(endpointMock); testExchange = mock(Exchange.class, RETURNS_DEEP_STUBS); Map<String, Map<String, Object>> tags = new HashMap(); tags.put("test1", Collections.singletonMap("testAddress1", 0)); tags.put("test1", Collections.singletonMap("testAddress2", true)); tags.put("test1", Collections.singletonMap("testAddress3", "TestString")); when(testExchange.getIn().getBody()) .thenReturn(tags); } @Test public void process() throws Exception { when(testExchange.getPattern()).thenReturn(ExchangePattern.InOnly); sut.process(testExchange); when(testExchange.getPattern()).thenReturn(ExchangePattern.InOut); sut.process(testExchange); when(testExchange.getIn().getBody()).thenReturn(2); } @Test public void processAsync() { sut.process(testExchange, doneSync -> { }); when(testExchange.getPattern()).thenReturn(ExchangePattern.InOnly); sut.process(testExchange, doneSync -> { }); when(testExchange.getPattern()).thenReturn(ExchangePattern.InOut); sut.process(testExchange, doneSync -> { }); } @Test public void doStop() throws Exception { sut.doStop(); } @Test public void doStopOpenRequest() throws Exception { sut.openRequests.incrementAndGet(); sut.doStop(); } }
Plc4XProducerTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/tasks/TestProcessingTimeService.java
{ "start": 8146, "end": 8268 }
enum ____ { CREATED, CANCELLED, DONE } } private static
CallbackTaskState
java
google__guice
extensions/servlet/src/com/google/inject/servlet/ServletsModuleBuilder.java
{ "start": 1211, "end": 2709 }
class ____ { private final Set<String> servletUris = Sets.newHashSet(); private final Binder binder; public ServletsModuleBuilder(Binder binder) { this.binder = binder; } //the first level of the EDSL-- public ServletModule.ServletKeyBindingBuilder serve(List<String> urlPatterns) { return new ServletKeyBindingBuilderImpl(parsePatterns(UriPatternType.SERVLET, urlPatterns)); } public ServletModule.ServletKeyBindingBuilder serveRegex(List<String> regexes) { return new ServletKeyBindingBuilderImpl(parsePatterns(UriPatternType.REGEX, regexes)); } private List<UriPatternMatcher> parsePatterns(UriPatternType type, List<String> patterns) { List<UriPatternMatcher> patternMatchers = new ArrayList<>(); for (String pattern : patterns) { if (!servletUris.add(pattern)) { binder .skipSources(ServletModule.class, ServletsModuleBuilder.class) .addError("More than one servlet was mapped to the same URI pattern: " + pattern); } else { UriPatternMatcher matcher = null; try { matcher = UriPatternType.get(type, pattern); } catch (IllegalArgumentException iae) { binder .skipSources(ServletModule.class, ServletsModuleBuilder.class) .addError("%s", iae.getMessage()); } if (matcher != null) { patternMatchers.add(matcher); } } } return patternMatchers; } //non-static inner
ServletsModuleBuilder
java
redisson__redisson
redisson/src/main/java/org/redisson/eviction/MultimapEvictionTask.java
{ "start": 908, "end": 2454 }
class ____ extends EvictionTask { private final String name; private final String timeoutSetName; public MultimapEvictionTask(String name, String timeoutSetName, CommandAsyncExecutor executor) { super(executor); this.name = name; this.timeoutSetName = timeoutSetName; } @Override String getName() { return name; } CompletionStage<Integer> execute() { return executor.evalWriteAsync(name, LongCodec.INSTANCE, RedisCommands.EVAL_INTEGER, "local expiredKeys = redis.call('zrangebyscore', KEYS[2], 0, ARGV[1], 'limit', 0, ARGV[2]); " + "if #expiredKeys > 0 then " + "redis.call('zrem', KEYS[2], unpack(expiredKeys)); " + "local values = redis.call('hmget', KEYS[1], unpack(expiredKeys)); " + "local keys = {}; " + "for i, v in ipairs(values) do " + "if v ~= false then " + "local name = '{' .. KEYS[1] .. '}:' .. v; " + "table.insert(keys, name); " + "end;" + "end; " + "if #keys > 0 then " + "redis.call('del', unpack(keys)); " + "end; " + "redis.call('hdel', KEYS[1], unpack(expiredKeys)); " + "end; " + "return #expiredKeys;", Arrays.asList(name, timeoutSetName), System.currentTimeMillis(), keysLimit); } }
MultimapEvictionTask
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3native/S3xLoginHelper.java
{ "start": 1662, "end": 5590 }
class ____ { private S3xLoginHelper() { } /** * Build the filesystem URI. * @param uri filesystem uri * @return the URI to use as the basis for FS operation and qualifying paths. * @throws NullPointerException if the URI has null parts. */ public static URI buildFSURI(URI uri) { // look for login secrets and fail if they are present. Objects.requireNonNull(uri, "null uri"); Objects.requireNonNull(uri.getScheme(), "null uri.getScheme()"); Objects.requireNonNull(uri.getHost(), "null uri host."); return URI.create(uri.getScheme() + "://" + uri.getHost()); } /** * Canonicalize the given URI. * * @param uri the URI to canonicalize * @param defaultPort default port to use in canonicalized URI if the input * URI has no port and this value is greater than 0 * @return a new, canonicalized URI. */ public static URI canonicalizeUri(URI uri, int defaultPort) { if (uri.getPort() == -1 && defaultPort > 0) { // reconstruct the uri with the default port set try { uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), defaultPort, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { // Should never happen! throw new AssertionError("Valid URI became unparseable: " + uri); } } return uri; } /** * Check the path, ignoring authentication details. * See {@code FileSystem.checkPath(Path)} for the operation of this. * Essentially * <ol> * <li>The URI is canonicalized.</li> * <li>If the schemas match, the hosts are compared.</li> * <li>If there is a mismatch between null/non-null host, the default FS * values are used to patch in the host.</li> * </ol> * That all originates in the core FS; the sole change here being to use * {@link URI#getHost()} over {@link URI#getAuthority()}. Some of that * code looks a relic of the code anti-pattern of using "hdfs:file.txt" * to define the path without declaring the hostname. It's retained * for compatibility. * @param conf FS configuration * @param fsUri the FS URI * @param path path to check * @param defaultPort default port of FS */ public static void checkPath(Configuration conf, URI fsUri, Path path, int defaultPort) { URI pathUri = path.toUri(); String thatScheme = pathUri.getScheme(); if (thatScheme == null) { // fs is relative return; } URI thisUri = canonicalizeUri(fsUri, defaultPort); String thisScheme = thisUri.getScheme(); //hostname and scheme are not case sensitive in these checks if (equalsIgnoreCase(thisScheme, thatScheme)) {// schemes match String thisHost = thisUri.getHost(); String thatHost = pathUri.getHost(); if (thatHost == null && // path's host is null thisHost != null) { // fs has a host URI defaultUri = FileSystem.getDefaultUri(conf); if (equalsIgnoreCase(thisScheme, defaultUri.getScheme())) { pathUri = defaultUri; // schemes match, so use this uri instead } else { pathUri = null; // can't determine auth of the path } } if (pathUri != null) { // canonicalize uri before comparing with this fs pathUri = canonicalizeUri(pathUri, defaultPort); thatHost = pathUri.getHost(); if (thisHost == thatHost || // hosts match (thisHost != null && equalsIgnoreCase(thisHost, thatHost))) { return; } } } // make sure the exception strips out any auth details throw new IllegalArgumentException( "Wrong FS " + pathUri + " -expected " + fsUri); } /** * Simple tuple of login details. */ public static
S3xLoginHelper
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/config/RegistryArtifactConfig.java
{ "start": 197, "end": 826 }
interface ____ { /** * Whether this catalog artifact is not supported by the registry or should simply be disabled on the client side. * * @return true, if the catalog represented by this artifact should be excluded from processing */ boolean isDisabled(); /** * Catalog artifact coordinates in the registry. * * @return catalog artifact coordinates in the registry */ ArtifactCoords getArtifact(); /** @return a mutable copy of this config */ default Mutable mutable() { return new RegistryArtifactConfigImpl.Builder(this); }
RegistryArtifactConfig
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/core/StaticFinalReflectionUtils.java
{ "start": 1256, "end": 3451 }
class ____ { /** * Used to support setting static fields that are final using Java's Unsafe. If the * field is not static final, use * {@link org.springframework.test.util.ReflectionTestUtils}. * @param field the field to set * @param newValue the new value */ static void setField(final Field field, final Object newValue) { try { field.setAccessible(true); int fieldModifiersMask = field.getModifiers(); boolean isFinalModifierPresent = (fieldModifiersMask & Modifier.FINAL) == Modifier.FINAL; if (isFinalModifierPresent) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { Unsafe unsafe = UnsafeUtils.getUnsafe(); long offset = unsafe.staticFieldOffset(field); Object base = unsafe.staticFieldBase(field); setFieldUsingUnsafe(base, field.getType(), offset, newValue, unsafe); return null; } catch (Throwable thrown) { throw new RuntimeException(thrown); } } }); } else { field.set(null, newValue); } } catch (SecurityException | IllegalAccessException | IllegalArgumentException ex) { throw new RuntimeException(ex); } } private static void setFieldUsingUnsafe(Object base, Class type, long offset, Object newValue, Unsafe unsafe) { if (type == Integer.TYPE) { unsafe.putInt(base, offset, ((Integer) newValue)); } else if (type == Short.TYPE) { unsafe.putShort(base, offset, ((Short) newValue)); } else if (type == Long.TYPE) { unsafe.putLong(base, offset, ((Long) newValue)); } else if (type == Byte.TYPE) { unsafe.putByte(base, offset, ((Byte) newValue)); } else if (type == Boolean.TYPE) { unsafe.putBoolean(base, offset, ((Boolean) newValue)); } else if (type == Float.TYPE) { unsafe.putFloat(base, offset, ((Float) newValue)); } else if (type == Double.TYPE) { unsafe.putDouble(base, offset, ((Double) newValue)); } else if (type == Character.TYPE) { unsafe.putChar(base, offset, ((Character) newValue)); } else { unsafe.putObject(base, offset, newValue); } } private StaticFinalReflectionUtils() { } }
StaticFinalReflectionUtils
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metagen/mappedsuperclass/attribute/AbstractNameable.java
{ "start": 315, "end": 597 }
class ____ { private String name; protected AbstractNameable() { } protected AbstractNameable(String name) { this.name = name; } @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } }
AbstractNameable
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteTestDescriptorTests.java
{ "start": 1526, "end": 3850 }
class ____ { final UniqueId engineId = UniqueId.forEngine(SuiteEngineDescriptor.ENGINE_ID); final UniqueId suiteId = engineId.append(SuiteTestDescriptor.SEGMENT_TYPE, "test"); final UniqueId jupiterEngineId = suiteId.append("engine", JupiterEngineDescriptor.ENGINE_ID); final UniqueId testClassId = jupiterEngineId.append(ClassTestDescriptor.SEGMENT_TYPE, SingleTestTestCase.class.getName()); final UniqueId methodId = testClassId.append(TestMethodTestDescriptor.SEGMENT_TYPE, "test(%s)".formatted(TestReporter.class.getName())); final ConfigurationParameters configurationParameters = new EmptyConfigurationParameters(); final OutputDirectoryCreator outputDirectoryCreator = OutputDirectoryCreators.dummyOutputDirectoryCreator(); final DiscoveryIssueReporter discoveryIssueReporter = DiscoveryIssueReporter.forwarding(mock(), engineId); final SuiteTestDescriptor suite = new SuiteTestDescriptor(suiteId, TestSuite.class, configurationParameters, outputDirectoryCreator, mock(), discoveryIssueReporter); @Test void suiteIsEmptyBeforeDiscovery() { suite.addDiscoveryRequestFrom(SelectClassesSuite.class); assertThat(suite.getChildren()).isEmpty(); } @Test void suiteDiscoversTestsFromClass() { suite.addDiscoveryRequestFrom(SelectClassesSuite.class); suite.discover(); assertThat(suite.getDescendants()).map(TestDescriptor::getUniqueId)// .containsExactly(jupiterEngineId, testClassId, methodId); } @Test void suiteDiscoversTestsFromUniqueId() { suite.addDiscoveryRequestFrom(methodId); suite.discover(); assertThat(suite.getDescendants()).map(TestDescriptor::getUniqueId)// .containsExactly(jupiterEngineId, testClassId, methodId); } @Test void discoveryPlanCanNotBeModifiedAfterDiscovery() { suite.addDiscoveryRequestFrom(SelectClassesSuite.class); suite.discover(); assertAll(// () -> assertPreconditionViolationFor(() -> suite.addDiscoveryRequestFrom(SelectClassesSuite.class))// .withMessage("discovery request cannot be modified after discovery"), () -> assertPreconditionViolationFor(() -> suite.addDiscoveryRequestFrom(methodId))// .withMessage("discovery request cannot be modified after discovery")); } @Test void suiteMayRegisterTests() { assertThat(suite.mayRegisterTests()).isTrue(); } @Suite static
SuiteTestDescriptorTests
java
apache__dubbo
dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/openapi/OpenAPIDefinitionResolver.java
{ "start": 1303, "end": 1677 }
interface ____ extends OpenAPIExtension { OpenAPI resolve(OpenAPI openAPI, ServiceMeta serviceMeta, OpenAPIChain chain); Collection<HttpMethods> resolve(PathItem pathItem, MethodMeta methodMeta, OperationContext context); Operation resolve(Operation operation, MethodMeta methodMeta, OperationContext context, OperationChain chain);
OpenAPIDefinitionResolver
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/CountDistinctIntAggregatorFunctionTests.java
{ "start": 1201, "end": 3461 }
class ____ extends AggregatorFunctionTestCase { @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { int max = between(1, Math.min(Integer.MAX_VALUE, Integer.MAX_VALUE / size)); return new SequenceIntBlockSourceOperator(blockFactory, LongStream.range(0, size).mapToInt(l -> between(-max, max))); } @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new CountDistinctIntAggregatorFunctionSupplier(40000); } @Override protected String expectedDescriptionOfAggregator() { return "count_distinct of ints"; } @Override protected void assertSimpleOutput(List<Page> input, Block result) { long expected = input.stream().flatMapToInt(p -> allInts(p.getBlock(0))).distinct().count(); long count = ((LongBlock) result).getLong(0); // HLL is an approximation algorithm and precision depends on the number of values computed and the precision_threshold param // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html // For a number of values close to 10k and precision_threshold=1000, precision should be less than 10% assertThat((double) count, closeTo(expected, expected * 0.1)); } @Override protected void assertOutputFromEmpty(Block b) { assertThat(b.getPositionCount(), equalTo(1)); assertThat(valuesAtPositions(b, 0, 1), equalTo(List.of(List.of(0L)))); } public void testRejectsDouble() { DriverContext driverContext = driverContext(); BlockFactory blockFactory = driverContext.blockFactory(); try ( Driver d = TestDriverFactory.create( driverContext, new CannedSourceOperator(Iterators.single(new Page(blockFactory.newDoubleArrayVector(new double[] { 1.0 }, 1).asBlock()))), List.of(simple().get(driverContext)), new PageConsumerOperator(page -> fail("shouldn't have made it this far")) ) ) { expectThrows(Exception.class, () -> runDriver(d)); // ### find a more specific exception type } } }
CountDistinctIntAggregatorFunctionTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/SingleTableNativeQueryTest.java
{ "start": 6058, "end": 6616 }
class ____ { @Id private String name; @ManyToOne private Family familyName; public Person() { } public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Family getFamilyName() { return familyName; } public void setFamilyName(Family familyName) { this.familyName = familyName; } @Override public String toString() { return name; } } @Entity(name = "Toy") @Table(name = "toy") public static
Person
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/indices/IndicesLifecycleListenerIT.java
{ "start": 13330, "end": 15156 }
class ____ implements IndexEventListener { // we keep track of all the states (ordered) a shard goes through final ConcurrentMap<ShardId, List<IndexShardState>> shardStates = new ConcurrentHashMap<>(); Settings creationSettings = Settings.EMPTY; Settings afterCloseSettings = Settings.EMPTY; @Override public void indexShardStateChanged( IndexShard indexShard, @Nullable IndexShardState previousState, IndexShardState newState, @Nullable String reason ) { List<IndexShardState> shardStateList = this.shardStates.putIfAbsent( indexShard.shardId(), new CopyOnWriteArrayList<>(new IndexShardState[] { newState }) ); if (shardStateList != null) { shardStateList.add(newState); } } @Override public void beforeIndexCreated(Index index, Settings indexSettings) { this.creationSettings = indexSettings; if (indexSettings.getAsBoolean("index.fail", false)) { throw new ElasticsearchException("failing on purpose"); } } @Override public void afterIndexShardClosed(ShardId shardId, @Nullable IndexShard indexShard, Settings indexSettings) { this.afterCloseSettings = indexSettings; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry<ShardId, List<IndexShardState>> entry : shardStates.entrySet()) { sb.append(entry.getKey()).append(" --> ").append(Strings.collectionToCommaDelimitedString(entry.getValue())).append("\n"); } return sb.toString(); } } }
IndexShardStateChangeListener
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/rest/action/cat/RestSnapshotAction.java
{ "start": 1519, "end": 1608 }
class ____ display information about snapshots */ @ServerlessScope(Scope.INTERNAL) public
to
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/TestSafeMode.java
{ "start": 1413, "end": 2744 }
class ____ { /** Federated HDFS cluster. */ private MiniRouterDFSCluster cluster; @BeforeEach public void setup() throws Exception { cluster = new MiniRouterDFSCluster(true, 2); // Start NNs and DNs and wait until ready cluster.startCluster(); // Start routers with only an RPC service cluster.startRouters(); // Register and verify all NNs with all routers cluster.registerNamenodes(); cluster.waitNamenodeRegistration(); // Setup the mount table cluster.installMockLocations(); // Making one Namenodes active per nameservice if (cluster.isHighAvailability()) { for (String ns : cluster.getNameservices()) { cluster.switchToActive(ns, NAMENODES[0]); cluster.switchToStandby(ns, NAMENODES[1]); } } cluster.waitActiveNamespaces(); } @AfterEach public void teardown() throws IOException { if (cluster != null) { cluster.shutdown(); cluster = null; } } @Test public void testProxySetSafemode() throws Exception { RouterContext routerContext = cluster.getRandomRouter(); ClientProtocol routerProtocol = routerContext.getClient().getNamenode(); routerProtocol.setSafeMode(SafeModeAction.SAFEMODE_GET, true); routerProtocol.setSafeMode(SafeModeAction.SAFEMODE_GET, false); } }
TestSafeMode
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/SearchSlowLogTests.java
{ "start": 2043, "end": 27349 }
class ____ extends ESSingleNodeTestCase { static MockAppender appender; static Logger queryLog = LogManager.getLogger(SearchSlowLog.INDEX_SEARCH_SLOWLOG_PREFIX + ".query"); static Logger fetchLog = LogManager.getLogger(SearchSlowLog.INDEX_SEARCH_SLOWLOG_PREFIX + ".fetch"); static Level origQueryLogLevel = queryLog.getLevel(); static Level origFetchLogLevel = fetchLog.getLevel(); @BeforeClass public static void init() throws IllegalAccessException { appender = new MockAppender("trace_appender"); appender.start(); Loggers.addAppender(queryLog, appender); Loggers.addAppender(fetchLog, appender); Loggers.setLevel(queryLog, Level.TRACE); Loggers.setLevel(fetchLog, Level.TRACE); } @AfterClass public static void cleanup() { Loggers.removeAppender(queryLog, appender); Loggers.removeAppender(fetchLog, appender); appender.stop(); Loggers.setLevel(queryLog, origQueryLogLevel); Loggers.setLevel(fetchLog, origFetchLogLevel); } @Override protected SearchContext createSearchContext(IndexService indexService) { return createSearchContext(indexService, new String[] {}); } protected SearchContext createSearchContext(IndexService indexService, String... groupStats) { final ShardSearchRequest request = new ShardSearchRequest(new ShardId(indexService.index(), 0), 0L, null); return new TestSearchContext(indexService) { @Override public List<String> groupStats() { return Arrays.asList(groupStats); } @Override public ShardSearchRequest request() { return request; } @Override public CancellableTask getTask() { return super.getTask(); } }; } public void testLevelPrecedence() { try (SearchContext ctx = searchContextWithSourceAndTask(createIndex("index"))) { String uuid = UUIDs.randomBase64UUID(); IndexSettings settings = new IndexSettings(createIndexMetadata("index", settings(uuid)), Settings.EMPTY); SearchSlowLog log = new SearchSlowLog(settings, mock(SlowLogFields.class)); // For this test, when level is not breached, the level below should be used. { log.onQueryPhase(ctx, 40L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.INFO)); log.onQueryPhase(ctx, 41L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.WARN)); log.onFetchPhase(ctx, 40L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.INFO)); log.onFetchPhase(ctx, 41L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.WARN)); } { log.onQueryPhase(ctx, 30L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.DEBUG)); log.onQueryPhase(ctx, 31L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.INFO)); log.onFetchPhase(ctx, 30L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.DEBUG)); log.onFetchPhase(ctx, 31L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.INFO)); } { log.onQueryPhase(ctx, 20L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.TRACE)); log.onQueryPhase(ctx, 21L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.DEBUG)); log.onFetchPhase(ctx, 20L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.TRACE)); log.onFetchPhase(ctx, 21L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.DEBUG)); } { log.onQueryPhase(ctx, 10L); assertNull(appender.getLastEventAndReset()); log.onQueryPhase(ctx, 11L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.TRACE)); log.onFetchPhase(ctx, 10L); assertNull(appender.getLastEventAndReset()); log.onFetchPhase(ctx, 11L); assertThat(appender.getLastEventAndReset().getLevel(), equalTo(Level.TRACE)); } } } private Settings.Builder settings(String uuid) { return Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(IndexMetadata.SETTING_INDEX_UUID, uuid) .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING.getKey(), "10nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING.getKey(), "20nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING.getKey(), "30nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING.getKey(), "40nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING.getKey(), "10nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING.getKey(), "20nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING.getKey(), "30nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING.getKey(), "40nanos"); } public void testTwoLoggersDifferentLevel() { try ( SearchContext ctx1 = searchContextWithSourceAndTask(createIndex("index-1")); SearchContext ctx2 = searchContextWithSourceAndTask(createIndex("index-2")) ) { IndexSettings settings1 = new IndexSettings( createIndexMetadata( "index-1", Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()) .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING.getKey(), "40nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING.getKey(), "40nanos") ), Settings.EMPTY ); SearchSlowLog log1 = new SearchSlowLog(settings1, mock(SlowLogFields.class)); IndexSettings settings2 = new IndexSettings( createIndexMetadata( "index-2", Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()) .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING.getKey(), "10nanos") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING.getKey(), "10nanos") ), Settings.EMPTY ); SearchSlowLog log2 = new SearchSlowLog(settings2, mock(SlowLogFields.class)); { // threshold set on WARN only, should not log log1.onQueryPhase(ctx1, 11L); assertNull(appender.getLastEventAndReset()); log1.onFetchPhase(ctx1, 11L); assertNull(appender.getLastEventAndReset()); // threshold set on TRACE, should log log2.onQueryPhase(ctx2, 11L); assertNotNull(appender.getLastEventAndReset()); log2.onFetchPhase(ctx2, 11L); assertNotNull(appender.getLastEventAndReset()); } } } public void testMultipleSlowLoggersUseSingleLog4jLogger() { LoggerContext context = (LoggerContext) LogManager.getContext(false); try (SearchContext ctx1 = searchContextWithSourceAndTask(createIndex("index-1"))) { IndexSettings settings1 = new IndexSettings(createIndexMetadata("index-1", settings(UUIDs.randomBase64UUID())), Settings.EMPTY); SearchSlowLog log1 = new SearchSlowLog(settings1, mock(SlowLogFields.class)); int numberOfLoggersBefore = context.getLoggers().size(); try (SearchContext ctx2 = searchContextWithSourceAndTask(createIndex("index-2"))) { IndexSettings settings2 = new IndexSettings( createIndexMetadata("index-2", settings(UUIDs.randomBase64UUID())), Settings.EMPTY ); SearchSlowLog log2 = new SearchSlowLog(settings2, mock(SlowLogFields.class)); int numberOfLoggersAfter = context.getLoggers().size(); assertThat(numberOfLoggersAfter, equalTo(numberOfLoggersBefore)); } } } private IndexMetadata createIndexMetadata(String index, Settings.Builder put) { return newIndexMeta(index, put.build()); } public void testSlowLogHasJsonFields() throws IOException { IndexService index = createIndex("foo"); try (SearchContext searchContext = searchContextWithSourceAndTask(index)) { ESLogMessage p = SearchSlowLog.SearchSlowLogMessage.of(Map.of(), searchContext, 10); assertThat(p.get("elasticsearch.slowlog.message"), equalTo("[foo][0]")); assertThat(p.get("elasticsearch.slowlog.took"), equalTo("10nanos")); assertThat(p.get("elasticsearch.slowlog.took_millis"), equalTo("0")); assertThat(p.get("elasticsearch.slowlog.total_hits"), equalTo("-1")); assertThat(p.get("elasticsearch.slowlog.stats"), equalTo("[]")); assertThat(p.get("elasticsearch.slowlog.search_type"), Matchers.nullValue()); assertThat(p.get("elasticsearch.slowlog.total_shards"), equalTo("1")); assertThat(p.get("elasticsearch.slowlog.source"), equalTo("{\\\"query\\\":{\\\"match_all\\\":{\\\"boost\\\":1.0}}}")); } } public void testSlowLogHasAdditionalFields() throws IOException { IndexService index = createIndex("foo"); try (SearchContext searchContext = searchContextWithSourceAndTask(index)) { ESLogMessage p = SearchSlowLog.SearchSlowLogMessage.of(Map.of("field1", "value1", "field2", "value2"), searchContext, 10); assertThat(p.get("field1"), equalTo("value1")); assertThat(p.get("field2"), equalTo("value2")); assertThat(p.get("elasticsearch.slowlog.message"), equalTo("[foo][0]")); assertThat(p.get("elasticsearch.slowlog.took"), equalTo("10nanos")); assertThat(p.get("elasticsearch.slowlog.took_millis"), equalTo("0")); assertThat(p.get("elasticsearch.slowlog.total_hits"), equalTo("-1")); assertThat(p.get("elasticsearch.slowlog.stats"), equalTo("[]")); assertThat(p.get("elasticsearch.slowlog.search_type"), Matchers.nullValue()); assertThat(p.get("elasticsearch.slowlog.total_shards"), equalTo("1")); assertThat(p.get("elasticsearch.slowlog.source"), equalTo("{\\\"query\\\":{\\\"match_all\\\":{\\\"boost\\\":1.0}}}")); } } public void testSlowLogsWithStats() throws IOException { IndexService index = createIndex("foo"); try (SearchContext searchContext = createSearchContext(index, "group1")) { SearchSourceBuilder source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()); searchContext.request().source(source); searchContext.setTask( new SearchShardTask(0, "n/a", "n/a", "test", null, Collections.singletonMap(Task.X_OPAQUE_ID_HTTP_HEADER, "my_id")) ); ESLogMessage p = SearchSlowLog.SearchSlowLogMessage.of(Map.of(), searchContext, 10); assertThat(p.get("elasticsearch.slowlog.stats"), equalTo("[\\\"group1\\\"]")); } try (SearchContext searchContext = createSearchContext(index, "group1", "group2");) { SearchSourceBuilder source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()); searchContext.request().source(source); searchContext.setTask( new SearchShardTask(0, "n/a", "n/a", "test", null, Collections.singletonMap(Task.X_OPAQUE_ID_HTTP_HEADER, "my_id")) ); ESLogMessage p = SearchSlowLog.SearchSlowLogMessage.of(Map.of(), searchContext, 10); assertThat(p.get("elasticsearch.slowlog.stats"), equalTo("[\\\"group1\\\", \\\"group2\\\"]")); } } public void testSlowLogSearchContextPrinterToLog() throws IOException { IndexService index = createIndex("foo"); try (SearchContext searchContext = searchContextWithSourceAndTask(index)) { ESLogMessage p = SearchSlowLog.SearchSlowLogMessage.of(Map.of(), searchContext, 10); assertThat(p.get("elasticsearch.slowlog.message"), equalTo("[foo][0]")); // Makes sure that output doesn't contain any new lines assertThat(p.get("elasticsearch.slowlog.source"), not(containsString("\n"))); assertThat(p.get("elasticsearch.slowlog.id"), equalTo("my_id")); } } public void testSetQueryLevels() { IndexMetadata metadata = newIndexMeta( "index", Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING.getKey(), "100ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING.getKey(), "200ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING.getKey(), "300ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING.getKey(), "400ms") .build() ); IndexSettings settings = new IndexSettings(metadata, Settings.EMPTY); SearchSlowLog log = new SearchSlowLog(settings, mock(SlowLogFields.class)); assertEquals(TimeValue.timeValueMillis(100).nanos(), log.getQueryTraceThreshold()); assertEquals(TimeValue.timeValueMillis(200).nanos(), log.getQueryDebugThreshold()); assertEquals(TimeValue.timeValueMillis(300).nanos(), log.getQueryInfoThreshold()); assertEquals(TimeValue.timeValueMillis(400).nanos(), log.getQueryWarnThreshold()); settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING.getKey(), "120ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING.getKey(), "220ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING.getKey(), "320ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING.getKey(), "420ms") .build() ) ); assertEquals(TimeValue.timeValueMillis(120).nanos(), log.getQueryTraceThreshold()); assertEquals(TimeValue.timeValueMillis(220).nanos(), log.getQueryDebugThreshold()); assertEquals(TimeValue.timeValueMillis(320).nanos(), log.getQueryInfoThreshold()); assertEquals(TimeValue.timeValueMillis(420).nanos(), log.getQueryWarnThreshold()); metadata = newIndexMeta("index", Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()).build()); settings.updateIndexMetadata(metadata); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryTraceThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryDebugThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryInfoThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryWarnThreshold()); settings = new IndexSettings(metadata, Settings.EMPTY); log = new SearchSlowLog(settings, mock(SlowLogFields.class)); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryTraceThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryDebugThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryInfoThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getQueryWarnThreshold()); try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_TRACE_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.query.trace"); } try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_DEBUG_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.query.debug"); } try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_INFO_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.query.info"); } try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_QUERY_WARN_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.query.warn"); } } public void testSetFetchLevels() { IndexMetadata metadata = newIndexMeta( "index", Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING.getKey(), "100ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING.getKey(), "200ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING.getKey(), "300ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING.getKey(), "400ms") .build() ); IndexSettings settings = new IndexSettings(metadata, Settings.EMPTY); SearchSlowLog log = new SearchSlowLog(settings, mock(SlowLogFields.class)); assertEquals(TimeValue.timeValueMillis(100).nanos(), log.getFetchTraceThreshold()); assertEquals(TimeValue.timeValueMillis(200).nanos(), log.getFetchDebugThreshold()); assertEquals(TimeValue.timeValueMillis(300).nanos(), log.getFetchInfoThreshold()); assertEquals(TimeValue.timeValueMillis(400).nanos(), log.getFetchWarnThreshold()); settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING.getKey(), "120ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING.getKey(), "220ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING.getKey(), "320ms") .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING.getKey(), "420ms") .build() ) ); assertEquals(TimeValue.timeValueMillis(120).nanos(), log.getFetchTraceThreshold()); assertEquals(TimeValue.timeValueMillis(220).nanos(), log.getFetchDebugThreshold()); assertEquals(TimeValue.timeValueMillis(320).nanos(), log.getFetchInfoThreshold()); assertEquals(TimeValue.timeValueMillis(420).nanos(), log.getFetchWarnThreshold()); metadata = newIndexMeta("index", Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()).build()); settings.updateIndexMetadata(metadata); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchTraceThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchDebugThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchInfoThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchWarnThreshold()); settings = new IndexSettings(metadata, Settings.EMPTY); log = new SearchSlowLog(settings, mock(SlowLogFields.class)); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchTraceThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchDebugThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchInfoThreshold()); assertEquals(TimeValue.MINUS_ONE.nanos(), log.getFetchWarnThreshold()); try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_TRACE_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.fetch.trace"); } try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_DEBUG_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.fetch.debug"); } try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_INFO_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.fetch.info"); } try { settings.updateIndexMetadata( newIndexMeta( "index", Settings.builder() .put(SearchSlowLog.INDEX_SEARCH_SLOWLOG_THRESHOLD_FETCH_WARN_SETTING.getKey(), "NOT A TIME VALUE") .build() ) ); fail(); } catch (IllegalArgumentException ex) { assertTimeValueException(ex, "index.search.slowlog.threshold.fetch.warn"); } } private void assertTimeValueException(final IllegalArgumentException e, final String key) { final String expected = "illegal value can't update [" + key + "] from [-1] to [NOT A TIME VALUE]"; assertThat(e, hasToString(containsString(expected))); assertNotNull(e.getCause()); assertThat(e.getCause(), instanceOf(IllegalArgumentException.class)); final IllegalArgumentException cause = (IllegalArgumentException) e.getCause(); final String causeExpected = "failed to parse setting [" + key + "] with value [NOT A TIME VALUE] as a time value: unit is missing or unrecognized"; assertThat(cause, hasToString(containsString(causeExpected))); } private IndexMetadata newIndexMeta(String name, Settings indexSettings) { return IndexMetadata.builder(name).settings(indexSettings(IndexVersion.current(), 1, 1).put(indexSettings)).build(); } private SearchContext searchContextWithSourceAndTask(IndexService index) { SearchContext ctx = createSearchContext(index); SearchSourceBuilder source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()); ctx.request().source(source); ctx.setTask(new SearchShardTask(0, "n/a", "n/a", "test", null, Collections.singletonMap(Task.X_OPAQUE_ID_HTTP_HEADER, "my_id"))); return ctx; } }
SearchSlowLogTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/UrlAssertionTests.java
{ "start": 1629, "end": 2370 }
class ____ { private MockMvc mockMvc; @BeforeEach public void setup() { this.mockMvc = standaloneSetup(new SimpleController()).build(); } @Test public void testRedirect() throws Exception { this.mockMvc.perform(get("/persons")).andExpect(redirectedUrl("/persons/1")); } @Test public void testRedirectPattern() throws Exception { this.mockMvc.perform(get("/persons")).andExpect(redirectedUrlPattern("/persons/*")); } @Test public void testForward() throws Exception { this.mockMvc.perform(get("/")).andExpect(forwardedUrl("/home")); } @Test public void testForwardPattern() throws Exception { this.mockMvc.perform(get("/")).andExpect(forwardedUrlPattern("/ho?e")); } @Controller private static
UrlAssertionTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/plugins/internal/SettingsExtension.java
{ "start": 844, "end": 1188 }
interface ____ { List<Setting<?>> getSettings(); /** * Loads a single SettingsExtension, or returns {@code null} if none are found. */ static List<SettingsExtension> load() { var loader = ServiceLoader.load(SettingsExtension.class); return loader.stream().map(p -> p.get()).toList(); } }
SettingsExtension
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/strings/Strings_assertIsSubstringOf_Test.java
{ "start": 1190, "end": 4154 }
class ____ extends StringsBaseTest { @Test void should_pass_if_actual_is_a_substring_of_given_string() { strings.assertIsSubstringOf(someInfo(), "Yo", "Yoda"); } @Test void should_pass_if_actual_is_equal_to_given_string() { strings.assertIsSubstringOf(someInfo(), "Yoda", "Yoda"); } @Test void should_pass_if_actual_is_empty() { strings.assertIsSubstringOf(someInfo(), "", "Yoda"); strings.assertIsSubstringOf(someInfo(), "", ""); } @Test void should_fail_if_actual_contains_given_string() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertIsSubstringOf(someInfo(), "Yoda", "oda")) .withMessage(shouldBeSubstring("Yoda", "oda", StandardComparisonStrategy.instance()).create()); } @Test void should_fail_if_actual_completely_different_from_given_string() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertIsSubstringOf(someInfo(), "Yoda", "Luke")) .withMessage(shouldBeSubstring("Yoda", "Luke", StandardComparisonStrategy.instance()).create()); } @Test void should_throw_error_if_sequence_is_null() { assertThatNullPointerException().isThrownBy(() -> strings.assertIsSubstringOf(someInfo(), "Yoda", null)) .withMessage("Expecting CharSequence not to be null"); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> strings.assertIsSubstringOf(someInfo(), null, "Yoda")) .withMessage(actualIsNull()); } @Test void should_pass_if_actual_is_a_part_of_sequence_only_according_to_custom_comparison_strategy() { stringsWithCaseInsensitiveComparisonStrategy.assertIsSubstringOf(someInfo(), "Yo", "Yoda"); stringsWithCaseInsensitiveComparisonStrategy.assertIsSubstringOf(someInfo(), "yo", "Yoda"); stringsWithCaseInsensitiveComparisonStrategy.assertIsSubstringOf(someInfo(), "YO", "Yoda"); } @Test void should_fail_if_actual_is_not_a_substring_of_sequence_according_to_custom_comparison_strategy() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> stringsWithCaseInsensitiveComparisonStrategy.assertIsSubstringOf(someInfo(), "Yoda", "Luke")) .withMessage(shouldBeSubstring("Yoda", "Luke", comparisonStrategy).create()); } }
Strings_assertIsSubstringOf_Test
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/typeutils/LegacyInstantTypeInfo.java
{ "start": 1557, "end": 2556 }
class ____ extends BasicTypeInfo<Instant> { private static final long serialVersionUID = 1L; private final int precision; public LegacyInstantTypeInfo(int precision) { super( Instant.class, new Class<?>[] {}, InstantSerializer.INSTANCE, InstantComparator.class); this.precision = precision; } @Override public boolean equals(Object obj) { if (!(obj instanceof LegacyInstantTypeInfo)) { return false; } LegacyInstantTypeInfo that = (LegacyInstantTypeInfo) obj; return this.precision == that.precision; } @Override public String toString() { return String.format("TIMESTAMP(%d) WITH LOCAL TIME ZONE", precision); } @Override public int hashCode() { return Objects.hash(this.getClass().getCanonicalName(), precision); } public int getPrecision() { return precision; } }
LegacyInstantTypeInfo
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ThrowIfUncheckedKnownUncheckedTest.java
{ "start": 2333, "end": 2889 }
class ____ { void x() { try { } catch (RuntimeException | Error e) { // BUG: Diagnostic contains: throwIfUnchecked(e); } } } """) .doTest(); } @Test public void knownCheckedException() { compilationHelper .addSourceLines( "Foo.java", """ import static com.google.common.base.Throwables.throwIfUnchecked; import java.io.IOException;
Foo
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Methods.java
{ "start": 25374, "end": 26888 }
interface ____ false; } List<Type> parameters = method.parameterTypes(); if (!parameters.isEmpty() && (beanArchiveIndex != null)) { String originalClassPackage = DotNames.packagePrefix(originalClazz.name()); for (Type type : parameters) { if (type.kind() == Kind.PRIMITIVE) { continue; } DotName typeName = type.name(); if (type.kind() == Kind.ARRAY) { Type componentType = type.asArrayType().constituent(); if (componentType.kind() == Kind.PRIMITIVE) { continue; } typeName = componentType.name(); } ClassInfo param = beanArchiveIndex.getClassByName(typeName); if (param == null) { LOGGER.warn(String.format( "Parameter type info not available: %s - unable to validate the parameter type's visibility for method %s declared on %s", type.name(), method.name(), method.declaringClass().name())); continue; } if (Modifier.isPublic(param.flags()) || Modifier.isProtected(param.flags())) { continue; } // e.g. parameters whose
return
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/DataSourceBuilder.java
{ "start": 26245, "end": 26692 }
class ____ extends MappedDataSourceProperties<OracleDataSource> { OracleDataSourceProperties() { add(DataSourceProperty.URL, OracleDataSource::getURL, OracleDataSource::setURL); add(DataSourceProperty.USERNAME, OracleDataSource::getUser, OracleDataSource::setUser); add(DataSourceProperty.PASSWORD, null, OracleDataSource::setPassword); } } /** * {@link DataSourceProperties} for H2. */ private static
OracleDataSourceProperties
java
google__auto
value/src/it/functional/src/main/java/com/google/auto/value/SimpleValueType.java
{ "start": 797, "end": 1857 }
class ____ { // The getters here are formatted as an illustration of what getters typically look in real // classes. In particular they have doc comments. /** Returns a string that is a nullable string. */ @Nullable public abstract String string(); /** Returns an integer that is an integer. */ public abstract int integer(); /** Returns a non-null map where the keys are strings and the values are longs. */ public abstract Map<String, Long> map(); public static SimpleValueType create( @Nullable String string, int integer, Map<String, Long> map) { // The subclass AutoValue_SimpleValueType is created by the annotation processor that is // triggered by the presence of the @AutoValue annotation. It has a constructor for each // of the abstract getter methods here, in order. The constructor stashes the values here // in private final fields, and each method is implemented to return the value of the // corresponding field. return new AutoValue_SimpleValueType(string, integer, map); } }
SimpleValueType
java
grpc__grpc-java
okhttp/src/test/java/io/grpc/okhttp/OkHttpClientStreamTest.java
{ "start": 2298, "end": 10143 }
class ____ { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); private static final int MAX_MESSAGE_SIZE = 100; private static final int INITIAL_WINDOW_SIZE = 65535; @Mock private MethodDescriptor.Marshaller<Void> marshaller; @Mock private FrameWriter mockedFrameWriter; private ExceptionHandlingFrameWriter frameWriter; @Mock private OkHttpClientTransport transport; @Mock private OutboundFlowController flowController; @Captor private ArgumentCaptor<List<Header>> headersCaptor; private final Object lock = new Object(); private final TransportTracer transportTracer = new TransportTracer(); private MethodDescriptor<?, ?> methodDescriptor; private OkHttpClientStream stream; @Before public void setUp() { methodDescriptor = MethodDescriptor.<Void, Void>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("testService/test") .setRequestMarshaller(marshaller) .setResponseMarshaller(marshaller) .build(); frameWriter = new ExceptionHandlingFrameWriter(transport, mockedFrameWriter); stream = new OkHttpClientStream( methodDescriptor, new Metadata(), frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost", "userAgent", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false); } @Test public void getType() { assertEquals(MethodType.UNARY, stream.getType()); } @Test public void cancel_notStarted() { final AtomicReference<Status> statusRef = new AtomicReference<>(); stream.start(new BaseClientStreamListener() { @Override public void closed( Status status, RpcProgress rpcProgress, Metadata trailers) { statusRef.set(status); assertTrue(Thread.holdsLock(lock)); } }); stream.cancel(Status.CANCELLED); assertEquals(Status.Code.CANCELLED, statusRef.get().getCode()); } @Test @SuppressWarnings("GuardedBy") public void cancel_started() { stream.start(new BaseClientStreamListener()); stream.transportState().start(1234); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { assertTrue(Thread.holdsLock(lock)); return null; } }).when(transport).finishStream( 1234, Status.CANCELLED, PROCESSED, true, ErrorCode.CANCEL, null); stream.cancel(Status.CANCELLED); verify(transport).finishStream(1234, Status.CANCELLED, PROCESSED,true, ErrorCode.CANCEL, null); } @Test @SuppressWarnings("GuardedBy") public void start_alreadyCancelled() { stream.start(new BaseClientStreamListener()); stream.cancel(Status.CANCELLED); stream.transportState().start(1234); verifyNoMoreInteractions(mockedFrameWriter); } @Test @SuppressWarnings("GuardedBy") public void start_userAgentRemoved() throws IOException { Metadata metaData = new Metadata(); metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application"); stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false); stream.start(new BaseClientStreamListener()); stream.transportState().start(3); verify(mockedFrameWriter) .synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()) .contains(new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application")); } @Test @SuppressWarnings("GuardedBy") public void start_headerFieldOrder() throws IOException { Metadata metaData = new Metadata(); metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application"); stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false); stream.start(new BaseClientStreamListener()); stream.transportState().start(3); verify(mockedFrameWriter) .synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()).containsExactly( Headers.HTTPS_SCHEME_HEADER, Headers.METHOD_HEADER, new Header(Header.TARGET_AUTHORITY, "localhost"), new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()), new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"), Headers.CONTENT_TYPE_HEADER, Headers.TE_HEADER) .inOrder(); } @Test @SuppressWarnings("GuardedBy") public void start_headerPlaintext() throws IOException { Metadata metaData = new Metadata(); metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application"); when(transport.isUsingPlaintext()).thenReturn(true); stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false); stream.start(new BaseClientStreamListener()); stream.transportState().start(3); verify(mockedFrameWriter) .synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()).containsExactly( Headers.HTTP_SCHEME_HEADER, Headers.METHOD_HEADER, new Header(Header.TARGET_AUTHORITY, "localhost"), new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()), new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"), Headers.CONTENT_TYPE_HEADER, Headers.TE_HEADER) .inOrder(); } @Test @SuppressWarnings("GuardedBy") public void getUnaryRequest() throws IOException { MethodDescriptor<?, ?> getMethod = MethodDescriptor.<Void, Void>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("service/method") .setIdempotent(true) .setSafe(true) .setRequestMarshaller(marshaller) .setResponseMarshaller(marshaller) .build(); stream = new OkHttpClientStream(getMethod, new Metadata(), frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, true); stream.start(new BaseClientStreamListener()); // GET streams send headers after halfClose is called. verify(mockedFrameWriter, times(0)).synStream( eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); verify(transport, times(0)).streamReadyToStart(isA(OkHttpClientStream.class), isA(String.class)); byte[] msg = "request".getBytes(Charset.forName("UTF-8")); stream.writeMessage(new ByteArrayInputStream(msg)); stream.halfClose(); verify(transport).streamReadyToStart(eq(stream), any(String.class)); stream.transportState().start(3); verify(mockedFrameWriter) .synStream(eq(true), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()).contains(Headers.METHOD_GET_HEADER); assertThat(headersCaptor.getValue()).contains( new Header(Header.TARGET_PATH, "/" + getMethod.getFullMethodName() + "?" + BaseEncoding.base64().encode(msg))); } // TODO(carl-mastrangelo): extract this out into a testing/ directory and remove other definitions // of it. private static
OkHttpClientStreamTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/BooleanFieldSerializerTest_primitive.java
{ "start": 550, "end": 2989 }
class ____ extends TestCase { public void test_0() { Assert.assertEquals("{\"value\":false}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullBooleanAsFalse)); } public void test_codec_no_asm() throws Exception { Entity v = new Entity(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":false}", text); Entity v1 = JSON.parseObject(text, Entity.class); Assert.assertEquals(v.getValue(), v1.getValue()); } public void test_codec() throws Exception { Entity v1 = parseObjectNoAsm("{value:1}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(true, v1.getValue()); } public void test_codec_0() throws Exception { Entity v1 = parseObjectNoAsm("{value:0}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } public void test_codec_1() throws Exception { Entity v1 = parseObjectNoAsm("{value:'true'}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(true, v1.getValue()); } public void test_codec_2() throws Exception { Entity v1 = parseObjectNoAsm("{value:null}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } public void test_codec_3() throws Exception { Entity v1 = parseObjectNoAsm("{value:\"\"}", Entity.class, JSON.DEFAULT_PARSER_FEATURE); Assert.assertEquals(false, v1.getValue()); } @SuppressWarnings("unchecked") public static final <T> T parseObjectNoAsm(String input, Type clazz, int featureValues, Feature... features) { if (input == null) { return null; } for (Feature feature : features) { featureValues = Feature.config(featureValues, feature, true); } ParserConfig config = new ParserConfig(); config.setAsmEnable(false); DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues); T value = (T) parser.parseObject(clazz); if (clazz != JSONArray.class) { parser.close(); } return (T) value; } public static
BooleanFieldSerializerTest_primitive
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/SubstringOfZeroTest.java
{ "start": 3404, "end": 3782 }
class ____ { void f() { String x = "HELLO"; String y = x.toLowerCase().substring(1, 3); } } """) .expectUnchanged() .doTest(); } @Test public void negativeVarsWithDifferentMethod() { helper .addInputLines( "Test.java", """
Test
java
apache__maven
its/core-it-suite/src/test/resources/mng-7529/mng7529-plugin/src/main/java/org/apache/maven/its/mng7529/plugin/ResolveMojo.java
{ "start": 1825, "end": 3092 }
class ____ extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession mavenSession; @Component private ProjectDependenciesResolver dependencyResolver; public void execute() throws MojoExecutionException { try { DefaultProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(mavenSession.getProjectBuildingRequest()); buildingRequest.setRemoteRepositories(project.getRemoteArtifactRepositories()); DependencyResolutionRequest request = new DefaultDependencyResolutionRequest(); request.setMavenProject(project); request.setRepositorySession(buildingRequest.getRepositorySession()); @SuppressWarnings("checkstyle:UnusedLocalVariable") DependencyResolutionResult result = dependencyResolver.resolve(request); getLog().info("Resolution successful, resolved ok"); } catch (Exception e) { getLog().error("Resolution failed, could not resolve ranged dependency" + " (you hit MNG-7529)"); } } }
ResolveMojo
java
google__guava
android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
{ "start": 13194, "end": 15182 }
class ____ method @Override public Object[] toArray() { Monitor monitor = this.monitor; monitor.enter(); try { return q.toArray(); } finally { monitor.leave(); } } /** * Returns an array containing all of the elements in this queue; the runtime type of the returned * array is that of the specified array. The returned array elements are in no particular order. * If the queue fits in the specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare (i.e., the array has more * elements than this queue), the element in the array immediately following the end of the queue * is set to {@code null}. * * <p>Like the {@link #toArray()} method, this method acts as bridge between array-based and * collection-based APIs. Further, this method allows precise control over the runtime type of the * output array, and may, under certain circumstances, be used to save allocation costs. * * <p>Suppose {@code x} is a queue known to contain only strings. The following code can be used * to dump the queue into a newly allocated array of {@code String}: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * <p>Note that {@code toArray(new Object[0])} is identical in function to {@code toArray()}. * * @param a the array into which the elements of the queue are to be stored, if it is big enough; * otherwise, a new array of the same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array is not a supertype of * the runtime type of every element in this queue * @throws NullPointerException if the specified array is null */ @CanIgnoreReturnValue // pushed down from
to
java
google__dagger
javatests/dagger/internal/codegen/ModuleFactoryGeneratorTest.java
{ "start": 30013, "end": 30391 }
class ____ extends ParentModule<String, Number, Double> {", " @Provides Number provideNumber() { return 1; }", "}"); Source integerChild = CompilerTests.javaSource("test.ChildIntegerModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "", "@Module", "
ChildNumberModule
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/atomic/reference/AtomicReferenceAssert_doesNotHaveNullValue_Test.java
{ "start": 1023, "end": 1645 }
class ____ { @Test void should_pass_when_actual_does_not_have_the_null_value() { // GIVEN AtomicReference<String> actual = new AtomicReference<>("foo"); // WHEN/THEN then(actual).doesNotHaveNullValue(); } @Test void should_fail_when_actual_has_the_null_value() { // GIVEN AtomicReference<String> actual = new AtomicReference<>(null); // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).doesNotHaveNullValue()); // THEN then(assertionError).hasMessage(shouldNotContainValue(actual, null).create()); } }
AtomicReferenceAssert_doesNotHaveNullValue_Test
java
apache__camel
components/camel-salesforce/camel-salesforce-maven-plugin/src/test/java/org/apache/camel/maven/SchemaMojoManualIT.java
{ "start": 1360, "end": 2375 }
class ____ { @TempDir public Path temp; @Test public void testExecuteJsonSchema() throws Exception { final SchemaMojo mojo = new SchemaMojo(); setup(mojo); mojo.includes = new String[] { "Account" }; mojo.outputDirectory = temp.toFile(); mojo.jsonSchemaFilename = "test-schema.json"; mojo.jsonSchemaId = JsonUtils.DEFAULT_ID_PREFIX; // generate code mojo.execute(); // validate generated schema final File schemaFile = mojo.outputDirectory.toPath().resolve("test-schema.json").toFile(); assertTrue(schemaFile.exists(), "Output file was not created"); final ObjectMapper objectMapper = JsonUtils.createObjectMapper(); final JsonSchema jsonSchema = objectMapper.readValue(schemaFile, JsonSchema.class); assertTrue(jsonSchema.isObjectSchema() && !((ObjectSchema) jsonSchema).getOneOf().isEmpty(), "Expected root JSON schema with oneOf element"); } }
SchemaMojoManualIT
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/NonAggregatedIdentifierMapping.java
{ "start": 1845, "end": 1866 }
class ____ */
mappings
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/DoubleFallibleState.java
{ "start": 599, "end": 1733 }
class ____ implements AggregatorState { private double value; private boolean seen; private boolean failed; DoubleFallibleState(double init) { this.value = init; } double doubleValue() { return value; } void doubleValue(double value) { this.value = value; } boolean seen() { return seen; } void seen(boolean seen) { this.seen = seen; } boolean failed() { return failed; } void failed(boolean failed) { this.failed = failed; } /** Extracts an intermediate view of the contents of this state. */ @Override public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) { assert blocks.length >= offset + 3; blocks[offset + 0] = driverContext.blockFactory().newConstantDoubleBlockWith(value, 1); blocks[offset + 1] = driverContext.blockFactory().newConstantBooleanBlockWith(seen, 1); blocks[offset + 2] = driverContext.blockFactory().newConstantBooleanBlockWith(failed, 1); } @Override public void close() {} }
DoubleFallibleState
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/security/token/SQLSecretManagerRetriableHandler.java
{ "start": 1735, "end": 1946 }
interface ____<T> { T doCall() throws SQLException; } } /** * Implementation of {@link SQLSecretManagerRetriableHandler} that uses a * {@link RetryProxy} to simplify the retryable operations. */
SQLCommand
java
apache__camel
components/camel-geocoder/src/main/java/org/apache/camel/component/geocoder/http/AuthenticationMethod.java
{ "start": 894, "end": 947 }
enum ____ { Basic, Digest }
AuthenticationMethod
java
apache__camel
components/camel-sql/src/main/java/org/apache/camel/component/sql/stored/SqlStoredComponent.java
{ "start": 1264, "end": 3728 }
class ____ extends DefaultComponent { @Metadata(autowired = true) private DataSource dataSource; @Metadata(label = "advanced", description = "Whether to detect the network address location of the JMS broker on startup." + " This information is gathered via reflection on the ConnectionFactory, and is vendor specific." + " This option can be used to turn this off.", defaultValue = "true") private boolean serviceLocationEnabled = true; @Override protected Endpoint createEndpoint(String uri, String template, Map<String, Object> parameters) throws Exception { SqlStoredEndpoint endpoint = new SqlStoredEndpoint(uri, this); endpoint.setServiceLocationEnabled(serviceLocationEnabled); endpoint.setTemplate(template); setProperties(endpoint, parameters); // endpoint configured data source takes precedence DataSource ds = dataSource; if (endpoint.getDataSource() != null) { ds = endpoint.getDataSource(); } if (ds == null) { throw new IllegalArgumentException("DataSource must be configured"); } // create template JdbcTemplate jdbcTemplate = new JdbcTemplate(ds); Map<String, Object> templateOptions = PropertiesHelper.extractProperties(parameters, "template."); PropertyBindingSupport.bindProperties(getCamelContext(), jdbcTemplate, templateOptions); // set template on endpoint endpoint.setJdbcTemplate(jdbcTemplate); endpoint.setDataSource(ds); endpoint.setTemplateOptions(templateOptions); return endpoint; } public DataSource getDataSource() { return dataSource; } /** * Sets the DataSource to use to communicate with the database. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public boolean isServiceLocationEnabled() { return serviceLocationEnabled; } /** * Whether to detect the network address location of the JMS broker on startup. This information is gathered via * reflection on the ConnectionFactory, and is vendor specific. This option can be used to turn this off. */ public void setServiceLocationEnabled(boolean serviceLocationEnabled) { this.serviceLocationEnabled = serviceLocationEnabled; } }
SqlStoredComponent
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/OperatorSnapshotFinalizerTest.java
{ "start": 6737, "end": 7320 }
class ____<T> extends DoneFuture<T> { private boolean done; PseudoNotDoneFuture(T payload) { super(payload); this.done = false; } @Override public void run() { super.run(); this.done = true; } @Override public boolean isDone() { return done; } @Override public T get() { try { return super.get(); } finally { this.done = true; } } } }
PseudoNotDoneFuture
java
apache__maven
impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvnup/goals/ApplyTest.java
{ "start": 1566, "end": 1978 }
class ____ { private Apply applyGoal; private StrategyOrchestrator mockOrchestrator; @BeforeEach void setUp() { mockOrchestrator = mock(StrategyOrchestrator.class); applyGoal = new Apply(mockOrchestrator); } private UpgradeContext createMockContext() { return TestUtils.createMockContext(); } @Nested @DisplayName("Modification Behavior")
ApplyTest
java
apache__camel
components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbFileOperations.java
{ "start": 1101, "end": 2470 }
interface ____ extends GenericFileOperations<FileIdBothDirectoryInformation> { /** * Connects to the remote server * * @param configuration configuration * @param exchange the exchange that trigger the connect (if any) * @return <tt>true</tt> if connected * @throws GenericFileOperationFailedException can be thrown */ boolean connect(SmbConfiguration configuration, Exchange exchange) throws GenericFileOperationFailedException; /** * Returns whether we are connected to the remote server or not * * @return <tt>true</tt> if connected, <tt>false</tt> if not * @throws GenericFileOperationFailedException can be thrown */ boolean isConnected() throws GenericFileOperationFailedException; /** * Disconnects from the remote server * * @throws GenericFileOperationFailedException can be thrown */ void disconnect() throws GenericFileOperationFailedException; /** * Forces a hard disconnect from the remote server and cause the client to be re-created on next poll. * * @throws GenericFileOperationFailedException can be thrown */ void forceDisconnect() throws GenericFileOperationFailedException; }
SmbFileOperations
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestGetBlocks.java
{ "start": 3004, "end": 25189 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestBlockManager.class); private static final int BLOCK_SIZE = 8192; private static final String[] RACKS = new String[]{"/d1/r1", "/d1/r1", "/d1/r2", "/d1/r2", "/d1/r2", "/d2/r3", "/d2/r3"}; private static final int NUM_DATA_NODES = RACKS.length; /** * Stop the heartbeat of a datanode in the MiniDFSCluster * * @param cluster * The MiniDFSCluster * @param hostName * The hostName of the datanode to be stopped * @return The DataNode whose heartbeat has been stopped */ private DataNode stopDataNodeHeartbeat(MiniDFSCluster cluster, String hostName) { for (DataNode dn : cluster.getDataNodes()) { if (dn.getDatanodeId().getHostName().equals(hostName)) { DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true); return dn; } } return null; } /** * Test if the datanodes returned by * {@link ClientProtocol#getBlockLocations(String, long, long)} is correct * when stale nodes checking is enabled. Also test during the scenario when 1) * stale nodes checking is enabled, 2) a writing is going on, 3) a datanode * becomes stale happen simultaneously * * @throws Exception */ @Test public void testReadSelectNonStaleDatanode() throws Exception { HdfsConfiguration conf = new HdfsConfiguration(); conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_KEY, true); long staleInterval = 30 * 1000 * 60; conf.setLong(DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY, staleInterval); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(NUM_DATA_NODES).racks(RACKS).build(); cluster.waitActive(); InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort()); DFSClient client = new DFSClient(addr, conf); List<DatanodeDescriptor> nodeInfoList = cluster.getNameNode() .getNamesystem().getBlockManager().getDatanodeManager() .getDatanodeListForReport(DatanodeReportType.LIVE); assertEquals(NUM_DATA_NODES, nodeInfoList.size(), "Unexpected number of datanodes"); FileSystem fileSys = cluster.getFileSystem(); FSDataOutputStream stm = null; try { // do the writing but do not close the FSDataOutputStream // in order to mimic the ongoing writing final Path fileName = new Path("/file1"); stm = fileSys.create(fileName, true, fileSys.getConf().getInt( CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096), (short) 3, BLOCK_SIZE); stm.write(new byte[(BLOCK_SIZE * 3) / 2]); // We do not close the stream so that // the writing seems to be still ongoing stm.hflush(); LocatedBlocks blocks = client.getNamenode().getBlockLocations( fileName.toString(), 0, BLOCK_SIZE); DatanodeInfo[] nodes = blocks.get(0).getLocations(); assertEquals(nodes.length, 3); DataNode staleNode = null; DatanodeDescriptor staleNodeInfo = null; // stop the heartbeat of the first node staleNode = this.stopDataNodeHeartbeat(cluster, nodes[0].getHostName()); assertNotNull(staleNode); // set the first node as stale staleNodeInfo = cluster.getNameNode().getNamesystem().getBlockManager() .getDatanodeManager() .getDatanode(staleNode.getDatanodeId()); DFSTestUtil.resetLastUpdatesWithOffset(staleNodeInfo, -(staleInterval + 1)); LocatedBlocks blocksAfterStale = client.getNamenode().getBlockLocations( fileName.toString(), 0, BLOCK_SIZE); DatanodeInfo[] nodesAfterStale = blocksAfterStale.get(0).getLocations(); assertEquals(nodesAfterStale.length, 3); assertEquals(nodesAfterStale[2].getHostName(), nodes[0].getHostName()); // restart the staleNode's heartbeat DataNodeTestUtils.setHeartbeatsDisabledForTests(staleNode, false); // reset the first node as non-stale, so as to avoid two stale nodes DFSTestUtil.resetLastUpdatesWithOffset(staleNodeInfo, 0); LocatedBlock lastBlock = client.getLocatedBlocks(fileName.toString(), 0, Long.MAX_VALUE).getLastLocatedBlock(); nodes = lastBlock.getLocations(); assertEquals(nodes.length, 3); // stop the heartbeat of the first node for the last block staleNode = this.stopDataNodeHeartbeat(cluster, nodes[0].getHostName()); assertNotNull(staleNode); // set the node as stale DatanodeDescriptor dnDesc = cluster.getNameNode().getNamesystem() .getBlockManager().getDatanodeManager() .getDatanode(staleNode.getDatanodeId()); DFSTestUtil.resetLastUpdatesWithOffset(dnDesc, -(staleInterval + 1)); LocatedBlock lastBlockAfterStale = client.getLocatedBlocks( fileName.toString(), 0, Long.MAX_VALUE).getLastLocatedBlock(); nodesAfterStale = lastBlockAfterStale.getLocations(); assertEquals(nodesAfterStale.length, 3); assertEquals(nodesAfterStale[2].getHostName(), nodes[0].getHostName()); } finally { if (stm != null) { stm.close(); } client.close(); cluster.shutdown(); } } /** * Test getBlocks. */ @Test public void testGetBlocks() throws Exception { DistributedFileSystem fs = null; Path testFile = null; BlockWithLocations[] locs; final int blkSize = 1024; final String filePath = "/tmp.txt"; final int blkLocsSize = 13; long fileLen = 12 * blkSize + 1; final short replicationFactor = (short) 2; final Configuration config = new HdfsConfiguration(); // set configurations config.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blkSize); config.setLong(DFSConfigKeys.DFS_BALANCER_GETBLOCKS_MIN_BLOCK_SIZE_KEY, blkSize); MiniDFSCluster cluster = new MiniDFSCluster.Builder(config) .numDataNodes(replicationFactor) .storagesPerDatanode(4) .build(); try { cluster.waitActive(); // the third block will not be visible to getBlocks testFile = new Path(filePath); DFSTestUtil.createFile(cluster.getFileSystem(), testFile, fileLen, replicationFactor, 0L); // get blocks & data nodes fs = cluster.getFileSystem(); DFSTestUtil.waitForReplication(fs, testFile, replicationFactor, 60000); RemoteIterator<LocatedFileStatus> it = fs.listLocatedStatus(testFile); LocatedFileStatus stat = it.next(); BlockLocation[] blockLocations = stat.getBlockLocations(); assertEquals(blkLocsSize, blockLocations.length); HdfsDataInputStream dis = (HdfsDataInputStream) fs.open(testFile); Collection<LocatedBlock> dinfo = dis.getAllBlocks(); dis.close(); DatanodeInfo[] dataNodes = dinfo.iterator().next().getLocations(); // get RPC client to namenode InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort()); NamenodeProtocol namenode = NameNodeProxies.createProxy(config, DFSUtilClient.getNNUri(addr), NamenodeProtocol.class).getProxy(); // Should return all 13 blocks, as minBlockSize is not passed locs = namenode.getBlocks(dataNodes[0], fileLen, 0, 0, null).getBlocks(); assertEquals(blkLocsSize, locs.length); assertEquals(locs[0].getStorageIDs().length, replicationFactor); assertEquals(locs[1].getStorageIDs().length, replicationFactor); // Should return 12 blocks, as minBlockSize is blkSize locs = namenode.getBlocks(dataNodes[0], fileLen, blkSize, 0, null).getBlocks(); assertEquals(blkLocsSize - 1, locs.length); assertEquals(locs[0].getStorageIDs().length, replicationFactor); assertEquals(locs[1].getStorageIDs().length, replicationFactor); // get blocks of size BlockSize from dataNodes[0] locs = namenode.getBlocks(dataNodes[0], blkSize, blkSize, 0, null).getBlocks(); assertEquals(locs.length, 1); assertEquals(locs[0].getStorageIDs().length, replicationFactor); // get blocks of size 1 from dataNodes[0] locs = namenode.getBlocks(dataNodes[0], 1, 1, 0, null).getBlocks(); assertEquals(locs.length, 1); assertEquals(locs[0].getStorageIDs().length, replicationFactor); // get blocks of size 0 from dataNodes[0] getBlocksWithException(namenode, dataNodes[0], 0, 0, RemoteException.class, "IllegalArgumentException"); // get blocks of size -1 from dataNodes[0] getBlocksWithException(namenode, dataNodes[0], -1, 0, RemoteException.class, "IllegalArgumentException"); // minBlockSize is -1 getBlocksWithException(namenode, dataNodes[0], blkSize, -1, RemoteException.class, "IllegalArgumentException"); // get blocks of size BlockSize from a non-existent datanode DatanodeInfo info = DFSTestUtil.getDatanodeInfo("1.2.3.4"); getBlocksWithException(namenode, info, replicationFactor, 0, RemoteException.class, "HadoopIllegalArgumentException"); testBlockIterator(cluster); // Namenode should refuse to provide block locations to the balancer // while in safemode. locs = namenode.getBlocks(dataNodes[0], fileLen, 0, 0, null).getBlocks(); assertEquals(blkLocsSize, locs.length); assertFalse(fs.isInSafeMode()); LOG.info("Entering safe mode"); fs.setSafeMode(SafeModeAction.ENTER); LOG.info("Entered safe mode"); assertTrue(fs.isInSafeMode()); getBlocksWithException(namenode, info, replicationFactor, 0, RemoteException.class, "Cannot execute getBlocks. Name node is in safe mode."); fs.setSafeMode(SafeModeAction.LEAVE); assertFalse(fs.isInSafeMode()); } finally { if (fs != null) { fs.delete(testFile, true); fs.close(); } cluster.shutdown(); } } private void getBlocksWithException(NamenodeProtocol namenode, DatanodeInfo datanode, long size, long minBlkSize, Class exClass, String msg) throws Exception { // Namenode should refuse should fail LambdaTestUtils.intercept(exClass, msg, () -> namenode.getBlocks(datanode, size, minBlkSize, 0, null)); } /** * BlockIterator iterates over all blocks belonging to DatanodeDescriptor * through multiple storages. * The test verifies that BlockIterator can be set to start iterating from * a particular starting block index. */ void testBlockIterator(MiniDFSCluster cluster) { FSNamesystem ns = cluster.getNamesystem(); String dId = cluster.getDataNodes().get(0).getDatanodeUuid(); DatanodeDescriptor dnd = BlockManagerTestUtil.getDatanode(ns, dId); DatanodeStorageInfo[] storages = dnd.getStorageInfos(); assertEquals(4, storages.length, "DataNode should have 4 storages"); Iterator<BlockInfo> dnBlockIt = null; // check illegal start block number try { dnBlockIt = BlockManagerTestUtil.getBlockIterator( cluster.getNamesystem(), dId, -1); assertTrue(false, "Should throw IllegalArgumentException"); } catch(IllegalArgumentException ei) { // as expected } assertNull(dnBlockIt, "Iterator should be null"); // form an array of all DataNode blocks int numBlocks = dnd.numBlocks(); BlockInfo[] allBlocks = new BlockInfo[numBlocks]; int idx = 0; for(DatanodeStorageInfo s : storages) { Iterator<BlockInfo> storageBlockIt = BlockManagerTestUtil.getBlockIterator(s); while(storageBlockIt.hasNext()) { allBlocks[idx++] = storageBlockIt.next(); try { storageBlockIt.remove(); assertTrue( false, "BlockInfo iterator should have been unmodifiable"); } catch (UnsupportedOperationException e) { //expected exception } } } // check iterator for every block as a starting point for(int i = 0; i < allBlocks.length; i++) { // create iterator starting from i dnBlockIt = BlockManagerTestUtil.getBlockIterator(ns, dId, i); assertTrue(dnBlockIt.hasNext(), "Block iterator should have next block"); // check iterator lists blocks in the desired order for(int j = i; j < allBlocks.length; j++) { assertEquals(allBlocks[j], dnBlockIt.next(), "Wrong block order"); } } // check start block number larger than numBlocks in the DataNode dnBlockIt = BlockManagerTestUtil.getBlockIterator( ns, dId, allBlocks.length + 1); assertFalse(dnBlockIt.hasNext(), "Iterator should not have next block"); } @Test public void testBlockKey() { Map<Block, Long> map = new HashMap<Block, Long>(); final Random RAN = new Random(); final long seed = RAN.nextLong(); System.out.println("seed=" + seed); RAN.setSeed(seed); long[] blkids = new long[10]; for (int i = 0; i < blkids.length; i++) { blkids[i] = 1000L + RAN.nextInt(100000); map.put(new Block(blkids[i], 0, blkids[i]), blkids[i]); } System.out.println("map=" + map.toString().replace(",", "\n ")); for (int i = 0; i < blkids.length; i++) { Block b = new Block(blkids[i], 0, HdfsConstants.GRANDFATHER_GENERATION_STAMP); Long v = map.get(b); System.out.println(b + " => " + v); assertEquals(blkids[i], v.longValue()); } } private boolean belongToFile(BlockWithLocations blockWithLocations, List<LocatedBlock> blocks) { for(LocatedBlock block : blocks) { if (block.getBlock().getLocalBlock().equals( blockWithLocations.getBlock())) { return true; } } return false; } /** * test GetBlocks with dfs.namenode.hot.block.interval. * Balancer prefer to get blocks which are belong to the cold files * created before this time period. */ @Test public void testGetBlocksWithHotBlockTimeInterval() throws Exception { final Configuration conf = new HdfsConfiguration(); final short repFactor = (short) 1; final int blockNum = 2; final int fileLen = BLOCK_SIZE * blockNum; final long hotInterval = 2000; conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf). numDataNodes(repFactor).build(); try { cluster.waitActive(); FileSystem fs = cluster.getFileSystem(); final DFSClient dfsclient = ((DistributedFileSystem) fs).getClient(); String fileOld = "/f.old"; DFSTestUtil.createFile(fs, new Path(fileOld), fileLen, repFactor, 0); List<LocatedBlock> locatedBlocksOld = dfsclient.getNamenode(). getBlockLocations(fileOld, 0, fileLen).getLocatedBlocks(); DatanodeInfo[] dataNodes = locatedBlocksOld.get(0).getLocations(); InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort()); NamenodeProtocol namenode = NameNodeProxies.createProxy(conf, DFSUtilClient.getNNUri(addr), NamenodeProtocol.class).getProxy(); // make the file as old. dfsclient.getNamenode().setTimes(fileOld, 0, 0); String fileNew = "/f.new"; DFSTestUtil.createFile(fs, new Path(fileNew), fileLen, repFactor, 0); List<LocatedBlock> locatedBlocksNew = dfsclient.getNamenode() .getBlockLocations(fileNew, 0, fileLen).getLocatedBlocks(); BlockWithLocations[] locsAll = namenode.getBlocks( dataNodes[0], fileLen*2, 0, hotInterval, null).getBlocks(); assertEquals(locsAll.length, 4); for(int i = 0; i < blockNum; i++) { assertTrue(belongToFile(locsAll[i], locatedBlocksOld)); } for(int i = blockNum; i < blockNum*2; i++) { assertTrue(belongToFile(locsAll[i], locatedBlocksNew)); } BlockWithLocations[] locs2 = namenode.getBlocks( dataNodes[0], fileLen*2, 0, hotInterval, null).getBlocks(); for(int i = 0; i < 2; i++) { assertTrue(belongToFile(locs2[i], locatedBlocksOld)); } } finally { cluster.shutdown(); } } @Test public void testReadSkipStaleStorage() throws Exception { final short repFactor = (short) 1; final int blockNum = 64; final int storageNum = 2; final int fileLen = BLOCK_SIZE * blockNum; final Path path = new Path("testReadSkipStaleStorage"); final Configuration conf = new HdfsConfiguration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(1) .storagesPerDatanode(storageNum) .build(); cluster.waitActive(); FileSystem fs = cluster.getFileSystem(); DFSTestUtil.createFile(fs, path, false, 1024, fileLen, BLOCK_SIZE, repFactor, 0, true); // get datanode info ClientProtocol client = NameNodeProxies.createProxy(conf, cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy(); DatanodeInfo[] dataNodes = client.getDatanodeReport(DatanodeReportType.ALL); // get storage info BlockManager bm0 = cluster.getNamesystem(0).getBlockManager(); DatanodeStorageInfo[] storageInfos = bm0.getDatanodeManager() .getDatanode(dataNodes[0].getDatanodeUuid()).getStorageInfos(); InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort()); NamenodeProtocol namenode = NameNodeProxies.createProxy(conf, DFSUtilClient.getNNUri(addr), NamenodeProtocol.class).getProxy(); // check blocks count equals to blockNum BlockWithLocations[] blocks = namenode.getBlocks( dataNodes[0], fileLen*2, 0, 0, null).getBlocks(); assertEquals(blockNum, blocks.length); // calculate the block count on storage[0] int count = 0; for (BlockWithLocations b : blocks) { for (String s : b.getStorageIDs()) { if (s.equals(storageInfos[0].getStorageID())) { count++; } } } // set storage[0] stale storageInfos[0].setBlockContentsStale(true); blocks = namenode.getBlocks( dataNodes[0], fileLen*2, 0, 0, null).getBlocks(); assertEquals(blockNum - count, blocks.length); // set all storage stale bm0.getDatanodeManager().markAllDatanodesStaleAndSetKeyUpdateIfNeed(); blocks = namenode.getBlocks( dataNodes[0], fileLen*2, 0, 0, null).getBlocks(); assertEquals(0, blocks.length); } @Test public void testChooseSpecifyStorageType() throws Exception { final short repFactor = (short) 1; final int fileLen = BLOCK_SIZE; final Configuration conf = new HdfsConfiguration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1) .storageTypes(new StorageType[] {StorageType.DISK, StorageType.SSD}). storagesPerDatanode(2).build()) { cluster.waitActive(); // Get storage info. ClientProtocol client = NameNodeProxies.createProxy(conf, cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy(); DatanodeInfo[] dataNodes = client.getDatanodeReport(DatanodeReportType.ALL); BlockManager bm0 = cluster.getNamesystem(0).getBlockManager(); DatanodeStorageInfo[] storageInfos = bm0.getDatanodeManager() .getDatanode(dataNodes[0].getDatanodeUuid()).getStorageInfos(); assert Arrays.stream(storageInfos) .anyMatch(datanodeStorageInfo -> { String storageTypeName = datanodeStorageInfo.getStorageType().name(); return storageTypeName.equals("SSD") || storageTypeName.equals("DISK"); }) : "No 'SSD' or 'DISK' storage types found."; // Create hdfs file. Path ssdDir = new Path("/testChooseSSD"); DistributedFileSystem fs = cluster.getFileSystem(); Path ssdFile = new Path(ssdDir, "file"); fs.mkdirs(ssdDir); fs.setStoragePolicy(ssdDir, "ALL_SSD"); DFSTestUtil.createFile(fs, ssdFile, false, 1024, fileLen, BLOCK_SIZE, repFactor, 0, true); DFSTestUtil.waitReplication(fs, ssdFile, repFactor); BlockLocation[] locations = fs.getClient() .getBlockLocations(ssdFile.toUri().getPath(), 0, Long.MAX_VALUE); assertEquals(1, locations.length); assertEquals("SSD", locations[0].getStorageTypes()[0].name()); Path diskDir = new Path("/testChooseDisk"); fs = cluster.getFileSystem(); Path diskFile = new Path(diskDir, "file"); fs.mkdirs(diskDir); fs.setStoragePolicy(diskDir, "HOT"); DFSTestUtil.createFile(fs, diskFile, false, 1024, fileLen, BLOCK_SIZE, repFactor, 0, true); DFSTestUtil.waitReplication(fs, diskFile, repFactor); locations = fs.getClient() .getBlockLocations(diskFile.toUri().getPath(), 0, Long.MAX_VALUE); assertEquals(1, locations.length); assertEquals("DISK", locations[0].getStorageTypes()[0].name()); InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort()); NamenodeProtocol namenode = NameNodeProxies.createProxy(conf, DFSUtilClient.getNNUri(addr), NamenodeProtocol.class).getProxy(); // Check blocks count equals to blockNum. // If StorageType is not specified will get all blocks. BlockWithLocations[] blocks = namenode.getBlocks( dataNodes[0], fileLen * 2, 0, 0, null).getBlocks(); assertEquals(2, blocks.length); // Check the count of blocks with a StorageType of DISK. blocks = namenode.getBlocks( dataNodes[0], fileLen * 2, 0, 0, StorageType.DISK).getBlocks(); assertEquals(1, blocks.length); assertEquals("DISK", blocks[0].getStorageTypes()[0].name()); // Check the count of blocks with a StorageType of SSD. blocks = namenode.getBlocks( dataNodes[0], fileLen * 2, 0, 0, StorageType.SSD).getBlocks(); assertEquals(1, blocks.length); assertEquals("SSD", blocks[0].getStorageTypes()[0].name()); } } }
TestGetBlocks
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Slide.java
{ "start": 1717, "end": 2470 }
class ____ { /** * Creates a sliding window. Sliding windows have a fixed size and slide by a specified slide * interval. If the slide interval is smaller than the window size, sliding windows are * overlapping. Thus, an element can be assigned to multiple windows. * * <p>For example, a sliding window of size 15 minutes with 5 minutes sliding interval groups * elements of 15 minutes and evaluates every five minutes. Each element is contained in three * consecutive * * @param size the size of the window as time or row-count interval * @return a partially specified sliding window */ public static SlideWithSize over(Expression size) { return new SlideWithSize(size); } }
Slide
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 9620, "end": 9707 }
class ____ {", " @Inject A() {}", " }", " static
A
java
elastic__elasticsearch
build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/precommit/LicenseHeadersTask.java
{ "start": 12465, "end": 12933 }
class ____ implements Serializable { private String licenseFamilyCategory; private String licenseFamilyName; private String substringPattern; public License(String licenseFamilyCategory, String licenseFamilyName, String substringPattern) { this.licenseFamilyCategory = licenseFamilyCategory; this.licenseFamilyName = licenseFamilyName; this.substringPattern = substringPattern; } } }
License
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/ClosureCleanerTest.java
{ "start": 15439, "end": 15749 }
class ____ implements Serializable { private final String raw; private SerializedPayload(String raw) { this.raw = raw; } private Object readResolve() throws IOException, ClassNotFoundException { return new Payload(raw); } } }
SerializedPayload
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/AnySetterForCreator562Test.java
{ "start": 2180, "end": 2501 }
class ____ { String a; JsonNode anySetterNode; @JsonCreator public PojoWithNodeAnySetter(@JsonProperty("a") String a, @JsonAnySetter JsonNode leftovers ) { this.a = a; anySetterNode = leftovers; } } static
PojoWithNodeAnySetter
java
apache__camel
components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovySetHeaderIssueTest.java
{ "start": 1126, "end": 2643 }
class ____ { private String name; public MySubOrder(String name) { this.name = name; } public String getSubOrderName() { return name; } } @Test public void testGroovySetHeader() throws Exception { getMockEndpoint("mock:0Endpoint").expectedMessageCount(1); getMockEndpoint("mock:1Endpoint").expectedMessageCount(1); getMockEndpoint("mock:2Endpoint").expectedMessageCount(1); getMockEndpoint("mock:3Endpoint").expectedMessageCount(1); getMockEndpoint("mock:4Endpoint").expectedMessageCount(1); getMockEndpoint("mock:5Endpoint").expectedMessageCount(1); getMockEndpoint("mock:6Endpoint").expectedMessageCount(1); getMockEndpoint("mock:7Endpoint").expectedMessageCount(1); getMockEndpoint("mock:8Endpoint").expectedMessageCount(1); getMockEndpoint("mock:9Endpoint").expectedMessageCount(1); for (int i = 0; i < 10; i++) { template.sendBody("direct:start", new MySubOrder("mock:" + i)); } MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .setHeader("mySlip").groovy("return \"${body.subOrderName}Endpoint\"") .routingSlip(header("mySlip")); } }; } }
MySubOrder
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/function/MethodInvokersFailableBiFunctionTest.java
{ "start": 1984, "end": 2433 }
interface ____ make sure we compile. final FailableBiFunction<MethodFixtures, String, String[], Throwable> func = MethodInvokers .asFailableBiFunction(getMethodForGetString1ArgThrowsChecked()); assertThrows(CustomCheckedException.class, () -> func.apply(INSTANCE, "A")); } @Test void testApply1ArgThrowsUnchecked() throws NoSuchMethodException, SecurityException { // Use a local variable typed to the
to
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/SessionAttributeMethodArgumentResolver.java
{ "start": 1386, "end": 2591 }
class ____ extends AbstractNamedValueArgumentResolver { public SessionAttributeMethodArgumentResolver(ConfigurableBeanFactory factory, ReactiveAdapterRegistry registry) { super(factory, registry); } @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(SessionAttribute.class); } @Override protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { SessionAttribute ann = parameter.getParameterAnnotation(SessionAttribute.class); Assert.state(ann != null, "No SessionAttribute annotation"); return new NamedValueInfo(ann.name(), ann.required(), ValueConstants.DEFAULT_NONE); } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override protected Mono<Object> resolveName(String name, MethodParameter parameter, ServerWebExchange exchange) { return exchange.getSession().mapNotNull(session -> session.getAttribute(name)); } @Override protected void handleMissingValue(String name, MethodParameter parameter) { throw new MissingRequestValueException( name, parameter.getNestedParameterType(), "session attribute", parameter); } }
SessionAttributeMethodArgumentResolver
java
spring-projects__spring-boot
documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/context/ShutdownEndpointDocumentationTests.java
{ "start": 1625, "end": 2028 }
class ____ extends MockMvcEndpointDocumentationTests { @Test void shutdown() { assertThat(this.mvc.post().uri("/actuator/shutdown")).hasStatusOk() .apply(MockMvcRestDocumentation.document("shutdown", responseFields( fieldWithPath("message").description("Message describing the result of the request.")))); } @Configuration(proxyBeanMethods = false) static
ShutdownEndpointDocumentationTests
java
quarkusio__quarkus
integration-tests/rest-client-reactive/src/test/java/io/quarkus/it/rest/client/ClientWithCustomObjectMapperTest.java
{ "start": 1367, "end": 3548 }
class ____ { MyClient clientAllowsUnknown; MyClient clientDisallowsUnknown; WireMockServer wireMockServer; @BeforeEach public void setUp() throws MalformedURLException { ClientObjectMapperUnknown.USED.set(false); ClientObjectMapperNoUnknown.USED.set(false); wireMockServer = new WireMockServer(options().port(20001)); wireMockServer.start(); clientAllowsUnknown = QuarkusRestClientBuilder.newBuilder() .baseUrl(new URL(wireMockServer.baseUrl())) .register(ClientObjectMapperUnknown.class) .build(MyClient.class); clientDisallowsUnknown = QuarkusRestClientBuilder.newBuilder() .baseUrl(new URL(wireMockServer.baseUrl())) .register(ClientObjectMapperNoUnknown.class) .build(MyClient.class); } @AfterEach public void tearDown() { wireMockServer.stop(); } @Test void testCustomObjectMappersShouldBeUsedInReader() { var json = "{ \"value\": \"someValue\", \"secondValue\": \"toBeIgnored\" }"; wireMockServer.stubFor( WireMock.get(WireMock.urlMatching("/client")) .willReturn(okJson(json))); // FAIL_ON_UNKNOWN_PROPERTIES disabled clientAllowsUnknown.get().subscribe().withSubscriber(UniAssertSubscriber.create()) .awaitItem().assertItem(new Request("someValue")); // FAIL_ON_UNKNOWN_PROPERTIES enabled clientDisallowsUnknown.get().subscribe().withSubscriber(UniAssertSubscriber.create()) .awaitFailure() .assertFailedWith(UnrecognizedPropertyException.class); } @Test void testCustomObjectMappersShouldBeUsedInWriter() { wireMockServer.stubFor( WireMock.post(WireMock.urlMatching("/client")) .willReturn(ok())); clientDisallowsUnknown.post(new Request()); assertThat(ClientObjectMapperNoUnknown.USED.get()).isTrue(); } @Path("/client") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public
ClientWithCustomObjectMapperTest