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/main/java/com/google/errorprone/bugpatterns/LoopConditionChecker.java
{ "start": 2208, "end": 3834 }
class ____ extends BugChecker implements ForLoopTreeMatcher, DoWhileLoopTreeMatcher, WhileLoopTreeMatcher { @Override public Description matchDoWhileLoop(DoWhileLoopTree tree, VisitorState state) { return check(tree.getCondition(), ImmutableList.of(tree.getCondition(), tree.getStatement())); } @Override public Description matchForLoop(ForLoopTree tree, VisitorState state) { if (tree.getCondition() == null) { return NO_MATCH; } return check( tree.getCondition(), ImmutableList.<Tree>builder() .add(tree.getCondition()) .add(tree.getStatement()) .addAll(tree.getUpdate()) .build()); } @Override public Description matchWhileLoop(WhileLoopTree tree, VisitorState state) { return check(tree.getCondition(), ImmutableList.of(tree.getCondition(), tree.getStatement())); } private Description check(ExpressionTree condition, ImmutableList<Tree> loopBodyTrees) { ImmutableSet<Symbol.VarSymbol> conditionVars = LoopConditionVisitor.scan(condition); if (conditionVars.isEmpty()) { return NO_MATCH; } for (Tree tree : loopBodyTrees) { if (UpdateScanner.scan(tree, conditionVars)) { return NO_MATCH; } } return buildDescription(condition) .setMessage( String.format( "condition variable(s) never modified in loop body: %s", Joiner.on(", ").join(conditionVars))) .build(); } /** Scan for loop conditions that are determined entirely by the state of local variables. */ private static
LoopConditionChecker
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_enum.java
{ "start": 718, "end": 757 }
enum ____ { AA, BB, CC } }
Type
java
apache__flink
flink-kubernetes/src/main/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdTaskManagerDecorator.java
{ "start": 1543, "end": 3613 }
class ____ extends AbstractKubernetesStepDecorator { private final KubernetesTaskManagerParameters kubernetesTaskManagerParameters; public CmdTaskManagerDecorator( KubernetesTaskManagerParameters kubernetesTaskManagerParameters) { this.kubernetesTaskManagerParameters = checkNotNull(kubernetesTaskManagerParameters); } @Override public FlinkPod decorateFlinkPod(FlinkPod flinkPod) { final Container mainContainerWithStartCmd = new ContainerBuilder(flinkPod.getMainContainer()) .withCommand(kubernetesTaskManagerParameters.getContainerEntrypoint()) .withArgs(getTaskManagerStartCommand()) .addToEnv( new EnvVarBuilder() .withName(Constants.ENV_TM_JVM_MEM_OPTS) .withValue( kubernetesTaskManagerParameters.getJvmMemOptsEnv()) .build()) .build(); return new FlinkPod.Builder(flinkPod).withMainContainer(mainContainerWithStartCmd).build(); } private List<String> getTaskManagerStartCommand() { final String resourceArgs = TaskExecutorProcessUtils.generateDynamicConfigsStr( kubernetesTaskManagerParameters .getContaineredTaskManagerParameters() .getTaskExecutorProcessSpec()); final String dynamicProperties = kubernetesTaskManagerParameters.getDynamicProperties(); return KubernetesUtils.getStartCommandWithBashWrapper( Constants.KUBERNETES_TASK_MANAGER_SCRIPT_PATH + " " + dynamicProperties + " " + resourceArgs + " " + kubernetesTaskManagerParameters.getEntrypointArgs()); } }
CmdTaskManagerDecorator
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/spi/Status.java
{ "start": 423, "end": 753 }
enum ____ { MANAGED, READ_ONLY, DELETED, GONE, LOADING, SAVING; public boolean isDeletedOrGone() { return this == DELETED || this == GONE; } public static @Nullable Status fromOrdinal(int ordinal) { final Status[] values = values(); return ordinal < 0 || ordinal >= values.length ? null : values[ordinal]; } }
Status
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/DelegateInjectionPointAssignabilityRules.java
{ "start": 377, "end": 5157 }
class ____ extends BeanTypeAssignabilityRules { private DelegateInjectionPointAssignabilityRules() { } private static final DelegateInjectionPointAssignabilityRules INSTANCE = new DelegateInjectionPointAssignabilityRules(); public static DelegateInjectionPointAssignabilityRules instance() { return INSTANCE; } @Override protected boolean parametersMatch(Type delegateParameter, Type beanParameter) { // this is the same as for bean types if (Types.isActualType(delegateParameter) && Types.isActualType(beanParameter)) { /* * the delegate type parameter and the bean type parameter are actual types with identical raw * type, and, if the type is parameterized, the bean type parameter is assignable to the delegate * type parameter according to these rules, or */ return matches(delegateParameter, beanParameter); } // this is the same as for bean types if (delegateParameter instanceof WildcardType && Types.isActualType(beanParameter)) { /* * the delegate type parameter is a wildcard, the bean type parameter is an actual type and the * actual type is assignable to the upper bound, if any, of the wildcard and assignable from the * lower bound, if any, of the wildcard, or */ return parametersMatch((WildcardType) delegateParameter, beanParameter); } // this is different to bean type rules if (delegateParameter instanceof WildcardType && beanParameter instanceof TypeVariable<?>) { /* * the delegate type parameter is a wildcard, the bean type parameter is a type variable and the * upper bound of the type variable is assignable to the upper bound, if any, of the wildcard and * assignable from the lower bound, if any, of the wildcard, or */ return parametersMatch((WildcardType) delegateParameter, (TypeVariable<?>) beanParameter); } // this is different to bean type rules if (delegateParameter instanceof TypeVariable<?> && beanParameter instanceof TypeVariable<?>) { /* * the delegate type parameter and the bean type parameter are both type variables and the upper * bound of the bean type parameter is assignable to the upper bound, if any, of the delegate type * parameter, or */ return parametersMatch((TypeVariable<?>) delegateParameter, (TypeVariable<?>) beanParameter); } // this is different to bean type rules if (delegateParameter instanceof TypeVariable<?> && Types.isActualType(beanParameter)) { /* * the delegate type parameter is a type variable, the bean type parameter is an actual type, and * the actual type is assignable to the upper bound, if any, of the type variable */ return parametersMatch((TypeVariable<?>) delegateParameter, beanParameter); } /* * this is not defined by the specification but is here to retain backward compatibility with previous * versions of Weld * see CDITCK-430 */ if (Object.class.equals(delegateParameter) && beanParameter instanceof TypeVariable<?>) { TypeVariable<?> beanParameterVariable = (TypeVariable<?>) beanParameter; return Object.class.equals(beanParameterVariable.getBounds()[0]); } return false; } @Override protected boolean parametersMatch(WildcardType delegateParameter, TypeVariable<?> beanParameter) { Type[] beanParameterBounds = getUppermostTypeVariableBounds(beanParameter); if (!lowerBoundsOfWildcardMatch(beanParameterBounds, delegateParameter)) { return false; } Type[] requiredUpperBounds = delegateParameter.getUpperBounds(); // upper bound of the type variable is assignable to the upper bound of the wildcard return boundsMatch(requiredUpperBounds, beanParameterBounds); } @Override protected boolean parametersMatch(TypeVariable<?> delegateParameter, TypeVariable<?> beanParameter) { return boundsMatch(getUppermostTypeVariableBounds(delegateParameter), getUppermostTypeVariableBounds(beanParameter)); } protected boolean parametersMatch(TypeVariable<?> delegateParameter, Type beanParameter) { for (Type type : getUppermostTypeVariableBounds(delegateParameter)) { if (!CovariantTypes.isAssignableFrom(type, beanParameter)) { return false; } } return true; } }
DelegateInjectionPointAssignabilityRules
java
apache__camel
components/camel-aws/camel-aws2-ses/src/test/java/org/apache/camel/component/aws2/ses/SESComponentClientRegistryTest.java
{ "start": 1068, "end": 2196 }
class ____ extends CamelTestSupport { @Test public void createEndpointWithMinimalSESClientConfiguration() throws Exception { AmazonSESClientMock awsSESClient = new AmazonSESClientMock(); context.getRegistry().bind("awsSesClient", awsSESClient); Ses2Component component = context.getComponent("aws2-ses", Ses2Component.class); Ses2Endpoint endpoint = (Ses2Endpoint) component.createEndpoint("aws2-ses://from@example.com"); assertNotNull(endpoint.getConfiguration().getAmazonSESClient()); } @Test public void createEndpointWithAutowire() throws Exception { AmazonSESClientMock awsSESClient = new AmazonSESClientMock(); context.getRegistry().bind("awsSesClient", awsSESClient); Ses2Component component = context.getComponent("aws2-ses", Ses2Component.class); Ses2Endpoint endpoint = (Ses2Endpoint) component.createEndpoint("aws2-ses://from@example.com?accessKey=xxx&secretKey=yyy"); assertSame(awsSESClient, endpoint.getConfiguration().getAmazonSESClient()); } }
SESComponentClientRegistryTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/date/DateDiffConstantMillisNanosEvaluator.java
{ "start": 6553, "end": 7887 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final DateDiff.Part datePartFieldUnit; private final EvalOperator.ExpressionEvaluator.Factory startTimestampMillis; private final EvalOperator.ExpressionEvaluator.Factory endTimestampNanos; private final ZoneId zoneId; public Factory(Source source, DateDiff.Part datePartFieldUnit, EvalOperator.ExpressionEvaluator.Factory startTimestampMillis, EvalOperator.ExpressionEvaluator.Factory endTimestampNanos, ZoneId zoneId) { this.source = source; this.datePartFieldUnit = datePartFieldUnit; this.startTimestampMillis = startTimestampMillis; this.endTimestampNanos = endTimestampNanos; this.zoneId = zoneId; } @Override public DateDiffConstantMillisNanosEvaluator get(DriverContext context) { return new DateDiffConstantMillisNanosEvaluator(source, datePartFieldUnit, startTimestampMillis.get(context), endTimestampNanos.get(context), zoneId, context); } @Override public String toString() { return "DateDiffConstantMillisNanosEvaluator[" + "datePartFieldUnit=" + datePartFieldUnit + ", startTimestampMillis=" + startTimestampMillis + ", endTimestampNanos=" + endTimestampNanos + ", zoneId=" + zoneId + "]"; } } }
Factory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/MultipleInheritanceTest.java
{ "start": 1900, "end": 2096 }
class ____ implements Serializable { @Column(name = "CAR_ID_1") protected String carId1; } @Entity(name = "BasicCar") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public static
CarPK
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java
{ "start": 24871, "end": 27875 }
class ____ extends TestBean { @SuppressWarnings("unused") public ExtendedTestBean setFoo(String s) { return this; } } BeanInfo bi = Introspector.getBeanInfo(ExtendedTestBean.class); BeanInfo ebi = new ExtendedBeanInfo(bi); boolean found = false; for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { if (pd.getName().equals("foo")) { found = true; break; } } assertThat(found).isTrue(); assertThat(ebi.getPropertyDescriptors()).hasSize(bi.getPropertyDescriptors().length+1); } /** * {@link BeanInfo#getPropertyDescriptors()} returns alphanumerically sorted. * Test that {@link ExtendedBeanInfo#getPropertyDescriptors()} does the same. */ @Test void propertyDescriptorOrderIsEqual() throws Exception { BeanInfo bi = Introspector.getBeanInfo(TestBean.class); BeanInfo ebi = new ExtendedBeanInfo(bi); for (int i = 0; i < bi.getPropertyDescriptors().length; i++) { assertThat(ebi.getPropertyDescriptors()[i].getName()).isEqualTo(bi.getPropertyDescriptors()[i].getName()); } } @Test void propertyDescriptorComparator() throws Exception { ExtendedBeanInfo.PropertyDescriptorComparator c = new ExtendedBeanInfo.PropertyDescriptorComparator(); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("a", null, null))).isEqualTo(0); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abc", null, null))).isEqualTo(0); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("b", null, null))).isLessThan(0); assertThat(c.compare(new PropertyDescriptor("b", null, null), new PropertyDescriptor("a", null, null))).isGreaterThan(0); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("abd", null, null))).isLessThan(0); assertThat(c.compare(new PropertyDescriptor("xyz", null, null), new PropertyDescriptor("123", null, null))).isGreaterThan(0); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("abc", null, null))).isLessThan(0); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("a", null, null))).isGreaterThan(0); assertThat(c.compare(new PropertyDescriptor("abc", null, null), new PropertyDescriptor("b", null, null))).isLessThan(0); assertThat(c.compare(new PropertyDescriptor(" ", null, null), new PropertyDescriptor("a", null, null))).isLessThan(0); assertThat(c.compare(new PropertyDescriptor("1", null, null), new PropertyDescriptor("a", null, null))).isLessThan(0); assertThat(c.compare(new PropertyDescriptor("a", null, null), new PropertyDescriptor("A", null, null))).isGreaterThan(0); } @Test void reproSpr8806() throws Exception { // does not throw Introspector.getBeanInfo(LawLibrary.class); // does not throw after the changes introduced in SPR-8806 new ExtendedBeanInfo(Introspector.getBeanInfo(LawLibrary.class)); } @Test void cornerSpr8949() throws Exception {
ExtendedTestBean
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/StandardComparisonStrategy_arrayContains_Test.java
{ "start": 1074, "end": 2316 }
class ____ extends AbstractTest_StandardComparisonStrategy { @Test void should_return_true_if_array_contains_value() { String[] hobbits = array("Merry", "Frodo", null, "Merry", "Sam"); assertThat(standardComparisonStrategy.arrayContains(hobbits, "Sam")).isTrue(); assertThat(standardComparisonStrategy.arrayContains(hobbits, "Merry")).isTrue(); assertThat(standardComparisonStrategy.arrayContains(hobbits, null)).isTrue(); } @Test void should_return_false_if_array_does_not_contain_value() { String[] hobbits = array("Merry", "Frodo", "Merry", "Sam"); assertThat(standardComparisonStrategy.arrayContains(hobbits, "Pippin")).isFalse(); assertThat(standardComparisonStrategy.arrayContains(hobbits, "SAM ")).isFalse(); assertThat(standardComparisonStrategy.arrayContains(hobbits, null)).isFalse(); } @Test void should_return_false_if_array_is_empty() { assertThat(standardComparisonStrategy.arrayContains(new String[] {}, "Pippin")).isFalse(); } @Test void should_fail_if_first_parameter_is_not_an_array() { assertThatIllegalArgumentException().isThrownBy(() -> standardComparisonStrategy.arrayContains("not an array", "Pippin")); } }
StandardComparisonStrategy_arrayContains_Test
java
mapstruct__mapstruct
integrationtest/src/test/resources/lombokModuleTest/src/main/java/org/mapstruct/itest/lombok/PersonDto.java
{ "start": 192, "end": 641 }
class ____ { private final String name; private final int age; private final AddressDto address; public PersonDto(String name, int age, AddressDto address) { this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public int getAge() { return age; } public AddressDto getAddress() { return address; } }
PersonDto
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/matchers/MatchersPrinterTest.java
{ "start": 462, "end": 2586 }
class ____ extends TestBase { private final MatchersPrinter printer = new MatchersPrinter(); @Test public void shouldGetArgumentsLine() { String line = printer.getArgumentsLine( (List) Arrays.asList(new Equals(1), new Equals(2)), new PrintSettings()); assertEquals("(1, 2);", line); } @Test public void shouldGetArgumentsBlock() { String line = printer.getArgumentsBlock( (List) Arrays.asList(new Equals(1), new Equals(2)), new PrintSettings()); assertEquals("(\n 1,\n 2\n);", line); } @Test public void shouldDescribeTypeInfoOnlyMarkedMatchers() { // when String line = printer.getArgumentsLine( (List) Arrays.asList(new Equals(1L), new Equals(2)), PrintSettings.verboseMatchers(1)); // then assertEquals("(1L, (Integer) 2);", line); } @Test public void shouldDescribeStringMatcher() { // when String line = printer.getArgumentsLine( (List) Arrays.asList(new Equals(1L), new Equals("x")), PrintSettings.verboseMatchers(1)); // then assertEquals("(1L, (String) \"x\");", line); } @Test public void shouldGetVerboseArgumentsInBlock() { // when String line = printer.getArgumentsBlock( (List) Arrays.asList(new Equals(1L), new Equals(2)), PrintSettings.verboseMatchers(0, 1)); // then assertEquals("(\n (Long) 1L,\n (Integer) 2\n);", line); } @Test public void shouldGetVerboseArgumentsEvenIfSomeMatchersAreNotVerbose() { // when String line = printer.getArgumentsLine( (List) Arrays.asList(new Equals(1L), NotNull.NOT_NULL), PrintSettings.verboseMatchers(0)); // then assertEquals("((Long) 1L, notNull());", line); } }
MatchersPrinterTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingSuperCallTest.java
{ "start": 7082, "end": 7316 }
interface ____ { @CallSuper default void doIt() {} } """) .addSourceLines( "Sub.java", """ import java.util.Objects; public
Super
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/access/expression/EvaluationContextPostProcessor.java
{ "start": 1004, "end": 1504 }
interface ____<I> { /** * Allows post processing of the {@link EvaluationContext}. Implementations may return * a new instance of {@link EvaluationContext} or modify the {@link EvaluationContext} * that was passed in. * @param context the original {@link EvaluationContext} * @param invocation the security invocation object (i.e. FilterInvocation) * @return the upated context. */ EvaluationContext postProcess(EvaluationContext context, I invocation); }
EvaluationContextPostProcessor
java
apache__hadoop
hadoop-tools/hadoop-azure-datalake/src/test/java/org/apache/hadoop/fs/adl/common/CustomMockTokenProvider.java
{ "start": 1097, "end": 1878 }
class ____ extends AzureADTokenProvider { private Random random; private long expiryTime; private int accessTokenRequestCount = 0; @Override public void initialize(Configuration configuration) throws IOException { random = new Random(); } @Override public String getAccessToken() throws IOException { accessTokenRequestCount++; return String.valueOf(random.nextInt()); } @Override public Date getExpiryTime() { Date before10Min = new Date(); before10Min.setTime(expiryTime); return before10Min; } public void setExpiryTimeInMillisAfter(long timeInMillis) { expiryTime = System.currentTimeMillis() + timeInMillis; } public int getAccessTokenRequestCount() { return accessTokenRequestCount; } }
CustomMockTokenProvider
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/annotation/AnnotationValueBuilder.java
{ "start": 1187, "end": 9566 }
class ____<T extends Annotation> { private final String annotationName; private final Map<CharSequence, Object> values = new LinkedHashMap<>(5); private final RetentionPolicy retentionPolicy; @Nullable private List<AnnotationValue<?>> stereotypes; @Nullable private Map<CharSequence, Object> defaultValues; /** * Default constructor. * * @param annotationName The annotation name */ @Internal AnnotationValueBuilder(String annotationName) { this(annotationName, RetentionPolicy.RUNTIME); } /** * Default constructor. * * @param annotationName The annotation name * @param retentionPolicy The retention policy */ @Internal AnnotationValueBuilder(String annotationName, RetentionPolicy retentionPolicy) { this.annotationName = annotationName; this.retentionPolicy = retentionPolicy != null ? retentionPolicy : RetentionPolicy.RUNTIME; } /** * Default constructor. * * @param annotation The annotation */ @Internal AnnotationValueBuilder(Class<?> annotation) { this(annotation.getName()); } /** * Default constructor. * * @param value An existing value * @param retentionPolicy The retention policy */ @Internal AnnotationValueBuilder(AnnotationValue<T> value, RetentionPolicy retentionPolicy) { this.annotationName = value.getAnnotationName(); this.values.putAll(value.getValues()); this.defaultValues = value.getDefaultValues(); this.stereotypes = value.getStereotypes() == null ? null : new ArrayList<>(value.getStereotypes()); this.retentionPolicy = retentionPolicy != null ? retentionPolicy : RetentionPolicy.RUNTIME; } /** * Build the actual {@link AnnotationValue}. * * @return The {@link AnnotationValue} */ @NonNull public AnnotationValue<T> build() { return new AnnotationValue<>(annotationName, values, defaultValues, retentionPolicy, stereotypes); } /** * Adds a stereotype of the annotation. * * @param annotation The stereotype * @return This builder */ @NonNull public AnnotationValueBuilder<T> stereotype(AnnotationValue<?> annotation) { if (annotation != null) { if (stereotypes == null) { stereotypes = new ArrayList<>(10); } stereotypes.add(annotation); } return this; } /** * Replaces the stereotype annotation. * * @param originalAnnotationValue The original annotation value * @param newAnnotationValue The new annotation value * @return This builder * @since 4.0.0 */ @NonNull public AnnotationValueBuilder<T> replaceStereotype(@NonNull AnnotationValue<?> originalAnnotationValue, @NonNull AnnotationValue<?> newAnnotationValue) { Objects.requireNonNull(stereotypes); List<AnnotationValue<?>> values = new ArrayList<>(stereotypes); int index = values.indexOf(originalAnnotationValue); if (index < 0) { throw new IllegalArgumentException("Unknown original annotation value!"); } values.set(index, newAnnotationValue); stereotypes = values; return this; } /** * Removes the stereotype annotation. * * @param annotationValueToRemove The annotation value to remove * @return This builder * @since 4.0.0 */ @NonNull public AnnotationValueBuilder<T> removeStereotype(@NonNull AnnotationValue<?> annotationValueToRemove) { Objects.requireNonNull(stereotypes); List<AnnotationValue<?>> values = new ArrayList<>(stereotypes); int index = values.indexOf(annotationValueToRemove); if (index < 0) { throw new IllegalArgumentException("Unknown annotation value!"); } values.remove(index); stereotypes = values; return this; } /** * Adds a stereotypes of the annotation. * * @param newStereotypes The stereotypes * @return This builder * @since 4.0.0 */ @NonNull public AnnotationValueBuilder<T> stereotypes(@NonNull Collection<AnnotationValue<?>> newStereotypes) { if (stereotypes == null) { stereotypes = new ArrayList<>(10); } stereotypes.addAll(newStereotypes); return this; } /** * Replaces stereotypes of the annotation. * * @param newStereotypes The stereotypes * @return This builder * @since 4.0.0 */ @NonNull public AnnotationValueBuilder<T> replaceStereotypes(@NonNull Collection<AnnotationValue<?>> newStereotypes) { stereotypes = new ArrayList<>(newStereotypes); return this; } /** * Sets the default values of the annotation. * * @param defaultValues The default values * @return This builder */ @NonNull public AnnotationValueBuilder<T> defaultValues(Map<? extends CharSequence, Object> defaultValues) { if (defaultValues != null) { if (this.defaultValues == null) { this.defaultValues = new LinkedHashMap<>(defaultValues); } else { this.defaultValues.putAll(defaultValues); } } return this; } /** * Sets the value member to the given integer value. * * @param i The integer * @return This builder */ @NonNull public AnnotationValueBuilder<T> value(int i) { return member(AnnotationMetadata.VALUE_MEMBER, i); } /** * Sets the value member to the given integer[] value. * * @param ints The integer[] * @return This builder */ @NonNull public AnnotationValueBuilder<T> values(@Nullable int... ints) { return member(AnnotationMetadata.VALUE_MEMBER, ints); } /** * Sets the value member to the given long value. * * @param i The long * @return This builder */ @NonNull public AnnotationValueBuilder<T> value(long i) { return member(AnnotationMetadata.VALUE_MEMBER, i); } /** * Sets the value member to the given long[] value. * * @param longs The long[] * @return This builder */ @NonNull public AnnotationValueBuilder<T> values(@Nullable long... longs) { return member(AnnotationMetadata.VALUE_MEMBER, longs); } /** * Sets the value member to the given string value. * * @param str The string * @return This builder */ @NonNull public AnnotationValueBuilder<T> value(@Nullable String str) { return member(AnnotationMetadata.VALUE_MEMBER, str); } /** * Sets the value member to the given String[] values. * * @param strings The String[] * @return This builder */ @NonNull public AnnotationValueBuilder<T> values(@Nullable String... strings) { return member(AnnotationMetadata.VALUE_MEMBER, strings); } /** * Sets the value member to the given boolean value. * * @param bool The boolean * @return This builder */ @NonNull public AnnotationValueBuilder<T> value(boolean bool) { return member(AnnotationMetadata.VALUE_MEMBER, bool); } /** * Sets the value member to the given char value. * * @param character The char * @return This builder * @since 3.0.0 */ @NonNull public AnnotationValueBuilder<T> value(char character) { return member(AnnotationMetadata.VALUE_MEMBER, character); } /** * Sets the value member to the given double value. * * @param number The double * @return This builder * @since 3.0.0 */ @NonNull public AnnotationValueBuilder<T> value(double number) { return member(AnnotationMetadata.VALUE_MEMBER, number); } /** * Sets the value member to the given float value. * * @param f The float * @return This builder * @since 3.0.0 */ @NonNull public AnnotationValueBuilder<T> value(float f) { return member(AnnotationMetadata.VALUE_MEMBER, f); } /** * Sets the value member to the given
AnnotationValueBuilder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/jdk/Java6CollectionsDeserTest.java
{ "start": 354, "end": 875 }
class ____ { // for [databind#216] @Test public void test16Types() throws Exception { final ObjectMapper mapper = new ObjectMapper(); Deque<?> dq = mapper.readValue("[1]", Deque.class); assertNotNull(dq); assertEquals(1, dq.size()); assertTrue(dq instanceof Deque<?>); NavigableSet<?> ns = mapper.readValue("[ true ]", NavigableSet.class); assertEquals(1, ns.size()); assertTrue(ns instanceof NavigableSet<?>); } }
Java6CollectionsDeserTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java
{ "start": 3413, "end": 4313 }
class ____<E> { private final Queue<E> blockq = new LinkedList<>(); /** Size of the queue */ synchronized int size() {return blockq.size();} /** Enqueue */ synchronized boolean offer(E e) { return blockq.offer(e); } /** Dequeue */ synchronized List<E> poll(int numBlocks) { if (numBlocks <= 0 || blockq.isEmpty()) { return null; } List<E> results = new ArrayList<>(); for(; !blockq.isEmpty() && numBlocks > 0; numBlocks--) { results.add(blockq.poll()); } return results; } /** * Returns <code>true</code> if the queue contains the specified element. */ synchronized boolean contains(E e) { return blockq.contains(e); } synchronized void clear() { blockq.clear(); } } /** * A list of CachedBlock objects on this datanode. */ public static
BlockQueue
java
reactor__reactor-core
reactor-core/src/jcstress/java/reactor/core/publisher/FluxPublishStressTest.java
{ "start": 4878, "end": 5781 }
class ____ extends RefCntConcurrentSubscriptionBaseStressTest<Object> { public RefCntConcurrentSubscriptionEmptySyncStressTest() { super(Flux.empty(), null); } @Actor public void subscribe1() { sharedSource.subscribe(subscriber1); } @Actor public void subscribe2() { sharedSource.subscribe(subscriber2); } @Arbiter public void arbiter(IIIIII_Result r) { r.r1 = subscriber1.onNextCalls.get(); r.r2 = subscriber2.onNextCalls.get(); r.r3 = subscriber1.onCompleteCalls.get(); r.r4 = subscriber2.onCompleteCalls.get(); r.r5 = subscriber1.onErrorCalls.get(); r.r6 = subscriber2.onErrorCalls.get(); } } @JCStressTest @Outcome(id = {"0, 0, 1, 1, 0, 0"}, expect = ACCEPTABLE, desc = "concurrent subscription succeeded") @State public static
RefCntConcurrentSubscriptionEmptySyncStressTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/component/ComponentState.java
{ "start": 866, "end": 951 }
enum ____ { INIT, FLEXING, STABLE, UPGRADING, CANCEL_UPGRADING }
ComponentState
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsClientThrottlingAnalyzer.java
{ "start": 1420, "end": 2739 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger( AbfsClientThrottlingAnalyzer.class); private static final int MIN_ANALYSIS_PERIOD_MS = 1000; private static final int MAX_ANALYSIS_PERIOD_MS = 30000; private static final double MIN_ACCEPTABLE_ERROR_PERCENTAGE = .1; private static final double MAX_EQUILIBRIUM_ERROR_PERCENTAGE = 1; private static final double RAPID_SLEEP_DECREASE_FACTOR = .75; private static final double RAPID_SLEEP_DECREASE_TRANSITION_PERIOD_MS = 150 * 1000; private static final double SLEEP_DECREASE_FACTOR = .975; private static final double SLEEP_INCREASE_FACTOR = 1.05; private int analysisPeriodMs; private volatile int sleepDuration = 0; private long consecutiveNoErrorCount = 0; private String name = null; private Timer timer = null; private AtomicReference<AbfsOperationMetrics> blobMetrics = null; private AtomicLong lastExecutionTime = null; private final AtomicBoolean isOperationOnAccountIdle = new AtomicBoolean(false); private AbfsConfiguration abfsConfiguration = null; private boolean accountLevelThrottlingEnabled = true; private AbfsClientThrottlingAnalyzer() { // hide default constructor } /** * Creates an instance of the <code>AbfsClientThrottlingAnalyzer</code>
AbfsClientThrottlingAnalyzer
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticatedPrincipal.java
{ "start": 1322, "end": 2567 }
interface ____ extends AuthenticatedPrincipal { /** * Get the first value of Saml2 token attribute by name * @param name the name of the attribute * @param <A> the type of the attribute * @return the first attribute value or {@code null} otherwise * @since 5.4 */ @Nullable default <A> A getFirstAttribute(String name) { List<A> values = getAttribute(name); return CollectionUtils.firstElement(values); } /** * Get the Saml2 token attribute by name * @param name the name of the attribute * @param <A> the type of the attribute * @return the attribute or {@code null} otherwise * @since 5.4 */ @Nullable default <A> List<A> getAttribute(String name) { return (List<A>) getAttributes().get(name); } /** * Get the Saml2 token attributes * @return the Saml2 token attributes * @since 5.4 */ default Map<String, List<Object>> getAttributes() { return Collections.emptyMap(); } /** * Get the {@link RelyingPartyRegistration} identifier * @return the {@link RelyingPartyRegistration} identifier * @since 5.6 */ default String getRelyingPartyRegistrationId() { return null; } default List<String> getSessionIndexes() { return Collections.emptyList(); } }
Saml2AuthenticatedPrincipal
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/data/DoubleBlock.java
{ "start": 8955, "end": 10176 }
interface ____ extends Block.Builder, BlockLoader.DoubleBuilder permits DoubleBlockBuilder { /** * Appends a double to the current entry. */ @Override Builder appendDouble(double value); /** * Copy the values in {@code block} from {@code beginInclusive} to * {@code endExclusive} into this builder. */ Builder copyFrom(DoubleBlock block, int beginInclusive, int endExclusive); /** * Copy the values in {@code block} at {@code position}. If this position * has a single value, this'll copy a single value. If this positions has * many values, it'll copy all of them. If this is {@code null}, then it'll * copy the {@code null}. */ Builder copyFrom(DoubleBlock block, int position); @Override Builder appendNull(); @Override Builder beginPositionEntry(); @Override Builder endPositionEntry(); @Override Builder copyFrom(Block block, int beginInclusive, int endExclusive); @Override Builder mvOrdering(Block.MvOrdering mvOrdering); @Override DoubleBlock build(); } }
Builder
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/state/internals/RocksDBRangeIteratorTest.java
{ "start": 1708, "end": 18054 }
class ____ { private final String storeName = "store"; private final String key1 = "a"; private final String key2 = "b"; private final String key3 = "c"; private final String key4 = "d"; private final String value = "value"; private final Bytes key1Bytes = Bytes.wrap(key1.getBytes()); private final Bytes key2Bytes = Bytes.wrap(key2.getBytes()); private final Bytes key3Bytes = Bytes.wrap(key3.getBytes()); private final Bytes key4Bytes = Bytes.wrap(key4.getBytes()); private final byte[] valueBytes = value.getBytes(); @Test public void shouldReturnAllKeysInTheRangeInForwardDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key1Bytes.get()) .thenReturn(key2Bytes.get()) .thenReturn(key3Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).next(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key3Bytes, true, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key1Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key2Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(3)).value(); verify(rocksIterator, times(3)).next(); } @Test public void shouldReturnAllKeysInTheRangeReverseDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seekForPrev(key3Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key3Bytes.get()) .thenReturn(key2Bytes.get()) .thenReturn(key1Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).prev(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key3Bytes, false, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key2Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key1Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(3)).value(); verify(rocksIterator, times(3)).prev(); } @Test public void shouldReturnAllKeysWhenLastKeyIsGreaterThanLargestKeyInStateStoreInForwardDirection() { final Bytes toBytes = Bytes.increment(key4Bytes); final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key1Bytes.get()) .thenReturn(key2Bytes.get()) .thenReturn(key3Bytes.get()) .thenReturn(key4Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).next(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, toBytes, true, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key1Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key2Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key4Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(4)).value(); verify(rocksIterator, times(4)).next(); } @Test public void shouldReturnAllKeysWhenLastKeyIsSmallerThanSmallestKeyInStateStoreInReverseDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seekForPrev(key4Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key4Bytes.get()) .thenReturn(key3Bytes.get()) .thenReturn(key2Bytes.get()) .thenReturn(key1Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).prev(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key4Bytes, false, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key4Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key2Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key1Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(4)).value(); verify(rocksIterator, times(4)).prev(); } @Test public void shouldReturnNoKeysWhenLastKeyIsSmallerThanSmallestKeyInStateStoreForwardDirection() { // key range in state store: [c-f] final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); when(rocksIterator.isValid()).thenReturn(false); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key2Bytes, true, true ); assertThat(rocksDBRangeIterator.hasNext(), is(false)); } @Test public void shouldReturnNoKeysWhenLastKeyIsLargerThanLargestKeyInStateStoreReverseDirection() { // key range in state store: [c-f] final String from = "g"; final String to = "h"; final Bytes fromBytes = Bytes.wrap(from.getBytes()); final Bytes toBytes = Bytes.wrap(to.getBytes()); final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seekForPrev(toBytes.get()); when(rocksIterator.isValid()) .thenReturn(false); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, fromBytes, toBytes, false, true ); assertThat(rocksDBRangeIterator.hasNext(), is(false)); } @Test public void shouldReturnAllKeysInPartiallyOverlappingRangeInForwardDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key2Bytes.get()) .thenReturn(key3Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).next(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key3Bytes, true, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key2Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(2)).value(); verify(rocksIterator, times(2)).next(); } @Test public void shouldReturnAllKeysInPartiallyOverlappingRangeInReverseDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); final String to = "e"; final Bytes toBytes = Bytes.wrap(to.getBytes()); doNothing().when(rocksIterator).seekForPrev(toBytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key4Bytes.get()) .thenReturn(key3Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).prev(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key3Bytes, toBytes, false, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key4Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(2)).value(); verify(rocksIterator, times(2)).prev(); } @Test public void shouldReturnTheCurrentKeyOnInvokingPeekNextKeyInForwardDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key2Bytes.get()) .thenReturn(key3Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).next(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key3Bytes, true, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key2Bytes)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key2Bytes)); assertThat(rocksDBRangeIterator.next().key, is(key2Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key3Bytes)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key3Bytes)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); assertThrows(NoSuchElementException.class, rocksDBRangeIterator::peekNextKey); verify(rocksIterator, times(2)).value(); verify(rocksIterator, times(2)).next(); } @Test public void shouldReturnTheCurrentKeyOnInvokingPeekNextKeyInReverseDirection() { final RocksIterator rocksIterator = mock(RocksIterator.class); final Bytes toBytes = Bytes.increment(key4Bytes); doNothing().when(rocksIterator).seekForPrev(toBytes.get()); when(rocksIterator.isValid()) .thenReturn(true) .thenReturn(true) .thenReturn(false); when(rocksIterator.key()) .thenReturn(key4Bytes.get()) .thenReturn(key3Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).prev(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key3Bytes, toBytes, false, true ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key4Bytes)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key4Bytes)); assertThat(rocksDBRangeIterator.next().key, is(key4Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key3Bytes)); assertThat(rocksDBRangeIterator.peekNextKey(), is(key3Bytes)); assertThat(rocksDBRangeIterator.next().key, is(key3Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); assertThrows(NoSuchElementException.class, rocksDBRangeIterator::peekNextKey); verify(rocksIterator, times(2)).value(); verify(rocksIterator, times(2)).prev(); } @Test public void shouldCloseIterator() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); doNothing().when(rocksIterator).close(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key2Bytes, true, true ); rocksDBRangeIterator.onClose(() -> { }); rocksDBRangeIterator.close(); verify(rocksIterator).close(); } @Test public void shouldCallCloseCallbackOnClose() { final RocksIterator rocksIterator = mock(RocksIterator.class); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key2Bytes, true, true ); final AtomicBoolean callbackCalled = new AtomicBoolean(false); rocksDBRangeIterator.onClose(() -> callbackCalled.set(true)); rocksDBRangeIterator.close(); assertThat(callbackCalled.get(), is(true)); } @Test public void shouldExcludeEndOfRange() { final RocksIterator rocksIterator = mock(RocksIterator.class); doNothing().when(rocksIterator).seek(key1Bytes.get()); when(rocksIterator.isValid()) .thenReturn(true); when(rocksIterator.key()) .thenReturn(key1Bytes.get()) .thenReturn(key2Bytes.get()); when(rocksIterator.value()).thenReturn(valueBytes); doNothing().when(rocksIterator).next(); final RocksDBRangeIterator rocksDBRangeIterator = new RocksDBRangeIterator( storeName, rocksIterator, key1Bytes, key2Bytes, true, false ); assertThat(rocksDBRangeIterator.hasNext(), is(true)); assertThat(rocksDBRangeIterator.next().key, is(key1Bytes)); assertThat(rocksDBRangeIterator.hasNext(), is(false)); verify(rocksIterator, times(2)).value(); verify(rocksIterator, times(2)).next(); } }
RocksDBRangeIteratorTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest_float.java
{ "start": 1152, "end": 1567 }
class ____ { private final float id; private final String name; @JSONCreator public Entity(@JSONField(name = "id") float id, @JSONField(name = "name") String name){ this.id = id; this.name = name; } public float getId() { return id; } public String getName() { return name; } } }
Entity
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/ftp/TestFTPContractMkdir.java
{ "start": 1088, "end": 1272 }
class ____ extends AbstractContractMkdirTest { @Override protected AbstractFSContract createContract(Configuration conf) { return new FTPContract(conf); } }
TestFTPContractMkdir
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/multipart/MultipartFormDataInput.java
{ "start": 387, "end": 638 }
class ____ implements MultipartFormDataInput { public static final Empty INSTANCE = new Empty(); @Override public Map<String, Collection<FormValue>> getValues() { return Collections.emptyMap(); } } }
Empty
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/TestRuntimeEstimators.java
{ "start": 25954, "end": 26268 }
class ____ extends CompositeService { final Clock clock; public MyAppMaster(Clock clock) { super(MyAppMaster.class.getName()); if (clock == null) { clock = SystemClock.getInstance(); } this.clock = clock; LOG.info("Created MyAppMaster"); } }
MyAppMaster
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/ClassLoaderUtil.java
{ "start": 1327, "end": 5031 }
class ____. For file URLs, it contains in addition whether the referenced file exists, is a * valid JAR file, or is a directory. * * <p>NOTE: This method makes a best effort to provide information about the classloader, and * never throws an exception. * * <p>NOTE: Passing {@code ClassLoader.getSystemClassLoader()} on Java 9+ will not return * anything interesting. * * @param loader The classloader to get the info string for. * @return The classloader information string. */ public static String getUserCodeClassLoaderInfo(ClassLoader loader) { if (loader instanceof URLClassLoader) { URLClassLoader cl = (URLClassLoader) loader; try { StringBuilder bld = new StringBuilder(); if (cl == ClassLoader.getSystemClassLoader()) { bld.append("System ClassLoader: "); } else { bld.append("URL ClassLoader:"); } for (URL url : cl.getURLs()) { bld.append(formatURL(url)); } return bld.toString(); } catch (Throwable t) { return "Cannot access classloader info due to an exception.\n" + ExceptionUtils.stringifyException(t); } } else if (loader == ClassLoader.getSystemClassLoader()) { // this branch is only reachable on Java9+ // where the system classloader is no longer a URLClassLoader return "System ClassLoader"; } else { return "No user code ClassLoader"; } } /** * Returns the interpretation of URL in string format. * * <p>If the URL is null, it returns '(null)'. * * <p>If the URL protocol is file, prepend 'file:' flag before the formatted URL. Otherwise, use * 'url: ' as the prefix instead. * * <p>Also, it checks whether the object that the URL directs to exists or not. If the object * exists, some additional checks should be performed in order to determine that the object is a * directory or a valid/invalid jar file. If the object does not exist, a missing flag should be * appended. * * @param url URL that should be formatted * @return The formatted URL * @throws IOException When JarFile cannot be closed */ public static String formatURL(URL url) throws IOException { StringBuilder bld = new StringBuilder(); bld.append("\n "); if (url == null) { bld.append("(null)"); } else if ("file".equals(url.getProtocol())) { String filePath = url.getPath(); File fileFile = new File(filePath); bld.append("file: '").append(filePath).append('\''); if (fileFile.exists()) { if (fileFile.isDirectory()) { bld.append(" (directory)"); } else { JarFile jar = null; try { jar = new JarFile(filePath); bld.append(" (valid JAR)"); } catch (Exception e) { bld.append(" (invalid JAR: ").append(e.getMessage()).append(')'); } finally { if (jar != null) { jar.close(); } } } } else { bld.append(" (missing)"); } } else { bld.append("url: ").append(url); } return bld.toString(); } /** * Checks, whether the
loader
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/hive/stmt/HiveLoadDataStatement.java
{ "start": 641, "end": 4147 }
class ____ extends SQLStatementImpl { private boolean local; private SQLExpr inpath; private boolean overwrite; private SQLExprTableSource into; private final List<SQLExpr> partition = new ArrayList<SQLExpr>(4); private SQLExternalRecordFormat format; private SQLExpr storedBy; private SQLExpr storedAs; private SQLExpr rowFormat; protected Map<String, SQLObject> serdeProperties = new LinkedHashMap<String, SQLObject>(); protected SQLExpr using; public HiveLoadDataStatement() { super(DbType.hive); } protected void accept0(SQLASTVisitor visitor) { if (visitor instanceof HiveASTVisitor) { accept0((HiveASTVisitor) visitor); } else { super.accept0(visitor); } } protected void accept0(HiveASTVisitor visitor) { if (visitor.visit(this)) { this.acceptChild(visitor, inpath); this.acceptChild(visitor, into); this.acceptChild(visitor, partition); this.acceptChild(visitor, storedAs); this.acceptChild(visitor, storedBy); this.acceptChild(visitor, rowFormat); } visitor.endVisit(this); } public boolean isLocal() { return local; } public void setLocal(boolean local) { this.local = local; } public SQLExpr getInpath() { return inpath; } public void setInpath(SQLExpr x) { if (x != null) { x.setParent(this); } this.inpath = x; } public boolean isOverwrite() { return overwrite; } public void setOverwrite(boolean overwrite) { this.overwrite = overwrite; } public SQLExprTableSource getInto() { return into; } public void setInto(SQLExprTableSource x) { if (x != null) { x.setParent(this); } this.into = x; } public void setInto(SQLExpr x) { if (x == null) { this.into = null; return; } setInto(new SQLExprTableSource(x)); } public List<SQLExpr> getPartition() { return partition; } public void addPartion(SQLAssignItem item) { if (item != null) { item.setParent(this); } this.partition.add(item); } public SQLExternalRecordFormat getFormat() { return format; } public void setFormat(SQLExternalRecordFormat x) { if (x != null) { x.setParent(this); } this.format = x; } public SQLExpr getStoredBy() { return storedBy; } public void setStoredBy(SQLExpr x) { if (x != null) { x.setParent(this); } this.storedBy = x; } public SQLExpr getStoredAs() { return storedAs; } public void setStoredAs(SQLExpr x) { if (x != null) { x.setParent(this); } this.storedAs = x; } public SQLExpr getRowFormat() { return rowFormat; } public void setRowFormat(SQLExpr x) { if (x != null) { x.setParent(this); } this.rowFormat = x; } public SQLExpr getUsing() { return using; } public void setUsing(SQLExpr x) { if (x != null) { x.setParent(this); } this.using = x; } public Map<String, SQLObject> getSerdeProperties() { return serdeProperties; } }
HiveLoadDataStatement
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
{ "start": 61402, "end": 65320 }
class ____, exit early in order // to avoid storing the resolved Class in the bean definition. if (dynamicLoader != null) { try { return dynamicLoader.loadClass(className); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) { logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex); } } } return ClassUtils.forName(className, dynamicLoader); } } // Resolve regularly, caching the result in the BeanDefinition... return mbd.resolveBeanClass(beanClassLoader); } /** * Evaluate the given String as contained in a bean definition, * potentially resolving it as an expression. * @param value the value to check * @param beanDefinition the bean definition that the value comes from * @return the resolved value * @see #setBeanExpressionResolver */ protected @Nullable Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) { if (this.beanExpressionResolver == null) { return value; } Scope scope = null; if (beanDefinition != null) { String scopeName = beanDefinition.getScope(); if (scopeName != null) { scope = getRegisteredScope(scopeName); } } return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); } /** * Predict the eventual bean type (of the processed bean instance) for the * specified bean. Called by {@link #getType} and {@link #isTypeMatch}. * Does not need to handle FactoryBeans specifically, since it is only * supposed to operate on the raw bean type. * <p>This implementation is simplistic in that it is not able to * handle factory methods and InstantiationAwareBeanPostProcessors. * It only predicts the bean type correctly for a standard bean. * To be overridden in subclasses, applying more sophisticated type detection. * @param beanName the name of the bean * @param mbd the merged bean definition to determine the type for * @param typesToMatch the types to match in case of internal type matching purposes * (also signals that the returned {@code Class} will never be exposed to application code) * @return the type of the bean, or {@code null} if not predictable */ protected @Nullable Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { Class<?> targetType = mbd.getTargetType(); if (targetType != null) { return targetType; } if (mbd.getFactoryMethodName() != null) { return null; } return resolveBeanClass(mbd, beanName, typesToMatch); } /** * Check whether the given bean is defined as a {@link FactoryBean}. * @param beanName the name of the bean * @param mbd the corresponding bean definition */ protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { Boolean result = mbd.isFactoryBean; if (result == null) { Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class); result = (beanType != null && FactoryBean.class.isAssignableFrom(beanType)); mbd.isFactoryBean = result; } return result; } /** * Determine the bean type for the given FactoryBean definition, as far as possible. * Only called if there is no singleton instance registered for the target bean * already. The implementation is allowed to instantiate the target factory bean if * {@code allowInit} is {@code true} and the type cannot be determined another way; * otherwise it is restricted to introspecting signatures and related metadata. * <p>If no {@link FactoryBean#OBJECT_TYPE_ATTRIBUTE} is set on the bean definition * and {@code allowInit} is {@code true}, the default implementation will create * the FactoryBean via {@code getBean} to call its {@code getObjectType} method. * Subclasses are encouraged to optimize this, typically by inspecting the generic * signature of the factory bean
loader
java
apache__spark
common/unsafe/src/main/java/org/apache/spark/sql/catalyst/util/CollationSupport.java
{ "start": 11052, "end": 12706 }
class ____ { public static UTF8String exec(final UTF8String v, final int collationId, boolean useICU) { CollationFactory.Collation collation = CollationFactory.fetchCollation(collationId); // Space trimming does not affect the output of this expression. if (collation.isUtf8BinaryType) { return useICU ? execBinaryICU(v) : execBinary(v); } else if (collation.isUtf8LcaseType) { return execLowercase(v); } else { return execICU(v, collationId); } } public static String genCode(final String v, final int collationId, boolean useICU) { CollationFactory.Collation collation = CollationFactory.fetchCollation(collationId); String expr = "CollationSupport.InitCap.exec"; if (collation.isUtf8BinaryType) { String funcName = useICU ? "BinaryICU" : "Binary"; return String.format(expr + "%s(%s)", funcName, v); } else if (collation.isUtf8LcaseType) { return String.format(expr + "Lowercase(%s)", v); } else { return String.format(expr + "ICU(%s, %d)", v, collationId); } } public static UTF8String execBinary(final UTF8String v) { return v.toLowerCase().toTitleCase(); } public static UTF8String execBinaryICU(final UTF8String v) { return CollationAwareUTF8String.toTitleCaseICU(v); } public static UTF8String execLowercase(final UTF8String v) { return CollationAwareUTF8String.toTitleCase(v); } public static UTF8String execICU(final UTF8String v, final int collationId) { return CollationAwareUTF8String.toTitleCase(v, collationId); } } public static
InitCap
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/properties/IfBuildPropertyRepeatableStereotypeTest.java
{ "start": 3772, "end": 3870 }
interface ____ { String hello(); } @NotMatchingProperty static abstract
MyService
java
apache__camel
components/camel-twitter/src/generated/java/org/apache/camel/component/twitter/search/TwitterSearchComponentConfigurer.java
{ "start": 741, "end": 6265 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { TwitterSearchComponent target = (TwitterSearchComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": target.setAccessToken(property(camelContext, java.lang.String.class, value)); return true; case "accesstokensecret": case "accessTokenSecret": target.setAccessTokenSecret(property(camelContext, java.lang.String.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "consumerkey": case "consumerKey": target.setConsumerKey(property(camelContext, java.lang.String.class, value)); return true; case "consumersecret": case "consumerSecret": target.setConsumerSecret(property(camelContext, java.lang.String.class, value)); return true; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": target.setHealthCheckConsumerEnabled(property(camelContext, boolean.class, value)); return true; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": target.setHealthCheckProducerEnabled(property(camelContext, boolean.class, value)); return true; case "httpproxyhost": case "httpProxyHost": target.setHttpProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "httpproxypassword": case "httpProxyPassword": target.setHttpProxyPassword(property(camelContext, java.lang.String.class, value)); return true; case "httpproxyport": case "httpProxyPort": target.setHttpProxyPort(property(camelContext, int.class, value)); return true; case "httpproxyuser": case "httpProxyUser": target.setHttpProxyUser(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return java.lang.String.class; case "accesstokensecret": case "accessTokenSecret": return java.lang.String.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "consumerkey": case "consumerKey": return java.lang.String.class; case "consumersecret": case "consumerSecret": return java.lang.String.class; case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return boolean.class; case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return boolean.class; case "httpproxyhost": case "httpProxyHost": return java.lang.String.class; case "httpproxypassword": case "httpProxyPassword": return java.lang.String.class; case "httpproxyport": case "httpProxyPort": return int.class; case "httpproxyuser": case "httpProxyUser": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { TwitterSearchComponent target = (TwitterSearchComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "accesstoken": case "accessToken": return target.getAccessToken(); case "accesstokensecret": case "accessTokenSecret": return target.getAccessTokenSecret(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "consumerkey": case "consumerKey": return target.getConsumerKey(); case "consumersecret": case "consumerSecret": return target.getConsumerSecret(); case "healthcheckconsumerenabled": case "healthCheckConsumerEnabled": return target.isHealthCheckConsumerEnabled(); case "healthcheckproducerenabled": case "healthCheckProducerEnabled": return target.isHealthCheckProducerEnabled(); case "httpproxyhost": case "httpProxyHost": return target.getHttpProxyHost(); case "httpproxypassword": case "httpProxyPassword": return target.getHttpProxyPassword(); case "httpproxyport": case "httpProxyPort": return target.getHttpProxyPort(); case "httpproxyuser": case "httpProxyUser": return target.getHttpProxyUser(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); default: return null; } } }
TwitterSearchComponentConfigurer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ParameterTest.java
{ "start": 11196, "end": 11682 }
class ____ { abstract void target(Object o); void test() { // BUG: Diagnostic contains: true target(1); } } """) .doTest(); } @Test public void getName_returnsConstant_withConstantFromOtherClass() { CompilationTestHelper.newInstance(PrintIsConstantFirstArgument.class, getClass()) .addSourceLines( "Test.java", """ abstract
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/security/token/hadoop/HadoopDelegationTokenConverterTest.java
{ "start": 1244, "end": 2164 }
class ____ { @Test public void testRoundTrip() throws IOException, ClassNotFoundException { final Text tokenKind = new Text("TEST_TOKEN_KIND"); final Text tokenService = new Text("TEST_TOKEN_SERVICE"); Credentials credentials = new Credentials(); credentials.addToken( tokenService, new Token<>(new byte[4], new byte[4], tokenKind, tokenService)); byte[] credentialsBytes = HadoopDelegationTokenConverter.serialize(credentials); Credentials deserializedCredentials = HadoopDelegationTokenConverter.deserialize(credentialsBytes); assertEquals(1, credentials.getAllTokens().size()); assertEquals(1, deserializedCredentials.getAllTokens().size()); assertNotNull(credentials.getToken(tokenService)); assertNotNull(deserializedCredentials.getToken(tokenService)); } }
HadoopDelegationTokenConverterTest
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/howto/dataaccess/configuretwodatasources/MyAdditionalDataSourceConfiguration.java
{ "start": 1108, "end": 1378 }
class ____ { @Qualifier("second") @Bean(defaultCandidate = false) @ConfigurationProperties("app.datasource") public HikariDataSource secondDataSource() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } }
MyAdditionalDataSourceConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/results/ResultBuilderBasicValued.java
{ "start": 475, "end": 699 }
interface ____ extends ResultBuilder { @Override BasicResult<?> buildResult( JdbcValuesMetadata jdbcResultsMetadata, int resultPosition, DomainResultCreationState domainResultCreationState); }
ResultBuilderBasicValued
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/SubtaskGatewayImplTest.java
{ "start": 1669, "end": 8483 }
class ____ { @Test void eventsPassThroughOpenGateway() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks(); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(11)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); final OperatorEvent event = new TestOperatorEvent(); final CompletableFuture<Acknowledge> future = gateway.sendEvent(event); assertThat(receiver.events).containsExactly(new EventWithSubtask(event, 11)); assertThat(future).isDone(); } @Test void closingMarkedGateway() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks(); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(11)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); gateway.markForCheckpoint(200L); final boolean isClosed = gateway.tryCloseGateway(200L); assertThat(isClosed).isTrue(); } @Test void notClosingUnmarkedGateway() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks(); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(11)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); final boolean isClosed = gateway.tryCloseGateway(123L); assertThat(isClosed).isFalse(); } @Test void notClosingGatewayForOtherMark() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks(); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(11)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); gateway.markForCheckpoint(100L); final boolean isClosed = gateway.tryCloseGateway(123L); assertThat(isClosed).isFalse(); } @Test void eventsBlockedByClosedGateway() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks(); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(1)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); gateway.markForCheckpoint(1L); gateway.tryCloseGateway(1L); final CompletableFuture<Acknowledge> future = gateway.sendEvent(new TestOperatorEvent()); assertThat(receiver.events).isEmpty(); assertThat(future).isNotDone(); } @Test void eventsReleasedAfterOpeningGateway() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasks(); final SubtaskGatewayImpl gateway0 = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(0)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); final SubtaskGatewayImpl gateway3 = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(3)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); List<SubtaskGatewayImpl> gateways = Arrays.asList(gateway3, gateway0); gateways.forEach(x -> x.markForCheckpoint(17L)); gateways.forEach(x -> x.tryCloseGateway(17L)); final OperatorEvent event1 = new TestOperatorEvent(); final OperatorEvent event2 = new TestOperatorEvent(); final CompletableFuture<Acknowledge> future1 = gateway3.sendEvent(event1); final CompletableFuture<Acknowledge> future2 = gateway0.sendEvent(event2); gateways.forEach(SubtaskGatewayImpl::openGatewayAndUnmarkAllCheckpoint); assertThat(receiver.events) .containsExactly(new EventWithSubtask(event1, 3), new EventWithSubtask(event2, 0)); assertThat(future1).isDone(); assertThat(future2).isDone(); } @Test void releasedEventsForwardSendFailures() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasksFailingRpcs(new FlinkException("test")); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( getUniqueElement(receiver.getAccessesForSubtask(10)), ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); gateway.markForCheckpoint(17L); gateway.tryCloseGateway(17L); final CompletableFuture<Acknowledge> future = gateway.sendEvent(new TestOperatorEvent()); gateway.openGatewayAndUnmarkAllCheckpoint(); assertThat(future).isCompletedExceptionally(); } @Test void optionalEventsIgnoreTaskNotRunning() { final EventReceivingTasks receiver = EventReceivingTasks.createForRunningTasksFailingRpcs( new FlinkException(new TaskNotRunningException("test"))); TestSubtaskAccess subtaskAccess = (TestSubtaskAccess) getUniqueElement(receiver.getAccessesForSubtask(10)); final SubtaskGatewayImpl gateway = new SubtaskGatewayImpl( subtaskAccess, ComponentMainThreadExecutorServiceAdapter.forMainThread(), new IncompleteFuturesTracker()); gateway.markForCheckpoint(17L); gateway.tryCloseGateway(17L); final CompletableFuture<Acknowledge> future = gateway.sendEvent(new TestOperatorEvent(42, true)); gateway.openGatewayAndUnmarkAllCheckpoint(); assertThat(future).isCompletedExceptionally(); assertThat(subtaskAccess.getTaskFailoverReasons()).isEmpty(); } private static <T> T getUniqueElement(Collection<T> collection) { Iterator<T> iterator = collection.iterator(); T element = iterator.next(); Preconditions.checkState(!iterator.hasNext()); return element; } }
SubtaskGatewayImplTest
java
google__gson
gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnFieldsTest.java
{ "start": 8643, "end": 9853 }
class ____ { @JsonAdapter(value = PartJsonFieldAnnotationAdapter.class) final Part part; private GadgetWithOptionalPart(Part part) { this.part = part; } } /** Regression test contributed through https://github.com/google/gson/issues/831 */ @Test public void testNonPrimitiveFieldAnnotationTakesPrecedenceOverDefault() { Gson gson = new Gson(); String json = gson.toJson(new GadgetWithOptionalPart(new Part("foo"))); assertThat(json).isEqualTo("{\"part\":\"PartJsonFieldAnnotationAdapter\"}"); GadgetWithOptionalPart gadget = gson.fromJson("{'part':'foo'}", GadgetWithOptionalPart.class); assertThat(gadget.part.name).isEqualTo("PartJsonFieldAnnotationAdapter"); } /** Regression test contributed through https://github.com/google/gson/issues/831 */ @Test public void testPrimitiveFieldAnnotationTakesPrecedenceOverDefault() { Gson gson = new Gson(); String json = gson.toJson(new GadgetWithPrimitivePart(42)); assertThat(json).isEqualTo("{\"part\":\"42\"}"); GadgetWithPrimitivePart gadget = gson.fromJson(json, GadgetWithPrimitivePart.class); assertThat(gadget.part).isEqualTo(42); } private static final
GadgetWithOptionalPart
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/NativeController.java
{ "start": 11962, "end": 12522 }
class ____ { private final CountDownLatch latch = new CountDownLatch(1); private final SetOnce<ControllerResponse> responseHolder = new SetOnce<>(); boolean hasResponded() { return latch.getCount() < 1; } void setResponse(ControllerResponse response) { responseHolder.set(response); latch.countDown(); } ControllerResponse getResponse() throws InterruptedException { latch.await(); return responseHolder.get(); } } }
ResponseTracker
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/NettyBufferPool.java
{ "start": 1387, "end": 9108 }
class ____ extends PooledByteBufAllocator { private static final Logger LOG = LoggerFactory.getLogger(NettyBufferPool.class); /** <tt>PoolArena&lt;ByteBuffer&gt;[]</tt> via Reflection. */ private final Object[] directArenas; /** Configured number of arenas. */ private final int numberOfArenas; /** Configured chunk size for the arenas. */ private final int chunkSize; /** We strictly prefer direct buffers and disallow heap allocations. */ private static final boolean PREFER_DIRECT = true; /** * Arenas allocate chunks of pageSize << maxOrder bytes. With these defaults, this results in * chunks of 4 MB. * * @see #MAX_ORDER */ private static final int PAGE_SIZE = 8192; /** * Arenas allocate chunks of pageSize << maxOrder bytes. With these defaults, this results in * chunks of 4 MB, which is smaller than the previous default (16 MB) to further reduce the * netty memory overhead. According to the test result, after introducing client side zero-copy * in FLINK-10742, 4 MB is enough to support large-scale netty shuffle. * * @see #PAGE_SIZE */ private static final int MAX_ORDER = 9; /** * Creates Netty's buffer pool with the specified number of direct arenas. * * @param numberOfArenas Number of arenas (recommended: 2 * number of task slots) */ public NettyBufferPool(int numberOfArenas) { super( PREFER_DIRECT, // No heap arenas, please. 0, // Number of direct arenas. Each arena allocates a chunk of 4 MB, i.e. // we allocate numDirectArenas * 4 MB of direct memory. This can grow // to multiple chunks per arena during runtime, but this should only // happen with a large amount of connections per task manager. We // control the memory allocations with low/high watermarks when writing // to the TCP channels. Chunks are allocated lazily. numberOfArenas, PAGE_SIZE, MAX_ORDER); checkArgument(numberOfArenas >= 1, "Number of arenas"); this.numberOfArenas = numberOfArenas; // Arenas allocate chunks of pageSize << maxOrder bytes. With these // defaults, this results in chunks of 4 MB. this.chunkSize = PAGE_SIZE << MAX_ORDER; Object[] allocDirectArenas = null; try { Field directArenasField = PooledByteBufAllocator.class.getDeclaredField("directArenas"); directArenasField.setAccessible(true); allocDirectArenas = (Object[]) directArenasField.get(this); } catch (Exception ignored) { LOG.warn("Memory statistics not available"); } finally { this.directArenas = allocDirectArenas; } } /** * Returns the number of arenas. * * @return Number of arenas. */ int getNumberOfArenas() { return numberOfArenas; } /** * Returns the chunk size. * * @return Chunk size. */ int getChunkSize() { return chunkSize; } // ------------------------------------------------------------------------ // Direct pool arena stats via Reflection. This is not safe when upgrading // Netty versions, but we are currently bound to the version we have (see // commit d92e422). In newer Netty versions these statistics are exposed. // ------------------------------------------------------------------------ /** * Returns the number of currently allocated bytes. * * <p>The stats are gathered via Reflection and are mostly relevant for debugging purposes. * * @return Number of currently allocated bytes. * @throws NoSuchFieldException Error getting the statistics (should not happen when the Netty * version stays the same). * @throws IllegalAccessException Error getting the statistics (should not happen when the Netty * version stays the same). */ public Optional<Long> getNumberOfAllocatedBytes() throws NoSuchFieldException, IllegalAccessException { if (directArenas != null) { long numChunks = 0; for (Object arena : directArenas) { numChunks += getNumberOfAllocatedChunks(arena, "qInit"); numChunks += getNumberOfAllocatedChunks(arena, "q000"); numChunks += getNumberOfAllocatedChunks(arena, "q025"); numChunks += getNumberOfAllocatedChunks(arena, "q050"); numChunks += getNumberOfAllocatedChunks(arena, "q075"); numChunks += getNumberOfAllocatedChunks(arena, "q100"); } long allocatedBytes = numChunks * chunkSize; return Optional.of(allocatedBytes); } else { return Optional.empty(); } } /** * Returns the number of allocated bytes of the given arena and chunk list. * * @param arena Arena to gather statistics about. * @param chunkListFieldName Chunk list to check. * @return Number of total allocated bytes by this arena. * @throws NoSuchFieldException Error getting the statistics (should not happen when the Netty * version stays the same). * @throws IllegalAccessException Error getting the statistics (should not happen when the Netty * version stays the same). */ private long getNumberOfAllocatedChunks(Object arena, String chunkListFieldName) throws NoSuchFieldException, IllegalAccessException { // Each PoolArena<ByteBuffer> stores its allocated PoolChunk<ByteBuffer> // instances grouped by usage (field qInit, q000, q025, etc.) in // PoolChunkList<ByteBuffer> lists. Each list has zero or more // PoolChunk<ByteBuffer> instances. // Chunk list of arena Field chunkListField = arena.getClass().getSuperclass().getDeclaredField(chunkListFieldName); chunkListField.setAccessible(true); Object chunkList = chunkListField.get(arena); // Count the chunks in the list Field headChunkField = chunkList.getClass().getDeclaredField("head"); headChunkField.setAccessible(true); Object headChunk = headChunkField.get(chunkList); if (headChunk == null) { return 0; } else { int numChunks = 0; Object current = headChunk; while (current != null) { Field nextChunkField = headChunk.getClass().getDeclaredField("next"); nextChunkField.setAccessible(true); current = nextChunkField.get(current); numChunks++; } return numChunks; } } // ------------------------------------------------------------------------ // Fakes heap buffer allocations with direct buffers currently. // ------------------------------------------------------------------------ @Override public ByteBuf heapBuffer() { return directBuffer(); } @Override public ByteBuf heapBuffer(int initialCapacity) { return directBuffer(initialCapacity); } @Override public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) { return directBuffer(initialCapacity, maxCapacity); } @Override public CompositeByteBuf compositeHeapBuffer() { return compositeDirectBuffer(); } @Override public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) { return compositeDirectBuffer(maxNumComponents); } }
NettyBufferPool
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/OneInputStreamTaskTest.java
{ "start": 49597, "end": 49877 }
class ____<T> extends AbstractStreamOperator<T> implements OneInputStreamOperator<T, T> { @Override public void processElement(StreamRecord<T> element) throws Exception { output.collect(element); } } static
PassThroughOperator
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/StreamPartitioner.java
{ "start": 3197, "end": 4041 }
interface ____<K, V> { /** * Determine the number(s) of the partition(s) to which a record with the given key and value should be sent, * for the given topic and current partition count * @param topic the topic name this record is sent to * @param key the key of the record * @param value the value of the record * @param numPartitions the total number of partitions * @return an Optional of Set of integers between 0 and {@code numPartitions-1}, * Empty optional means using default partitioner * Optional of an empty set means the record won't be sent to any partitions i.e drop it. * Optional of Set of integers means the partitions to which the record should be sent to. * */ Optional<Set<Integer>> partitions(String topic, K key, V value, int numPartitions); }
StreamPartitioner
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/internal/ContextBuilder.java
{ "start": 1212, "end": 1866 }
class ____ * is used. * * @return this fluent object */ ContextBuilder withClassLoader(ClassLoader classLoader); /** * Set the {@code closeFuture} to use, when none is specified the Vert.x close future is used. * * @return this fluent object */ ContextBuilder withCloseFuture(CloseFuture closeFuture); /** * Set the {@code workerPool} to use, when none is specified, the default worker pool is assigned. * * @return this fluent object */ ContextBuilder withWorkerPool(WorkerPool workerPool); /** * @return a context using the resources specified in this builder */ ContextInternal build(); }
loader
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TransientOverrideAsPersistentJoinedTests.java
{ "start": 9439, "end": 9841 }
class ____ extends Employee { public Editor(String name, String title) { super( name ); setTitle( title ); } @Column(name = "e_title") public String getTitle() { return super.getTitle(); } public void setTitle(String title) { super.setTitle( title ); } protected Editor() { // this form used by Hibernate super(); } } @Entity(name = "Writer") public static
Editor
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BadImportTest.java
{ "start": 7923, "end": 8053 }
class ____ { // BUG: Diagnostic contains: A.B.Builder builder; Builder builder; static
Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnTypeTest.java
{ "start": 11588, "end": 12514 }
class ____ { ImmutableList<Integer> foo() { if (hashCode() > 0) { return ImmutableList.of(1); } else if (hashCode() < 0) { ImmutableList.Builder<Integer> ints = ImmutableList.builder(); ints.add(2); return ints.build(); } else { List<Integer> ints = Lists.newArrayList(1, 3); ints.add(2); return ImmutableList.copyOf(ints); } } } """) .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void refactoringTreeMap() { refactoringHelper .addInputLines( "Test.java", """ import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.TreeMap; final
Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3609/Issue3609Mapper.java
{ "start": 401, "end": 645 }
class ____ { @SubclassMapping(source = CarDto.class, target = Car.class) @BeanMapping(ignoreUnmappedSourceProperties = "id") public abstract Vehicle toVehicle(VehicleDto vehicle); //CHECKSTYLE:OFF public static
Issue3609Mapper
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/lazyload_common_property/Father.java
{ "start": 720, "end": 1201 }
class ____ { private Integer id; private String name; private GrandFather grandFather; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public GrandFather getGrandFather() { return grandFather; } public void setGrandFather(GrandFather grandFather) { this.grandFather = grandFather; } }
Father
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/TreatKeywordTest.java
{ "start": 12605, "end": 12685 }
class ____ extends Dog { public Greyhound() { super( true ); } } }
Greyhound
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/discovery/TransportAddressConnector.java
{ "start": 623, "end": 935 }
interface ____ { /** * Identify the node at the given address and, if it is a master node and not the local node then establish a full connection to it. */ void connectToRemoteMasterNode(TransportAddress transportAddress, ActionListener<ProbeConnectionResult> listener); }
TransportAddressConnector
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/file/FileAssert_isDirectoryRecursivelyContaining_SyntaxAndPattern_Test.java
{ "start": 907, "end": 1386 }
class ____ extends FileAssertBaseTest { private final String syntaxAndPattern = "glob:*.java"; @Override protected FileAssert invoke_api_method() { return assertions.isDirectoryRecursivelyContaining(syntaxAndPattern); } @Override protected void verify_internal_effects() { verify(files).assertIsDirectoryRecursivelyContaining(getInfo(assertions), getActual(assertions), syntaxAndPattern); } }
FileAssert_isDirectoryRecursivelyContaining_SyntaxAndPattern_Test
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/multipart/support/RequestPartServletServerHttpRequest.java
{ "start": 1782, "end": 4721 }
class ____ extends ServletServerHttpRequest { private final MultipartHttpServletRequest multipartRequest; private final String requestPartName; private final HttpHeaders multipartHeaders; /** * Create a new {@code RequestPartServletServerHttpRequest} instance. * @param request the current servlet request * @param requestPartName the name of the part to adapt to the {@link ServerHttpRequest} contract * @throws MissingServletRequestPartException if the request part cannot be found * @throws MultipartException if MultipartHttpServletRequest cannot be initialized */ public RequestPartServletServerHttpRequest(HttpServletRequest request, String requestPartName) throws MissingServletRequestPartException { super(request); this.multipartRequest = MultipartResolutionDelegate.asMultipartHttpServletRequest(request); this.requestPartName = requestPartName; HttpHeaders multipartHeaders = this.multipartRequest.getMultipartHeaders(requestPartName); if (multipartHeaders == null) { throw new MissingServletRequestPartException(requestPartName); } this.multipartHeaders = multipartHeaders; } @Override public HttpHeaders getHeaders() { return this.multipartHeaders; } @Override public InputStream getBody() throws IOException { // Prefer Servlet Part resolution to cover file as well as parameter streams boolean servletParts = (this.multipartRequest instanceof StandardMultipartHttpServletRequest); if (servletParts) { Part part = retrieveServletPart(); if (part != null) { return part.getInputStream(); } } // Spring-style distinction between MultipartFile and String parameters MultipartFile file = this.multipartRequest.getFile(this.requestPartName); if (file != null) { return file.getInputStream(); } String paramValue = this.multipartRequest.getParameter(this.requestPartName); if (paramValue != null) { return new ByteArrayInputStream(paramValue.getBytes(determineCharset())); } // Fallback: Servlet Part resolution even if not indicated if (!servletParts) { Part part = retrieveServletPart(); if (part != null) { return part.getInputStream(); } } throw new IllegalStateException("No body available for request part '" + this.requestPartName + "'"); } private @Nullable Part retrieveServletPart() { try { return this.multipartRequest.getPart(this.requestPartName); } catch (Exception ex) { throw new MultipartException("Failed to retrieve request part '" + this.requestPartName + "'", ex); } } private Charset determineCharset() { MediaType contentType = getHeaders().getContentType(); if (contentType != null) { Charset charset = contentType.getCharset(); if (charset != null) { return charset; } } String encoding = this.multipartRequest.getCharacterEncoding(); return (encoding != null ? Charset.forName(encoding) : FORM_CHARSET); } }
RequestPartServletServerHttpRequest
java
apache__flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/DataStreamUtils.java
{ "start": 1329, "end": 4505 }
class ____ { // ------------------------------------------------------------------------ // Deriving a KeyedStream from a stream already partitioned by key // without a shuffle // ------------------------------------------------------------------------ /** * Reinterprets the given {@link DataStream} as a {@link KeyedStream}, which extracts keys with * the given {@link KeySelector}. * * <p>IMPORTANT: For every partition of the base stream, the keys of events in the base stream * must be partitioned exactly in the same way as if it was created through a {@link * DataStream#keyBy(KeySelector)}. * * @param stream The data stream to reinterpret. For every partition, this stream must be * partitioned exactly in the same way as if it was created through a {@link * DataStream#keyBy(KeySelector)}. * @param keySelector Function that defines how keys are extracted from the data stream. * @param <T> Type of events in the data stream. * @param <K> Type of the extracted keys. * @return The reinterpretation of the {@link DataStream} as a {@link KeyedStream}. */ public static <T, K> KeyedStream<T, K> reinterpretAsKeyedStream( DataStream<T> stream, KeySelector<T, K> keySelector) { return reinterpretAsKeyedStream( stream, keySelector, TypeExtractor.getKeySelectorTypes(keySelector, stream.getType())); } /** * Reinterprets the given {@link DataStream} as a {@link KeyedStream}, which extracts keys with * the given {@link KeySelector}. * * <p>IMPORTANT: For every partition of the base stream, the keys of events in the base stream * must be partitioned exactly in the same way as if it was created through a {@link * DataStream#keyBy(KeySelector)}. * * @param stream The data stream to reinterpret. For every partition, this stream must be * partitioned exactly in the same way as if it was created through a {@link * DataStream#keyBy(KeySelector)}. * @param keySelector Function that defines how keys are extracted from the data stream. * @param typeInfo Explicit type information about the key type. * @param <T> Type of events in the data stream. * @param <K> Type of the extracted keys. * @return The reinterpretation of the {@link DataStream} as a {@link KeyedStream}. */ public static <T, K> KeyedStream<T, K> reinterpretAsKeyedStream( DataStream<T> stream, KeySelector<T, K> keySelector, TypeInformation<K> typeInfo) { PartitionTransformation<T> partitionTransformation = new PartitionTransformation<>( stream.getTransformation(), new ForwardPartitioner<>()); return new KeyedStream<>(stream, partitionTransformation, keySelector, typeInfo); } // ------------------------------------------------------------------------ /** Private constructor to prevent instantiation. */ private DataStreamUtils() {} // ------------------------------------------------------------------------ }
DataStreamUtils
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/DialectChecks.java
{ "start": 6558, "end": 6718 }
class ____ implements DialectCheck { public boolean isMatch(Dialect dialect) { return dialect.forceLobAsLastValue(); } } public static
ForceLobAsLastValue
java
resilience4j__resilience4j
resilience4j-circuitbreaker/src/main/java/io/github/resilience4j/circuitbreaker/CircuitBreaker.java
{ "start": 43066, "end": 43203 }
class ____ future to add CircuitBreaking functionality around invocation. * * @param <T> of return type */ final
decorates
java
quarkusio__quarkus
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddStatefulSetResourceDecorator.java
{ "start": 658, "end": 3765 }
class ____ extends ResourceProvidingDecorator<KubernetesListFluent<?>> { private final String name; private final PlatformConfiguration config; public AddStatefulSetResourceDecorator(String name, PlatformConfiguration config) { this.name = name; this.config = config; } @Override public void visit(KubernetesListFluent<?> list) { StatefulSetBuilder builder = list.buildItems().stream() .filter(this::containsStatefulSetResource) .map(replaceExistingStatefulSetResource(list)) .findAny() .orElseGet(this::createStatefulSetResource) .accept(StatefulSetBuilder.class, this::initStatefulSetResourceWithDefaults); list.addToItems(builder.build()); } private boolean containsStatefulSetResource(HasMetadata metadata) { return STATEFULSET.equalsIgnoreCase(metadata.getKind()) && name.equals(metadata.getMetadata().getName()); } private void initStatefulSetResourceWithDefaults(StatefulSetBuilder builder) { StatefulSetFluent<?>.SpecNested<StatefulSetBuilder> spec = builder.editOrNewSpec(); spec.editOrNewSelector() .endSelector() .editOrNewTemplate() .editOrNewSpec() .endSpec() .editOrNewMetadata() .endMetadata() .endTemplate(); // defaults for: // - replicas if (spec.getReplicas() == null) { spec.withReplicas(1); } // - service name if (Strings.isNullOrEmpty(spec.getServiceName())) { spec.withServiceName(name); } // - match labels if (spec.buildSelector().getMatchLabels() == null) { spec.editSelector().withMatchLabels(new HashMap<>()).endSelector(); } // - termination grace period seconds if (spec.buildTemplate().getSpec().getTerminationGracePeriodSeconds() == null) { spec.editTemplate().editSpec().withTerminationGracePeriodSeconds(10L).endSpec().endTemplate(); } // - container if (!containsContainerWithName(spec)) { spec.editTemplate().editSpec().addNewContainer().withName(name).endContainer().endSpec().endTemplate(); } spec.endSpec(); } private StatefulSetBuilder createStatefulSetResource() { return new StatefulSetBuilder().withNewMetadata().withName(name).endMetadata(); } private Function<HasMetadata, StatefulSetBuilder> replaceExistingStatefulSetResource(KubernetesListFluent<?> list) { return metadata -> { list.removeFromItems(metadata); return new StatefulSetBuilder((StatefulSet) metadata); }; } private boolean containsContainerWithName(StatefulSetFluent<?>.SpecNested<StatefulSetBuilder> spec) { List<Container> containers = spec.buildTemplate().getSpec().getContainers(); return containers == null || containers.stream().anyMatch(c -> name.equals(c.getName())); } }
AddStatefulSetResourceDecorator
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/FuzzyEnumParamConverterProviderTest.java
{ "start": 3990, "end": 8329 }
class ____ { } private <T> ParamConverter<T> getConverter(Class<T> rawType) { return requireNonNull(paramConverterProvider.getConverter(rawType, null, new Annotation[] {})); } @Test void testFuzzyEnum() { final ParamConverter<Fuzzy> converter = getConverter(Fuzzy.class); assertThat(converter.fromString(null)).isNull(); assertThat(converter.fromString("A.1")).isSameAs(Fuzzy.A_1); assertThat(converter.fromString("A-1")).isSameAs(Fuzzy.A_1); assertThat(converter.fromString("A_1")).isSameAs(Fuzzy.A_1); assertThat(converter.fromString(" A_1")).isSameAs(Fuzzy.A_1); assertThat(converter.fromString("A_1 ")).isSameAs(Fuzzy.A_1); assertThat(converter.fromString("A_2")).isSameAs(Fuzzy.A_2); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> converter.fromString("B")) .matches(e -> e.getResponse().getStatus() == 400) .extracting(Throwable::getMessage) .matches(msg -> msg.contains("A_1")) .matches(msg -> msg.contains("A_2")); } @Test void testToString() { final ParamConverter<WithToString> converter = getConverter(WithToString.class); assertThat(converter.toString(WithToString.A_1)).isEqualTo("<A_1>"); } @Test void testNonEnum() { assertThat(paramConverterProvider.getConverter(Klass.class, null, new Annotation[] {})).isNull(); } @Test void testEnumViaExplicitFromString() { final ParamConverter<ExplicitFromString> converter = getConverter(ExplicitFromString.class); assertThat(converter.fromString("1")).isSameAs(ExplicitFromString.A); assertThat(converter.fromString("2")).isSameAs(ExplicitFromString.B); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> converter.fromString("3")) .matches(e -> e.getResponse().getStatus() == 400) .extracting(Throwable::getMessage) .matches(msg -> msg.contains("is not a valid ExplicitFromString")); } @Test void testEnumViaExplicitFromStringThatThrowsWebApplicationException() { final ParamConverter<ExplicitFromStringThrowsWebApplicationException> converter = getConverter(ExplicitFromStringThrowsWebApplicationException.class); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> converter.fromString("3")) .extracting(e -> e.getResponse().getStatusInfo()) .matches(e -> e.getStatusCode() == 418) .matches(e -> e.getReasonPhrase().contains("I am a teapot")); } @Test void testEnumViaExplicitFromStringThatThrowsOtherException() { final ParamConverter<ExplicitFromStringThrowsOtherException> converter = getConverter(ExplicitFromStringThrowsOtherException.class); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> converter.fromString("1")) .matches(e -> e.getResponse().getStatus() == 400) .extracting(Throwable::getMessage) .matches(msg -> msg.contains("Failed to convert")); } @Test void testEnumViaExplicitFromStringNonStatic() { final ParamConverter<ExplicitFromStringNonStatic> converter = getConverter(ExplicitFromStringNonStatic.class); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> converter.fromString("1")) .matches(e -> e.getResponse().getStatus() == 400) .extracting(Throwable::getMessage) .matches(msg -> msg.contains("A")) .matches(msg -> msg.contains("B")); assertThat(converter.fromString("A")).isSameAs(ExplicitFromStringNonStatic.A); } @Test void testEnumViaExplicitFromStringPrivate() { final ParamConverter<ExplicitFromStringPrivate> converter = getConverter(ExplicitFromStringPrivate.class); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> converter.fromString("1")) .matches(e -> e.getResponse().getStatus() == 400) .extracting(Throwable::getMessage) .matches(msg -> msg.contains("Not permitted to call fromString on ExplicitFromStringPrivate")); } }
Klass
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java
{ "start": 2824, "end": 14795 }
class ____<SB extends SuggestionBuilder<SB>> extends ESTestCase { private static final int NUMBER_OF_TESTBUILDERS = 20; protected static NamedWriteableRegistry namedWriteableRegistry; protected static NamedXContentRegistry xContentRegistry; /** * setup for the whole base test class */ @BeforeClass public static void init() { SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList()); namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables()); xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents()); } @AfterClass public static void afterClass() { namedWriteableRegistry = null; xContentRegistry = null; } /** * Test serialization and deserialization of the suggestion builder */ public void testSerialization() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB original = randomTestBuilder(); SB deserialized = copy(original); assertEquals(deserialized, original); assertEquals(deserialized.hashCode(), original.hashCode()); assertNotSame(deserialized, original); } } /** * returns a random suggestion builder, setting the common options randomly */ protected SB randomTestBuilder() { return randomSuggestionBuilder(); } public static void setCommonPropertiesOnRandomBuilder(SuggestionBuilder<?> randomSuggestion) { randomSuggestion.text(randomAlphaOfLengthBetween(2, 20)); // have to set the text because we don't know if the global text was set maybeSet(randomSuggestion::prefix, randomAlphaOfLengthBetween(2, 20)); maybeSet(randomSuggestion::regex, randomAlphaOfLengthBetween(2, 20)); maybeSet(randomSuggestion::analyzer, randomAlphaOfLengthBetween(2, 20)); maybeSet(randomSuggestion::size, randomIntBetween(1, 20)); maybeSet(randomSuggestion::shardSize, randomIntBetween(1, 20)); } /** * create a randomized {@link SuggestBuilder} that is used in further tests */ protected abstract SB randomSuggestionBuilder(); /** * Test equality and hashCode properties */ public void testEqualsAndHashcode() { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { checkEqualsAndHashCode(randomTestBuilder(), this::copy, this::mutate); } } /** * creates random suggestion builder, renders it to xContent and back to new * instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB suggestionBuilder = randomTestBuilder(); XContentBuilder xContentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { xContentBuilder.prettyPrint(); } xContentBuilder.startObject(); suggestionBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); xContentBuilder.endObject(); XContentBuilder shuffled = shuffleXContent(xContentBuilder, shuffleProtectedFields()); try (XContentParser parser = createParser(shuffled)) { // we need to skip the start object and the name, those will be parsed by outer SuggestBuilder parser.nextToken(); SuggestionBuilder<?> secondSuggestionBuilder = SuggestionBuilder.fromXContent(parser); assertNotSame(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode()); } } } public void testBuild() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB suggestionBuilder = randomTestBuilder(); Settings indexSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()).build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings( new Index(randomAlphaOfLengthBetween(1, 10), "_na_"), indexSettings ); ScriptService scriptService = mock(ScriptService.class); MappedFieldType fieldType = mockFieldType(suggestionBuilder.field()); IndexAnalyzers indexAnalyzers = (type, name) -> new NamedAnalyzer(name, AnalyzerScope.INDEX, new SimpleAnalyzer()); ; MapperService mapperService = mock(MapperService.class); when(mapperService.getIndexAnalyzers()).thenReturn(indexAnalyzers); when(scriptService.compile(any(Script.class), any())).then( invocation -> new TestTemplateService.MockTemplateScript.Factory(((Script) invocation.getArguments()[0]).getIdOrCode()) ); List<FieldMapper> mappers = Collections.singletonList(new MockFieldMapper(fieldType)); MappingLookup lookup = MappingLookup.fromMappers(Mapping.EMPTY, mappers, emptyList()); SearchExecutionContext mockContext = new SearchExecutionContext( 0, 0, idxSettings, null, null, mapperService, lookup, null, scriptService, parserConfig(), namedWriteableRegistry, null, null, System::currentTimeMillis, null, null, () -> true, null, emptyMap(), MapperMetrics.NOOP ); SuggestionContext suggestionContext = suggestionBuilder.build(mockContext); assertEquals(toBytesRef(suggestionBuilder.text()), suggestionContext.getText()); if (suggestionBuilder.text() != null && suggestionBuilder.prefix() == null) { assertEquals(toBytesRef(suggestionBuilder.text()), suggestionContext.getPrefix()); } else { assertEquals(toBytesRef(suggestionBuilder.prefix()), suggestionContext.getPrefix()); } assertEquals(toBytesRef(suggestionBuilder.regex()), suggestionContext.getRegex()); assertEquals(suggestionBuilder.field(), suggestionContext.getField()); int expectedSize = suggestionBuilder.size() != null ? suggestionBuilder.size : 5; assertEquals(expectedSize, suggestionContext.getSize()); Integer expectedShardSize = suggestionBuilder.shardSize != null ? suggestionBuilder.shardSize : Math.max(expectedSize, 5); assertEquals(expectedShardSize, suggestionContext.getShardSize()); assertSame(mockContext, suggestionContext.getSearchExecutionContext()); if (suggestionBuilder.analyzer() != null) { assertEquals(suggestionBuilder.analyzer(), ((NamedAnalyzer) suggestionContext.getAnalyzer()).name()); } else { assertEquals("fieldSearchAnalyzer", ((NamedAnalyzer) suggestionContext.getAnalyzer()).name()); } assertSuggestionContext(suggestionBuilder, suggestionContext); } } public void testBuildWithUnmappedField() { Settings.Builder builder = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()); if (randomBoolean()) { builder.put(IndexSettings.ALLOW_UNMAPPED.getKey(), randomBoolean()); } Settings indexSettings = builder.build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings( new Index(randomAlphaOfLengthBetween(1, 10), "_na_"), indexSettings ); SearchExecutionContext mockContext = new SearchExecutionContext( 0, 0, idxSettings, null, null, mock(MapperService.class), MappingLookup.EMPTY, null, null, parserConfig(), namedWriteableRegistry, null, null, System::currentTimeMillis, null, null, () -> true, null, emptyMap(), MapperMetrics.NOOP ); if (randomBoolean()) { mockContext.setAllowUnmappedFields(randomBoolean()); } SB suggestionBuilder = randomTestBuilder(); IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> suggestionBuilder.build(mockContext)); assertEquals("no mapping found for field [" + suggestionBuilder.field + "]", iae.getMessage()); } /** * put implementation dependent assertions in the sub-type test */ protected abstract void assertSuggestionContext(SB builder, SuggestionContext context) throws IOException; protected MappedFieldType mockFieldType(String fieldName) { MappedFieldType fieldType = mock(MappedFieldType.class); when(fieldType.name()).thenReturn(fieldName.intern()); // intern field name to not trip assertions that ensure all field names are // interned NamedAnalyzer searchAnalyzer = new NamedAnalyzer("fieldSearchAnalyzer", AnalyzerScope.INDEX, new SimpleAnalyzer()); TextSearchInfo tsi = new TextSearchInfo(TextFieldMapper.Defaults.FIELD_TYPE, null, searchAnalyzer, searchAnalyzer); when(fieldType.getTextSearchInfo()).thenReturn(tsi); return fieldType; } /** * Subclasses can override this method and return a set of fields which should be protected from * recursive random shuffling in the {@link #testFromXContent()} test case */ protected String[] shuffleProtectedFields() { return new String[0]; } private SB mutate(SB firstBuilder) throws IOException { SB mutation = copy(firstBuilder); assertNotSame(mutation, firstBuilder); // change ither one of the shared SuggestionBuilder parameters, or delegate to the specific tests mutate method if (randomBoolean()) { switch (randomIntBetween(0, 5)) { case 0 -> mutation.text(randomValueOtherThan(mutation.text(), () -> randomAlphaOfLengthBetween(2, 20))); case 1 -> mutation.prefix(randomValueOtherThan(mutation.prefix(), () -> randomAlphaOfLengthBetween(2, 20))); case 2 -> mutation.regex(randomValueOtherThan(mutation.regex(), () -> randomAlphaOfLengthBetween(2, 20))); case 3 -> mutation.analyzer(randomValueOtherThan(mutation.analyzer(), () -> randomAlphaOfLengthBetween(2, 20))); case 4 -> mutation.size(randomValueOtherThan(mutation.size(), () -> randomIntBetween(1, 20))); case 5 -> mutation.shardSize(randomValueOtherThan(mutation.shardSize(), () -> randomIntBetween(1, 20))); } } else { mutateSpecificParameters(firstBuilder); } return mutation; } /** * take and input {@link SuggestBuilder} and return another one that is * different in one aspect (to test non-equality) */ protected abstract void mutateSpecificParameters(SB firstBuilder) throws IOException; @SuppressWarnings("unchecked") protected SB copy(SB original) throws IOException { return copyWriteable( original, namedWriteableRegistry, (Writeable.Reader<SB>) namedWriteableRegistry.getReader(SuggestionBuilder.class, original.getWriteableName()) ); } @Override protected NamedXContentRegistry xContentRegistry() { return xContentRegistry; } }
AbstractSuggestionBuilderTestCase
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
{ "start": 23311, "end": 24774 }
class ____ search * @param imports the imports collected so far * @param visited used to track visited classes and interfaces to prevent infinite * recursion * @throws IOException if there is any problem reading metadata from the named class */ private void collectImports(SourceClass sourceClass, Set<SourceClass> imports, Set<SourceClass> visited) throws IOException { if (visited.add(sourceClass)) { for (SourceClass ifc : sourceClass.getInterfaces()) { collectImports(ifc, imports, visited); } for (SourceClass annotation : sourceClass.getAnnotations()) { String annName = annotation.getMetadata().getClassName(); if (!annName.equals(Import.class.getName())) { collectImports(annotation, imports, visited); } } imports.addAll(sourceClass.getAnnotationAttributes(Import.class.getName(), "value")); } } private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass, Collection<SourceClass> importCandidates, Predicate<String> filter, boolean checkForCircularImports) { if (importCandidates.isEmpty()) { return; } if (checkForCircularImports && isChainedImportOnStack(configClass)) { this.problemReporter.error(new CircularImportProblem(configClass, this.importStack)); } else { this.importStack.push(configClass); try { for (SourceClass candidate : importCandidates) { if (candidate.isAssignable(ImportSelector.class)) { // Candidate
to
java
google__guice
core/src/com/google/inject/internal/ProviderMethod.java
{ "start": 12312, "end": 14043 }
class ____<T> extends ProviderMethod<T> { final BiFunction<Object, Object[], Object> fastMethod; FastClassProviderMethod( Key<T> key, Method method, Object instance, ImmutableSet<Dependency<?>> dependencies, Class<? extends Annotation> scopeAnnotation, Annotation annotation, BiFunction<Object, Object[], Object> fastMethod) { super(key, method, instance, dependencies, scopeAnnotation, annotation); this.fastMethod = fastMethod; } @SuppressWarnings("unchecked") @Override public T doProvision(Object[] parameters) throws InvocationTargetException { try { return (T) fastMethod.apply(instance, parameters); } catch (Throwable e) { throw new InvocationTargetException(e); // match JDK reflection behaviour } } @Override MethodHandle doProvisionHandle(MethodHandle[] parameters) { // We can hit this case if the method is package private and we are using bytecode gen but // a security manager is installed that blocks access to `setAccessible`. // (Object[]) -> Object var apply = MethodHandles.insertArguments(BIFUNCTION_APPLY_HANDLE.bindTo(fastMethod), 0, instance) // Cast the parameter type to be an Object array .asType(methodType(Object.class, Object[].class)); // (InternalContext) -> Object apply = MethodHandles.filterArguments( apply, 0, InternalMethodHandles.buildObjectArrayFactory(parameters)); return apply; } } /** * A {@link ProviderMethod} implementation that invokes the method using normal java reflection. */ private static final
FastClassProviderMethod
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/actuate/endpoint/web/AbstractWebMvcEndpointHandlerMapping.java
{ "start": 4389, "end": 11702 }
class ____ extends RequestMappingInfoHandlerMapping implements InitializingBean { private final EndpointMapping endpointMapping; private final Collection<ExposableWebEndpoint> endpoints; private final EndpointMediaTypes endpointMediaTypes; private final @Nullable CorsConfiguration corsConfiguration; private final boolean shouldRegisterLinksMapping; private final Method handleMethod = getHandleMethod(); private RequestMappingInfo.BuilderConfiguration builderConfig = new RequestMappingInfo.BuilderConfiguration(); /** * Creates a new {@code WebEndpointHandlerMapping} that provides mappings for the * operations of the given {@code webEndpoints}. * @param endpointMapping the base mapping for all endpoints * @param endpoints the web endpoints * @param endpointMediaTypes media types consumed and produced by the endpoints * @param shouldRegisterLinksMapping whether the links endpoint should be registered */ public AbstractWebMvcEndpointHandlerMapping(EndpointMapping endpointMapping, Collection<ExposableWebEndpoint> endpoints, EndpointMediaTypes endpointMediaTypes, boolean shouldRegisterLinksMapping) { this(endpointMapping, endpoints, endpointMediaTypes, null, shouldRegisterLinksMapping); } /** * Creates a new {@code AbstractWebMvcEndpointHandlerMapping} that provides mappings * for the operations of the given endpoints. * @param endpointMapping the base mapping for all endpoints * @param endpoints the web endpoints * @param endpointMediaTypes media types consumed and produced by the endpoints * @param corsConfiguration the CORS configuration for the endpoints or {@code null} * @param shouldRegisterLinksMapping whether the links endpoint should be registered */ public AbstractWebMvcEndpointHandlerMapping(EndpointMapping endpointMapping, Collection<ExposableWebEndpoint> endpoints, EndpointMediaTypes endpointMediaTypes, @Nullable CorsConfiguration corsConfiguration, boolean shouldRegisterLinksMapping) { this.endpointMapping = endpointMapping; this.endpoints = endpoints; this.endpointMediaTypes = endpointMediaTypes; this.corsConfiguration = corsConfiguration; this.shouldRegisterLinksMapping = shouldRegisterLinksMapping; setOrder(-100); } private static Method getHandleMethod() { Method method = ReflectionUtils.findMethod(OperationHandler.class, "handle", HttpServletRequest.class, Map.class); Assert.state(method != null, "'method' must not be null"); return method; } @Override public void afterPropertiesSet() { this.builderConfig = new RequestMappingInfo.BuilderConfiguration(); this.builderConfig.setPatternParser(getPatternParser()); super.afterPropertiesSet(); } @Override protected void initHandlerMethods() { for (ExposableWebEndpoint endpoint : this.endpoints) { for (WebOperation operation : endpoint.getOperations()) { registerMappingForOperation(endpoint, operation); } } if (this.shouldRegisterLinksMapping) { registerLinksMapping(); } } @Override protected HandlerMethod createHandlerMethod(Object handler, Method method) { HandlerMethod handlerMethod = super.createHandlerMethod(handler, method); return new WebMvcEndpointHandlerMethod(handlerMethod.getBean(), handlerMethod.getMethod()); } private void registerMappingForOperation(ExposableWebEndpoint endpoint, WebOperation operation) { WebOperationRequestPredicate predicate = operation.getRequestPredicate(); String path = predicate.getPath(); String matchAllRemainingPathSegmentsVariable = predicate.getMatchAllRemainingPathSegmentsVariable(); if (matchAllRemainingPathSegmentsVariable != null) { path = path.replace("{*" + matchAllRemainingPathSegmentsVariable + "}", "**"); } registerMapping(endpoint, predicate, operation, path); } protected void registerMapping(ExposableWebEndpoint endpoint, WebOperationRequestPredicate predicate, WebOperation operation, String path) { ServletWebOperation servletWebOperation = wrapServletWebOperation(endpoint, operation, new ServletWebOperationAdapter(operation)); registerMapping(createRequestMappingInfo(predicate, path), new OperationHandler(servletWebOperation), this.handleMethod); } /** * Hook point that allows subclasses to wrap the {@link ServletWebOperation} before * it's called. Allows additional features, such as security, to be added. * @param endpoint the source endpoint * @param operation the source operation * @param servletWebOperation the servlet web operation to wrap * @return a wrapped servlet web operation */ protected ServletWebOperation wrapServletWebOperation(ExposableWebEndpoint endpoint, WebOperation operation, ServletWebOperation servletWebOperation) { return servletWebOperation; } private RequestMappingInfo createRequestMappingInfo(WebOperationRequestPredicate predicate, String path) { String subPath = this.endpointMapping.createSubPath(path); List<String> paths = new ArrayList<>(); paths.add(subPath); if (!StringUtils.hasLength(subPath)) { paths.add("/"); } return RequestMappingInfo.paths(paths.toArray(new String[0])) .options(this.builderConfig) .methods(RequestMethod.valueOf(predicate.getHttpMethod().name())) .consumes(predicate.getConsumes().toArray(new String[0])) .produces(predicate.getProduces().toArray(new String[0])) .build(); } private void registerLinksMapping() { String path = this.endpointMapping.getPath(); String linksPath = (StringUtils.hasLength(path)) ? this.endpointMapping.createSubPath("/") : "/"; RequestMappingInfo mapping = RequestMappingInfo.paths(linksPath) .methods(RequestMethod.GET) .produces(this.endpointMediaTypes.getProduced().toArray(new String[0])) .options(this.builderConfig) .build(); LinksHandler linksHandler = getLinksHandler(); Method links = ReflectionUtils.findMethod(linksHandler.getClass(), "links", HttpServletRequest.class, HttpServletResponse.class); Assert.state(links != null, "'links' must not be null"); registerMapping(mapping, linksHandler, links); } @Override protected boolean hasCorsConfigurationSource(Object handler) { return this.corsConfiguration != null; } @Override protected @Nullable CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mapping) { return this.corsConfiguration; } @Override protected @Nullable CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request); return (corsConfiguration != null) ? corsConfiguration : this.corsConfiguration; } @Override protected boolean isHandler(Class<?> beanType) { return false; } @Override protected @Nullable RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { return null; } /** * Return the Handler providing actuator links at the root endpoint. * @return the links handler */ protected abstract LinksHandler getLinksHandler(); /** * Return the web endpoints being mapped. * @return the endpoints */ public Collection<ExposableWebEndpoint> getEndpoints() { return this.endpoints; } /** * Handler providing actuator links at the root endpoint. */ @FunctionalInterface protected
AbstractWebMvcEndpointHandlerMapping
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/endpoints/NoOnOpenOrOnMessageInSubEndpointTest.java
{ "start": 1092, "end": 1258 }
class ____ { @OnClose public void onClose() { // Ignored. } } } }
SubEndpointWithoutOnOpenAndOnMessage
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/literal/QueryLiteralTest.java
{ "start": 9137, "end": 11016 }
class ____ { @Id @GeneratedValue private Integer id; private Letter letterOrdinal; @Enumerated(EnumType.STRING) private Letter letterString; private Numbers numbersImplicit; @Convert(converter = NumberStringConverter.class) private Numbers numbersImplicitOverridden; private IntegerWrapper integerWrapper; private StringWrapper stringWrapper; @Convert(converter = PreFixedStringConverter.class) @Column(name = "same_type_converter") private String sameTypeConverter; public Integer getId() { return id; } public Letter getLetterOrdinal() { return letterOrdinal; } public void setLetterOrdinal(Letter letterOrdinal) { this.letterOrdinal = letterOrdinal; } public Letter getLetterString() { return letterString; } public void setLetterString(Letter letterString) { this.letterString = letterString; } public Numbers getNumbersImplicit() { return numbersImplicit; } public void setNumbersImplicit(Numbers numbersImplicit) { this.numbersImplicit = numbersImplicit; } public Numbers getNumbersImplicitOverridden() { return numbersImplicitOverridden; } public void setNumbersImplicitOverridden(Numbers numbersImplicitOverridden) { this.numbersImplicitOverridden = numbersImplicitOverridden; } public IntegerWrapper getIntegerWrapper() { return integerWrapper; } public void setIntegerWrapper(IntegerWrapper integerWrapper) { this.integerWrapper = integerWrapper; } public StringWrapper getStringWrapper() { return stringWrapper; } public void setStringWrapper(StringWrapper stringWrapper) { this.stringWrapper = stringWrapper; } public String getSameTypeConverter() { return sameTypeConverter; } public void setSameTypeConverter(String sameTypeConverter) { this.sameTypeConverter = sameTypeConverter; } } public static
EntityConverter
java
apache__flink
flink-metrics/flink-metrics-datadog/src/main/java/org/apache/flink/metrics/datadog/MetricType.java
{ "start": 899, "end": 1086 }
enum ____ { /** * Names of 'gauge' and 'count' must not be changed since they are mapped to json objects in a * Datadog-defined format. */ gauge, count }
MetricType
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/container/RebalanceLockOnSlaveIT.java
{ "start": 1877, "end": 9537 }
class ____ extends ContainerIntegrationTestBase { private static final String THREE_REPLICA_CONSUMER_GROUP = "SyncConsumerOffsetIT_ConsumerThreeReplica"; private static DefaultMQProducer mqProducer; private static DefaultMQPushConsumer mqConsumerThreeReplica1; private static DefaultMQPushConsumer mqConsumerThreeReplica2; private static DefaultMQPushConsumer mqConsumerThreeReplica3; public RebalanceLockOnSlaveIT() { } @BeforeClass public static void beforeClass() throws Exception { mqProducer = createProducer("SyncConsumerOffsetIT_Producer"); mqProducer.start(); mqConsumerThreeReplica1 = createPushConsumer(THREE_REPLICA_CONSUMER_GROUP); mqConsumerThreeReplica1.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); mqConsumerThreeReplica1.subscribe(THREE_REPLICAS_TOPIC, "*"); mqConsumerThreeReplica2 = createPushConsumer(THREE_REPLICA_CONSUMER_GROUP); mqConsumerThreeReplica2.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); mqConsumerThreeReplica2.subscribe(THREE_REPLICAS_TOPIC, "*"); mqConsumerThreeReplica3 = createPushConsumer(THREE_REPLICA_CONSUMER_GROUP); mqConsumerThreeReplica3.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); mqConsumerThreeReplica3.subscribe(THREE_REPLICAS_TOPIC, "*"); } @AfterClass public static void afterClass() { if (mqProducer != null) { mqProducer.shutdown(); } } @Test public void lockFromSlave() throws Exception { awaitUntilSlaveOK(); mqConsumerThreeReplica3.registerMessageListener((MessageListenerOrderly) (msgs, context) -> ConsumeOrderlyStatus.SUCCESS); mqConsumerThreeReplica3.start(); final Set<MessageQueue> mqSet = mqConsumerThreeReplica3.fetchSubscribeMessageQueues(THREE_REPLICAS_TOPIC); assertThat(targetTopicMqCount(mqSet, THREE_REPLICAS_TOPIC)).isEqualTo(24); for (MessageQueue mq : mqSet) { await().atMost(Duration.ofSeconds(60)).until(() -> mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getRebalanceImpl().lock(mq)); } isolateBroker(master3With3Replicas); mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getmQClientFactory().updateTopicRouteInfoFromNameServer(THREE_REPLICAS_TOPIC); FindBrokerResult result = mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getmQClientFactory().findBrokerAddressInSubscribe( master3With3Replicas.getBrokerConfig().getBrokerName(), MixAll.MASTER_ID, true); assertThat(result).isNotNull(); for (MessageQueue mq : mqSet) { if (mq.getBrokerName().equals(master3With3Replicas.getBrokerConfig().getBrokerName())) { await().atMost(Duration.ofSeconds(60)).until(() -> mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getRebalanceImpl().lock(mq)); } } removeSlaveBroker(1, brokerContainer1, master3With3Replicas); assertThat(brokerContainer1.getSlaveBrokers().size()).isEqualTo(1); mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getmQClientFactory().updateTopicRouteInfoFromNameServer(THREE_REPLICAS_TOPIC); for (MessageQueue mq : mqSet) { if (mq.getBrokerName().equals(master3With3Replicas.getBrokerConfig().getBrokerName())) { await().atMost(Duration.ofSeconds(60)).until(() -> !mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getRebalanceImpl().lock(mq)); } } cancelIsolatedBroker(master3With3Replicas); createAndAddSlave(1, brokerContainer1, master3With3Replicas); awaitUntilSlaveOK(); mqConsumerThreeReplica3.shutdown(); await().atMost(100, TimeUnit.SECONDS).until(() -> mqConsumerThreeReplica3.getDefaultMQPushConsumerImpl().getServiceState() == ServiceState.SHUTDOWN_ALREADY); } @Ignore @Test public void multiConsumerLockFromSlave() throws MQClientException, InterruptedException { awaitUntilSlaveOK(); mqConsumerThreeReplica1.registerMessageListener((MessageListenerOrderly) (msgs, context) -> ConsumeOrderlyStatus.SUCCESS); mqConsumerThreeReplica1.start(); mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().doRebalance(); Set<MessageQueue> mqSet1 = filterMessageQueue(mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().getRebalanceImpl().getProcessQueueTable().keySet(), THREE_REPLICAS_TOPIC); assertThat(mqSet1.size()).isEqualTo(24); isolateBroker(master3With3Replicas); System.out.printf("%s isolated%n", master3With3Replicas.getBrokerConfig().getCanonicalName()); Thread.sleep(5000); mqConsumerThreeReplica2.registerMessageListener((MessageListenerOrderly) (msgs, context) -> ConsumeOrderlyStatus.SUCCESS); mqConsumerThreeReplica2.start(); Thread.sleep(5000); mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().getmQClientFactory().updateTopicRouteInfoFromNameServer(THREE_REPLICAS_TOPIC); mqConsumerThreeReplica2.getDefaultMQPushConsumerImpl().getmQClientFactory().updateTopicRouteInfoFromNameServer(THREE_REPLICAS_TOPIC); assertThat(mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().getmQClientFactory().findBrokerAddressInSubscribe( master3With3Replicas.getBrokerConfig().getBrokerName(), MixAll.MASTER_ID, true)).isNotNull(); mqConsumerThreeReplica2.getDefaultMQPushConsumerImpl().getmQClientFactory().findBrokerAddressInSubscribe( master3With3Replicas.getBrokerConfig().getBrokerName(), MixAll.MASTER_ID, true); assertThat(mqConsumerThreeReplica2.getDefaultMQPushConsumerImpl().getmQClientFactory().findBrokerAddressInSubscribe( master3With3Replicas.getBrokerConfig().getBrokerName(), MixAll.MASTER_ID, true)).isNotNull(); mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().doRebalance(); mqConsumerThreeReplica2.getDefaultMQPushConsumerImpl().doRebalance(); Set<MessageQueue> mqSet2 = filterMessageQueue(mqConsumerThreeReplica2.getDefaultMQPushConsumerImpl().getRebalanceImpl().getProcessQueueTable().keySet(), THREE_REPLICAS_TOPIC); mqSet1 = filterMessageQueue(mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().getRebalanceImpl().getProcessQueueTable().keySet(), THREE_REPLICAS_TOPIC); List<MessageQueue> mqList = new ArrayList<>(); for (MessageQueue mq : mqSet2) { if (mq.getTopic().equals(THREE_REPLICAS_TOPIC)) { mqList.add(mq); } } for (MessageQueue mq : mqSet1) { if (mq.getTopic().equals(THREE_REPLICAS_TOPIC)) { mqList.add(mq); } } await().atMost(Duration.ofSeconds(30)).until(() -> mqList.size() == 24); cancelIsolatedBroker(master3With3Replicas); awaitUntilSlaveOK(); mqConsumerThreeReplica1.shutdown(); mqConsumerThreeReplica2.shutdown(); await().atMost(100, TimeUnit.SECONDS).until(() -> mqConsumerThreeReplica1.getDefaultMQPushConsumerImpl().getServiceState() == ServiceState.SHUTDOWN_ALREADY && mqConsumerThreeReplica2.getDefaultMQPushConsumerImpl().getServiceState() == ServiceState.SHUTDOWN_ALREADY ); } private static int targetTopicMqCount(Set<MessageQueue> mqSet, String topic) { int count = 0; for (MessageQueue mq : mqSet) { if (mq.getTopic().equals(topic)) { count++; } } return count; } }
RebalanceLockOnSlaveIT
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/AclStorage.java
{ "start": 2949, "end": 3140 }
class ____ that input ACL entry lists have already been * validated and sorted according to the rules enforced by * {@link AclTransformation}. */ @InterfaceAudience.Private public final
assume
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/generics/ErroneousSourceTargetMapper3.java
{ "start": 316, "end": 524 }
interface ____ { ErroneousSourceTargetMapper3 INSTANCE = Mappers.getMapper( ErroneousSourceTargetMapper3.class ); ErroneousTarget3 sourceToTarget(ErroneousSource3 source); }
ErroneousSourceTargetMapper3
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 269483, "end": 269667 }
class ____ extends ReflectiveIndexAccessor { ColorsIndexAccessor() { super(Colors.class, int.class, "get", "set"); } } /** * Type that can be indexed by an
ColorsIndexAccessor
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/DeprecationRoleDescriptorConsumerTests.java
{ "start": 1608, "end": 20311 }
class ____ extends ESTestCase { private ThreadPool threadPool; @Before public void init() throws Exception { this.threadPool = mock(ThreadPool.class); ExecutorService executorService = mock(ExecutorService.class); Mockito.doAnswer((Answer) invocation -> { final Runnable arg0 = (Runnable) invocation.getArguments()[0]; arg0.run(); return null; }).when(executorService).execute(Mockito.isA(Runnable.class)); when(threadPool.generic()).thenReturn(executorService); when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); } public void testSimpleAliasAndIndexPair() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index", "alias"); final RoleDescriptor roleOverAlias = new RoleDescriptor( "roleOverAlias", new String[] { "read" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges(randomFrom("read", "write", "delete", "index"), "alias") }, null ); final RoleDescriptor roleOverIndex = new RoleDescriptor( "roleOverIndex", new String[] { "manage" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges(randomFrom("read", "write", "delete", "index"), "index") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(roleOverAlias, roleOverIndex)); verifyLogger(deprecationLogger, "roleOverAlias", "alias", "index"); verifyNoMoreInteractions(deprecationLogger); } public void testRoleGrantsOnIndexAndAliasPair() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index", "alias"); addIndex(projectBuilder, "index1", "alias2"); final RoleDescriptor roleOverIndexAndAlias = new RoleDescriptor( "roleOverIndexAndAlias", new String[] { "manage_watcher" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges(randomFrom("read", "write", "delete", "index"), "index", "alias") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(roleOverIndexAndAlias)); verifyNoMoreInteractions(deprecationLogger); } public void testMultiplePrivilegesLoggedOnce() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index", "alias"); addIndex(projectBuilder, "index2", "alias2"); final RoleDescriptor roleOverAlias = new RoleDescriptor( "roleOverAlias", new String[] { "manage_watcher" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("write", "alias"), indexPrivileges("manage_ilm", "alias") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(roleOverAlias)); verifyLogger(deprecationLogger, "roleOverAlias", "alias", "index"); verifyNoMoreInteractions(deprecationLogger); } public void testMultiplePrivilegesLoggedForEachAlias() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index", "alias", "alias3"); addIndex(projectBuilder, "index2", "alias2", "alias", "alias4"); addIndex(projectBuilder, "index3", "alias3", "alias"); addIndex(projectBuilder, "index4", "alias4", "alias"); addIndex(projectBuilder, "foo", "bar"); final RoleDescriptor roleMultiplePrivileges = new RoleDescriptor( "roleMultiplePrivileges", new String[] { "manage_watcher" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("write", "index2", "alias"), indexPrivileges("read", "alias4"), indexPrivileges("delete_index", "alias3", "index"), indexPrivileges("create_index", "alias3", "index3") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(roleMultiplePrivileges)); verifyLogger(deprecationLogger, "roleMultiplePrivileges", "alias", "index, index3, index4"); verifyLogger(deprecationLogger, "roleMultiplePrivileges", "alias4", "index2, index4"); verifyNoMoreInteractions(deprecationLogger); } public void testPermissionsOverlapping() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index1", "alias1", "bar"); addIndex(projectBuilder, "index2", "alias2", "baz"); addIndex(projectBuilder, "foo", "bar"); final RoleDescriptor roleOverAliasAndIndex = new RoleDescriptor( "roleOverAliasAndIndex", new String[] { "read_ilm" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("monitor", "index2", "alias1"), indexPrivileges("monitor", "index1", "alias2") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(roleOverAliasAndIndex)); verifyNoMoreInteractions(deprecationLogger); } public void testOverlappingAcrossMultipleRoleDescriptors() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index1", "alias1", "bar"); addIndex(projectBuilder, "index2", "alias2", "baz"); addIndex(projectBuilder, "foo", "bar"); final RoleDescriptor role1 = new RoleDescriptor( "role1", new String[] { "monitor_watcher" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("monitor", "index2", "alias1") }, null ); final RoleDescriptor role2 = new RoleDescriptor( "role2", new String[] { "read_ccr" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("monitor", "index1", "alias2") }, null ); final RoleDescriptor role3 = new RoleDescriptor( "role3", new String[] { "monitor_ml" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("index", "bar") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(role1, role2, role3)); verifyLogger(deprecationLogger, "role1", "alias1", "index1"); verifyLogger(deprecationLogger, "role2", "alias2", "index2"); verifyLogger(deprecationLogger, "role3", "bar", "foo, index1"); verifyNoMoreInteractions(deprecationLogger); } public void testDailyRoleCaching() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index1", "alias1", "far"); addIndex(projectBuilder, "index2", "alias2", "baz"); addIndex(projectBuilder, "foo", "bar"); RoleDescriptor someRole = new RoleDescriptor( "someRole", new String[] { "monitor_rollup" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("monitor", "i*", "bar") }, null ); final DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); final String cacheKeyBefore = DeprecationRoleDescriptorConsumer.buildCacheKey(someRole); deprecationConsumer.accept(Arrays.asList(someRole)); verifyLogger(deprecationLogger, "someRole", "bar", "foo"); verifyNoMoreInteractions(deprecationLogger); deprecationConsumer.accept(Arrays.asList(someRole)); final String cacheKeyAfter = DeprecationRoleDescriptorConsumer.buildCacheKey(someRole); // we don't do this test if it crosses days if (false == cacheKeyBefore.equals(cacheKeyAfter)) { return; } verifyNoMoreInteractions(deprecationLogger); RoleDescriptor differentRoleSameName = new RoleDescriptor( "someRole", new String[] { "manage_pipeline" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("write", "i*", "baz") }, null ); deprecationConsumer.accept(Arrays.asList(differentRoleSameName)); final String cacheKeyAfterParty = DeprecationRoleDescriptorConsumer.buildCacheKey(differentRoleSameName); // we don't do this test if it crosses days if (false == cacheKeyBefore.equals(cacheKeyAfterParty)) { return; } verifyNoMoreInteractions(deprecationLogger); } public void testWildcards() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index", "alias", "alias3"); addIndex(projectBuilder, "index2", "alias", "alias2", "alias4"); addIndex(projectBuilder, "index3", "alias", "alias3"); addIndex(projectBuilder, "index4", "alias", "alias4"); addIndex(projectBuilder, "foo", "bar", "baz"); final RoleDescriptor roleGlobalWildcard = new RoleDescriptor( "roleGlobalWildcard", new String[] { "manage_token" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges(randomFrom("write", "delete_index", "read_cross_cluster"), "*") }, null ); final ClusterService clusterService = mockClusterService(projectBuilder); final ProjectResolver projectResolver = TestProjectResolvers.singleProject(projectBuilder.getId()); new DeprecationRoleDescriptorConsumer(clusterService, projectResolver, threadPool, deprecationLogger).accept( Arrays.asList(roleGlobalWildcard) ); verifyNoMoreInteractions(deprecationLogger); final RoleDescriptor roleGlobalWildcard2 = new RoleDescriptor( "roleGlobalWildcard2", new String[] { "manage_index_templates" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges(randomFrom("write", "delete_index", "read_cross_cluster"), "i*", "a*") }, null ); new DeprecationRoleDescriptorConsumer(clusterService, projectResolver, threadPool, deprecationLogger).accept( Arrays.asList(roleGlobalWildcard2) ); verifyNoMoreInteractions(deprecationLogger); final RoleDescriptor roleWildcardOnIndices = new RoleDescriptor( "roleWildcardOnIndices", new String[] { "manage_watcher" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("write", "index*", "alias", "alias3"), indexPrivileges("read", "foo") }, null ); new DeprecationRoleDescriptorConsumer(clusterService, projectResolver, threadPool, deprecationLogger).accept( Arrays.asList(roleWildcardOnIndices) ); verifyNoMoreInteractions(deprecationLogger); final RoleDescriptor roleWildcardOnAliases = new RoleDescriptor( "roleWildcardOnAliases", new String[] { "manage_watcher" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("write", "alias*", "index", "index3"), indexPrivileges("read", "foo", "index2") }, null ); new DeprecationRoleDescriptorConsumer(clusterService, projectResolver, threadPool, deprecationLogger).accept( Arrays.asList(roleWildcardOnAliases) ); verifyLogger(deprecationLogger, "roleWildcardOnAliases", "alias", "index2, index4"); verifyLogger(deprecationLogger, "roleWildcardOnAliases", "alias2", "index2"); verifyLogger(deprecationLogger, "roleWildcardOnAliases", "alias4", "index2, index4"); verifyNoMoreInteractions(deprecationLogger); } public void testMultipleIndicesSameAlias() throws Exception { final DeprecationLogger deprecationLogger = mock(DeprecationLogger.class); final ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(randomProjectIdOrDefault()); addIndex(projectBuilder, "index1", "alias1"); addIndex(projectBuilder, "index2", "alias1", "alias2"); addIndex(projectBuilder, "index3", "alias2"); final RoleDescriptor roleOverAliasAndIndex = new RoleDescriptor( "roleOverAliasAndIndex", new String[] { "manage_ml" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("delete_index", "alias1", "index1") }, null ); DeprecationRoleDescriptorConsumer deprecationConsumer = new DeprecationRoleDescriptorConsumer( mockClusterService(projectBuilder), TestProjectResolvers.singleProject(projectBuilder.getId()), threadPool, deprecationLogger ); deprecationConsumer.accept(Arrays.asList(roleOverAliasAndIndex)); verifyLogger(deprecationLogger, "roleOverAliasAndIndex", "alias1", "index2"); verifyNoMoreInteractions(deprecationLogger); final RoleDescriptor roleOverAliases = new RoleDescriptor( "roleOverAliases", new String[] { "manage_security" }, new RoleDescriptor.IndicesPrivileges[] { indexPrivileges("monitor", "alias1", "alias2") }, null ); deprecationConsumer.accept(Arrays.asList(roleOverAliases)); verifyLogger(deprecationLogger, "roleOverAliases", "alias1", "index1, index2"); verifyLogger(deprecationLogger, "roleOverAliases", "alias2", "index2, index3"); verifyNoMoreInteractions(deprecationLogger); } private void addIndex(ProjectMetadata.Builder projectBuilder, String index, String... aliases) { final IndexMetadata.Builder indexprojectBuilder = IndexMetadata.builder(index) .settings(Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersionUtils.randomVersion())) .numberOfShards(1) .numberOfReplicas(1); for (final String alias : aliases) { indexprojectBuilder.putAlias(AliasMetadata.builder(alias).build()); } projectBuilder.put(indexprojectBuilder.build(), false); } private ClusterService mockClusterService(ProjectMetadata.Builder project) { final ClusterService clusterService = mock(ClusterService.class); final ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).metadata(Metadata.builder().put(project)).build(); when(clusterService.state()).thenReturn(clusterState); return clusterService; } private RoleDescriptor.IndicesPrivileges indexPrivileges(String priv, String... indicesOrAliases) { return RoleDescriptor.IndicesPrivileges.builder() .indices(indicesOrAliases) .privileges(priv) .grantedFields(randomArray(0, 2, String[]::new, () -> randomBoolean() ? null : randomAlphaOfLengthBetween(1, 4))) .query(randomBoolean() ? null : "{ }") .build(); } private void verifyLogger(DeprecationLogger deprecationLogger, String roleName, String aliasName, String indexNames) { verify(deprecationLogger).warn( DeprecationCategory.SECURITY, "index_permissions_on_alias", "Role [" + roleName + "] contains index privileges covering the [" + aliasName + "] alias but which do not cover some of the indices that it points to [" + indexNames + "]. Granting privileges over an" + " alias and hence granting privileges over all the indices that the alias points to is deprecated and will be removed" + " in a future version of Elasticsearch. Instead define permissions exclusively on index names or index name patterns." ); } }
DeprecationRoleDescriptorConsumerTests
java
elastic__elasticsearch
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/MergedGeoLines.java
{ "start": 7207, "end": 7458 }
class ____ not overlapping * and as such we do not need to perform a merge-sort, and instead can simply concatenate ordered lines. * The final result is either truncated or simplified based on the simplify parameter. */ static final
are
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/LocalStateMachineLearningNlpOnly.java
{ "start": 527, "end": 821 }
class ____ extends LocalStateMachineLearning { public LocalStateMachineLearningNlpOnly(final Settings settings, final Path configPath) { super(settings, configPath, new MlTestExtensionLoader(new MlTestExtension(true, true, false, false, true))); } }
LocalStateMachineLearningNlpOnly
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/GuiceNestedCombineTest.java
{ "start": 7143, "end": 7758 }
class ____ extends AbstractModule {} public void test() { foo(new ModuleA(), Modules.combine(new ModuleB(), new ModuleC())); } public void foo(Module a, Module b) {} } """) .expectUnchanged() .doTest(); } @Test public void partialVarargs_collapsed() { refactoringTestHelper .addInputLines( "Test.java", """ import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.util.Modules;
ModuleC
java
quarkusio__quarkus
extensions/mailer/runtime/src/test/java/io/quarkus/mailer/runtime/FakeSmtpTestBase.java
{ "start": 4506, "end": 5119 }
class ____ implements MailersRuntimeConfig { private DefaultMailerRuntimeConfig defaultMailerRuntimeConfig; DefaultMailersRuntimeConfig() { this(new DefaultMailerRuntimeConfig()); } DefaultMailersRuntimeConfig(DefaultMailerRuntimeConfig defaultMailerRuntimeConfig) { this.defaultMailerRuntimeConfig = defaultMailerRuntimeConfig; } @Override public Map<String, MailerRuntimeConfig> mailers() { return Map.of(Mailers.DEFAULT_MAILER_NAME, defaultMailerRuntimeConfig); } } static
DefaultMailersRuntimeConfig
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/FactoryUtil.java
{ "start": 57524, "end": 59050 }
class ____ implements ModelProviderFactory.Context { private final ObjectIdentifier objectIdentifier; private final ResolvedCatalogModel catalogModel; private final ReadableConfig configuration; private final ClassLoader classLoader; private final boolean isTemporary; public DefaultModelProviderContext( ObjectIdentifier objectIdentifier, ResolvedCatalogModel catalogModel, ReadableConfig configuration, ClassLoader classLoader, boolean isTemporary) { this.objectIdentifier = objectIdentifier; this.catalogModel = catalogModel; this.configuration = configuration; this.classLoader = classLoader; this.isTemporary = isTemporary; } @Override public ObjectIdentifier getObjectIdentifier() { return objectIdentifier; } @Override public ResolvedCatalogModel getCatalogModel() { return catalogModel; } @Override public ReadableConfig getConfiguration() { return configuration; } @Override public ClassLoader getClassLoader() { return classLoader; } @Override public boolean isTemporary() { return isTemporary; } } /** Default implementation of {@link DynamicTableFactory.Context}. */ @Internal public static
DefaultModelProviderContext
java
apache__flink
flink-table/flink-table-api-java-bridge/src/main/java/org/apache/flink/table/connector/sink/legacy/SinkFunctionProvider.java
{ "start": 1348, "end": 1530 }
interface ____ based on the {@link SinkFunction} API, which is due to be removed. * Use {@link org.apache.flink.table.connector.sink.SinkV2Provider} instead. */ @Internal public
is
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-cos/src/main/java/org/apache/hadoop/fs/cosn/CosNInputStream.java
{ "start": 1758, "end": 9998 }
class ____ { public static final int INIT = 1; public static final int SUCCESS = 0; public static final int ERROR = -1; private final ReentrantLock lock = new ReentrantLock(); private Condition readyCondition = lock.newCondition(); private byte[] buffer; private int status; private long start; private long end; public ReadBuffer(long start, long end) { this.start = start; this.end = end; this.buffer = new byte[(int) (this.end - this.start) + 1]; this.status = INIT; } public void lock() { this.lock.lock(); } public void unLock() { this.lock.unlock(); } public void await(int waitStatus) throws InterruptedException { while (this.status == waitStatus) { readyCondition.await(); } } public void signalAll() { readyCondition.signalAll(); } public byte[] getBuffer() { return this.buffer; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public long getStart() { return start; } public long getEnd() { return end; } } private FileSystem.Statistics statistics; private final Configuration conf; private final NativeFileSystemStore store; private final String key; private long position = 0; private long nextPos = 0; private long fileSize; private long partRemaining; private final long preReadPartSize; private final int maxReadPartNumber; private byte[] buffer; private boolean closed; private final ExecutorService readAheadExecutorService; private final Queue<ReadBuffer> readBufferQueue; public CosNInputStream(Configuration conf, NativeFileSystemStore store, FileSystem.Statistics statistics, String key, long fileSize, ExecutorService readAheadExecutorService) { super(); this.conf = conf; this.store = store; this.statistics = statistics; this.key = key; this.fileSize = fileSize; this.preReadPartSize = conf.getLong( CosNConfigKeys.READ_AHEAD_BLOCK_SIZE_KEY, CosNConfigKeys.DEFAULT_READ_AHEAD_BLOCK_SIZE); this.maxReadPartNumber = conf.getInt( CosNConfigKeys.READ_AHEAD_QUEUE_SIZE, CosNConfigKeys.DEFAULT_READ_AHEAD_QUEUE_SIZE); this.readAheadExecutorService = readAheadExecutorService; this.readBufferQueue = new ArrayDeque<>(this.maxReadPartNumber); this.closed = false; } private synchronized void reopen(long pos) throws IOException { long partSize; if (pos < 0) { throw new EOFException(FSExceptionMessages.NEGATIVE_SEEK); } else if (pos > this.fileSize) { throw new EOFException(FSExceptionMessages.CANNOT_SEEK_PAST_EOF); } else { if (pos + this.preReadPartSize > this.fileSize) { partSize = this.fileSize - pos; } else { partSize = this.preReadPartSize; } } this.buffer = null; boolean isRandomIO = true; if (pos == this.nextPos) { isRandomIO = false; } else { while (this.readBufferQueue.size() != 0) { if (this.readBufferQueue.element().getStart() != pos) { this.readBufferQueue.poll(); } else { break; } } } this.nextPos = pos + partSize; int currentBufferQueueSize = this.readBufferQueue.size(); long lastByteStart; if (currentBufferQueueSize == 0) { lastByteStart = pos - partSize; } else { ReadBuffer[] readBuffers = this.readBufferQueue.toArray( new ReadBuffer[currentBufferQueueSize]); lastByteStart = readBuffers[currentBufferQueueSize - 1].getStart(); } int maxLen = this.maxReadPartNumber - currentBufferQueueSize; for (int i = 0; i < maxLen && i < (currentBufferQueueSize + 1) * 2; i++) { if (lastByteStart + partSize * (i + 1) > this.fileSize) { break; } long byteStart = lastByteStart + partSize * (i + 1); long byteEnd = byteStart + partSize - 1; if (byteEnd >= this.fileSize) { byteEnd = this.fileSize - 1; } ReadBuffer readBuffer = new ReadBuffer(byteStart, byteEnd); if (readBuffer.getBuffer().length == 0) { readBuffer.setStatus(ReadBuffer.SUCCESS); } else { this.readAheadExecutorService.execute( new CosNFileReadTask( this.conf, this.key, this.store, readBuffer)); } this.readBufferQueue.add(readBuffer); if (isRandomIO) { break; } } ReadBuffer readBuffer = this.readBufferQueue.poll(); if (null != readBuffer) { readBuffer.lock(); try { readBuffer.await(ReadBuffer.INIT); if (readBuffer.getStatus() == ReadBuffer.ERROR) { this.buffer = null; } else { this.buffer = readBuffer.getBuffer(); } } catch (InterruptedException e) { LOG.warn("An interrupted exception occurred " + "when waiting a read buffer."); } finally { readBuffer.unLock(); } } if (null == this.buffer) { throw new IOException("Null IO stream"); } this.position = pos; this.partRemaining = partSize; } @Override public void seek(long pos) throws IOException { if (pos < 0) { throw new EOFException(FSExceptionMessages.NEGATIVE_SEEK); } if (pos > this.fileSize) { throw new EOFException(FSExceptionMessages.CANNOT_SEEK_PAST_EOF); } if (this.position == pos) { return; } if (pos > position && pos < this.position + partRemaining) { long len = pos - this.position; this.position = pos; this.partRemaining -= len; } else { this.reopen(pos); } } @Override public long getPos() { return this.position; } @Override public boolean seekToNewSource(long targetPos) { // Currently does not support to seek the offset of a new source return false; } @Override public int read() throws IOException { if (this.closed) { throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED); } if (this.partRemaining <= 0 && this.position < this.fileSize) { this.reopen(this.position); } int byteRead = -1; if (this.partRemaining != 0) { byteRead = this.buffer[ (int) (this.buffer.length - this.partRemaining)] & 0xff; } if (byteRead >= 0) { this.position++; this.partRemaining--; if (null != this.statistics) { this.statistics.incrementBytesRead(byteRead); } } return byteRead; } @Override public int read(byte[] b, int off, int len) throws IOException { if (this.closed) { throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED); } if (len == 0) { return 0; } if (off < 0 || len < 0 || len > b.length) { throw new IndexOutOfBoundsException(); } int bytesRead = 0; while (position < fileSize && bytesRead < len) { if (partRemaining <= 0) { reopen(position); } int bytes = 0; for (int i = this.buffer.length - (int) partRemaining; i < this.buffer.length; i++) { b[off + bytesRead] = this.buffer[i]; bytes++; bytesRead++; if (off + bytesRead >= len) { break; } } if (bytes > 0) { this.position += bytes; this.partRemaining -= bytes; } else if (this.partRemaining != 0) { throw new IOException( "Failed to read from stream. Remaining: " + this.partRemaining); } } if (null != this.statistics && bytesRead > 0) { this.statistics.incrementBytesRead(bytesRead); } return bytesRead == 0 ? -1 : bytesRead; } @Override public int available() throws IOException { if (this.closed) { throw new IOException(FSExceptionMessages.STREAM_IS_CLOSED); } long remaining = this.fileSize - this.position; if (remaining > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int)remaining; } @Override public void close() { if (this.closed) { return; } this.closed = true; this.buffer = null; } }
ReadBuffer
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestNoHaRMFailoverProxyProvider.java
{ "start": 2044, "end": 2292 }
class ____ { // Default port of yarn RM private static final int RM1_PORT = 8032; private static final int RM2_PORT = 8031; private static final int NUMNODEMANAGERS = 1; private Configuration conf; private
TestNoHaRMFailoverProxyProvider
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/recovery/PeerRecoveryTargetService.java
{ "start": 27385, "end": 27705 }
interface ____ { void onRecoveryDone( RecoveryState state, ShardLongFieldRange timestampMillisFieldRange, ShardLongFieldRange eventIngestedMillisFieldRange ); void onRecoveryFailure(RecoveryFailedException e, boolean sendShardFailure); }
RecoveryListener
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/jaxws/CxfProducerOperationTest.java
{ "start": 1143, "end": 4193 }
class ____ extends CxfProducerTest { private static final String NAMESPACE = "http://apache.org/hello_world_soap_http"; @Override protected String getSimpleEndpointUri() { return "cxf://" + getSimpleServerAddress() + "?serviceClass=org.apache.camel.component.cxf.jaxws.HelloService" + "&defaultOperationName=" + ECHO_OPERATION; } @Override protected String getJaxwsEndpointUri() { return "cxf://" + getJaxWsServerAddress() + "?serviceClass=org.apache.hello_world_soap_http.Greeter" + "&defaultOperationName=" + GREET_ME_OPERATION + "&defaultOperationNamespace=" + NAMESPACE; } @Override protected Exchange sendSimpleMessage() { return sendSimpleMessage(getSimpleEndpointUri()); } private Exchange sendSimpleMessage(String endpointUri) { Exchange exchange = template.send(endpointUri, new Processor() { public void process(final Exchange exchange) { final List<String> params = new ArrayList<>(); params.add(TEST_MESSAGE); exchange.getIn().setBody(params); exchange.getIn().setHeader(Exchange.FILE_NAME, "testFile"); exchange.getIn().setHeader("requestObject", new DefaultCxfBinding()); } }); return exchange; } @Override protected Exchange sendJaxWsMessage() { Exchange exchange = template.send(getJaxwsEndpointUri(), new Processor() { public void process(final Exchange exchange) { final List<String> params = new ArrayList<>(); params.add(TEST_MESSAGE); exchange.getIn().setBody(params); exchange.getIn().setHeader(Exchange.FILE_NAME, "testFile"); } }); return exchange; } @Test public void testSendingComplexParameter() throws Exception { Exchange exchange = template.send(getSimpleEndpointUri(), new Processor() { public void process(final Exchange exchange) { // we need to override the operation name first final List<String> para1 = new ArrayList<>(); para1.add("para1"); final List<String> para2 = new ArrayList<>(); para2.add("para2"); List<List<String>> parameters = new ArrayList<>(); parameters.add(para1); parameters.add(para2); // The object array version is working too // Object[] parameters = new Object[] {para1, para2}; exchange.getIn().setBody(parameters); exchange.getIn().setHeader(CxfConstants.OPERATION_NAME, "complexParameters"); } }); if (exchange.getException() != null) { throw exchange.getException(); } assertEquals("param:para1para2", exchange.getMessage().getBody(String.class), "Get a wrong response."); } }
CxfProducerOperationTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/GlobPattern.java
{ "start": 1167, "end": 4835 }
class ____ { private static final char BACKSLASH = '\\'; private Pattern compiled; private boolean hasWildcard = false; /** * Construct the glob pattern object with a glob pattern string * @param globPattern the glob pattern string */ public GlobPattern(String globPattern) { set(globPattern); } /** * @return the compiled pattern */ public Pattern compiled() { return compiled; } /** * Compile glob pattern string * @param globPattern the glob pattern * @return the pattern object */ public static Pattern compile(String globPattern) { return new GlobPattern(globPattern).compiled(); } /** * Match input against the compiled glob pattern * @param s input chars * @return true for successful matches */ public boolean matches(CharSequence s) { return compiled.matcher(s).matches(); } /** * Set and compile a glob pattern * @param glob the glob pattern string */ public void set(String glob) { StringBuilder regex = new StringBuilder(); int setOpen = 0; int curlyOpen = 0; int len = glob.length(); hasWildcard = false; for (int i = 0; i < len; i++) { char c = glob.charAt(i); switch (c) { case BACKSLASH: if (++i >= len) { error("Missing escaped character", glob, i); } regex.append(c).append(glob.charAt(i)); continue; case '.': case '$': case '(': case ')': case '|': case '+': // escape regex special chars that are not glob special chars regex.append(BACKSLASH); break; case '*': regex.append('.'); hasWildcard = true; break; case '?': regex.append('.'); hasWildcard = true; continue; case '{': // start of a group regex.append("(?:"); // non-capturing curlyOpen++; hasWildcard = true; continue; case ',': regex.append(curlyOpen > 0 ? '|' : c); continue; case '}': if (curlyOpen > 0) { // end of a group curlyOpen--; regex.append(")"); continue; } break; case '[': if (setOpen > 0) { error("Unclosed character class", glob, i); } setOpen++; hasWildcard = true; break; case '^': // ^ inside [...] can be unescaped if (setOpen == 0) { regex.append(BACKSLASH); } break; case '!': // [! needs to be translated to [^ regex.append(setOpen > 0 && '[' == glob.charAt(i - 1) ? '^' : '!'); continue; case ']': // Many set errors like [][] could not be easily detected here, // as []], []-] and [-] are all valid POSIX glob and java regex. // We'll just let the regex compiler do the real work. setOpen = 0; break; default: } regex.append(c); } if (setOpen > 0) { error("Unclosed character class", glob, len); } if (curlyOpen > 0) { error("Unclosed group", glob, len); } compiled = Pattern.compile(regex.toString(), Pattern.DOTALL); } /** * @return true if this is a wildcard pattern (with special chars) */ public boolean hasWildcard() { return hasWildcard; } private static void error(String message, String pattern, int pos) { String fullMessage = String.format("%s at pos %d", message, pos); throw new PatternSyntaxException(fullMessage, pattern); } }
GlobPattern
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/MedianAbsoluteDeviation.java
{ "start": 1679, "end": 5551 }
class ____ extends NumericAggregate implements SurrogateExpression { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Expression.class, "MedianAbsoluteDeviation", MedianAbsoluteDeviation::new ); // TODO: Add parameter @FunctionInfo( returnType = "double", description = "Returns the median absolute deviation, a measure of variability. It is a robust " + "statistic, meaning that it is useful for describing data that may have outliers, " + "or may not be normally distributed. For such data it can be more descriptive " + "than standard deviation." + "\n\n" + "It is calculated as the median of each data point’s deviation from the median of " + "the entire sample. That is, for a random variable `X`, the median absolute " + "deviation is `median(|median(X) - X|)`.", note = "Like <<esql-percentile>>, `MEDIAN_ABSOLUTE_DEVIATION` is <<esql-percentile-approximate,usually approximate>>.", appendix = """ ::::{warning} `MEDIAN_ABSOLUTE_DEVIATION` is also {wikipedia}/Nondeterministic_algorithm[non-deterministic]. This means you can get slightly different results using the same data. ::::""", type = FunctionType.AGGREGATE, examples = { @Example(file = "median_absolute_deviation", tag = "median-absolute-deviation"), @Example( description = "The expression can use inline functions. For example, to calculate the " + "median absolute deviation of the maximum values of a multivalued column, first " + "use `MV_MAX` to get the maximum value per row, and use the result with the " + "`MEDIAN_ABSOLUTE_DEVIATION` function", file = "median_absolute_deviation", tag = "docsStatsMADNestedExpression" ), } ) public MedianAbsoluteDeviation(Source source, @Param(name = "number", type = { "double", "integer", "long" }) Expression field) { this(source, field, Literal.TRUE, NO_WINDOW); } public MedianAbsoluteDeviation(Source source, Expression field, Expression filter, Expression window) { super(source, field, filter, window, emptyList()); } private MedianAbsoluteDeviation(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected NodeInfo<MedianAbsoluteDeviation> info() { return NodeInfo.create(this, MedianAbsoluteDeviation::new, field(), filter(), window()); } @Override public MedianAbsoluteDeviation replaceChildren(List<Expression> newChildren) { return new MedianAbsoluteDeviation(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2)); } @Override public MedianAbsoluteDeviation withFilter(Expression filter) { return new MedianAbsoluteDeviation(source(), field(), filter, window()); } @Override protected AggregatorFunctionSupplier longSupplier() { return new MedianAbsoluteDeviationLongAggregatorFunctionSupplier(); } @Override protected AggregatorFunctionSupplier intSupplier() { return new MedianAbsoluteDeviationIntAggregatorFunctionSupplier(); } @Override protected AggregatorFunctionSupplier doubleSupplier() { return new MedianAbsoluteDeviationDoubleAggregatorFunctionSupplier(); } @Override public Expression surrogate() { var s = source(); var field = field(); if (field.foldable()) { return new MvMedianAbsoluteDeviation(s, new ToDouble(s, field)); } return null; } }
MedianAbsoluteDeviation
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/converter/stream/ReaderCache.java
{ "start": 1387, "end": 2345 }
class ____ extends StringReader implements StreamCache { private final String data; public ReaderCache(String data) { super(data); this.data = data; } @Override public void close() { // Do not release the string for caching } @Override public void reset() { try { super.reset(); } catch (IOException e) { // ignore } } @Override public void writeTo(OutputStream os) throws IOException { os.write(data.getBytes()); } @Override public StreamCache copy(Exchange exchange) throws IOException { return new ReaderCache(data); } @Override public boolean inMemory() { return true; } @Override public long length() { return data.length(); } @Override public long position() { return -1; } String getData() { return data; } }
ReaderCache
java
apache__kafka
core/src/main/java/kafka/server/share/SharePartition.java
{ "start": 182894, "end": 183537 }
class ____ { // This offset could be different from offsetMetadata.messageOffset if it's in the middle of a batch. private long offset; private LogOffsetMetadata offsetMetadata; OffsetMetadata() { offset = -1; } long offset() { return offset; } LogOffsetMetadata offsetMetadata() { return offsetMetadata; } void updateOffsetMetadata(long offset, LogOffsetMetadata offsetMetadata) { this.offset = offset; this.offsetMetadata = offsetMetadata; } } /** * PersisterBatch
OffsetMetadata
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/HibernateMultitenancyTests.java
{ "start": 2008, "end": 3265 }
class ____ { @Autowired RoleRepository roleRepository; @Autowired EntityManager em; @AfterEach void tearDown() { HibernateCurrentTenantIdentifierResolver.removeTenantIdentifier(); } @Test // GH-3425 void testPersistenceProviderFromFactoryWithoutTenant() { PersistenceProvider provider = PersistenceProvider.fromEntityManager(em); assumeThat(provider).isEqualTo(PersistenceProvider.HIBERNATE); } @Test // GH-3425 void testRepositoryWithTenant() { HibernateCurrentTenantIdentifierResolver.setTenantIdentifier("tenant-id"); assertThatNoException().isThrownBy(() -> roleRepository.findAll()); } @Test // GH-3425 void testRepositoryWithoutTenantFails() { assertThatThrownBy(() -> roleRepository.findAll()).isInstanceOf(RuntimeException.class); } @Transactional List<Role> insertAndQuery() { roleRepository.save(new Role("DRUMMER")); roleRepository.flush(); return roleRepository.findAll(); } @ImportResource("classpath:multitenancy-test.xml") @Configuration @EnableJpaRepositories(basePackageClasses = HibernateRepositoryTests.class, considerNestedRepositories = true, includeFilters = @ComponentScan.Filter(classes = { RoleRepository.class }, type = FilterType.ASSIGNABLE_TYPE)) static
HibernateMultitenancyTests
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/Loader.java
{ "start": 16286, "end": 16561 }
class ____ name. This method respects the {@link LoaderUtil#IGNORE_TCCL_PROPERTY IGNORE_TCCL_PROPERTY} Log4j property. If this property is * specified and set to anything besides {@code false}, then the default ClassLoader will be used. * * @param className The
by
java
resilience4j__resilience4j
resilience4j-spring/src/test/java/io/github/resilience4j/fallback/JdkProxyFallbackAspectTest.java
{ "start": 1653, "end": 1817 }
class ____ { @Bean public TestDummyService fallbackTestDummyService() { return new FallbackTestDummyService(); } } }
TestConfig
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/engine/support/hierarchical/ResourceLockTests.java
{ "start": 938, "end": 6702 }
class ____ { @Test void nopLocks() { assertCompatible(nopLock(), nopLock()); assertCompatible(nopLock(), singleLock(anyReadOnlyResource())); assertCompatible(nopLock(), compositeLock(anyReadOnlyResource())); } @Test void readOnlySingleLocks() { ExclusiveResource bR = readOnlyResource("b"); assertCompatible(singleLock(bR), nopLock()); assertCompatible(singleLock(bR), singleLock(bR)); assertIncompatible(singleLock(bR), singleLock(readWriteResource("b")), "read-write conflict"); assertIncompatible(singleLock(bR), singleLock(readOnlyResource("a")), "lock acquisition order"); assertCompatible(singleLock(bR), singleLock(readOnlyResource("c"))); assertIncompatible(singleLock(bR), singleLock(GLOBAL_READ), "lock acquisition order"); assertIncompatible(singleLock(bR), singleLock(GLOBAL_READ_WRITE), "lock acquisition order"); assertCompatible(singleLock(bR), compositeLock(bR, readOnlyResource("c"))); assertIncompatible(singleLock(bR), compositeLock(readOnlyResource("a1"), readOnlyResource("a2"), bR), "lock acquisition order"); } @Test void readWriteSingleLocks() { ExclusiveResource bRW = readWriteResource("b"); assertCompatible(singleLock(bRW), nopLock()); assertIncompatible(singleLock(bRW), singleLock(bRW), "isolation guarantees"); assertIncompatible(singleLock(bRW), compositeLock(bRW), "isolation guarantees"); assertIncompatible(singleLock(bRW), singleLock(readOnlyResource("a")), "lock acquisition order"); assertIncompatible(singleLock(bRW), singleLock(readOnlyResource("b")), "isolation guarantees"); assertIncompatible(singleLock(bRW), singleLock(readOnlyResource("c")), "isolation guarantees"); assertIncompatible(singleLock(bRW), singleLock(GLOBAL_READ), "lock acquisition order"); assertIncompatible(singleLock(bRW), singleLock(GLOBAL_READ_WRITE), "lock acquisition order"); assertIncompatible(singleLock(bRW), compositeLock(bRW, readOnlyResource("c")), "isolation guarantees"); assertIncompatible(singleLock(bRW), compositeLock(readOnlyResource("a1"), readOnlyResource("a2"), bRW), "lock acquisition order"); } @Test void globalReadLock() { assertCompatible(singleLock(GLOBAL_READ), nopLock()); assertCompatible(singleLock(GLOBAL_READ), singleLock(GLOBAL_READ)); assertCompatible(singleLock(GLOBAL_READ), singleLock(anyReadOnlyResource())); assertCompatible(singleLock(GLOBAL_READ), singleLock(anyReadWriteResource())); assertIncompatible(singleLock(GLOBAL_READ), singleLock(GLOBAL_READ_WRITE), "read-write conflict"); } @Test void readOnlyCompositeLocks() { ExclusiveResource bR = readOnlyResource("b"); assertCompatible(compositeLock(bR), nopLock()); assertCompatible(compositeLock(bR), singleLock(bR)); assertCompatible(compositeLock(bR), compositeLock(bR)); assertIncompatible(compositeLock(bR), singleLock(GLOBAL_READ), "lock acquisition order"); assertIncompatible(compositeLock(bR), singleLock(GLOBAL_READ_WRITE), "lock acquisition order"); assertIncompatible(compositeLock(bR), compositeLock(readOnlyResource("a")), "lock acquisition order"); assertCompatible(compositeLock(bR), compositeLock(readOnlyResource("c"))); assertIncompatible(compositeLock(bR), compositeLock(readWriteResource("b")), "read-write conflict"); assertIncompatible(compositeLock(bR), compositeLock(bR, readWriteResource("b")), "read-write conflict"); } @Test void readWriteCompositeLocks() { ExclusiveResource bRW = readWriteResource("b"); assertCompatible(compositeLock(bRW), nopLock()); assertIncompatible(compositeLock(bRW), singleLock(bRW), "isolation guarantees"); assertIncompatible(compositeLock(bRW), compositeLock(bRW), "isolation guarantees"); assertIncompatible(compositeLock(bRW), singleLock(readOnlyResource("a")), "lock acquisition order"); assertIncompatible(compositeLock(bRW), singleLock(readOnlyResource("b")), "isolation guarantees"); assertIncompatible(compositeLock(bRW), singleLock(readOnlyResource("c")), "isolation guarantees"); assertIncompatible(compositeLock(bRW), singleLock(GLOBAL_READ), "lock acquisition order"); assertIncompatible(compositeLock(bRW), singleLock(GLOBAL_READ_WRITE), "lock acquisition order"); assertIncompatible(compositeLock(bRW), compositeLock(readOnlyResource("a")), "lock acquisition order"); assertIncompatible(compositeLock(bRW), compositeLock(readOnlyResource("b"), readOnlyResource("c")), "isolation guarantees"); } private static void assertCompatible(ResourceLock first, ResourceLock second) { assertTrue(first.isCompatible(second), "Expected locks to be compatible:\n(1) %s\n(2) %s".formatted(first, second)); } private static void assertIncompatible(ResourceLock first, ResourceLock second, String reason) { assertFalse(first.isCompatible(second), "Expected locks to be incompatible due to %s:\n(1) %s\n(2) %s".formatted(reason, first, second)); } private static ResourceLock nopLock() { return NopLock.INSTANCE; } private static SingleLock singleLock(ExclusiveResource resource) { return new SingleLock(resource, anyLock()); } private static CompositeLock compositeLock(ExclusiveResource... resources) { return new CompositeLock(List.of(resources), Arrays.stream(resources).map(__ -> anyLock()).toList()); } private static ExclusiveResource anyReadOnlyResource() { return readOnlyResource("key"); } private static ExclusiveResource anyReadWriteResource() { return readWriteResource("key"); } private static ExclusiveResource readOnlyResource(String key) { return new ExclusiveResource(key, LockMode.READ); } private static ExclusiveResource readWriteResource(String key) { return new ExclusiveResource(key, LockMode.READ_WRITE); } private static Lock anyLock() { return new ReentrantLock(); } }
ResourceLockTests
java
apache__camel
components/camel-asterisk/src/main/java/org/apache/camel/component/asterisk/AsteriskAction.java
{ "start": 1156, "end": 1865 }
enum ____ implements Function<Exchange, ManagerAction> { QUEUE_STATUS { @Override public ManagerAction apply(Exchange exchange) { return new QueueStatusAction(); } }, SIP_PEERS { @Override public ManagerAction apply(Exchange exchange) { return new SipPeersAction(); } }, EXTENSION_STATE { @Override public ManagerAction apply(Exchange exchange) { return new ExtensionStateAction( exchange.getIn().getHeader(AsteriskConstants.EXTENSION, String.class), exchange.getIn().getHeader(AsteriskConstants.CONTEXT, String.class)); } } }
AsteriskAction
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LangChain4jAgentEndpointBuilderFactory.java
{ "start": 1563, "end": 4550 }
interface ____ extends EndpointProducerBuilder { default AdvancedLangChain4jAgentEndpointBuilder advanced() { return (AdvancedLangChain4jAgentEndpointBuilder) this; } /** * The agent to use for the component. * * The option is a: * <code>org.apache.camel.component.langchain4j.agent.api.Agent</code> * type. * * Group: producer * * @param agent the value to set * @return the dsl builder */ default LangChain4jAgentEndpointBuilder agent(org.apache.camel.component.langchain4j.agent.api.Agent agent) { doSetProperty("agent", agent); return this; } /** * The agent to use for the component. * * The option will be converted to a * <code>org.apache.camel.component.langchain4j.agent.api.Agent</code> * type. * * Group: producer * * @param agent the value to set * @return the dsl builder */ default LangChain4jAgentEndpointBuilder agent(String agent) { doSetProperty("agent", agent); return this; } /** * The agent factory to use for creating agents if no Agent is provided. * * The option is a: * <code>org.apache.camel.component.langchain4j.agent.api.AgentFactory</code> type. * * Group: producer * * @param agentFactory the value to set * @return the dsl builder */ default LangChain4jAgentEndpointBuilder agentFactory(org.apache.camel.component.langchain4j.agent.api.AgentFactory agentFactory) { doSetProperty("agentFactory", agentFactory); return this; } /** * The agent factory to use for creating agents if no Agent is provided. * * The option will be converted to a * <code>org.apache.camel.component.langchain4j.agent.api.AgentFactory</code> type. * * Group: producer * * @param agentFactory the value to set * @return the dsl builder */ default LangChain4jAgentEndpointBuilder agentFactory(String agentFactory) { doSetProperty("agentFactory", agentFactory); return this; } /** * Tags for discovering and calling Camel route tools. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param tags the value to set * @return the dsl builder */ default LangChain4jAgentEndpointBuilder tags(String tags) { doSetProperty("tags", tags); return this; } } /** * Advanced builder for endpoint for the LangChain4j Agent component. */ public
LangChain4jAgentEndpointBuilder
java
apache__kafka
server-common/src/main/java/org/apache/kafka/common/DirectoryId.java
{ "start": 967, "end": 5718 }
class ____ { /** * A Uuid that is used to represent an unspecified log directory, * that is expected to have been previously selected to host an * associated replica. This contrasts with {@code UNASSIGNED_DIR}, * which is associated with (typically new) replicas that may not * yet have been placed in any log directory. */ public static final Uuid MIGRATING = new Uuid(0L, 0L); /** * A Uuid that is used to represent directories that are pending an assignment. */ public static final Uuid UNASSIGNED = new Uuid(0L, 1L); /** * A Uuid that is used to represent unspecified offline dirs. */ public static final Uuid LOST = new Uuid(0L, 2L); /** * Static factory to generate a directory ID. * * This will not generate a reserved UUID (first 100), or one whose string representation * starts with a dash ("-") */ public static Uuid random() { while (true) { // Uuid.randomUuid does not generate Uuids whose string representation starts with a // dash. Uuid uuid = Uuid.randomUuid(); if (!DirectoryId.reserved(uuid)) { return uuid; } } } /** * Check if a directory ID is part of the first 100 reserved IDs. * * @param uuid the directory ID to check. * @return true only if the directory ID is reserved. */ public static boolean reserved(Uuid uuid) { return uuid.getMostSignificantBits() == 0 && uuid.getLeastSignificantBits() < 100; } /** * Build a mapping from replica to directory based on two lists of the same size and order. * @param replicas The replicas, represented by the broker IDs * @param directories The directory information * @return A map, linking each replica to its assigned directory * @throws IllegalArgumentException If replicas and directories have different lengths, * or if there are duplicate broker IDs in the replica list */ public static Map<Integer, Uuid> createAssignmentMap(int[] replicas, Uuid[] directories) { if (replicas.length != directories.length) { throw new IllegalArgumentException("The lengths for replicas and directories do not match."); } Map<Integer, Uuid> assignments = new HashMap<>(); for (int i = 0; i < replicas.length; i++) { int brokerId = replicas[i]; Uuid directory = directories[i]; if (assignments.put(brokerId, directory) != null) { throw new IllegalArgumentException("Duplicate broker ID in assignment"); } } return assignments; } /** * Create an array with the specified number of entries set to {@link #UNASSIGNED}. */ public static Uuid[] unassignedArray(int length) { return array(length, UNASSIGNED); } /** * Create an array with the specified number of entries set to {@link #MIGRATING}. */ public static Uuid[] migratingArray(int length) { return array(length, MIGRATING); } /** * Create an array with the specified number of entries set to the specified value. */ private static Uuid[] array(int length, Uuid value) { Uuid[] array = new Uuid[length]; Arrays.fill(array, value); return array; } /** * Check if a directory is online, given a sorted list of online directories. * @param dir The directory to check * @param sortedOnlineDirs The sorted list of online directories * @return true if the directory is considered online, false otherwise */ public static boolean isOnline(Uuid dir, List<Uuid> sortedOnlineDirs) { if (UNASSIGNED.equals(dir) || MIGRATING.equals(dir)) { return true; } if (LOST.equals(dir)) { return false; } // The only time we should have a size be 0 is if we were at a MV prior to 3.7-IV2 // and the system was upgraded. In this case the original list of directories was purged // during broker registration, so we don't know if the directory is online. We assume // that a broker will halt if all its log directories are down. Eventually the broker // will send another registration request with information about all log directories. // Refer KAFKA-16162 for more information if (sortedOnlineDirs.isEmpty()) { return true; } return Collections.binarySearch(sortedOnlineDirs, dir) >= 0; } }
DirectoryId
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/KeywordFieldMapper.java
{ "start": 57657, "end": 59453 }
class ____ extends CustomDocValuesField { private final Set<BytesRef> uniqueValues; private int docValuesByteCount = 0; MultiValuedBinaryDocValuesField(String name) { super(name); // linked hash set to maintain insertion order of elements uniqueValues = new LinkedHashSet<>(); } public void add(final BytesRef value) { if (uniqueValues.add(value)) { // might as well track these on the go as opposed to having to loop through all entries later docValuesByteCount += value.length; } } /** * Encodes the collection of binary doc values as a single contiguous binary array, wrapped in {@link BytesRef}. This array takes * the form of [doc value count][length of value 1][value 1][length of value 2][value 2]... */ @Override public BytesRef binaryValue() { int docValuesCount = uniqueValues.size(); // the + 1 is for the total doc values count, which is prefixed at the start of the array int streamSize = docValuesByteCount + (docValuesCount + 1) * Integer.BYTES; try (BytesStreamOutput out = new BytesStreamOutput(streamSize)) { out.writeVInt(docValuesCount); for (BytesRef value : uniqueValues) { int valueLength = value.length; out.writeVInt(valueLength); out.writeBytes(value.bytes, value.offset, valueLength); } return out.bytes().toBytesRef(); } catch (IOException e) { throw new ElasticsearchException("Failed to get binary value", e); } } } }
MultiValuedBinaryDocValuesField
java
apache__camel
components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyServerBootstrapConfiguration.java
{ "start": 5786, "end": 9073 }
class ____ could be used to return an SSL Handler") protected SslHandler sslHandler; @UriParam(label = "security", description = "To configure security using SSLContextParameters") protected SSLContextParameters sslContextParameters; @UriParam(label = "consumer,security", description = "Configures whether the server needs client authentication when using SSL.") protected boolean needClientAuth; @UriParam(label = "security", description = "Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can" + " prefix with classpath:, file:, or http: to load the resource from different systems.") @Metadata(supportFileReference = true) protected String keyStoreResource; @UriParam(label = "security", description = "Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can" + " prefix with classpath:, file:, or http: to load the resource from different systems.") @Metadata(supportFileReference = true) protected String trustStoreResource; @UriParam(label = "security", description = "Keystore format to be used for payload encryption. Defaults to JKS if not set") protected String keyStoreFormat; @UriParam(label = "security", description = "Security provider to be used for payload encryption. Defaults to SunX509 if not set.") protected String securityProvider; @UriParam(defaultValue = DEFAULT_ENABLED_PROTOCOLS, label = "security", description = "Which protocols to enable when using SSL") protected String enabledProtocols = DEFAULT_ENABLED_PROTOCOLS; @UriParam(label = "security", secret = true, description = "Password to use for the keyStore and trustStore. The same password must be configured for both resources.") protected String passphrase; @UriParam(label = "advanced", description = "Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and" + " is only supported on some platforms. You need to add the netty JAR for the host operating system you are using." + " See more details at: http://netty.io/wiki/native-transports.html") protected boolean nativeTransport; @UriParam(label = "consumer,advanced", description = "Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint") protected EventLoopGroup bossGroup; @UriParam(label = "advanced", description = "To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple" + " consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads.") protected EventLoopGroup workerGroup; @UriParam(label = "advanced", description = "To use an explicit ChannelGroup.") protected ChannelGroup channelGroup; @UriParam(label = "common,advanced", description = "When using UDP then this option can be used to specify a network
that
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java
{ "start": 10343, "end": 14464 }
enum ____ { UNSUBSCRIBED { @Override public <T> void onSubscribe(AbstractListenerWriteProcessor<T> processor, Subscription subscription) { Assert.notNull(subscription, "Subscription must not be null"); if (processor.changeState(this, REQUESTED)) { processor.subscription = subscription; subscription.request(1); } else { super.onSubscribe(processor, subscription); } } @Override public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { // This can happen on (very early) completion notification from container.. processor.changeStateToComplete(this); } }, REQUESTED { @Override public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) { if (processor.isDataEmpty(data)) { Assert.state(processor.subscription != null, "No subscription"); processor.subscription.request(1); } else { processor.dataReceived(data); processor.changeStateToReceived(this); } } @Override public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { processor.readyToCompleteAfterLastWrite = true; processor.changeStateToReceived(this); } }, RECEIVED { @SuppressWarnings("deprecation") @Override public <T> void onWritePossible(AbstractListenerWriteProcessor<T> processor) { if (processor.readyToCompleteAfterLastWrite) { processor.changeStateToComplete(RECEIVED); } else if (processor.changeState(this, WRITING)) { T data = processor.currentData; Assert.state(data != null, "No data"); try { if (processor.write(data)) { if (processor.changeState(WRITING, REQUESTED)) { processor.currentData = null; if (processor.sourceCompleted) { processor.readyToCompleteAfterLastWrite = true; processor.changeStateToReceived(REQUESTED); } else { Assert.state(processor.subscription != null, "No subscription"); processor.subscription.request(1); } } } else { processor.changeStateToReceived(WRITING); } } catch (IOException ex) { processor.writingFailed(ex); } } } @Override public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { processor.sourceCompleted = true; // A competing write might have completed very quickly if (processor.state.get() == State.REQUESTED) { processor.changeStateToComplete(State.REQUESTED); } } }, WRITING { @Override public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { processor.sourceCompleted = true; // A competing write might have completed very quickly if (processor.state.get() == State.REQUESTED) { processor.changeStateToComplete(State.REQUESTED); } } }, COMPLETED { @Override public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) { // ignore } @Override public <T> void onError(AbstractListenerWriteProcessor<T> processor, Throwable ex) { // ignore } @Override public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { // ignore } }; public <T> void onSubscribe(AbstractListenerWriteProcessor<T> processor, Subscription subscription) { subscription.cancel(); } public <T> void onNext(AbstractListenerWriteProcessor<T> processor, T data) { processor.discardData(data); processor.cancel(); processor.onError(new IllegalStateException("Illegal onNext without demand")); } public <T> void onError(AbstractListenerWriteProcessor<T> processor, Throwable ex) { if (processor.changeState(this, COMPLETED)) { processor.discardCurrentData(); processor.writingComplete(); processor.resultPublisher.publishError(ex); } else { processor.state.get().onError(processor, ex); } } public <T> void onComplete(AbstractListenerWriteProcessor<T> processor) { throw new IllegalStateException(toString()); } public <T> void onWritePossible(AbstractListenerWriteProcessor<T> processor) { // ignore } } }
State
java
apache__dubbo
dubbo-metadata/dubbo-metadata-report-zookeeper/src/main/java/org/apache/dubbo/metadata/store/zookeeper/ZookeeperMetadataReport.java
{ "start": 2714, "end": 9484 }
class ____ extends AbstractMetadataReport { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ZookeeperMetadataReport.class); private final String root; ZookeeperClient zkClient; private ConcurrentMap<String, MappingDataListener> casListenerMap = new ConcurrentHashMap<>(); public ZookeeperMetadataReport(URL url, ZookeeperClientManager zookeeperClientManager) { super(url); if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } String group = url.getGroup(DEFAULT_ROOT); if (!group.startsWith(PATH_SEPARATOR)) { group = PATH_SEPARATOR + group; } this.root = group; zkClient = zookeeperClientManager.connect(url); } protected String toRootDir() { if (root.equals(PATH_SEPARATOR)) { return root; } return root + PATH_SEPARATOR; } @Override protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { storeMetadata(providerMetadataIdentifier, serviceDefinitions); } @Override protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { storeMetadata(consumerMetadataIdentifier, value); } @Override protected void doSaveMetadata(ServiceMetadataIdentifier metadataIdentifier, URL url) { zkClient.createOrUpdate(getNodePath(metadataIdentifier), URL.encode(url.toFullString()), false); } @Override protected void doRemoveMetadata(ServiceMetadataIdentifier metadataIdentifier) { zkClient.delete(getNodePath(metadataIdentifier)); } @Override protected List<String> doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { String content = zkClient.getContent(getNodePath(metadataIdentifier)); if (StringUtils.isEmpty(content)) { return Collections.emptyList(); } return new ArrayList<>(Collections.singletonList(URL.decode(content))); } @Override protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urls) { zkClient.createOrUpdate(getNodePath(subscriberMetadataIdentifier), urls, false); } @Override protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { return zkClient.getContent(getNodePath(subscriberMetadataIdentifier)); } @Override public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { return zkClient.getContent(getNodePath(metadataIdentifier)); } private void storeMetadata(MetadataIdentifier metadataIdentifier, String v) { zkClient.createOrUpdate(getNodePath(metadataIdentifier), v, false); } String getNodePath(BaseMetadataIdentifier metadataIdentifier) { return toRootDir() + metadataIdentifier.getUniqueKey(KeyTypeEnum.PATH); } @Override public void publishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { String path = getNodePath(identifier); if (StringUtils.isBlank(zkClient.getContent(path)) && StringUtils.isNotEmpty(metadataInfo.getContent())) { zkClient.createOrUpdate(path, metadataInfo.getContent(), false); } } @Override public void unPublishAppMetadata(SubscriberMetadataIdentifier identifier, MetadataInfo metadataInfo) { String path = getNodePath(identifier); if (StringUtils.isNotEmpty(zkClient.getContent(path))) { zkClient.delete(path); } } @Override public MetadataInfo getAppMetadata(SubscriberMetadataIdentifier identifier, Map<String, String> instanceMetadata) { String content = zkClient.getContent(getNodePath(identifier)); return JsonUtils.toJavaObject(content, MetadataInfo.class); } @Override public Set<String> getServiceAppMapping(String serviceKey, MappingListener listener, URL url) { String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey); MappingDataListener mappingDataListener = ConcurrentHashMapUtils.computeIfAbsent(casListenerMap, path, _k -> { MappingDataListener newMappingListener = new MappingDataListener(serviceKey, path); zkClient.addDataListener(path, newMappingListener); return newMappingListener; }); mappingDataListener.addListener(listener); return getAppNames(zkClient.getContent(path)); } @Override public void removeServiceAppMappingListener(String serviceKey, MappingListener listener) { String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey); if (null != casListenerMap.get(path)) { removeCasServiceMappingListener(path, listener); } } @Override public Set<String> getServiceAppMapping(String serviceKey, URL url) { String path = buildPathKey(DEFAULT_MAPPING_GROUP, serviceKey); return getAppNames(zkClient.getContent(path)); } @Override public ConfigItem getConfigItem(String serviceKey, String group) { String path = buildPathKey(group, serviceKey); return zkClient.getConfigItem(path); } @Override public boolean registerServiceAppMapping(String key, String group, String content, Object ticket) { try { if (ticket != null && !(ticket instanceof Stat)) { throw new IllegalArgumentException("zookeeper publishConfigCas requires stat type ticket"); } String pathKey = buildPathKey(group, key); zkClient.createOrUpdate(pathKey, content, false, ticket == null ? null : ((Stat) ticket).getVersion()); return true; } catch (Exception e) { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "zookeeper publishConfigCas failed.", e); return false; } } @Override public void destroy() { super.destroy(); // release zk client reference, but should not close it zkClient = null; } private String buildPathKey(String group, String serviceKey) { return toRootDir() + group + PATH_SEPARATOR + serviceKey; } private void removeCasServiceMappingListener(String path, MappingListener listener) { MappingDataListener mappingDataListener = casListenerMap.get(path); mappingDataListener.removeListener(listener); if (mappingDataListener.isEmpty()) { zkClient.removeDataListener(path, mappingDataListener); casListenerMap.remove(path, mappingDataListener); } } private static
ZookeeperMetadataReport
java
apache__kafka
server/src/main/java/org/apache/kafka/server/AssignmentsManager.java
{ "start": 9665, "end": 10080 }
class ____ implements EventQueue.Event { @Override public void run() { try { maybeSendAssignments(); } catch (Exception e) { log.error("Unexpected exception in MaybeSendAssignmentsEvent", e); } } } /** * An event that handles the controller's response to our request. */ private
MaybeSendAssignmentsEvent
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/filter/TestRestFilter.java
{ "start": 1182, "end": 2372 }
class ____ implements RestFilter, Listener { private static final Logger LOGGER = LoggerFactory.getLogger(TestRestFilter.class); private final int priority; private final String[] patterns; public TestRestFilter() { this(50); } public TestRestFilter(int priority, String... patterns) { this.priority = priority; this.patterns = patterns; } @Override public int getPriority() { return priority; } @Override public String[] getPatterns() { return patterns; } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws Exception { LOGGER.info("{} path '{}' doFilter", request.path(), this); chain.doFilter(request, response); } @Override public void onResponse(Result result, HttpRequest request, HttpResponse response) throws Exception { LOGGER.info("{} path '{}' onResponse", request.path(), this); } @Override public void onError(Throwable t, HttpRequest request, HttpResponse response) throws Exception { LOGGER.info("{} path '{}' onError", request.path(), this); } }
TestRestFilter
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/H2LegacySqlAstTranslator.java
{ "start": 2422, "end": 12498 }
class ____<T extends JdbcOperation> extends AbstractSqlAstTranslator<T> { private boolean renderAsArray; public H2LegacySqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) { super( sessionFactory, statement ); } @Override public void visitStandardTableInsert(TableInsertStandard tableInsert) { if ( getDialect().getVersion().isSameOrAfter( 2 ) || CollectionHelper.isEmpty( tableInsert.getReturningColumns() ) ) { final boolean closeWrapper = renderReturningClause( tableInsert.getReturningColumns() ); super.visitStandardTableInsert( tableInsert ); if ( closeWrapper ) { appendSql( ')' ); } } else { visitReturningInsertStatement( tableInsert ); } } @Override public void visitStandardTableUpdate(TableUpdateStandard tableUpdate) { final boolean closeWrapper = renderReturningClause( tableUpdate.getReturningColumns() ); super.visitStandardTableUpdate( tableUpdate ); if ( closeWrapper ) { appendSql( ')' ); } } protected boolean renderReturningClause(List<ColumnReference> returningColumns) { if ( isEmpty( returningColumns ) ) { return false; } appendSql( "select " ); for ( int i = 0; i < returningColumns.size(); i++ ) { if ( i > 0 ) { appendSql( ", " ); } appendSql( returningColumns.get( i ).getColumnExpression() ); } appendSql( " from final table (" ); return true; } @Override protected void visitReturningColumns(List<ColumnReference> returningColumns) { // do nothing - this is handled via `#renderReturningClause` } public void visitReturningInsertStatement(TableInsertStandard tableInsert) { assert tableInsert.getReturningColumns() != null && !tableInsert.getReturningColumns().isEmpty(); final H2IdentityColumnSupport identitySupport = (H2IdentityColumnSupport) getSessionFactory() .getJdbcServices() .getDialect() .getIdentityColumnSupport(); identitySupport.render( tableInsert, this::appendSql, (columnReference) -> columnReference.accept( this ), () -> super.visitStandardTableInsert( tableInsert ), getSessionFactory() ); } @Override protected void visitInsertStatementOnly(InsertSelectStatement statement) { if ( statement.getConflictClause() == null || statement.getConflictClause().isDoNothing() ) { // Render plain insert statement and possibly run into unique constraint violation super.visitInsertStatementOnly( statement ); } else { visitInsertStatementEmulateMerge( statement ); } } @Override protected void visitDeleteStatementOnly(DeleteStatement statement) { if ( hasNonTrivialFromClause( statement.getFromClause() ) ) { appendSql( "delete from " ); final Stack<Clause> clauseStack = getClauseStack(); try { clauseStack.push( Clause.DELETE ); super.renderDmlTargetTableExpression( statement.getTargetTable() ); append( " dml_target_" ); } finally { clauseStack.pop(); } visitWhereClause( determineWhereClauseRestrictionWithJoinEmulation( statement, "dml_target_" ) ); visitReturningColumns( statement.getReturningColumns() ); } else { super.visitDeleteStatementOnly( statement ); } } @Override protected void visitUpdateStatementOnly(UpdateStatement statement) { if ( hasNonTrivialFromClause( statement.getFromClause() ) ) { visitUpdateStatementEmulateMerge( statement ); } else { super.visitUpdateStatementOnly( statement ); } } @Override protected void renderDmlTargetTableExpression(NamedTableReference tableReference) { super.renderDmlTargetTableExpression( tableReference ); if ( getClauseStack().getCurrent() != Clause.INSERT ) { renderTableReferenceIdentificationVariable( tableReference ); } } @Override protected void visitConflictClause(ConflictClause conflictClause) { if ( conflictClause != null ) { if ( conflictClause.isDoUpdate() && conflictClause.getConstraintName() != null ) { throw new IllegalQueryOperationException( "Insert conflict 'do update' clause with constraint name is not supported" ); } } } @Override public void visitCteContainer(CteContainer cteContainer) { // H2 has various bugs in different versions that make it impossible to use CTEs with parameters reliably withParameterRenderingMode( SqlAstNodeRenderingMode.INLINE_PARAMETERS, () -> super.visitCteContainer( cteContainer ) ); } @Override protected boolean needsCteInlining() { // CTEs in H2 are just so buggy, that we can't reliably use them return true; } @Override protected boolean shouldInlineCte(TableGroup tableGroup) { return tableGroup instanceof CteTableGroup && !getCteStatement( tableGroup.getPrimaryTableReference().getTableId() ).isRecursive(); } @Override protected String getArrayContainsFunction() { return "array_contains"; } @Override protected void renderExpressionAsClauseItem(Expression expression) { expression.accept( this ); } @Override public void visitBooleanExpressionPredicate(BooleanExpressionPredicate booleanExpressionPredicate) { final boolean isNegated = booleanExpressionPredicate.isNegated(); if ( isNegated ) { appendSql( "not(" ); } booleanExpressionPredicate.getExpression().accept( this ); if ( isNegated ) { appendSql( CLOSE_PARENTHESIS ); } } @Override public void visitOffsetFetchClause(QueryPart queryPart) { if ( isRowsOnlyFetchClauseType( queryPart ) ) { if ( supportsOffsetFetchClause() ) { renderOffsetFetchClause( queryPart, true ); } else { renderLimitOffsetClause( queryPart ); } } else { if ( supportsOffsetFetchClausePercentWithTies() ) { renderOffsetFetchClause( queryPart, true ); } else { // FETCH PERCENT and WITH TIES were introduced along with window functions throw new IllegalArgumentException( "Can't emulate fetch clause type: " + queryPart.getFetchClauseType() ); } } } @Override protected void renderSelectTupleComparison( List<SqlSelection> lhsExpressions, SqlTuple tuple, ComparisonOperator operator) { emulateSelectTupleComparison( lhsExpressions, tuple.getExpressions(), operator, true ); } @Override public void visitInSubQueryPredicate(InSubQueryPredicate inSubQueryPredicate) { final SqlTuple lhsTuple; // As of 1.4.200 this is supported if ( getDialect().getVersion().isBefore( 1, 4, 200 ) && ( lhsTuple = SqlTupleContainer.getSqlTuple( inSubQueryPredicate.getTestExpression() ) ) != null && lhsTuple.getExpressions().size() != 1 ) { inSubQueryPredicate.getTestExpression().accept( this ); if ( inSubQueryPredicate.isNegated() ) { appendSql( " not" ); } appendSql( " in" ); final boolean renderAsArray = this.renderAsArray; this.renderAsArray = true; inSubQueryPredicate.getSubQuery().accept( this ); this.renderAsArray = renderAsArray; } else { super.visitInSubQueryPredicate( inSubQueryPredicate ); } } @Override protected void visitSqlSelections(SelectClause selectClause) { final boolean renderAsArray = this.renderAsArray; this.renderAsArray = false; if ( renderAsArray ) { append( OPEN_PARENTHESIS ); } super.visitSqlSelections( selectClause ); if ( renderAsArray ) { append( CLOSE_PARENTHESIS ); } } @Override protected void renderPartitionItem(Expression expression) { if ( expression instanceof Literal ) { appendSql( "'0' || '0'" ); } else if ( expression instanceof Summarization ) { // This could theoretically be emulated by rendering all grouping variations of the query and // connect them via union all but that's probably pretty inefficient and would have to happen // on the query spec level throw new UnsupportedOperationException( "Summarization is not supported by DBMS" ); } else { expression.accept( this ); } } @Override public void visitBinaryArithmeticExpression(BinaryArithmeticExpression arithmeticExpression) { appendSql( OPEN_PARENTHESIS ); visitArithmeticOperand( arithmeticExpression.getLeftHandOperand() ); appendSql( arithmeticExpression.getOperator().getOperatorSqlTextString() ); visitArithmeticOperand( arithmeticExpression.getRightHandOperand() ); appendSql( CLOSE_PARENTHESIS ); } @Override protected void visitArithmeticOperand(Expression expression) { render( expression, SqlAstNodeRenderingMode.NO_PLAIN_PARAMETER ); } @Override protected boolean renderPrimaryTableReference(TableGroup tableGroup, LockMode lockMode) { final TableReference tableRef = tableGroup.getPrimaryTableReference(); // The H2 parser can't handle a sub-query as first element in a nested join // i.e. `join ( (select ...) alias join ... )`, so we have to introduce a dummy table reference if ( getSqlBuffer().charAt( getSqlBuffer().length() - 1 ) == '(' && ( tableRef instanceof QueryPartTableReference || tableRef.getTableId().startsWith( "(select" ) ) ) { appendSql( "dual cross join " ); } return super.renderPrimaryTableReference( tableGroup, lockMode ); } @Override public void visitLikePredicate(LikePredicate likePredicate) { super.visitLikePredicate( likePredicate ); // Custom implementation because H2 uses backslash as the default escape character // We can override this by specifying an empty escape character // See http://www.h2database.com/html/grammar.html#like_predicate_right_hand_side if ( likePredicate.getEscapeCharacter() == null ) { appendSql( " escape ''" ); } } protected boolean allowsNullPrecedence() { return getClauseStack().getCurrent() != Clause.WITHIN_GROUP || getDialect().supportsNullPrecedence(); } private boolean supportsOffsetFetchClause() { return getDialect().getVersion().isSameOrAfter( 1, 4, 195 ); } private boolean supportsOffsetFetchClausePercentWithTies() { // Introduction of TIES clause https://github.com/h2database/h2database/commit/876e9fbe7baf11d01675bfe871aac2cf1b6104ce // Introduction of PERCENT support https://github.com/h2database/h2database/commit/f45913302e5f6ad149155a73763c0c59d8205849 return getDialect().getVersion().isSameOrAfter( 1, 4, 198 ); } }
H2LegacySqlAstTranslator
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/cobar/HintsTest.java
{ "start": 900, "end": 2275 }
class ____ extends TestCase { public void test_hints_0() throws Exception { String sql = "CREATE /*!32302 TEMPORARY */ TABLE t (a INT);"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("CREATE /*!32302 TEMPORARY */ TABLE t (\n\ta INT\n);", output); } public void test_hints_1() throws Exception { String sql = "SELECT /*! STRAIGHT_JOIN */ col1 FROM table1,table2"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("SELECT /*! STRAIGHT_JOIN */ col1\nFROM table1, table2", output); } public void test_hints_none() throws Exception { String sql = "SELECT /* STRAIGHT_JOIN */ col1 FROM table1,table2"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals( "SELECT /* STRAIGHT_JOIN */\n" + "\tcol1\n" + "FROM table1, table2", output); } }
HintsTest