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
processing__processing4
app/src/processing/app/syntax/InputHandler.java
{ "start": 15564, "end": 16286 }
class ____ implements ActionListener { public void actionPerformed(ActionEvent evt) { JEditTextArea textArea = getTextArea(evt); if (!textArea.isEditable()) { textArea.getToolkit().beep(); return; } if (textArea.getSelectionStart() != textArea.getSelectionStop()) { textArea.setSelectedText(""); } else { int caret = textArea.getCaretPosition(); if (caret == textArea.getDocumentLength()) { textArea.getToolkit().beep(); return; } try { textArea.getDocument().remove(caret,1); } catch(BadLocationException bl) { bl.printStackTrace(); } } } } public static
delete
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ConditionAndGroupGenericParameterTypeShouldBeTheSame.java
{ "start": 942, "end": 1731 }
class ____ extends BasicErrorMessageFactory { public ConditionAndGroupGenericParameterTypeShouldBeTheSame(Object actual, Condition<?> condition) { super("%nExpecting actual: %s to have the same generic type as condition %s", actual, condition); } /** * Creates a new <code>{@link ConditionAndGroupGenericParameterTypeShouldBeTheSame}</code> * @param actual the actual value in the failed assertion. * @param condition the {@code Condition}. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeSameGenericBetweenIterableAndCondition(Object actual, Condition<?> condition) { return new ConditionAndGroupGenericParameterTypeShouldBeTheSame(actual, condition); } }
ConditionAndGroupGenericParameterTypeShouldBeTheSame
java
apache__flink
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStIncrementalCheckpointUtils.java
{ "start": 13855, "end": 14190 }
class ____ represents the result of a range check of the actual keys in a RocksDB * instance against the proclaimed key-group range of the instance. In short, this checks if the * instance contains any keys (or tombstones for keys) that don't belong in the instance's * key-groups range. */ public static final
that
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/AggregatorFunctionSupplier.java
{ "start": 526, "end": 1931 }
interface ____ extends Describable { List<IntermediateStateDesc> nonGroupingIntermediateStateDesc(); List<IntermediateStateDesc> groupingIntermediateStateDesc(); AggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels); GroupingAggregatorFunction groupingAggregator(DriverContext driverContext, List<Integer> channels); default Aggregator.Factory aggregatorFactory(AggregatorMode mode, List<Integer> channels) { return new Aggregator.Factory() { @Override public Aggregator apply(DriverContext driverContext) { return new Aggregator(aggregator(driverContext, channels), mode); } @Override public String describe() { return AggregatorFunctionSupplier.this.describe(); } }; } default GroupingAggregator.Factory groupingAggregatorFactory(AggregatorMode mode, List<Integer> channels) { return new GroupingAggregator.Factory() { @Override public GroupingAggregator apply(DriverContext driverContext) { return new GroupingAggregator(groupingAggregator(driverContext, channels), mode); } @Override public String describe() { return AggregatorFunctionSupplier.this.describe(); } }; } }
AggregatorFunctionSupplier
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java
{ "start": 5306, "end": 6020 }
class ____ of the * associated {@link PropertyEditor} as value. * @see ConfigurableListableBeanFactory#registerCustomEditor */ public void setCustomEditors(Map<Class<?>, Class<? extends PropertyEditor>> customEditors) { this.customEditors = customEditors; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.propertyEditorRegistrars != null) { for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) { beanFactory.addPropertyEditorRegistrar(propertyEditorRegistrar); } } if (this.customEditors != null) { this.customEditors.forEach(beanFactory::registerCustomEditor); } } }
name
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/actuator/endpoints/security/exposeall/MySecurityConfiguration.java
{ "start": 1100, "end": 1374 }
class ____ { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) { http.securityMatcher(EndpointRequest.toAnyEndpoint()); http.authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()); return http.build(); } }
MySecurityConfiguration
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/IndexingPressureMonitor.java
{ "start": 1379, "end": 1582 }
interface ____ receiving notifications about indexing pressure events. * Implementations can respond to tracking of primary operations and rejections * of large indexing operations. */
for
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/update/SqmAssignment.java
{ "start": 458, "end": 1825 }
class ____<T> implements SqmCacheable { private final SqmPath<T> targetPath; private final SqmExpression<? extends T> value; public SqmAssignment(SqmPath<T> targetPath, SqmExpression<? extends T> value) { this.targetPath = targetPath; this.value = value; this.value.applyInferableType( targetPath.getNodeType() ); } public SqmAssignment<T> copy(SqmCopyContext context) { return new SqmAssignment<>( targetPath.copy( context ), value.copy( context ) ); } /** * The attribute/path to be updated */ public SqmPath<T> getTargetPath() { return targetPath; } /** * The new value */ public SqmExpression<? extends T> getValue() { return value; } @Override public boolean equals(@Nullable Object object) { return object instanceof SqmAssignment<?> that && targetPath.equals( that.targetPath ) && value.equals( that.value ); } @Override public int hashCode() { int result = targetPath.hashCode(); result = 31 * result + value.hashCode(); return result; } @Override public boolean isCompatible(Object object) { return object instanceof SqmAssignment<?> that && targetPath.isCompatible( that.targetPath ) && value.isCompatible( that.value ); } @Override public int cacheHashCode() { int result = targetPath.cacheHashCode(); result = 31 * result + value.cacheHashCode(); return result; } }
SqmAssignment
java
greenrobot__greendao
tests/DaoTest/src/androidTest/java/org/greenrobot/greendao/daotest/entity/AutoincrementEntityTest.java
{ "start": 1130, "end": 2058 }
class ____ extends AbstractDaoSessionTest<DaoMaster, DaoSession> { public AutoincrementEntityTest() { super(DaoMaster.class); } public void testAutoincrement() { AutoincrementEntity entity = new AutoincrementEntity(); daoSession.insert(entity); Long id1 = entity.getId(); assertNotNull(id1); daoSession.delete(entity); AutoincrementEntity entity2 = new AutoincrementEntity(); daoSession.insert(entity2); assertEquals(id1 + 1, (long) entity2.getId()); } public void testNoAutoincrement() { SimpleEntity entity = new SimpleEntity(); daoSession.insert(entity); Long id1 = entity.getId(); assertNotNull(id1); daoSession.delete(entity); SimpleEntity entity2 = new SimpleEntity(); daoSession.insert(entity2); assertEquals(id1, entity2.getId()); } }
AutoincrementEntityTest
java
apache__maven
compat/maven-compat/src/test/java/org/apache/maven/artifact/resolver/filter/FilterHashEqualsTest.java
{ "start": 1013, "end": 1740 }
class ____ { @Test void testIncludesExcludesArtifactFilter() { List<String> patterns = Arrays.asList("c", "d", "e"); IncludesArtifactFilter f1 = new IncludesArtifactFilter(patterns); IncludesArtifactFilter f2 = new IncludesArtifactFilter(patterns); assertTrue(f1.equals(f2), "Expected " + f1 + " to equal " + f2); assertTrue(f2.equals(f1), "Expected " + f2 + " to equal " + f1); assertTrue(f1.hashCode() == f2.hashCode()); IncludesArtifactFilter f3 = new IncludesArtifactFilter(Arrays.asList("d", "c", "e")); assertTrue(f1.equals(f3), "Expected " + f1 + " to equal " + f3); assertTrue(f1.hashCode() == f3.hashCode()); } }
FilterHashEqualsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TransientOverrideAsPersistentJoinedTests.java
{ "start": 9841, "end": 10762 }
class ____ extends Employee { private Group group; public Writer(String name, Group group) { super( name ); setGroup( group ); } // Cannot have a constraint on e_title because // Editor#title (which uses the same e_title column) can be non-null, // and there is no associated group. @ManyToOne(optional = false) @JoinColumn(name = "e_title", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) public Group getGroup() { return group; } @Column(name = "e_title", insertable = false, updatable = false) public String getTitle() { return super.getTitle(); } public void setTitle(String title) { super.setTitle( title ); } protected Writer() { // this form used by Hibernate super(); } protected void setGroup(Group group) { this.group = group; setTitle( group.getName() ); } } @Entity(name = "Group") @Table(name = "WorkGroup") public static
Writer
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/function/FailableTest.java
{ "start": 5913, "end": 70769 }
class ____<T, P> { private T acceptedObject; private P acceptedPrimitiveObject1; private P acceptedPrimitiveObject2; private Throwable throwable; Testable(final Throwable throwable) { this.throwable = throwable; } public T getAcceptedObject() { return acceptedObject; } public P getAcceptedPrimitiveObject1() { return acceptedPrimitiveObject1; } public P getAcceptedPrimitiveObject2() { return acceptedPrimitiveObject2; } public void setThrowable(final Throwable throwable) { this.throwable = throwable; } void test() throws Throwable { test(throwable); } public Object test(final Object input1, final Object input2) throws Throwable { test(throwable); return acceptedObject; } void test(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } } public boolean testAsBooleanPrimitive() throws Throwable { return testAsBooleanPrimitive(throwable); } public boolean testAsBooleanPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return false; } public double testAsDoublePrimitive() throws Throwable { return testAsDoublePrimitive(throwable); } public double testAsDoublePrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } public Integer testAsInteger() throws Throwable { return testAsInteger(throwable); } public Integer testAsInteger(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } public int testAsIntPrimitive() throws Throwable { return testAsIntPrimitive(throwable); } public int testAsIntPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } public long testAsLongPrimitive() throws Throwable { return testAsLongPrimitive(throwable); } public long testAsLongPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } public short testAsShortPrimitive() throws Throwable { return testAsShortPrimitive(throwable); } public short testAsShortPrimitive(final Throwable throwable) throws Throwable { if (throwable != null) { throw throwable; } return 0; } void testDouble(final double i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) (Double) i; } public double testDoubleDouble(final double i, final double j) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) (Double) i; acceptedPrimitiveObject2 = (P) (Double) j; return 3d; } void testInt(final int i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) (Integer) i; } void testLong(final long i) throws Throwable { test(throwable); acceptedPrimitiveObject1 = (P) (Long) i; } void testObjDouble(final T object, final double i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) (Double) i; } void testObjInt(final T object, final int i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) (Integer) i; } void testObjLong(final T object, final long i) throws Throwable { test(throwable); acceptedObject = object; acceptedPrimitiveObject1 = (P) (Long) i; } } private static final OutOfMemoryError ERROR = new OutOfMemoryError(); private static final IllegalStateException ILLEGAL_STATE_EXCEPTION = new IllegalStateException(); @BeforeEach void beforeEach() { FailureOnOddInvocations.reset(); } @Test void testAcceptBiConsumer() { final Testable<?, ?> testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable, ILLEGAL_STATE_EXCEPTION)); assertSame(ILLEGAL_STATE_EXCEPTION, e); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable, ERROR)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(Testable::test, testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); Failable.accept(Testable::test, testable, (Throwable) null); } @Test void testAcceptConsumer() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(Testable::test, testable)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(Testable::test, testable)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(Testable::test, testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); Failable.accept(Testable::test, testable); } @Test void testAcceptDoubleConsumer() { final Testable<?, Double> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testDouble, 1d)); assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testDouble, 1d)); assertSame(ERROR, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testDouble, 1d)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Failable.accept(testable::testDouble, 1d); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test void testAcceptIntConsumer() { final Testable<?, Integer> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testInt, 1)); assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testInt, 1)); assertSame(ERROR, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testInt, 1)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Failable.accept(testable::testInt, 1); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test void testAcceptLongConsumer() { final Testable<?, Long> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testLong, 1L)); assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testLong, 1L)); assertSame(ERROR, e); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testLong, 1L)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Failable.accept(testable::testLong, 1L); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test void testAcceptObjDoubleConsumer() { final Testable<String, Double> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); assertSame(ERROR, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testObjDouble, "X", 1d)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Failable.accept(testable::testObjDouble, "X", 1d); assertEquals("X", testable.getAcceptedObject()); assertEquals(1d, testable.getAcceptedPrimitiveObject1()); } @Test void testAcceptObjIntConsumer() { final Testable<String, Integer> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjInt, "X", 1)); assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjInt, "X", 1)); assertSame(ERROR, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testObjInt, "X", 1)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Failable.accept(testable::testObjInt, "X", 1); assertEquals("X", testable.getAcceptedObject()); assertEquals(1, testable.getAcceptedPrimitiveObject1()); } @Test void testAcceptObjLongConsumer() { final Testable<String, Long> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); assertSame(ILLEGAL_STATE_EXCEPTION, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); assertSame(ERROR, e); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.accept(testable::testObjLong, "X", 1L)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertNull(testable.getAcceptedObject()); assertNull(testable.getAcceptedPrimitiveObject1()); testable.setThrowable(null); Failable.accept(testable::testObjLong, "X", 1L); assertEquals("X", testable.getAcceptedObject()); assertEquals(1L, testable.getAcceptedPrimitiveObject1()); } @Test void testApplyBiFunction() { final Testable<?, ?> testable = new Testable<>(null); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.apply(Testable::testAsInteger, testable, ILLEGAL_STATE_EXCEPTION)); assertSame(ILLEGAL_STATE_EXCEPTION, e); e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable, ERROR)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); e = assertThrows(UncheckedIOException.class, () -> Failable.apply(Testable::testAsInteger, testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); final Integer i = Failable.apply(Testable::testAsInteger, testable, (Throwable) null); assertNotNull(i); assertEquals(0, i.intValue()); } @Test void testApplyDoubleBinaryOperator() { final Testable<?, Double> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final Throwable e = assertThrows(IllegalStateException.class, () -> Failable.applyAsDouble(testable::testDoubleDouble, 1d, 2d)); assertSame(ILLEGAL_STATE_EXCEPTION, e); final Testable<?, Double> testable2 = new Testable<>(null); final double i = Failable.applyAsDouble(testable2::testDoubleDouble, 1d, 2d); assertEquals(3d, i); } @Test void testApplyFunction() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.apply(Testable::testAsInteger, testable)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.apply(Testable::testAsInteger, testable)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.apply(Testable::testAsInteger, testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); final Integer i = Failable.apply(Testable::testAsInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } @Test void testApplyNonNull() throws SomeException { // No checked exceptions in signatures assertEquals("A", Failable.applyNonNull("a", String::toUpperCase)); assertNull(Failable.applyNonNull((String) null, String::toUpperCase)); assertNull(Failable.applyNonNull("a", s -> null)); assertThrows(NullPointerException.class, () -> Failable.applyNonNull("a", null)); // Checked exceptions in signatures final FailureOnInvocationCount obj1 = new FailureOnInvocationCount(1); assertEquals(1, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj1::inc)).value); assertEquals(2, Failable.applyNonNull(1, obj1::inc)); } @Test void testApplyNonNull2() throws SomeException, IOException { // No checked exceptions in signatures assertEquals("A", Failable.applyNonNull(" a ", String::toUpperCase, String::trim)); assertNull(Failable.applyNonNull((String) null, String::toUpperCase, String::trim)); assertNull(Failable.applyNonNull(" a ", s -> null, String::trim)); assertNull(Failable.applyNonNull(" a ", String::toUpperCase, s -> null)); assertThrows(NullPointerException.class, () -> Failable.applyNonNull(" a ", null, String::trim)); assertThrows(NullPointerException.class, () -> Failable.applyNonNull(" a ", String::toUpperCase, null)); // Same checked exceptions in signatures final FailureOnInvocationCount obj1 = new FailureOnInvocationCount(1); final FailureOnInvocationCount obj2 = new FailureOnInvocationCount(2); assertEquals(1, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj1::inc, obj1::inc)).value); assertEquals(2, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj2::inc, obj2::inc)).value); assertEquals(3, Failable.applyNonNull(1, obj1::inc, obj1::inc)); assertEquals(3, Failable.applyNonNull(1, obj2::inc, obj2::inc)); // Different checked exceptions in signatures obj1.reset(); obj2.reset(); assertEquals(1, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj1::inc, obj1::incIo)).value); assertEquals(2, ((SomeException) assertThrows(IOException.class, () -> Failable.applyNonNull(1, obj2::inc, obj2::incIo)).getCause()).value); assertEquals(3, Failable.applyNonNull(1, obj1::inc, obj1::incIo)); assertEquals(3, Failable.applyNonNull(1, obj2::inc, obj2::incIo)); } @Test void testApplyNonNull3() throws SomeException, IOException, ClassNotFoundException { // No checked exceptions in signatures assertEquals("CBA", Failable.applyNonNull(" abc ", String::toUpperCase, String::trim, StringUtils::reverse)); assertNull(Failable.applyNonNull((String) null, String::toUpperCase, String::trim, StringUtils::reverse)); assertNull(Failable.applyNonNull(" abc ", s -> null, String::trim, StringUtils::reverse)); assertNull(Failable.applyNonNull(" abc ", String::toUpperCase, s -> null, StringUtils::reverse)); assertNull(Failable.applyNonNull(" abc ", String::toUpperCase, String::trim, s -> null)); assertThrows(NullPointerException.class, () -> Failable.applyNonNull(" abc ", null, String::trim, StringUtils::reverse)); assertThrows(NullPointerException.class, () -> Failable.applyNonNull(" abc ", String::toUpperCase, null, StringUtils::reverse)); assertThrows(NullPointerException.class, () -> Failable.applyNonNull(" abc ", String::toUpperCase, String::trim, null)); // Same checked exceptions in signatures final FailureOnInvocationCount obj1 = new FailureOnInvocationCount(1); final FailureOnInvocationCount obj2 = new FailureOnInvocationCount(2); final FailureOnInvocationCount obj3 = new FailureOnInvocationCount(3); assertEquals(1, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj1::inc, obj1::inc, obj1::inc)).value); assertEquals(2, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj2::inc, obj2::inc, obj2::inc)).value); assertEquals(3, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj3::inc, obj3::inc, obj3::inc)).value); assertEquals(4, Failable.applyNonNull(1, obj1::inc, obj1::inc, obj1::inc)); assertEquals(4, Failable.applyNonNull(1, obj2::inc, obj2::inc, obj2::inc)); assertEquals(4, Failable.applyNonNull(1, obj3::inc, obj3::inc, obj3::inc)); // Different checked exceptions in signatures obj1.reset(); obj2.reset(); obj3.reset(); assertEquals(1, assertThrows(SomeException.class, () -> Failable.applyNonNull(1, obj1::inc, obj1::incIo, obj1::incIo)).value); assertEquals(2, ((SomeException) assertThrows(IOException.class, () -> Failable.applyNonNull(1, obj2::inc, obj2::incIo, obj2::incIo)).getCause()).value); assertEquals(3, ((SomeException) assertThrows(IOException.class, () -> Failable.applyNonNull(1, obj3::inc, obj3::incIo, obj3::incIo)).getCause()).value); assertEquals(4, Failable.applyNonNull(1, obj1::inc, obj1::incIo, obj1::incIo)); assertEquals(4, Failable.applyNonNull(1, obj2::inc, obj2::incIo, obj2::incIo)); assertEquals(4, Failable.applyNonNull(1, obj3::inc, obj3::incIo, obj3::incIo)); } @Test void testAsCallable() { FailureOnOddInvocations.invocations = 0; final FailableCallable<FailureOnOddInvocations, SomeException> failableCallable = FailureOnOddInvocations::new; final Callable<FailureOnOddInvocations> callable = Failable.asCallable(failableCallable); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, callable::call); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); final FailureOnOddInvocations instance; try { instance = callable.call(); } catch (final Exception ex) { throw Failable.rethrow(ex); } assertNotNull(instance); } @Test void testAsConsumer() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final Consumer<Testable<?, ?>> consumer = Failable.asConsumer(Testable::test); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); Failable.accept(Testable::test, testable); } @Test void testAsRunnable() { FailureOnOddInvocations.invocations = 0; final Runnable runnable = Failable.asRunnable(FailureOnOddInvocations::new); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, runnable::run); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); // Even invocations, should not throw an exception runnable.run(); } @Test void testAsSupplier() { FailureOnOddInvocations.invocations = 0; final FailableSupplier<FailureOnOddInvocations, Throwable> failableSupplier = FailureOnOddInvocations::new; final Supplier<FailureOnOddInvocations> supplier = Failable.asSupplier(failableSupplier); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, supplier::get); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); assertNotNull(supplier.get()); } @Test void testBiConsumer() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableBiConsumer<Testable<?, ?>, Throwable, Throwable> failableBiConsumer = (t, th) -> { t.setThrowable(th); t.test(); }; final BiConsumer<Testable<?, ?>, Throwable> consumer = Failable.asBiConsumer(failableBiConsumer); Throwable e = assertThrows(IllegalStateException.class, () -> consumer.accept(testable, ILLEGAL_STATE_EXCEPTION)); assertSame(ILLEGAL_STATE_EXCEPTION, e); e = assertThrows(OutOfMemoryError.class, () -> consumer.accept(testable, ERROR)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failableBiConsumer.accept(testable, ERROR)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> consumer.accept(testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); consumer.accept(testable, null); } @Test void testBiConsumerAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableBiConsumer<Testable<?, ?>, Throwable, Throwable> failing = (t, th) -> { t.setThrowable(th); t.test(); }; final FailableBiConsumer<Testable<?, ?>, Throwable, Throwable> nop = FailableBiConsumer.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(testable, ERROR)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(testable, ERROR)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testBiFunction() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final FailableBiFunction<Testable<?, ?>, Throwable, Integer, Throwable> failableBiFunction = (t, th) -> { t.setThrowable(th); return t.testAsInteger(); }; final BiFunction<Testable<?, ?>, Throwable, Integer> biFunction = Failable.asBiFunction(failableBiFunction); Throwable e = assertThrows(IllegalStateException.class, () -> biFunction.apply(testable, ILLEGAL_STATE_EXCEPTION)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> biFunction.apply(testable, ERROR)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> biFunction.apply(testable, ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertEquals(0, biFunction.apply(testable, null).intValue()); } @Test void testBiFunctionAndThen() throws IOException { // Unchecked usage pattern in JRE final BiFunction<Object, Integer, Integer> nopBiFunction = (t, u) -> null; final Function<Object, Integer> nopFunction = t -> null; nopBiFunction.andThen(nopFunction); // Checked usage pattern final FailableBiFunction<Object, Integer, Integer, IOException> failingBiFunctionTest = (t, u) -> { throw new IOException(); }; final FailableFunction<Object, Integer, IOException> failingFunction = t -> { throw new IOException(); }; final FailableBiFunction<Object, Integer, Integer, IOException> nopFailableBiFunction = FailableBiFunction .nop(); final FailableFunction<Object, Integer, IOException> nopFailableFunction = FailableFunction.nop(); // assertThrows(IOException.class, () -> failingBiFunctionTest.andThen(failingFunction).apply(null, null)); assertThrows(IOException.class, () -> failingBiFunctionTest.andThen(nopFailableFunction).apply(null, null)); // assertThrows(IOException.class, () -> nopFailableBiFunction.andThen(failingFunction).apply(null, null)); nopFailableBiFunction.andThen(nopFailableFunction).apply(null, null); // Documented in Javadoc edge-case. assertNullPointerException(() -> failingBiFunctionTest.andThen(null)); } @Test @DisplayName("Test that asPredicate(FailableBiPredicate) is converted to -> BiPredicate ") void testBiPredicate() { FailureOnOddInvocations.invocations = 0; final FailableBiPredicate<Object, Object, Throwable> failableBiPredicate = (t1, t2) -> FailureOnOddInvocations .testGetBool(); final BiPredicate<?, ?> predicate = Failable.asBiPredicate(failableBiPredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null, null)); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); assertTrue(predicate.test(null, null)); } @Test void testBiPredicateAnd() throws Throwable { assertTrue(FailableBiPredicate.TRUE.and(FailableBiPredicate.TRUE).test(null, null)); assertFalse(FailableBiPredicate.TRUE.and(FailableBiPredicate.FALSE).test(null, null)); assertFalse(FailableBiPredicate.FALSE.and(FailableBiPredicate.TRUE).test(null, null)); assertFalse(FailableBiPredicate.FALSE.and(FailableBiPredicate.FALSE).test(null, null)); // null tests assertNullPointerException( () -> assertFalse(FailableBiPredicate.falsePredicate().and(null).test(null, null))); assertNullPointerException( () -> assertTrue(FailableBiPredicate.truePredicate().and(null).test(null, null))); } @Test void testBiPredicateNegate() throws Throwable { assertFalse(FailableBiPredicate.TRUE.negate().test(null, null)); assertFalse(FailableBiPredicate.truePredicate().negate().test(null, null)); assertTrue(FailableBiPredicate.FALSE.negate().test(null, null)); assertTrue(FailableBiPredicate.falsePredicate().negate().test(null, null)); } @Test void testBiPredicateOr() throws Throwable { assertTrue(FailableBiPredicate.TRUE.or(FailableBiPredicate.TRUE).test(null, null)); assertTrue(FailableBiPredicate.TRUE.or(FailableBiPredicate.FALSE).test(null, null)); assertTrue(FailableBiPredicate.FALSE.or(FailableBiPredicate.TRUE).test(null, null)); assertFalse(FailableBiPredicate.FALSE.or(FailableBiPredicate.FALSE).test(null, null)); // null tests assertNullPointerException( () -> assertFalse(FailableBiPredicate.falsePredicate().or(null).test(null, null))); assertNullPointerException( () -> assertTrue(FailableBiPredicate.truePredicate().or(null).test(null, null))); } @Test void testByteConsumerAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableByteConsumer<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); }; final FailableByteConsumer<Throwable> nop = FailableByteConsumer.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept((byte) 0)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept((byte) 0)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testCallable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Failable.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); final FailureOnOddInvocations instance = Failable.call(FailureOnOddInvocations::new); assertNotNull(instance); } @Test void testConsumerAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableConsumer<Throwable, Throwable> failableConsumer = th -> { testable.setThrowable(th); testable.test(); }; final FailableConsumer<Throwable, Throwable> nop = FailableConsumer.nop(); final Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failableConsumer).accept(ERROR)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failableConsumer.andThen(null)); } @Test void testDoubleConsumerAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableDoubleConsumer<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); }; final FailableDoubleConsumer<Throwable> nop = FailableDoubleConsumer.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(0d)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(0d)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testDoublePredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; final FailableDoublePredicate<Throwable> failablePredicate = FailureOnOddInvocations::testDouble; assertThrows(SomeException.class, () -> failablePredicate.test(1d)); failablePredicate.test(1d); } @Test void testDoublePredicateAnd() throws Throwable { assertTrue(FailableDoublePredicate.TRUE.and(FailableDoublePredicate.TRUE).test(0)); assertFalse(FailableDoublePredicate.TRUE.and(FailableDoublePredicate.FALSE).test(0)); assertFalse(FailableDoublePredicate.FALSE.and(FailableDoublePredicate.TRUE).test(0)); assertFalse(FailableDoublePredicate.FALSE.and(FailableDoublePredicate.FALSE).test(0)); // null tests assertNullPointerException( () -> assertFalse(FailableDoublePredicate.falsePredicate().and(null).test(0))); assertNullPointerException( () -> assertTrue(FailableDoublePredicate.truePredicate().and(null).test(0))); } @Test void testDoublePredicateNegate() throws Throwable { assertFalse(FailableDoublePredicate.TRUE.negate().test(0d)); assertFalse(FailableDoublePredicate.truePredicate().negate().test(0d)); assertTrue(FailableDoublePredicate.FALSE.negate().test(0d)); assertTrue(FailableDoublePredicate.falsePredicate().negate().test(0d)); } @Test void testDoublePredicateOr() throws Throwable { assertTrue(FailableDoublePredicate.TRUE.or(FailableDoublePredicate.TRUE).test(0)); assertTrue(FailableDoublePredicate.TRUE.or(FailableDoublePredicate.FALSE).test(0)); assertTrue(FailableDoublePredicate.FALSE.or(FailableDoublePredicate.TRUE).test(0)); assertFalse(FailableDoublePredicate.FALSE.or(FailableDoublePredicate.FALSE).test(0)); // null tests assertNullPointerException( () -> assertFalse(FailableDoublePredicate.falsePredicate().or(null).test(0))); assertNullPointerException( () -> assertTrue(FailableDoublePredicate.truePredicate().or(null).test(0))); } @Test void testDoubleUnaryOperatorAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableDoubleUnaryOperator<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0d; }; final FailableDoubleUnaryOperator<Throwable> nop = FailableDoubleUnaryOperator.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).applyAsDouble(0d)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).applyAsDouble(0d)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testDoubleUnaryOperatorCompose() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableDoubleUnaryOperator<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0d; }; final FailableDoubleUnaryOperator<Throwable> nop = FailableDoubleUnaryOperator.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).applyAsDouble(0d)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).applyAsDouble(0d)); assertSame(ERROR, e); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.compose(null)); } @Test void testDoubleUnaryOperatorIdentity() throws Throwable { final FailableDoubleUnaryOperator<Throwable> nop = FailableDoubleUnaryOperator.identity(); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> nop.compose(null)); } @Test void testFailableBiFunctionNop() throws Throwable { assertNull(FailableBiFunction.nop().apply("Foo", "Bar"), "Expect NOP to return null"); } @Test void testFailableConsumerNop() throws Throwable { // Expect nothing thrown FailableConsumer.nop().accept("Foo"); } @Test void testFailableDoubleFunctionNop() throws Throwable { assertNull(FailableDoubleFunction.nop().apply(Double.MAX_VALUE), "Expect NOP to return null"); } @Test void testFailableDoubleToIntFunctionNop() throws Throwable { assertEquals(0, FailableDoubleToIntFunction.nop().applyAsInt(Double.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableDoubleToLongFunctionNop() throws Throwable { assertEquals(0, FailableDoubleToLongFunction.nop().applyAsLong(Double.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableIntFunctionNop() throws Throwable { assertNull(FailableIntFunction.nop().apply(Integer.MAX_VALUE), "Expect NOP to return null"); } @Test void testFailableIntToDoubleFunctionNop() throws Throwable { assertEquals(0, FailableIntToDoubleFunction.nop().applyAsDouble(Integer.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableIntToFloatFunctionNop() throws Throwable { assertEquals(0, FailableIntToFloatFunction.nop().applyAsFloat(Integer.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableIntToLongFunctionNop() throws Throwable { assertEquals(0, FailableIntToLongFunction.nop().applyAsLong(Integer.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableLongFunctionNop() throws Throwable { assertNull(FailableLongFunction.nop().apply(Long.MAX_VALUE), "Expect NOP to return null"); } @Test void testFailableLongToDoubleFunctionNop() throws Throwable { assertEquals(0, FailableLongToDoubleFunction.nop().applyAsDouble(Long.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableLongToIntFunctionNop() throws Throwable { assertEquals(0, FailableLongToIntFunction.nop().applyAsInt(Long.MAX_VALUE), "Expect NOP to return 0"); } @Test void testFailableObjDoubleConsumerNop() throws Throwable { // Expect nothing thrown FailableObjDoubleConsumer.nop().accept("Foo", Double.MAX_VALUE); } @Test void testFailableObjIntConsumerNop() throws Throwable { // Expect nothing thrown FailableObjIntConsumer.nop().accept("Foo", Integer.MAX_VALUE); } @Test void testFailableObjLongConsumerNop() throws Throwable { // Expect nothing thrown FailableObjLongConsumer.nop().accept("Foo", Long.MAX_VALUE); } @Test void testFailableToBooleanFunctionNop() throws Throwable { assertEquals(false, FailableToBooleanFunction.nop().applyAsBoolean("Foo"), "Expect NOP to return false"); } @Test void testFailableToDoubleBiFunctionNop() throws Throwable { assertEquals(0, FailableToDoubleBiFunction.nop().applyAsDouble("Foo", "Bar"), "Expect NOP to return 0"); } @Test void testFailableToDoubleFunctionNop() throws Throwable { assertEquals(0, FailableToDoubleFunction.nop().applyAsDouble("Foo"), "Expect NOP to return 0"); } @Test void testFailableToIntBiFunctionNop() throws Throwable { assertEquals(0, FailableToIntBiFunction.nop().applyAsInt("Foo", "Bar"), "Expect NOP to return 0"); } @Test void testFailableToIntFunctionNop() throws Throwable { assertEquals(0, FailableToIntFunction.nop().applyAsInt("Foo"), "Expect NOP to return 0"); } @Test void testFailableToLongBiFunctionNop() throws Throwable { assertEquals(0, FailableToLongBiFunction.nop().applyAsLong("Foo", "Bar"), "Expect NOP to return 0"); } @Test void testFailableToLongFunctionNop() throws Throwable { assertEquals(0, FailableToLongFunction.nop().applyAsLong("Foo"), "Expect NOP to return 0"); } @Test void testFunction() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); final FailableFunction<Throwable, Integer, Throwable> failableFunction = th -> { testable.setThrowable(th); return testable.testAsInteger(); }; final Function<Throwable, Integer> function = Failable.asFunction(failableFunction); Throwable e = assertThrows(IllegalStateException.class, () -> function.apply(ILLEGAL_STATE_EXCEPTION)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> function.apply(ERROR)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> function.apply(ioe)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); assertEquals(0, function.apply(null).intValue()); } @Test void testFunctionAndThen() throws IOException { // Unchecked usage pattern in JRE final Function<Object, Integer> nopFunction = t -> null; nopFunction.andThen(nopFunction); // Checked usage pattern final FailableFunction<Object, Integer, IOException> failingFunction = t -> { throw new IOException(); }; final FailableFunction<Object, Integer, IOException> nopFailableFunction = FailableFunction.nop(); // assertThrows(IOException.class, () -> failingFunction.andThen(failingFunction).apply(null)); assertThrows(IOException.class, () -> failingFunction.andThen(nopFailableFunction).apply(null)); // assertThrows(IOException.class, () -> nopFailableFunction.andThen(failingFunction).apply(null)); nopFailableFunction.andThen(nopFailableFunction).apply(null); // Documented in Javadoc edge-case. assertNullPointerException(() -> failingFunction.andThen(null)); } @Test void testFunctionCompose() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableFunction<Object, Integer, Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0; }; final FailableFunction<Object, Integer, Throwable> nop = FailableFunction.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).apply(0)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).apply(0)); assertSame(ERROR, e); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.compose(null)); } @Test void testFunctionFunction() throws Exception { assertEquals("foo", FailableFunction.function(this::throwingFunction).andThen(this::throwingFunction).apply("foo")); } @Test void testFunctionIdentity() throws Throwable { final FailableFunction<Integer, Integer, Throwable> nop = FailableFunction.identity(); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> nop.compose(null)); } @Test void testGetAsBooleanSupplier() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.getAsBoolean(testable::testAsBooleanPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); assertFalse(Failable.getAsBoolean(testable::testAsBooleanPrimitive)); } @Test void testGetAsDoubleSupplier() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.getAsDouble(testable::testAsDoublePrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); assertEquals(0, Failable.getAsDouble(testable::testAsDoublePrimitive)); } @Test void testGetAsIntSupplier() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.getAsInt(testable::testAsIntPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); final int i = Failable.getAsInt(testable::testAsInteger); assertEquals(0, i); } @Test void testGetAsLongSupplier() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.getAsLong(testable::testAsLongPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); final long i = Failable.getAsLong(testable::testAsLongPrimitive); assertEquals(0, i); } @Test void testGetAsShortSupplier() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.getAsShort(testable::testAsShortPrimitive)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsShort(testable::testAsShortPrimitive)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.getAsShort(testable::testAsShortPrimitive)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); final short i = Failable.getAsShort(testable::testAsShortPrimitive); assertEquals(0, i); } @Test void testGetFromSupplier() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Failable.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); final FailureOnOddInvocations instance = Failable.call(FailureOnOddInvocations::new); assertNotNull(instance); } @Test void testGetSupplier() { final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION); Throwable e = assertThrows(IllegalStateException.class, () -> Failable.get(testable::testAsInteger)); assertSame(ILLEGAL_STATE_EXCEPTION, e); testable.setThrowable(ERROR); e = assertThrows(OutOfMemoryError.class, () -> Failable.get(testable::testAsInteger)); assertSame(ERROR, e); final IOException ioe = new IOException("Unknown I/O error"); testable.setThrowable(ioe); e = assertThrows(UncheckedIOException.class, () -> Failable.get(testable::testAsInteger)); final Throwable t = e.getCause(); assertNotNull(t); assertSame(ioe, t); testable.setThrowable(null); final Integer i = Failable.apply(Testable::testAsInteger, testable); assertNotNull(i); assertEquals(0, i.intValue()); } @Test void testIntConsumerAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableIntConsumer<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); }; final FailableIntConsumer<Throwable> nop = FailableIntConsumer.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(0)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(0)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testIntPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; final FailableIntPredicate<Throwable> failablePredicate = FailureOnOddInvocations::testInt; assertThrows(SomeException.class, () -> failablePredicate.test(1)); failablePredicate.test(1); } @Test void testIntPredicateAnd() throws Throwable { assertTrue(FailableIntPredicate.TRUE.and(FailableIntPredicate.TRUE).test(0)); assertFalse(FailableIntPredicate.TRUE.and(FailableIntPredicate.FALSE).test(0)); assertFalse(FailableIntPredicate.FALSE.and(FailableIntPredicate.TRUE).test(0)); assertFalse(FailableIntPredicate.FALSE.and(FailableIntPredicate.FALSE).test(0)); // null tests assertNullPointerException( () -> assertFalse(FailableIntPredicate.falsePredicate().and(null).test(0))); assertNullPointerException( () -> assertTrue(FailableIntPredicate.truePredicate().and(null).test(0))); } @Test void testIntPredicateNegate() throws Throwable { assertFalse(FailableIntPredicate.TRUE.negate().test(0)); assertFalse(FailableIntPredicate.truePredicate().negate().test(0)); assertTrue(FailableIntPredicate.FALSE.negate().test(0)); assertTrue(FailableIntPredicate.falsePredicate().negate().test(0)); } @Test void testIntPredicateOr() throws Throwable { assertTrue(FailableIntPredicate.TRUE.or(FailableIntPredicate.TRUE).test(0)); assertTrue(FailableIntPredicate.TRUE.or(FailableIntPredicate.FALSE).test(0)); assertTrue(FailableIntPredicate.FALSE.or(FailableIntPredicate.TRUE).test(0)); assertFalse(FailableIntPredicate.FALSE.or(FailableIntPredicate.FALSE).test(0)); // null tests assertNullPointerException( () -> assertFalse(FailableIntPredicate.falsePredicate().or(null).test(0))); assertNullPointerException( () -> assertTrue(FailableIntPredicate.truePredicate().or(null).test(0))); } @Test void testIntUnaryOperatorAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableIntUnaryOperator<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0; }; final FailableIntUnaryOperator<Throwable> nop = FailableIntUnaryOperator.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).applyAsInt(0)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).applyAsInt(0)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testIntUnaryOperatorCompose() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableIntUnaryOperator<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0; }; final FailableIntUnaryOperator<Throwable> nop = FailableIntUnaryOperator.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).applyAsInt(0)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).applyAsInt(0)); assertSame(ERROR, e); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.compose(null)); } @Test void testIntUnaryOperatorIdentity() throws Throwable { final FailableIntUnaryOperator<Throwable> nop = FailableIntUnaryOperator.identity(); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> nop.compose(null)); } @Test void testLongConsumerAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableLongConsumer<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); }; final FailableLongConsumer<Throwable> nop = FailableLongConsumer.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).accept(0L)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).accept(0L)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testLongPredicate() throws Throwable { FailureOnOddInvocations.invocations = 0; final FailableLongPredicate<Throwable> failablePredicate = FailureOnOddInvocations::testLong; assertThrows(SomeException.class, () -> failablePredicate.test(1L)); failablePredicate.test(1L); } @Test void testLongPredicateAnd() throws Throwable { assertTrue(FailableLongPredicate.TRUE.and(FailableLongPredicate.TRUE).test(0)); assertFalse(FailableLongPredicate.TRUE.and(FailableLongPredicate.FALSE).test(0)); assertFalse(FailableLongPredicate.FALSE.and(FailableLongPredicate.TRUE).test(0)); assertFalse(FailableLongPredicate.FALSE.and(FailableLongPredicate.FALSE).test(0)); // null tests assertNullPointerException(() -> assertFalse(FailableLongPredicate.falsePredicate().and(null).test(0))); assertNullPointerException(() -> assertTrue(FailableLongPredicate.truePredicate().and(null).test(0))); } @Test void testLongPredicateNegate() throws Throwable { assertFalse(FailableLongPredicate.TRUE.negate().test(0L)); assertFalse(FailableLongPredicate.truePredicate().negate().test(0L)); assertTrue(FailableLongPredicate.FALSE.negate().test(0L)); assertTrue(FailableLongPredicate.falsePredicate().negate().test(0L)); } @Test void testLongPredicateOr() throws Throwable { assertTrue(FailableLongPredicate.TRUE.or(FailableLongPredicate.TRUE).test(0)); assertTrue(FailableLongPredicate.TRUE.or(FailableLongPredicate.FALSE).test(0)); assertTrue(FailableLongPredicate.FALSE.or(FailableLongPredicate.TRUE).test(0)); assertFalse(FailableLongPredicate.FALSE.or(FailableLongPredicate.FALSE).test(0)); // null tests assertNullPointerException(() -> assertFalse(FailableLongPredicate.falsePredicate().or(null).test(0))); assertNullPointerException(() -> assertTrue(FailableLongPredicate.truePredicate().or(null).test(0))); } @Test void testLongUnaryOperatorAndThen() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableLongUnaryOperator<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0L; }; final FailableLongUnaryOperator<Throwable> nop = FailableLongUnaryOperator.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.andThen(failing).applyAsLong(0L)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.andThen(nop).applyAsLong(0L)); assertSame(ERROR, e); // Does not throw nop.andThen(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.andThen(null)); } @Test void testLongUnaryOperatorCompose() throws Throwable { final Testable<?, ?> testable = new Testable<>(null); final FailableLongUnaryOperator<Throwable> failing = t -> { testable.setThrowable(ERROR); testable.test(); return 0L; }; final FailableLongUnaryOperator<Throwable> nop = FailableLongUnaryOperator.nop(); Throwable e = assertThrows(OutOfMemoryError.class, () -> nop.compose(failing).applyAsLong(0L)); assertSame(ERROR, e); e = assertThrows(OutOfMemoryError.class, () -> failing.compose(nop).applyAsLong(0L)); assertSame(ERROR, e); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> failing.compose(null)); } @Test void testLongUnaryOperatorIdentity() throws Throwable { final FailableLongUnaryOperator<Throwable> nop = FailableLongUnaryOperator.identity(); // Does not throw nop.compose(nop); // Documented in Javadoc edge-case. assertNullPointerException(() -> nop.compose(null)); } @Test @DisplayName("Test that asPredicate(FailablePredicate) is converted to -> Predicate ") void testPredicate() { FailureOnOddInvocations.invocations = 0; final FailablePredicate<Object, Throwable> failablePredicate = t -> FailureOnOddInvocations.testGetBool(); final Predicate<?> predicate = Failable.asPredicate(failablePredicate); final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> predicate.test(null)); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); final boolean instance = predicate.test(null); assertNotNull(instance); } @Test void testPredicateAnd() throws Throwable { assertTrue(FailablePredicate.TRUE.and(FailablePredicate.TRUE).test(null)); assertFalse(FailablePredicate.TRUE.and(FailablePredicate.FALSE).test(null)); assertFalse(FailablePredicate.FALSE.and(FailablePredicate.TRUE).test(null)); assertFalse(FailablePredicate.FALSE.and(FailablePredicate.FALSE).test(null)); // null tests assertNullPointerException(() -> assertFalse(FailablePredicate.FALSE.and(null).test(null))); assertNullPointerException(() -> assertTrue(FailablePredicate.TRUE.and(null).test(null))); } @Test void testPredicateNegate() throws Throwable { assertFalse(FailablePredicate.TRUE.negate().test(null)); assertFalse(FailablePredicate.truePredicate().negate().test(null)); assertTrue(FailablePredicate.FALSE.negate().test(null)); assertTrue(FailablePredicate.falsePredicate().negate().test(null)); } @Test void testPredicateOr() throws Throwable { assertTrue(FailablePredicate.TRUE.or(FailablePredicate.TRUE).test(null)); assertTrue(FailablePredicate.TRUE.or(FailablePredicate.FALSE).test(null)); assertTrue(FailablePredicate.FALSE.or(FailablePredicate.TRUE).test(null)); assertFalse(FailablePredicate.FALSE.or(FailablePredicate.FALSE).test(null)); // null tests assertNullPointerException(() -> assertFalse(FailablePredicate.FALSE.or(null).test(null))); assertNullPointerException(() -> assertTrue(FailablePredicate.TRUE.or(null).test(null))); } @Test void testRunnable() { FailureOnOddInvocations.invocations = 0; final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class, () -> Failable.run(FailureOnOddInvocations::new)); final Throwable cause = e.getCause(); assertNotNull(cause); assertInstanceOf(SomeException.class, cause); assertEquals("Odd Invocation: 1", cause.getMessage()); // Even invocations, should not throw an exception Failable.run(FailureOnOddInvocations::new); Failable.run(null); } /** * Tests that our failable
Testable
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/NodeAttributeOpCode.java
{ "start": 1057, "end": 1240 }
enum ____ { /** * Default as No OP. */ NO_OP, /** * EQUALS op code for Attribute. */ EQ, /** * NOT EQUALS op code for Attribute. */ NE }
NodeAttributeOpCode
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java
{ "start": 3156, "end": 13021 }
class ____ { private String filterProcessesUrl = "/oauth2/token"; private AuthenticationManager authenticationManager; private RequestMatcher requestMatcher; private AuthenticationConverter authenticationConverter; private OAuth2ClientAuthenticationFilter filter; private final HttpMessageConverter<OAuth2Error> errorHttpResponseConverter = new OAuth2ErrorHttpMessageConverter(); @BeforeEach public void setUp() { this.authenticationManager = mock(AuthenticationManager.class); this.requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.POST, this.filterProcessesUrl); this.filter = new OAuth2ClientAuthenticationFilter(this.authenticationManager, this.requestMatcher); this.authenticationConverter = mock(AuthenticationConverter.class); this.filter.setAuthenticationConverter(this.authenticationConverter); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void constructorWhenAuthenticationManagerNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new OAuth2ClientAuthenticationFilter(null, this.requestMatcher)) .withMessage("authenticationManager cannot be null"); } @Test public void constructorWhenRequestMatcherNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new OAuth2ClientAuthenticationFilter(this.authenticationManager, null)) .withMessage("requestMatcher cannot be null"); } @Test public void setAuthenticationConverterWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationConverter(null)) .withMessage("authenticationConverter cannot be null"); } @Test public void setAuthenticationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationSuccessHandler(null)) .withMessage("authenticationSuccessHandler cannot be null"); } @Test public void setAuthenticationFailureHandlerWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationFailureHandler(null)) .withMessage("authenticationFailureHandler cannot be null"); } @Test public void doFilterWhenRequestDoesNotMatchThenNotProcessed() throws Exception { String requestUri = "/path"; MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); request.setServletPath(requestUri); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); verifyNoInteractions(this.authenticationConverter); } @Test public void doFilterWhenRequestMatchesAndEmptyCredentialsThenNotProcessed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); verifyNoInteractions(this.authenticationManager); } @Test public void doFilterWhenRequestMatchesAndInvalidCredentialsThenInvalidRequestError() throws Exception { given(this.authenticationConverter.convert(any(HttpServletRequest.class))) .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); OAuth2Error error = readError(response); assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } // gh-889 @Test public void doFilterWhenRequestMatchesAndClientIdContainsNonPrintableASCIIThenInvalidRequestError() throws Exception { // Hex 00 -> null String clientId = new String(Hex.decode("00"), StandardCharsets.UTF_8); assertWhenInvalidClientIdThenInvalidRequestError(clientId); // Hex 0a61 -> line feed + a clientId = new String(Hex.decode("0a61"), StandardCharsets.UTF_8); assertWhenInvalidClientIdThenInvalidRequestError(clientId); // Hex 1b -> escape clientId = new String(Hex.decode("1b"), StandardCharsets.UTF_8); assertWhenInvalidClientIdThenInvalidRequestError(clientId); // Hex 1b61 -> escape + a clientId = new String(Hex.decode("1b61"), StandardCharsets.UTF_8); assertWhenInvalidClientIdThenInvalidRequestError(clientId); } private void assertWhenInvalidClientIdThenInvalidRequestError(String clientId) throws Exception { given(this.authenticationConverter.convert(any(HttpServletRequest.class))) .willReturn(new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, "secret", null)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); verifyNoInteractions(this.authenticationManager); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); OAuth2Error error = readError(response); assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @Test public void doFilterWhenRequestMatchesAndBadCredentialsThenInvalidClientError() throws Exception { given(this.authenticationConverter.convert(any(HttpServletRequest.class))) .willReturn(new OAuth2ClientAuthenticationToken("clientId", ClientAuthenticationMethod.CLIENT_SECRET_BASIC, "invalid-secret", null)); given(this.authenticationManager.authenticate(any(Authentication.class))) .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); verify(this.authenticationManager).authenticate(any()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value()); OAuth2Error error = readError(response); assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @Test public void doFilterWhenRequestMatchesAndValidCredentialsThenProcessed() throws Exception { final String remoteAddress = "remote-address"; RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); given(this.authenticationConverter.convert(any(HttpServletRequest.class))) .willReturn(new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null)); given(this.authenticationManager.authenticate(any(Authentication.class))) .willReturn(new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret())); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); request.setRemoteAddr(remoteAddress); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); assertThat(authentication).isInstanceOf(OAuth2ClientAuthenticationToken.class); assertThat(((OAuth2ClientAuthenticationToken) authentication).getRegisteredClient()) .isEqualTo(registeredClient); ArgumentCaptor<OAuth2ClientAuthenticationToken> authenticationRequestCaptor = ArgumentCaptor .forClass(OAuth2ClientAuthenticationToken.class); verify(this.authenticationManager).authenticate(authenticationRequestCaptor.capture()); assertThat(authenticationRequestCaptor).extracting(ArgumentCaptor::getValue) .extracting(OAuth2ClientAuthenticationToken::getDetails) .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(remoteAddress); } private OAuth2Error readError(MockHttpServletResponse response) throws Exception { MockClientHttpResponse httpResponse = new MockClientHttpResponse(response.getContentAsByteArray(), HttpStatus.valueOf(response.getStatus())); return this.errorHttpResponseConverter.read(OAuth2Error.class, httpResponse); } }
OAuth2ClientAuthenticationFilterTests
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/packagescan/resource/DefaultResourceLoader.java
{ "start": 2873, "end": 3096 }
class ____ at the time of actual resource access (since 5.3). */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Return the ClassLoader to load
loader
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionBeforeChainedSedaRoutesTest.java
{ "start": 973, "end": 3287 }
class ____ extends ContextTestSupport { @Test public void testOnCompletionChained() throws Exception { final var body = "<body>"; final var completionMockEndpoint = getMockEndpoint("mock:completion"); completionMockEndpoint.expectedMessageCount(5); completionMockEndpoint.expectedBodiesReceived( "completion:a", "completion:b", "completion:c", body, "completion:d"); template.sendBody("direct:a", body); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:a") .onCompletion() .modeBeforeConsumer() .log("a - done") .process(exchange -> exchange.getMessage().setBody("completion:a")) .to("mock:completion") .end() .to("seda:b"); from("seda:b") .onCompletion() .modeBeforeConsumer() .log("b - done") .process(exchange -> exchange.getMessage().setBody("completion:b")) .to("mock:completion") .end() .delay(100) .to("seda:c"); from("seda:c") .onCompletion() .modeBeforeConsumer() .log("c - done") .process(exchange -> exchange.getMessage().setBody("completion:c")) .to("mock:completion") .end() .delay(100) .to("seda:d"); from("seda:d") .onCompletion() .modeBeforeConsumer() .log("d - done") .process(exchange -> exchange.getMessage().setBody("completion:d")) .to("mock:completion") .end() .delay(100) .to("mock:completion"); } }; } }
OnCompletionBeforeChainedSedaRoutesTest
java
quarkusio__quarkus
extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/SmallRyeHealthDevUiProcessor.java
{ "start": 821, "end": 2677 }
class ____ { @BuildStep(onlyIf = IsDevelopment.class) @Record(ExecutionTime.STATIC_INIT) CardPageBuildItem create(NonApplicationRootPathBuildItem nonApplicationRootPathBuildItem, SmallRyeHealthBuildTimeConfig config, ManagementInterfaceBuildTimeConfig managementBuildTimeConfig, LaunchModeBuildItem launchModeBuildItem, SmallRyeHealthRecorder unused) { CardPageBuildItem pageBuildItem = new CardPageBuildItem(); pageBuildItem.setLogo("smallrye_dark.svg", "smallrye_light.svg"); pageBuildItem.addLibraryVersion("io.smallrye", "smallrye-health", "SmallRye Health", "https://github.com/smallrye/smallrye-health/"); pageBuildItem.addLibraryVersion("org.eclipse.microprofile.health", "microprofile-health-api", "MicroProfile Health", "https://github.com/microprofile/microprofile-health"); String path = nonApplicationRootPathBuildItem.resolveManagementPath(config.rootPath(), managementBuildTimeConfig, launchModeBuildItem, config.managementEnabled()); pageBuildItem.addPage(Page.webComponentPageBuilder() .title("Health") .icon("font-awesome-solid:stethoscope") .componentLink("qwc-smallrye-health-ui.js") .dynamicLabelJsonRPCMethodName("getStatus") .streamingLabelJsonRPCMethodName("streamStatus", "interval")); pageBuildItem.addPage(Page.externalPageBuilder("Raw") .icon("font-awesome-solid:heart-circle-bolt") .url(path, path) .isJsonContent()); return pageBuildItem; } @BuildStep JsonRPCProvidersBuildItem createJsonRPCService() { return new JsonRPCProvidersBuildItem(HealthJsonRPCService.class); } }
SmallRyeHealthDevUiProcessor
java
apache__rocketmq
example/src/main/java/org/apache/rocketmq/example/operation/Producer.java
{ "start": 1404, "end": 4171 }
class ____ { public static void main(String[] args) throws MQClientException, InterruptedException { CommandLine commandLine = buildCommandline(args); if (commandLine != null) { String group = commandLine.getOptionValue('g'); String topic = commandLine.getOptionValue('t'); String tags = commandLine.getOptionValue('a'); String keys = commandLine.getOptionValue('k'); String msgCount = commandLine.getOptionValue('c'); DefaultMQProducer producer = new DefaultMQProducer(group); producer.setInstanceName(Long.toString(System.currentTimeMillis())); producer.start(); for (int i = 0; i < Integer.parseInt(msgCount); i++) { try { Message msg = new Message( topic, tags, keys, ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET)); SendResult sendResult = producer.send(msg); System.out.printf("%-8d %s%n", i, sendResult); } catch (Exception e) { e.printStackTrace(); Thread.sleep(1000); } } producer.shutdown(); } } public static CommandLine buildCommandline(String[] args) { final Options options = new Options(); Option opt = new Option("h", "help", false, "Print help"); opt.setRequired(false); options.addOption(opt); opt = new Option("g", "producerGroup", true, "Producer Group Name"); opt.setRequired(true); options.addOption(opt); opt = new Option("t", "topic", true, "Topic Name"); opt.setRequired(true); options.addOption(opt); opt = new Option("a", "tags", true, "Tags Name"); opt.setRequired(true); options.addOption(opt); opt = new Option("k", "keys", true, "Keys Name"); opt.setRequired(true); options.addOption(opt); opt = new Option("c", "msgCount", true, "Message Count"); opt.setRequired(true); options.addOption(opt); DefaultParser parser = new DefaultParser(); HelpFormatter hf = new HelpFormatter(); hf.setWidth(110); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); if (commandLine.hasOption('h')) { hf.printHelp("producer", options, true); return null; } } catch (ParseException e) { hf.printHelp("producer", options, true); return null; } return commandLine; } }
Producer
java
quarkusio__quarkus
extensions/kafka-client/runtime/src/test/java/io/quarkus/kafka/client/runtime/KafkaBindingConverterTest.java
{ "start": 423, "end": 5588 }
class ____ { private final static Path rootPath = Paths.get("src/test/resources/service-binding"); private final static String BINDING_DIRECTORY_NOT_KAFKA = "not-kafka"; private final static String BINDING_DIRECTORY_KAFKA_BOOTSTRAP_CAMELCASE = "kafka-bootstrap-camelcase"; private final static String BINDING_DIRECTORY_KAFKA_BOOTSTRAP_WITH_HYPHEN = "kafka-bootstrap-with-hyphen"; private final static String BINDING_DIRECTORY_KAFKA_SASL_PLAIN = "kafka-sasl-plain"; private final static String BINDING_DIRECTORY_KAFKA_SASL_SCRAM_512 = "kafka-sasl-scram-512"; private final static String BINDING_DIRECTORY_KAFKA_SASL_SCRAM_256 = "kafka-sasl-scram-256"; private final KafkaBindingConverter converter = new KafkaBindingConverter(); @Test public void testNoKafkaServiceBinding() { ServiceBinding fooServiceBinding = new ServiceBinding(rootPath.resolve(BINDING_DIRECTORY_NOT_KAFKA)); Optional<ServiceBindingConfigSource> configSourceOptional = converter.convert(List.of(fooServiceBinding)); assertThat(configSourceOptional).isEmpty(); } @Test public void testKafkaBootstrapWithCamelCaseServiceBinding() { ServiceBinding kafkaServiceBinding = new ServiceBinding(rootPath.resolve(BINDING_DIRECTORY_KAFKA_BOOTSTRAP_CAMELCASE)); Optional<ServiceBindingConfigSource> configSourceOptional = converter.convert(List.of(kafkaServiceBinding)); assertThat(configSourceOptional).isPresent(); Map<String, String> properties = configSourceOptional.get().getProperties(); assertThat(properties.get("kafka.bootstrap.servers")).isEqualTo("localhost:9092"); assertThat(properties.get("kafka.security.protocol")).isEqualTo("PLAINTEXT"); } @Test public void testKafkaBootstrapWithHyphenServiceBinding() { ServiceBinding kafkaServiceBinding = new ServiceBinding( rootPath.resolve(BINDING_DIRECTORY_KAFKA_BOOTSTRAP_WITH_HYPHEN)); Optional<ServiceBindingConfigSource> configSourceOptional = converter.convert(List.of(kafkaServiceBinding)); assertThat(configSourceOptional).isPresent(); Map<String, String> properties = configSourceOptional.get().getProperties(); assertThat(properties.get("kafka.bootstrap.servers")).isEqualTo("localhost:9093"); assertThat(properties.get("kafka.security.protocol")).isEqualTo("PLAINTEXT"); } @Test public void testKafkaSaslPlainServiceBinding() { ServiceBinding kafkaServiceBinding = new ServiceBinding(rootPath.resolve(BINDING_DIRECTORY_KAFKA_SASL_PLAIN)); Optional<ServiceBindingConfigSource> configSourceOptional = converter.convert(List.of(kafkaServiceBinding)); assertThat(configSourceOptional).isPresent(); Map<String, String> properties = configSourceOptional.get().getProperties(); assertThat(properties.get("kafka.bootstrap.servers")).isEqualTo("localhost:9092"); assertThat(properties.get("kafka.security.protocol")).isEqualTo("SASL_PLAINTEXT"); assertThat(properties.get("kafka.sasl.mechanism")).isEqualTo("PLAIN"); assertThat(properties.get("kafka.sasl.jaas.config")).isEqualTo( "org.apache.kafka.common.security.plain.PlainLoginModule required username='my-user' password='my-pass';"); } @Test public void testKafkaSaslScram512ServiceBinding() { ServiceBinding kafkaServiceBinding = new ServiceBinding(rootPath.resolve(BINDING_DIRECTORY_KAFKA_SASL_SCRAM_512)); Optional<ServiceBindingConfigSource> configSourceOptional = converter.convert(List.of(kafkaServiceBinding)); assertThat(configSourceOptional).isPresent(); Map<String, String> properties = configSourceOptional.get().getProperties(); assertThat(properties.get("kafka.bootstrap.servers")).isEqualTo("localhost:9092"); assertThat(properties.get("kafka.security.protocol")).isEqualTo("SASL_PLAINTEXT"); assertThat(properties.get("kafka.sasl.mechanism")).isEqualTo("SCRAM-SHA-512"); assertThat(properties.get("kafka.sasl.jaas.config")).isEqualTo( "org.apache.kafka.common.security.scram.ScramLoginModule required username='my-user' password='my-pass';"); } @Test public void testKafkaSaslScram256ServiceBinding() { ServiceBinding kafkaServiceBinding = new ServiceBinding(rootPath.resolve(BINDING_DIRECTORY_KAFKA_SASL_SCRAM_256)); Optional<ServiceBindingConfigSource> configSourceOptional = converter.convert(List.of(kafkaServiceBinding)); assertThat(configSourceOptional).isPresent(); Map<String, String> properties = configSourceOptional.get().getProperties(); assertThat(properties.get("kafka.bootstrap.servers")).isEqualTo("localhost:9092"); assertThat(properties.get("kafka.security.protocol")).isEqualTo("SASL_PLAINTEXT"); assertThat(properties.get("kafka.sasl.mechanism")).isEqualTo("SCRAM-SHA-256"); assertThat(properties.get("kafka.sasl.jaas.config")).isEqualTo( "org.apache.kafka.common.security.scram.ScramLoginModule required username='my-user' password='my-pass';"); } }
KafkaBindingConverterTest
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/rest/DeleteDefinition.java
{ "start": 1169, "end": 1294 }
class ____ extends VerbDefinition { @Override public String asVerb() { return "delete"; } }
DeleteDefinition
java
google__guice
core/test/com/google/inject/ScopesTest.java
{ "start": 7297, "end": 7435 }
interface ____ {} @SuppressWarnings("InjectScopeAnnotationOnInterfaceOrAbstractClass") // for testing @Component @Singleton
Component
java
apache__logging-log4j2
log4j-1.2-api/src/test/java/org/apache/log4j/config/SyslogAppenderConfigurationTest.java
{ "start": 1807, "end": 4851 }
class ____ { private static ServerSocket tcpSocket; @BeforeAll static void setup() throws IOException { // TCP appenders log an error if there is no server socket tcpSocket = new ServerSocket(0); System.setProperty("syslog.port", Integer.toString(tcpSocket.getLocalPort())); } @AfterAll static void cleanup() throws IOException { System.clearProperty("syslog.port"); tcpSocket.close(); } private void check(final Protocol expected, final Configuration configuration) { final Map<String, Appender> appenders = configuration.getAppenders(); assertNotNull(appenders); final String appenderName = "syslog"; final Appender appender = appenders.get(appenderName); assertNotNull(appender, "Missing appender " + appenderName); final SyslogAppender syslogAppender = (SyslogAppender) appender; @SuppressWarnings("resource") final AbstractSocketManager manager = syslogAppender.getManager(); final String prefix = expected + ":"; assertTrue( manager.getName().startsWith(prefix), () -> String.format("'%s' does not start with '%s'", manager.getName(), prefix)); // Threshold final ThresholdFilter filter = (ThresholdFilter) syslogAppender.getFilter(); assertEquals(Level.DEBUG, filter.getLevel()); // Host assertEquals("localhost", manager.getHost()); // Port assertEquals(tcpSocket.getLocalPort(), manager.getPort()); } private void checkProtocolPropertiesConfig(final Protocol expected, final String xmlPath) throws IOException { check(expected, TestConfigurator.configure(xmlPath).getConfiguration()); } private void checkProtocolXmlConfig(final Protocol expected, final String xmlPath) throws IOException { check(expected, TestConfigurator.configure(xmlPath).getConfiguration()); } @Test void testPropertiesProtocolDefault() throws Exception { checkProtocolPropertiesConfig(Protocol.TCP, "target/test-classes/log4j1-syslog-protocol-default.properties"); } @Test void testPropertiesProtocolTcp() throws Exception { checkProtocolPropertiesConfig(Protocol.TCP, "target/test-classes/log4j1-syslog-protocol-tcp.properties"); } @Test void testPropertiesProtocolUdp() throws Exception { checkProtocolPropertiesConfig(Protocol.UDP, "target/test-classes/log4j1-syslog-protocol-udp.properties"); } @Test void testXmlProtocolDefault() throws Exception { checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-syslog.xml"); } @Test void testXmlProtocolTcp() throws Exception { checkProtocolXmlConfig(Protocol.TCP, "target/test-classes/log4j1-syslog-protocol-tcp.xml"); } @Test void testXmlProtocolUdp() throws Exception { checkProtocolXmlConfig(Protocol.UDP, "target/test-classes/log4j1-syslog-protocol-udp.xml"); } }
SyslogAppenderConfigurationTest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/service/registry/HttpServiceProxyRegistryFactoryBean.java
{ "start": 11892, "end": 12407 }
class ____ implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection() .registerType(TypeReference.of(GroupAdapterInitializer.REST_CLIENT_HTTP_SERVICE_GROUP_ADAPTER), MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS) .registerTypeIfPresent(classLoader, GroupAdapterInitializer.WEB_CLIENT_HTTP_SERVICE_GROUP_ADAPTER, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } }
HttpServiceProxyRegistryRuntimeHints
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/proxy/config/legacy/GlobalNonProxyTest.java
{ "start": 242, "end": 429 }
class ____ extends AbstractGlobalNonProxyTest { @RegisterExtension static final QuarkusUnitTest config = config("global-non-proxy-test-application.properties"); }
GlobalNonProxyTest
java
processing__processing4
java/src/processing/mode/java/PreprocSketch.java
{ "start": 6375, "end": 8339 }
class ____ { public Sketch sketch; public CompilationUnit compilationUnit; public String[] classPathArray; public ClassPath classPath; public URLClassLoader classLoader; public String[] searchClassPathArray; public int[] tabStartOffsets = new int[0]; public String scrubbedPdeCode; public String pdeCode; public String javaCode; public OffsetMapper offsetMapper; public boolean hasSyntaxErrors; public boolean hasCompilationErrors; public final List<ImportStatement> programImports = new ArrayList<>(); public final List<ImportStatement> coreAndDefaultImports = new ArrayList<>(); public final List<ImportStatement> codeFolderImports = new ArrayList<>(); public final List<Problem> otherProblems = new ArrayList<>(); public List<IProblem> iproblems; public Map<String, Integer> javaFileMapping; public PreprocSketch build() { return new PreprocSketch(this); } } public static PreprocSketch empty() { return new Builder().build(); } private PreprocSketch(Builder b) { sketch = b.sketch; compilationUnit = b.compilationUnit; classPathArray = b.classPathArray; classPath = b.classPath; classLoader = b.classLoader; searchClassPathArray = b.searchClassPathArray; tabStartOffsets = b.tabStartOffsets; scrubbedPdeCode = b.scrubbedPdeCode; pdeCode = b.pdeCode; javaCode = b.javaCode; offsetMapper = b.offsetMapper != null ? b.offsetMapper : OffsetMapper.EMPTY_MAPPER; hasSyntaxErrors = b.hasSyntaxErrors; hasCompilationErrors = b.hasCompilationErrors; otherProblems = b.otherProblems; javaFileMapping = b.javaFileMapping; iproblems = b.iproblems; programImports = Collections.unmodifiableList(b.programImports); coreAndDefaultImports = Collections.unmodifiableList(b.coreAndDefaultImports); codeFolderImports = Collections.unmodifiableList(b.codeFolderImports); } }
Builder
java
elastic__elasticsearch
x-pack/plugin/snapshot-repo-test-kit/src/main/java/org/elasticsearch/repositories/blobstore/testkit/analyze/RandomBlobContentStream.java
{ "start": 490, "end": 3158 }
class ____ extends InputStream { private final long length; private final RandomBlobContent randomBlobContent; private long position; private long markPosition; /** * @param randomBlobContent The (simulated) content of the blob. * @param length The length of this stream. */ RandomBlobContentStream(RandomBlobContent randomBlobContent, long length) { assert 0 < length; this.randomBlobContent = randomBlobContent; this.length = length; } private int bufferPosition() { return Math.toIntExact(position % randomBlobContent.buffer.length); } @Override public int read() { randomBlobContent.ensureNotCancelled(position + "/" + length); if (length <= position) { return -1; } final int b = Byte.toUnsignedInt(randomBlobContent.buffer[bufferPosition()]); position += 1; if (position == length) { randomBlobContent.onLastRead(); } return b; } @Override public int read(byte[] b, int off, int len) { randomBlobContent.ensureNotCancelled(position + "+" + len + "/" + length); if (length <= position) { return -1; } len = Math.toIntExact(Math.min(len, length - position)); int remaining = len; while (0 < remaining) { assert position < length : position + " vs " + length; final int bufferPosition = bufferPosition(); final int copied = Math.min(randomBlobContent.buffer.length - bufferPosition, remaining); System.arraycopy(randomBlobContent.buffer, bufferPosition, b, off, copied); off += copied; remaining -= copied; position += copied; } assert position <= length : position + " vs " + length; if (position == length) { randomBlobContent.onLastRead(); } return len; } @Override public void close() { randomBlobContent.onLastRead(); } @Override public boolean markSupported() { return true; } @Override public synchronized void mark(int readlimit) { markPosition = position; } @Override public synchronized void reset() { position = markPosition; } @Override public long skip(long n) { final long oldPosition = position; position = Math.min(length, position + n); return position - oldPosition; } @Override public int available() { return Math.toIntExact(Math.min(length - position, Integer.MAX_VALUE)); } }
RandomBlobContentStream
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ReflectionSupport.java
{ "start": 6854, "end": 9014 }
class ____ filter; never {@code null} * @return an immutable list of all such classes found; never {@code null} * but potentially empty * @see #findAllClassesInPackage(String, Predicate, Predicate) * @see #findAllClassesInModule(String, Predicate, Predicate) * @see ResourceSupport#findAllResourcesInClasspathRoot(URI, ResourceFilter) */ public static List<Class<?>> findAllClassesInClasspathRoot(URI root, Predicate<Class<?>> classFilter, Predicate<String> classNameFilter) { return ReflectionUtils.findAllClassesInClasspathRoot(root, classFilter, classNameFilter); } /** * Find all {@linkplain Resource resources} in the supplied classpath {@code root} * that match the specified {@code resourceFilter} predicate. * * <p>The classpath scanning algorithm searches recursively in subpackages * beginning with the root of the classpath. * * @param root the URI for the classpath root in which to scan; never * {@code null} * @param resourceFilter the resource type filter; never {@code null} * @return an immutable list of all such resources found; never {@code null} * but potentially empty * @since 1.11 * @see #findAllResourcesInPackage(String, Predicate) * @see #findAllResourcesInModule(String, Predicate) * @deprecated Please use {@link ResourceSupport#findAllResourcesInClasspathRoot(URI, ResourceFilter)} instead */ @API(status = DEPRECATED, since = "1.14") @Deprecated(since = "1.14", forRemoval = true) @SuppressWarnings("removal") public static List<Resource> findAllResourcesInClasspathRoot(URI root, Predicate<Resource> resourceFilter) { return toSupportResourcesList( ResourceSupport.findAllResourcesInClasspathRoot(root, toResourceFilter(resourceFilter))); } /** * Find all {@linkplain Class classes} in the supplied classpath {@code root} * that match the specified {@code classFilter} and {@code classNameFilter} * predicates. * * <p>The classpath scanning algorithm searches recursively in subpackages * beginning with the root of the classpath. * * @param root the URI for the classpath root in which to scan; never * {@code null} * @param classFilter the
name
java
apache__flink
flink-metrics/flink-metrics-jmx/src/main/java/org/apache/flink/metrics/jmx/JMXReporter.java
{ "start": 10503, "end": 10602 }
interface ____ extends MetricMBean { Object getValue(); } private static
JmxGaugeMBean
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/parser/ast/access/EnvironmentAccess.java
{ "start": 1572, "end": 2977 }
class ____ extends ExpressionNode { private static final ClassElement STRING_ELEMENT = ClassElement.of(String.class); private static final Method GET_PROPERTY_METHOD = ReflectionUtils.getRequiredMethod(ExpressionEvaluationContext.class, "getProperty", String.class); private final ExpressionNode propertyName; public EnvironmentAccess(ExpressionNode propertyName) { this.propertyName = propertyName; } @Override protected ExpressionDef generateExpression(ExpressionCompilationContext ctx) { return ctx.expressionEvaluationContextVar() .invoke(GET_PROPERTY_METHOD, propertyName.compile(ctx)); } @Override protected ClassElement doResolveClassElement(ExpressionVisitorContext ctx) { resolveType(ctx); return ctx.visitorContext().getClassElement(String.class).orElse(STRING_ELEMENT); } @Override protected TypeDef doResolveType(@NonNull ExpressionVisitorContext ctx) { TypeDef propertyNameType = propertyName.resolveType(ctx); if (!propertyNameType.equals(STRING)) { throw new ExpressionCompilationException("Invalid environment access operation. The expression inside environment " + "access must resolve to String value of property name"); } // Property value is always returned as string return STRING; } }
EnvironmentAccess
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/any/discriminator/meta/Order.java
{ "start": 527, "end": 959 }
class ____ { @Id public Integer id; @Basic public String name; //tag::associations-any-discriminator-meta-example[] @Any @PaymentDiscriminationDef @Column(name = "payment_type") @JoinColumn(name = "payment_fk") public Payment payment; //end::associations-any-discriminator-meta-example[] protected Order() { // for Hibernate use } public Order(Integer id, String name) { this.id = id; this.name = name; } }
Order
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/join/ComposableRecordReader.java
{ "start": 1562, "end": 2602 }
class ____. */ abstract int id(); /** * Return the key this RecordReader would supply on a call to next(K,V) */ abstract K key(); /** * Clone the key at the head of this RecordReader into the object provided. */ abstract void key(K key) throws IOException; /** * Create instance of key. */ abstract K createKey(); /** * Create instance of value. */ abstract V createValue(); /** * Returns true if the stream is not empty, but provides no guarantee that * a call to next(K,V) will succeed. */ abstract boolean hasNext(); /** * Skip key-value pairs with keys less than or equal to the key provided. */ abstract void skip(K key) throws IOException, InterruptedException; /** * While key-value pairs from this RecordReader match the given key, register * them with the JoinCollector provided. */ @SuppressWarnings("unchecked") abstract void accept(CompositeRecordReader.JoinCollector jc, K key) throws IOException, InterruptedException; }
occupies
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/test/java/io/quarkus/bootstrap/model/PlatformImportsTest.java
{ "start": 6262, "end": 7560 }
class ____ { private final Path path; private Properties props = new Properties(); private PlatformProps() throws IOException { path = Files.createTempFile("quarkus", "platform-imports"); } private void setRelease(PlatformReleaseInfo release) { props.setProperty(release.getPropertyName(), release.getPropertyValue()); } private void setProperty(String name, String value) { props.setProperty(name, value); } private void importRelease(PlatformImportsImpl pi) throws IOException { try (BufferedWriter w = Files.newBufferedWriter(path)) { props.store(w, "test playground platform props"); } props = new Properties(); try (BufferedReader reader = Files.newBufferedReader(path)) { props.load(reader); } for (Map.Entry<?, ?> prop : props.entrySet()) { if (PlatformImportsImpl.isPlatformReleaseInfo(prop.getKey().toString())) { pi.addPlatformRelease(prop.getKey().toString(), prop.getValue().toString()); } } } private void delete() { IoUtils.recursiveDelete(path); } } }
PlatformProps
java
google__truth
core/src/main/java/com/google/common/truth/Correspondence.java
{ "start": 18577, "end": 19369 }
class ____ { * static final Correspondence<MyRecord, MyRecord> EQUIVALENCE = * Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to") * .formattingDiffsUsing(MyRecordTestHelper::formatRecordDiff); * static boolean recordsEquivalent(MyRecord actual, MyRecord expected) { * // code to check whether records should be considered equivalent for testing purposes * } * static String formatRecordDiff(MyRecord actual, MyRecord expected) { * // code to format the diff between the records * } * } * }</pre> */ public Correspondence<A, E> formattingDiffsUsing(DiffFormatter<? super A, ? super E> formatter) { return FormattingDiffs.create(this, formatter); } /** * A functional
MyRecordTestHelper
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/schemagen/SchemaCreateDropUtf8WithoutHbm2DdlCharsetNameTest.java
{ "start": 1269, "end": 3376 }
class ____ { private File createSchema; private File dropSchema; private EntityManagerFactoryBuilder entityManagerFactoryBuilder; protected Map getConfig() { final Map<Object, Object> config = Environment.getProperties(); ServiceRegistryUtil.applySettings( config ); config.put( JAKARTA_HBM2DDL_SCRIPTS_CREATE_TARGET, createSchema.toPath() ); config.put( JAKARTA_HBM2DDL_SCRIPTS_DROP_TARGET, dropSchema.toPath() ); config.put( JAKARTA_HBM2DDL_SCRIPTS_ACTION, "drop-and-create" ); ArrayList<Class> classes = new ArrayList<Class>(); classes.addAll( Arrays.asList( new Class[] {TestEntity.class} ) ); config.put( AvailableSettings.LOADED_CLASSES, classes ); return config; } @BeforeEach public void setUp() throws IOException { createSchema = File.createTempFile( "create_schema", ".sql" ); dropSchema = File.createTempFile( "drop_schema", ".sql" ); createSchema.deleteOnExit(); dropSchema.deleteOnExit(); entityManagerFactoryBuilder = Bootstrap.getEntityManagerFactoryBuilder( new BaseEntityManagerFunctionalTestCase.TestingPersistenceUnitDescriptorImpl( getClass().getSimpleName() ), getConfig() ); } @AfterEach public void destroy() { if ( entityManagerFactoryBuilder != null ) { entityManagerFactoryBuilder.cancel(); } } @Test @JiraKey(value = "HHH-10972") public void testEncoding() throws Exception { entityManagerFactoryBuilder.generateSchema(); final String fileContent = new String( Files.readAllBytes( createSchema.toPath() ) ) .toLowerCase(); assertTrue( fileContent.contains( expectedTableName() ) ); assertTrue( fileContent.contains( expectedFieldName() ) ); final String dropFileContent = new String( Files.readAllBytes( dropSchema.toPath() ) ).toLowerCase(); assertTrue( dropFileContent.contains( expectedTableName() ) ); } protected String expectedTableName() { return "test_" + (char) 233 + "ntity"; } protected String expectedFieldName() { return "fi" + (char) 233 + "ld"; } @Entity @Table(name = "test_" + (char) 233 +"ntity") public static
SchemaCreateDropUtf8WithoutHbm2DdlCharsetNameTest
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/Unifiable.java
{ "start": 829, "end": 1059 }
interface ____<T> extends Serializable { /** * Returns all valid unification paths (if any) from this {@code Unifier} that unify this with * {@code target}. */ Choice<Unifier> unify(T target, Unifier unifier); }
Unifiable
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanParameterValueOverloadedTest.java
{ "start": 1027, "end": 2211 }
class ____ extends ContextTestSupport { @Test public void testBeanParameterValueBoolean() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); template.sendBody("direct:start", "World"); assertMockEndpointsSatisfied(); } @Test public void testBeanParameterValueBoolean2() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); template.sendBody("direct:start2", "World"); assertMockEndpointsSatisfied(); } @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("foo", new MyBean()); return jndi; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("bean:foo?method=bar(*,true)").to("mock:result"); from("direct:start2").to("bean:foo?method=bar(${body},false,true)").to("mock:result"); } }; } public static
BeanParameterValueOverloadedTest
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ConstantExpressions.java
{ "start": 7477, "end": 13340 }
interface ____ { /** Represents a constant literal. */ public static record Literal(Object object) implements ConstantExpression { @Override public void accept(ConstantExpressionVisitor visitor) { visitor.visitConstant(object()); } @Override public final String toString() { return object().toString(); } } /** Represents a binary equals call on two constant expressions. */ public static record ConstantEquals(ConstantExpression lhs, ConstantExpression rhs) implements ConstantExpression { @Override public void accept(ConstantExpressionVisitor visitor) { lhs().accept(visitor); rhs().accept(visitor); } @Override public final boolean equals(@Nullable Object other) { if (!(other instanceof ConstantEquals that)) { return false; } return (lhs().equals(that.lhs()) && rhs().equals(that.rhs())) || (lhs().equals(that.rhs()) && rhs().equals(that.lhs())); } @Override public final String toString() { return format("%s equals %s", lhs(), rhs()); } @Override public final int hashCode() { return lhs().hashCode() + rhs().hashCode(); } } /** * Represents both a constant method call or a constant field/local access, depending on the * actual type of {@code symbol}. */ public static record PureMethodInvocation( Symbol symbol, ImmutableList<ConstantExpression> arguments, Optional<ConstantExpression> receiver) implements ConstantExpression { @Override public void accept(ConstantExpressionVisitor visitor) { visitor.visitIdentifier(symbol()); arguments().forEach(a -> a.accept(visitor)); receiver().ifPresent(r -> r.accept(visitor)); } @Override public final String toString() { String receiver = receiver().map(r -> r + ".").orElse(""); if (symbol() instanceof VarSymbol || symbol() instanceof ClassSymbol) { return receiver + symbol().getSimpleName(); } return receiver + (isStatic(symbol()) ? symbol().owner.getSimpleName() + "." : "") + symbol().getSimpleName() + arguments().stream().map(Object::toString).collect(joining(", ", "(", ")")); } } void accept(ConstantExpressionVisitor visitor); } public Optional<ConstantExpression> constantExpression(ExpressionTree tree, VisitorState state) { if (tree.getKind().equals(Kind.EQUAL_TO) || tree.getKind().equals(Kind.NOT_EQUAL_TO)) { BinaryTree binaryTree = (BinaryTree) tree; Optional<ConstantExpression> lhs = constantExpression(binaryTree.getLeftOperand(), state); Optional<ConstantExpression> rhs = constantExpression(binaryTree.getRightOperand(), state); if (lhs.isPresent() && rhs.isPresent()) { return Optional.of(new ConstantExpression.ConstantEquals(lhs.get(), rhs.get())); } } Object value = constValue(tree); if (value != null && tree instanceof LiteralTree) { return Optional.of(new ConstantExpression.Literal(value)); } return symbolizeImmutableExpression(tree, state).map(x -> x); } /** Returns whether {@code aTree} and {@code bTree} seem to correspond to the same expression. */ public boolean isSame(ExpressionTree aTree, ExpressionTree bTree, VisitorState state) { var a = constantExpression(aTree, state); if (a.isEmpty()) { return false; } var b = constantExpression(bTree, state); return b.isPresent() && a.get().equals(b.get()); } /** * Returns a list of the methods called to get to this expression, as well as a terminating * variable if needed. */ public Optional<ConstantExpression.PureMethodInvocation> symbolizeImmutableExpression( ExpressionTree tree, VisitorState state) { var receiver = tree instanceof MethodInvocationTree || tree instanceof MemberSelectTree ? getReceiver(tree) : null; Symbol symbol = getSymbol(tree); Optional<ConstantExpression> receiverConstant; if (receiver == null || (symbol != null && isStatic(symbol))) { receiverConstant = Optional.empty(); } else { receiverConstant = constantExpression(receiver, state); if (receiverConstant.isEmpty()) { return Optional.empty(); } } if (isPureIdentifier(tree)) { return Optional.of( new ConstantExpression.PureMethodInvocation( getSymbol(tree), ImmutableList.of(), receiverConstant)); } else if (tree instanceof MethodInvocationTree methodInvocationTree && pureMethods.matches(tree, state)) { ImmutableList.Builder<ConstantExpression> arguments = ImmutableList.builder(); for (ExpressionTree argument : methodInvocationTree.getArguments()) { Optional<ConstantExpression> argumentConstant = constantExpression(argument, state); if (argumentConstant.isEmpty()) { return Optional.empty(); } arguments.add(argumentConstant.get()); } return Optional.of( new ConstantExpression.PureMethodInvocation( getSymbol(tree), arguments.build(), receiverConstant)); } else { return Optional.empty(); } } private static boolean isPureIdentifier(ExpressionTree receiver) { if (!(receiver instanceof IdentifierTree || receiver instanceof MemberSelectTree)) { return false; } Symbol symbol = getSymbol(receiver); return symbol.owner.isEnum() || (symbol instanceof VarSymbol && isConsideredFinal(symbol)) || symbol instanceof ClassSymbol || symbol instanceof PackageSymbol; } /** Visitor for scanning over the components of a constant expression. */ public
ConstantExpression
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/string/RTrimEvaluator.java
{ "start": 4022, "end": 4582 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory val; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory val) { this.source = source; this.val = val; } @Override public RTrimEvaluator get(DriverContext context) { return new RTrimEvaluator(source, val.get(context), context); } @Override public String toString() { return "RTrimEvaluator[" + "val=" + val + "]"; } } }
Factory
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/query/SimpleQueryStringBuilderTests.java
{ "start": 2095, "end": 36233 }
class ____ extends AbstractQueryTestCase<SimpleQueryStringBuilder> { @Override protected SimpleQueryStringBuilder doCreateTestQueryBuilder() { // we avoid strings with "now" since those can have different caching policies that are checked elsewhere String queryText = randomValueOtherThanMany( s -> s.toLowerCase(Locale.ROOT).contains("now"), () -> randomAlphaOfLengthBetween(1, 10) ); SimpleQueryStringBuilder result = new SimpleQueryStringBuilder(queryText); if (randomBoolean()) { result.analyzeWildcard(randomBoolean()); } if (randomBoolean()) { result.minimumShouldMatch(randomMinimumShouldMatch()); } if (randomBoolean()) { result.analyzer(randomAnalyzer()); } if (randomBoolean()) { result.defaultOperator(randomFrom(Operator.values())); } if (randomBoolean()) { result.quoteFieldSuffix(TestUtil.randomSimpleString(random())); } if (randomBoolean()) { Set<SimpleQueryStringFlag> flagSet = new HashSet<>(); int size = randomIntBetween(0, SimpleQueryStringFlag.values().length); for (int i = 0; i < size; i++) { flagSet.add(randomFrom(SimpleQueryStringFlag.values())); } if (flagSet.size() > 0) { result.flags(flagSet.toArray(new SimpleQueryStringFlag[flagSet.size()])); } } int fieldCount = randomIntBetween(0, 2); Map<String, Float> fields = new HashMap<>(); for (int i = 0; i < fieldCount; i++) { if (i == 0) { String fieldName = randomFrom(TEXT_FIELD_NAME, TEXT_ALIAS_FIELD_NAME); fields.put(fieldName, AbstractQueryBuilder.DEFAULT_BOOST); } else { fields.put(KEYWORD_FIELD_NAME, 2.0f / randomIntBetween(1, 20)); } } result.fields(fields); if (randomBoolean()) { result.autoGenerateSynonymsPhraseQuery(randomBoolean()); } if (randomBoolean()) { result.fuzzyPrefixLength(randomIntBetween(0, 5)); } if (randomBoolean()) { result.fuzzyMaxExpansions(randomIntBetween(1, 5)); } if (randomBoolean()) { result.fuzzyTranspositions(randomBoolean()); } // TODO extend checks in doAssertLuceneQuery for the three failing cases result.type( randomFrom( List.of( MultiMatchQueryBuilder.Type.BEST_FIELDS, MultiMatchQueryBuilder.Type.MOST_FIELDS, MultiMatchQueryBuilder.Type.PHRASE ) ) ); return result; } public void testDefaults() { SimpleQueryStringBuilder qb = new SimpleQueryStringBuilder("The quick brown fox."); assertEquals("Wrong default default boost.", AbstractQueryBuilder.DEFAULT_BOOST, qb.boost(), 0.001); assertEquals( "Wrong default default boost field.", AbstractQueryBuilder.DEFAULT_BOOST, SimpleQueryStringBuilder.DEFAULT_BOOST, 0.001 ); assertEquals("Wrong default flags.", SimpleQueryStringFlag.ALL.value, qb.flags()); assertEquals("Wrong default flags field.", SimpleQueryStringFlag.ALL.value(), SimpleQueryStringBuilder.DEFAULT_FLAGS); assertEquals("Wrong default default operator.", Operator.OR, qb.defaultOperator()); assertEquals("Wrong default default operator field.", Operator.OR, SimpleQueryStringBuilder.DEFAULT_OPERATOR); assertEquals("Wrong default default analyze_wildcard.", false, qb.analyzeWildcard()); assertEquals("Wrong default default analyze_wildcard field.", false, SimpleQueryStringBuilder.DEFAULT_ANALYZE_WILDCARD); assertEquals("Wrong default default lenient.", false, qb.lenient()); assertEquals("Wrong default default lenient field.", false, SimpleQueryStringBuilder.DEFAULT_LENIENT); assertEquals("Wrong default default fuzzy prefix length.", FuzzyQuery.defaultPrefixLength, qb.fuzzyPrefixLength()); assertEquals( "Wrong default default fuzzy prefix length field.", FuzzyQuery.defaultPrefixLength, SimpleQueryStringBuilder.DEFAULT_FUZZY_PREFIX_LENGTH ); assertEquals("Wrong default default fuzzy max expansions.", FuzzyQuery.defaultMaxExpansions, qb.fuzzyMaxExpansions()); assertEquals( "Wrong default default fuzzy max expansions field.", FuzzyQuery.defaultMaxExpansions, SimpleQueryStringBuilder.DEFAULT_FUZZY_MAX_EXPANSIONS ); assertEquals("Wrong default default fuzzy transpositions.", FuzzyQuery.defaultTranspositions, qb.fuzzyTranspositions()); assertEquals( "Wrong default default fuzzy transpositions field.", FuzzyQuery.defaultTranspositions, SimpleQueryStringBuilder.DEFAULT_FUZZY_TRANSPOSITIONS ); assertEquals(SimpleQueryStringBuilder.DEFAULT_TYPE, qb.type()); } public void testDefaultNullComplainFlags() { SimpleQueryStringBuilder qb = new SimpleQueryStringBuilder("The quick brown fox."); qb.flags((SimpleQueryStringFlag[]) null); assertEquals( "Setting flags to null should result in returning to default value.", SimpleQueryStringBuilder.DEFAULT_FLAGS, qb.flags() ); } public void testDefaultEmptyComplainFlags() { SimpleQueryStringBuilder qb = new SimpleQueryStringBuilder("The quick brown fox."); qb.flags(new SimpleQueryStringFlag[] {}); assertEquals( "Setting flags to empty should result in returning to default value.", SimpleQueryStringBuilder.DEFAULT_FLAGS, qb.flags() ); } public void testDefaultNullComplainOp() { SimpleQueryStringBuilder qb = new SimpleQueryStringBuilder("The quick brown fox."); qb.defaultOperator(null); qb.type(null); assertEquals( "Setting operator to null should result in returning to default value.", SimpleQueryStringBuilder.DEFAULT_OPERATOR, qb.defaultOperator() ); assertEquals("Setting type to null should result in returning to default value.", SimpleQueryStringBuilder.DEFAULT_TYPE, qb.type()); } // Check operator handling, and default field handling. public void testDefaultOperatorHandling() throws IOException { SimpleQueryStringBuilder qb = new SimpleQueryStringBuilder("The quick brown fox.").field(TEXT_FIELD_NAME); SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); searchExecutionContext.setAllowUnmappedFields(true); // to avoid occasional cases // in setup where we didn't // add types but strict field // resolution BooleanQuery boolQuery = (BooleanQuery) qb.toQuery(searchExecutionContext); assertThat(shouldClauses(boolQuery), is(4)); qb.defaultOperator(Operator.AND); boolQuery = (BooleanQuery) qb.toQuery(searchExecutionContext); assertThat(shouldClauses(boolQuery), is(0)); qb.defaultOperator(Operator.OR); boolQuery = (BooleanQuery) qb.toQuery(searchExecutionContext); assertThat(shouldClauses(boolQuery), is(4)); } public void testIllegalConstructorArg() { expectThrows(IllegalArgumentException.class, () -> new SimpleQueryStringBuilder((String) null)); } public void testFieldCannotBeNull() { SimpleQueryStringBuilder qb = createTestQueryBuilder(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field(null)); assertEquals("supplied field is null or empty", e.getMessage()); } public void testFieldCannotBeNullAndWeighted() { SimpleQueryStringBuilder qb = createTestQueryBuilder(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field(null, AbstractQueryBuilder.DEFAULT_BOOST)); assertEquals("supplied field is null or empty", e.getMessage()); } public void testFieldCannotBeEmpty() { SimpleQueryStringBuilder qb = createTestQueryBuilder(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field("")); assertEquals("supplied field is null or empty", e.getMessage()); } public void testFieldCannotBeEmptyAndWeighted() { SimpleQueryStringBuilder qb = createTestQueryBuilder(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field("", AbstractQueryBuilder.DEFAULT_BOOST)); assertEquals("supplied field is null or empty", e.getMessage()); } /** * The following should fail fast - never silently set the map containing * fields and weights to null but refuse to accept null instead. * */ public void testFieldsCannotBeSetToNull() { SimpleQueryStringBuilder qb = createTestQueryBuilder(); NullPointerException e = expectThrows(NullPointerException.class, () -> qb.fields(null)); assertEquals("fields cannot be null", e.getMessage()); } /* * This assumes that Lucene query parsing is being checked already, adding * checks only for our parsing extensions. * * Also this relies on {@link SimpleQueryStringTests} to test most of the * actual functionality of query parsing. */ @Override protected void doAssertLuceneQuery(SimpleQueryStringBuilder queryBuilder, Query query, SearchExecutionContext context) { assertThat(query, notNullValue()); if (queryBuilder.value().isEmpty()) { assertThat(query, instanceOf(MatchNoDocsQuery.class)); } else if (queryBuilder.fields().size() > 1) { assertThat(query, instanceOf(DisjunctionMaxQuery.class)); DisjunctionMaxQuery maxQuery = (DisjunctionMaxQuery) query; for (Query disjunct : maxQuery.getDisjuncts()) { assertThat( disjunct, either(instanceOf(TermQuery.class)).or(instanceOf(BoostQuery.class)).or(instanceOf(MatchNoDocsQuery.class)) ); Query termQuery = disjunct; if (disjunct instanceof BoostQuery) { termQuery = ((BoostQuery) disjunct).getQuery(); } if (termQuery instanceof TermQuery inner) { assertThat(inner.getTerm().bytes().toString(), is(inner.getTerm().bytes().toString().toLowerCase(Locale.ROOT))); } else { assertThat(termQuery, instanceOf(MatchNoDocsQuery.class)); } } } else if (queryBuilder.fields().size() == 1) { Map.Entry<String, Float> field = queryBuilder.fields().entrySet().iterator().next(); if (query instanceof MatchNoDocsQuery == false) { assertTermOrBoostQuery(query, field.getKey(), queryBuilder.value(), field.getValue()); } } else if (queryBuilder.fields().size() == 0) { assertThat( query, either(instanceOf(DisjunctionMaxQuery.class)).or(instanceOf(MatchNoDocsQuery.class)).or(instanceOf(TermQuery.class)) ); if (query instanceof DisjunctionMaxQuery) { for (Query disjunct : (DisjunctionMaxQuery) query) { assertThat(disjunct, either(instanceOf(TermQuery.class)).or(instanceOf(MatchNoDocsQuery.class))); } } } else { fail( "Encountered lucene query type we do not have a validation implementation for in our " + SimpleQueryStringBuilderTests.class.getSimpleName() ); } } private static int shouldClauses(BooleanQuery query) { int result = 0; for (BooleanClause c : query.clauses()) { if (c.occur() == BooleanClause.Occur.SHOULD) { result++; } } return result; } public void testToQueryBoost() throws IOException { SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); SimpleQueryStringBuilder simpleQueryStringBuilder = new SimpleQueryStringBuilder("test"); simpleQueryStringBuilder.field(TEXT_FIELD_NAME, 5); Query query = simpleQueryStringBuilder.toQuery(searchExecutionContext); assertThat(query, instanceOf(BoostQuery.class)); BoostQuery boostQuery = (BoostQuery) query; assertThat(boostQuery.getBoost(), equalTo(5f)); assertThat(boostQuery.getQuery(), instanceOf(TermQuery.class)); simpleQueryStringBuilder = new SimpleQueryStringBuilder("test"); simpleQueryStringBuilder.field(TEXT_FIELD_NAME, 5); simpleQueryStringBuilder.boost(2); query = simpleQueryStringBuilder.toQuery(searchExecutionContext); boostQuery = (BoostQuery) query; assertThat(boostQuery.getBoost(), equalTo(2f)); assertThat(boostQuery.getQuery(), instanceOf(BoostQuery.class)); boostQuery = (BoostQuery) boostQuery.getQuery(); assertThat(boostQuery.getBoost(), equalTo(5f)); assertThat(boostQuery.getQuery(), instanceOf(TermQuery.class)); } public void testNegativeFlags() throws IOException { String query = "{\"simple_query_string\": {\"query\": \"foo bar\", \"flags\": -1}}"; SimpleQueryStringBuilder builder = new SimpleQueryStringBuilder("foo bar"); builder.flags(SimpleQueryStringFlag.ALL); assertParsedQuery(query, builder); SimpleQueryStringBuilder otherBuilder = new SimpleQueryStringBuilder("foo bar"); otherBuilder.flags(-1); assertThat(builder, equalTo(otherBuilder)); } public void testFromSimpleJson() throws IOException { String json = """ { "simple_query_string" : { "query" : "\\"fried eggs\\" +(eggplant | potato) -frittata", "fields" : [ "body^5.0" ], "type" : "best_fields" } }"""; SimpleQueryStringBuilder parsed = (SimpleQueryStringBuilder) parseQuery(json); checkGeneratedJson(json, parsed); assertEquals(json, "\"fried eggs\" +(eggplant | potato) -frittata", parsed.value()); assertEquals(json, 1, parsed.fields().size()); assertEquals(json, 0, parsed.fuzzyPrefixLength()); assertEquals(json, 50, parsed.fuzzyMaxExpansions()); assertEquals(json, true, parsed.fuzzyTranspositions()); assertEquals(json, MultiMatchQueryBuilder.Type.BEST_FIELDS, parsed.type()); } public void testFromJson() throws IOException { String json = """ { "simple_query_string" : { "query" : "\\"fried eggs\\" +(eggplant | potato) -frittata", "fields" : [ "body^5.0" ], "analyzer" : "snowball", "flags" : 8, "default_operator" : "and", "lenient" : false, "analyze_wildcard" : true, "quote_field_suffix" : ".quote", "auto_generate_synonyms_phrase_query" : false, "fuzzy_prefix_length" : 1, "fuzzy_max_expansions" : 5, "fuzzy_transpositions" : false, "type" : "cross_fields", "boost" : 2.0 } }"""; SimpleQueryStringBuilder parsed = (SimpleQueryStringBuilder) parseQuery(json); checkGeneratedJson(json, parsed); assertEquals(json, "\"fried eggs\" +(eggplant | potato) -frittata", parsed.value()); assertEquals(json, 1, parsed.fields().size()); assertEquals(json, "snowball", parsed.analyzer()); assertEquals(json, ".quote", parsed.quoteFieldSuffix()); assertEquals(json, 1, parsed.fuzzyPrefixLength()); assertEquals(json, 5, parsed.fuzzyMaxExpansions()); assertEquals(json, false, parsed.fuzzyTranspositions()); assertEquals(json, MultiMatchQueryBuilder.Type.CROSS_FIELDS, parsed.type()); } public void testMinimumShouldMatch() throws IOException { SearchExecutionContext searchExecutionContext = createSearchExecutionContext(); int numberOfTerms = randomIntBetween(1, 4); StringBuilder queryString = new StringBuilder(); for (int i = 0; i < numberOfTerms; i++) { queryString.append("t" + i + " "); } SimpleQueryStringBuilder simpleQueryStringBuilder = new SimpleQueryStringBuilder(queryString.toString().trim()); if (randomBoolean()) { simpleQueryStringBuilder.defaultOperator(Operator.AND); } int numberOfFields = randomIntBetween(1, 4); for (int i = 0; i < numberOfFields; i++) { simpleQueryStringBuilder.field(TEXT_FIELD_NAME); } int percent = randomIntBetween(1, 100); simpleQueryStringBuilder.minimumShouldMatch(percent + "%"); Query query = simpleQueryStringBuilder.toQuery(searchExecutionContext); // check special case: one term & one field should get simplified to a TermQuery if (numberOfFields * numberOfTerms == 1) { assertThat(query, instanceOf(TermQuery.class)); } else if (numberOfTerms == 1) { assertThat(query, either(instanceOf(DisjunctionMaxQuery.class)).or(instanceOf(TermQuery.class))); } else { assertThat(query, instanceOf(BooleanQuery.class)); BooleanQuery boolQuery = (BooleanQuery) query; int expectedMinimumShouldMatch = numberOfTerms * percent / 100; if (simpleQueryStringBuilder.defaultOperator().equals(Operator.AND)) { expectedMinimumShouldMatch = 0; } assertEquals(expectedMinimumShouldMatch, boolQuery.getMinimumNumberShouldMatch()); } } public void testExpandedTerms() throws Exception { // Prefix Query query = new SimpleQueryStringBuilder("aBc*").field(TEXT_FIELD_NAME) .analyzer("whitespace") .toQuery(createSearchExecutionContext()); assertEquals(new PrefixQuery(new Term(TEXT_FIELD_NAME, "aBc")), query); query = new SimpleQueryStringBuilder("aBc*").field(TEXT_FIELD_NAME).analyzer("standard").toQuery(createSearchExecutionContext()); assertEquals(new PrefixQuery(new Term(TEXT_FIELD_NAME, "abc")), query); // Fuzzy query = new SimpleQueryStringBuilder("aBc~1").field(TEXT_FIELD_NAME).analyzer("whitespace").toQuery(createSearchExecutionContext()); FuzzyQuery expected = new FuzzyQuery(new Term(TEXT_FIELD_NAME, "aBc"), 1); assertEquals(expected, query); query = new SimpleQueryStringBuilder("aBc~1").field(TEXT_FIELD_NAME).analyzer("standard").toQuery(createSearchExecutionContext()); expected = new FuzzyQuery(new Term(TEXT_FIELD_NAME, "abc"), 1); assertEquals(expected, query); } public void testAnalyzeWildcard() throws IOException { SimpleQueryStringQueryParser.Settings settings = new SimpleQueryStringQueryParser.Settings(); settings.analyzeWildcard(true); SimpleQueryStringQueryParser parser = new SimpleQueryStringQueryParser( new StandardAnalyzer(), Collections.singletonMap(TEXT_FIELD_NAME, 1.0f), -1, settings, createSearchExecutionContext() ); for (Operator op : Operator.values()) { BooleanClause.Occur defaultOp = op.toBooleanClauseOccur(); parser.setDefaultOperator(defaultOp); Query query = parser.parse("first foo-bar-foobar* last"); Query expectedQuery = new BooleanQuery.Builder().add( new BooleanClause(new TermQuery(new Term(TEXT_FIELD_NAME, "first")), defaultOp) ) .add( new BooleanQuery.Builder().add(new BooleanClause(new TermQuery(new Term(TEXT_FIELD_NAME, "foo")), defaultOp)) .add(new BooleanClause(new TermQuery(new Term(TEXT_FIELD_NAME, "bar")), defaultOp)) .add(new BooleanClause(new PrefixQuery(new Term(TEXT_FIELD_NAME, "foobar")), defaultOp)) .build(), defaultOp ) .add(new BooleanClause(new TermQuery(new Term(TEXT_FIELD_NAME, "last")), defaultOp)) .build(); assertThat(query, equalTo(expectedQuery)); } } public void testAnalyzerWildcardWithSynonyms() throws IOException { SimpleQueryStringQueryParser.Settings settings = new SimpleQueryStringQueryParser.Settings(); settings.analyzeWildcard(true); SimpleQueryStringQueryParser parser = new SimpleQueryStringQueryParser( new MockRepeatAnalyzer(), Collections.singletonMap(TEXT_FIELD_NAME, 1.0f), -1, settings, createSearchExecutionContext() ); for (Operator op : Operator.values()) { BooleanClause.Occur defaultOp = op.toBooleanClauseOccur(); parser.setDefaultOperator(defaultOp); Query query = parser.parse("first foo-bar-foobar* last"); Query expectedQuery = new BooleanQuery.Builder().add( new BooleanClause( new SynonymQuery.Builder(TEXT_FIELD_NAME).addTerm(new Term(TEXT_FIELD_NAME, "first")) .addTerm(new Term(TEXT_FIELD_NAME, "first")) .build(), defaultOp ) ) .add( new BooleanQuery.Builder().add( new BooleanClause( new SynonymQuery.Builder(TEXT_FIELD_NAME).addTerm(new Term(TEXT_FIELD_NAME, "foo")) .addTerm(new Term(TEXT_FIELD_NAME, "foo")) .build(), defaultOp ) ) .add( new BooleanClause( new SynonymQuery.Builder(TEXT_FIELD_NAME).addTerm(new Term(TEXT_FIELD_NAME, "bar")) .addTerm(new Term(TEXT_FIELD_NAME, "bar")) .build(), defaultOp ) ) .add( new BooleanQuery.Builder().add( new BooleanClause(new PrefixQuery(new Term(TEXT_FIELD_NAME, "foobar")), BooleanClause.Occur.SHOULD) ) .add(new BooleanClause(new PrefixQuery(new Term(TEXT_FIELD_NAME, "foobar")), BooleanClause.Occur.SHOULD)) .build(), defaultOp ) .build(), defaultOp ) .add( new BooleanClause( new SynonymQuery.Builder(TEXT_FIELD_NAME).addTerm(new Term(TEXT_FIELD_NAME, "last")) .addTerm(new Term(TEXT_FIELD_NAME, "last")) .build(), defaultOp ) ) .build(); assertThat(query, equalTo(expectedQuery)); } } public void testAnalyzerWithGraph() { SimpleQueryStringQueryParser.Settings settings = new SimpleQueryStringQueryParser.Settings(); settings.analyzeWildcard(true); SimpleQueryStringQueryParser parser = new SimpleQueryStringQueryParser( new MockSynonymAnalyzer(), Collections.singletonMap(TEXT_FIELD_NAME, 1.0f), -1, settings, createSearchExecutionContext() ); for (Operator op : Operator.values()) { BooleanClause.Occur defaultOp = op.toBooleanClauseOccur(); parser.setDefaultOperator(defaultOp); // non-phrase won't detect multi-word synonym because of whitespace splitting Query query = parser.parse("guinea pig"); Query expectedQuery = new BooleanQuery.Builder().add( new BooleanClause(new TermQuery(new Term(TEXT_FIELD_NAME, "guinea")), defaultOp) ).add(new BooleanClause(new TermQuery(new Term(TEXT_FIELD_NAME, "pig")), defaultOp)).build(); assertThat(query, equalTo(expectedQuery)); // phrase will pick it up query = parser.parse("\"guinea pig\""); SpanTermQuery span1 = new SpanTermQuery(new Term(TEXT_FIELD_NAME, "guinea")); SpanTermQuery span2 = new SpanTermQuery(new Term(TEXT_FIELD_NAME, "pig")); expectedQuery = new SpanOrQuery( new SpanNearQuery(new SpanQuery[] { span1, span2 }, 0, true), new SpanTermQuery(new Term(TEXT_FIELD_NAME, "cavy")) ); assertThat(query, equalTo(expectedQuery)); // phrase with slop query = parser.parse("big \"tiny guinea pig\"~2"); PhraseQuery pq1 = new PhraseQuery.Builder().add(new Term(TEXT_FIELD_NAME, "tiny")) .add(new Term(TEXT_FIELD_NAME, "guinea")) .add(new Term(TEXT_FIELD_NAME, "pig")) .setSlop(2) .build(); PhraseQuery pq2 = new PhraseQuery.Builder().add(new Term(TEXT_FIELD_NAME, "tiny")) .add(new Term(TEXT_FIELD_NAME, "cavy")) .setSlop(2) .build(); expectedQuery = new BooleanQuery.Builder().add(new TermQuery(new Term(TEXT_FIELD_NAME, "big")), defaultOp) .add( new BooleanQuery.Builder().add(pq1, BooleanClause.Occur.SHOULD).add(pq2, BooleanClause.Occur.SHOULD).build(), defaultOp ) .build(); assertThat(query, equalTo(expectedQuery)); } } public void testQuoteFieldSuffix() { SimpleQueryStringQueryParser.Settings settings = new SimpleQueryStringQueryParser.Settings(); settings.analyzeWildcard(true); settings.quoteFieldSuffix("_2"); SimpleQueryStringQueryParser parser = new SimpleQueryStringQueryParser( new MockSynonymAnalyzer(), Collections.singletonMap(TEXT_FIELD_NAME, 1.0f), -1, settings, createSearchExecutionContext() ); assertEquals(new TermQuery(new Term(TEXT_FIELD_NAME, "bar")), parser.parse("bar")); assertEquals(new TermQuery(new Term(KEYWORD_FIELD_NAME, "bar")), parser.parse("\"bar\"")); // Now check what happens if the quote field does not exist settings.quoteFieldSuffix(".quote"); parser = new SimpleQueryStringQueryParser( new MockSynonymAnalyzer(), Collections.singletonMap(TEXT_FIELD_NAME, 1.0f), -1, settings, createSearchExecutionContext() ); assertEquals(new TermQuery(new Term(TEXT_FIELD_NAME, "bar")), parser.parse("bar")); assertEquals(new TermQuery(new Term(TEXT_FIELD_NAME, "bar")), parser.parse("\"bar\"")); } public void testToFuzzyQuery() throws Exception { Query query = new SimpleQueryStringBuilder("text~2").field(TEXT_FIELD_NAME) .fuzzyPrefixLength(2) .fuzzyMaxExpansions(5) .fuzzyTranspositions(false) .toQuery(createSearchExecutionContext()); FuzzyQuery expected = new FuzzyQuery(new Term(TEXT_FIELD_NAME, "text"), 2, 2, 5, false); assertEquals(expected, query); } public void testLenientToPrefixQuery() throws Exception { Query query = new SimpleQueryStringBuilder("t*").field(DATE_FIELD_NAME) .field(TEXT_FIELD_NAME) .lenient(true) .toQuery(createSearchExecutionContext()); List<Query> expectedQueries = new ArrayList<>(); expectedQueries.add(new MatchNoDocsQuery("")); expectedQueries.add(new PrefixQuery(new Term(TEXT_FIELD_NAME, "t"))); DisjunctionMaxQuery expected = new DisjunctionMaxQuery(expectedQueries, 1.0f); assertEquals(expected, query); } public void testWithStopWords() throws Exception { Query query = new SimpleQueryStringBuilder("the quick fox").field(TEXT_FIELD_NAME) .analyzer("stop") .toQuery(createSearchExecutionContext()); Query expected = new BooleanQuery.Builder().add(new TermQuery(new Term(TEXT_FIELD_NAME, "quick")), BooleanClause.Occur.SHOULD) .add(new TermQuery(new Term(TEXT_FIELD_NAME, "fox")), BooleanClause.Occur.SHOULD) .build(); assertEquals(expected, query); query = new SimpleQueryStringBuilder("the quick fox").field(TEXT_FIELD_NAME) .field(KEYWORD_FIELD_NAME) .analyzer("stop") .toQuery(createSearchExecutionContext()); expected = new BooleanQuery.Builder().add( new DisjunctionMaxQuery( Arrays.asList(new TermQuery(new Term(TEXT_FIELD_NAME, "quick")), new TermQuery(new Term(KEYWORD_FIELD_NAME, "quick"))), 1.0f ), BooleanClause.Occur.SHOULD ) .add( new DisjunctionMaxQuery( Arrays.asList(new TermQuery(new Term(TEXT_FIELD_NAME, "fox")), new TermQuery(new Term(KEYWORD_FIELD_NAME, "fox"))), 1.0f ), BooleanClause.Occur.SHOULD ) .build(); assertEquals(expected, query); query = new SimpleQueryStringBuilder("the").field(TEXT_FIELD_NAME) .field(KEYWORD_FIELD_NAME) .analyzer("stop") .toQuery(createSearchExecutionContext()); assertEquals(new MatchNoDocsQuery(), query); query = new BoolQueryBuilder().should(new SimpleQueryStringBuilder("the").field(TEXT_FIELD_NAME).analyzer("stop")) .toQuery(createSearchExecutionContext()); expected = new BooleanQuery.Builder().add(new MatchNoDocsQuery(), BooleanClause.Occur.SHOULD).build(); assertEquals(expected, query); query = new BoolQueryBuilder().should( new SimpleQueryStringBuilder("the").field(TEXT_FIELD_NAME).field(KEYWORD_FIELD_NAME).analyzer("stop") ).toQuery(createSearchExecutionContext()); assertEquals(expected, query); } public void testWithPrefixStopWords() throws Exception { Query query = new SimpleQueryStringBuilder("the* quick fox").field(TEXT_FIELD_NAME) .analyzer("stop") .toQuery(createSearchExecutionContext()); BooleanQuery expected = new BooleanQuery.Builder().add( new PrefixQuery(new Term(TEXT_FIELD_NAME, "the")), BooleanClause.Occur.SHOULD ) .add(new TermQuery(new Term(TEXT_FIELD_NAME, "quick")), BooleanClause.Occur.SHOULD) .add(new TermQuery(new Term(TEXT_FIELD_NAME, "fox")), BooleanClause.Occur.SHOULD) .build(); assertEquals(expected, query); } /** * Test for behavior reported in https://github.com/elastic/elasticsearch/issues/34708 * Unmapped field can lead to MatchNoDocsQuerys in disjunction queries. If tokens are eliminated (e.g. because * the tokenizer removed them as punctuation) on regular fields, this can leave only MatchNoDocsQuerys in the * disjunction clause. Instead those disjunctions should be eliminated completely. */ public void testUnmappedFieldNoTokenWithAndOperator() throws IOException { Query query = new SimpleQueryStringBuilder("first & second").field(TEXT_FIELD_NAME) .field("unmapped") .field("another_unmapped") .defaultOperator(Operator.AND) .toQuery(createSearchExecutionContext()); BooleanQuery expected = new BooleanQuery.Builder().add(new TermQuery(new Term(TEXT_FIELD_NAME, "first")), BooleanClause.Occur.MUST) .add(new TermQuery(new Term(TEXT_FIELD_NAME, "second")), BooleanClause.Occur.MUST) .build(); assertEquals(expected, query); query = new SimpleQueryStringBuilder("first & second").field("unmapped") .field("another_unmapped") .defaultOperator(Operator.AND) .toQuery(createSearchExecutionContext()); expected = new BooleanQuery.Builder().add(new MatchNoDocsQuery(), BooleanClause.Occur.MUST) .add(new MatchNoDocsQuery(), BooleanClause.Occur.MUST) .add(new MatchNoDocsQuery(), BooleanClause.Occur.MUST) .build(); assertEquals(expected, query); } public void testNegativeFieldBoost() { IllegalArgumentException exc = expectThrows( IllegalArgumentException.class, () -> new SimpleQueryStringBuilder("the quick fox").field(TEXT_FIELD_NAME, -1.0f) .field(KEYWORD_FIELD_NAME) .toQuery(createSearchExecutionContext()) ); assertThat(exc.getMessage(), containsString("negative [boost]")); } public void testLenientFlag() throws Exception { SimpleQueryStringBuilder query = new SimpleQueryStringBuilder("test").field(BINARY_FIELD_NAME); SearchExecutionContext context = createSearchExecutionContext(); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> query.toQuery(context)); assertEquals("Field [mapped_binary] of type [binary] does not support match queries", e.getMessage()); query.lenient(true); assertThat(query.toQuery(context), instanceOf(MatchNoDocsQuery.class)); } }
SimpleQueryStringBuilderTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/NullValueViaCreatorTest.java
{ "start": 451, "end": 689 }
class ____ { Contained<String> contained; @JsonCreator public Container(@JsonProperty("contained") Contained<String> contained) { this.contained = contained; } } protected static
Container
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/AnyAnnotation.java
{ "start": 527, "end": 1832 }
class ____ implements Any, AttributeMarker, AttributeMarker.Fetchable, AttributeMarker.Optionalable { private jakarta.persistence.FetchType fetch; private boolean optional; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public AnyAnnotation(ModelsContext modelContext) { this.fetch = jakarta.persistence.FetchType.EAGER; this.optional = true; } /** * Used in creating annotation instances from JDK variant */ public AnyAnnotation(Any annotation, ModelsContext modelContext) { this.fetch = annotation.fetch(); this.optional = annotation.optional(); } /** * Used in creating annotation instances from Jandex variant */ public AnyAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { this.fetch = (jakarta.persistence.FetchType) attributeValues.get( "fetch" ); this.optional = (boolean) attributeValues.get( "optional" ); } @Override public Class<? extends Annotation> annotationType() { return Any.class; } @Override public jakarta.persistence.FetchType fetch() { return fetch; } public void fetch(jakarta.persistence.FetchType value) { this.fetch = value; } @Override public boolean optional() { return optional; } public void optional(boolean value) { this.optional = value; } }
AnyAnnotation
java
spring-projects__spring-framework
spring-instrument/src/main/java/org/springframework/instrument/InstrumentationSavingAgent.java
{ "start": 2235, "end": 2547 }
class ____ not used as Java agent when this * JVM was started or it wasn't installed as agent using the Attach API. * @see org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#getInstrumentation() */ public static Instrumentation getInstrumentation() { return instrumentation; } }
was
java
processing__processing4
core/src/processing/opengl/PGraphicsOpenGL.java
{ "start": 2257, "end": 27547 }
class ____<T> extends WeakReference<T> { protected Disposable(T obj) { super(obj, refQueue); drainRefQueueBounded(); reachableWeakReferences.add(this); } public void dispose() { reachableWeakReferences.remove(this); disposeNative(); } abstract public void disposeNative(); } // Basic rendering parameters: /** Whether the PGraphics object is ready to render or not. */ public boolean initialized; /** Flush modes: continuously (geometry is flushed after each call to * endShape) when-full (geometry is accumulated until a maximum size is * reached. */ static protected final int FLUSH_CONTINUOUSLY = 0; static protected final int FLUSH_WHEN_FULL = 1; /** Type of geometry: immediate is that generated with beginShape/vertex/ * endShape, retained is the result of creating a PShapeOpenGL object with * createShape. */ static protected final int IMMEDIATE = 0; static protected final int RETAINED = 1; /** Current flush mode. */ protected int flushMode = FLUSH_WHEN_FULL; // ........................................................ // VBOs for immediate rendering: protected VertexBuffer bufPolyVertex; protected VertexBuffer bufPolyColor; protected VertexBuffer bufPolyNormal; protected VertexBuffer bufPolyTexcoord; protected VertexBuffer bufPolyAmbient; protected VertexBuffer bufPolySpecular; protected VertexBuffer bufPolyEmissive; protected VertexBuffer bufPolyShininess; protected VertexBuffer bufPolyIndex; protected boolean polyBuffersCreated = false; protected int polyBuffersContext; protected VertexBuffer bufLineVertex; protected VertexBuffer bufLineColor; protected VertexBuffer bufLineAttrib; protected VertexBuffer bufLineIndex; protected boolean lineBuffersCreated = false; protected int lineBuffersContext; protected VertexBuffer bufPointVertex; protected VertexBuffer bufPointColor; protected VertexBuffer bufPointAttrib; protected VertexBuffer bufPointIndex; protected boolean pointBuffersCreated = false; protected int pointBuffersContext; // Generic vertex attributes (only for polys) protected AttributeMap polyAttribs; static protected final int INIT_VERTEX_BUFFER_SIZE = 256; static protected final int INIT_INDEX_BUFFER_SIZE = 512; // ........................................................ // GL parameters static protected boolean glParamsRead = false; /** Extensions used by Processing */ static public boolean npotTexSupported; static public boolean autoMipmapGenSupported; static public boolean fboMultisampleSupported; static public boolean packedDepthStencilSupported; static public boolean anisoSamplingSupported; static public boolean blendEqSupported; static public boolean readBufferSupported; static public boolean drawBufferSupported; /** Some hardware limits */ static public int maxTextureSize; static public int maxSamples; static public float maxAnisoAmount; static public int depthBits; static public int stencilBits; /** OpenGL information strings */ static public String OPENGL_VENDOR; static public String OPENGL_RENDERER; static public String OPENGL_VERSION; static public String OPENGL_EXTENSIONS; static public String GLSL_VERSION; // ........................................................ // Shaders static protected URL defColorShaderVertURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/ColorVert.glsl"); static protected URL defTextureShaderVertURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/TexVert.glsl"); static protected URL defLightShaderVertURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/LightVert.glsl"); static protected URL defTexlightShaderVertURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/TexLightVert.glsl"); static protected URL defColorShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/ColorFrag.glsl"); static protected URL defTextureShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/TexFrag.glsl"); static protected URL defLightShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/LightFrag.glsl"); static protected URL defTexlightShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/TexLightFrag.glsl"); static protected URL defLineShaderVertURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/LineVert.glsl"); static protected URL defLineShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/LineFrag.glsl"); static protected URL defPointShaderVertURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/PointVert.glsl"); static protected URL defPointShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/PointFrag.glsl"); static protected URL maskShaderFragURL = PGraphicsOpenGL.class.getResource("/processing/opengl/shaders/MaskFrag.glsl"); protected PShader defColorShader; protected PShader defTextureShader; protected PShader defLightShader; protected PShader defTexlightShader; protected PShader defLineShader; protected PShader defPointShader; protected PShader maskShader; protected PShader polyShader; protected PShader lineShader; protected PShader pointShader; // ........................................................ // Tessellator, geometry protected InGeometry inGeo; protected TessGeometry tessGeo; protected TexCache texCache; protected Tessellator tessellator; // ........................................................ // Depth sorter protected DepthSorter sorter; protected boolean isDepthSortingEnabled; // ........................................................ // Async pixel reader protected AsyncPixelReader asyncPixelReader; protected boolean asyncPixelReaderInitialized; // Keeps track of ongoing transfers so that they can be finished. // Set is copied to the List when we need to iterate it // so that readers can remove themselves from the Set during // iteration if they don't have any ongoing transfers. protected static final Set<PGraphicsOpenGL.AsyncPixelReader> ongoingPixelTransfers = new HashSet<>(); protected static final List<PGraphicsOpenGL.AsyncPixelReader> ongoingPixelTransfersIterable = new ArrayList<>(); // ........................................................ // Camera: /** Camera field of view. */ public float cameraFOV; /** Default position of the camera. */ public float cameraX, cameraY, cameraZ; /** Distance of the near and far planes. */ public float cameraNear, cameraFar; /** Aspect ratio of camera's view. */ public float cameraAspect; /** Default camera properties. */ public float defCameraFOV; public float defCameraX, defCameraY, defCameraZ; public float defCameraNear, defCameraFar; public float defCameraAspect; /** Distance between camera eye and center. */ protected float eyeDist; /** Flag to indicate that we are inside beginCamera/endCamera block. */ protected boolean manipulatingCamera; // ........................................................ // All the matrices required for camera and geometry transformations. public PMatrix3D projection; public PMatrix3D camera; public PMatrix3D cameraInv; public PMatrix3D modelview; public PMatrix3D modelviewInv; public PMatrix3D projmodelview; // To pass to shaders protected float[] glProjection; protected float[] glModelview; protected float[] glProjmodelview; protected float[] glNormal; // Useful to have around. static protected PMatrix3D identity = new PMatrix3D(); /** * Marks when changes to the size have occurred, so that the camera * will be reset in beginDraw(). */ protected boolean sized; static protected final int MATRIX_STACK_DEPTH = 32; protected int modelviewStackDepth; protected int projectionStackDepth; /** Modelview matrix stack **/ protected float[][] modelviewStack = new float[MATRIX_STACK_DEPTH][16]; /** Inverse modelview matrix stack **/ protected float[][] modelviewInvStack = new float[MATRIX_STACK_DEPTH][16]; /** Camera matrix stack **/ protected float[][] cameraStack = new float[MATRIX_STACK_DEPTH][16]; /** Inverse camera matrix stack **/ protected float[][] cameraInvStack = new float[MATRIX_STACK_DEPTH][16]; /** Projection matrix stack **/ protected float[][] projectionStack = new float[MATRIX_STACK_DEPTH][16]; // ........................................................ // Lights: public boolean lights; public int lightCount = 0; /** Light types */ public int[] lightType; /** Light positions */ public float[] lightPosition; /** Light direction (normalized vector) */ public float[] lightNormal; /** * Ambient colors for lights. */ public float[] lightAmbient; /** * Diffuse colors for lights. */ public float[] lightDiffuse; /** * Specular colors for lights. Internally these are stored as numbers between * 0 and 1. */ public float[] lightSpecular; /** Light falloff */ public float[] lightFalloffCoefficients; /** Light spot parameters: Cosine of light spot angle * and concentration */ public float[] lightSpotParameters; /** Current specular color for lighting */ public float[] currentLightSpecular; /** Current light falloff */ public float currentLightFalloffConstant; public float currentLightFalloffLinear; public float currentLightFalloffQuadratic; // ........................................................ // Texturing: protected int textureWrap = CLAMP; protected int textureSampling = Texture.TRILINEAR; // ........................................................ // Clipping protected boolean clip = false; /** Clipping rectangle. */ protected int[] clipRect = {0, 0, 0, 0}; // ........................................................ // Text: /** Font texture of currently selected font. */ FontTexture textTex; // ....................................................... // Framebuffer stack: static protected final int FB_STACK_DEPTH = 16; protected int fbStackDepth; protected FrameBuffer[] fbStack; protected FrameBuffer drawFramebuffer; protected FrameBuffer readFramebuffer; protected FrameBuffer currentFramebuffer; // ....................................................... // Offscreen rendering: protected FrameBuffer offscreenFramebuffer; protected FrameBuffer multisampleFramebuffer; protected boolean offscreenMultisample; protected boolean pixOpChangedFB; // ........................................................ // Screen surface: /** Texture containing the current frame */ protected Texture texture = null; /** Texture containing the previous frame */ protected Texture ptexture = null; /** IntBuffer wrapping the pixels array. */ protected IntBuffer pixelBuffer; /** Array to store pixels in OpenGL format. */ protected int[] nativePixels; /** IntBuffer wrapping the native pixels array. */ protected IntBuffer nativePixelBuffer; /** texture used to apply a filter on the screen image. */ protected Texture filterTexture = null; /** PImage that wraps filterTexture. */ protected PImage filterImage; // ........................................................ // Utility variables: /** True if we are inside a beginDraw()/endDraw() block. */ protected boolean drawing = false; /** Used to detect continuous use of the smooth/noSmooth functions */ protected boolean smoothDisabled = false; protected int smoothCallCount = 0; protected int lastSmoothCall = -10; /** Used to avoid flushing the geometry when blendMode() is called with the * same blend mode as the last */ protected int lastBlendMode = -1; /** Type of pixels operation. */ static protected final int OP_NONE = 0; static protected final int OP_READ = 1; static protected final int OP_WRITE = 2; protected int pixelsOp = OP_NONE; /** Viewport dimensions. */ protected IntBuffer viewport; protected boolean openContour = false; protected boolean breakShape = false; protected boolean defaultEdges = false; static protected final int EDGE_MIDDLE = 0; static protected final int EDGE_START = 1; static protected final int EDGE_STOP = 2; static protected final int EDGE_SINGLE = 3; static protected final int EDGE_CLOSE = -1; /** Used in round point and ellipse tessellation. The * number of subdivisions per round point or ellipse is * calculated with the following formula: * n = min(M, max(N, (TWO_PI * size / F))) * where size is a measure of the dimensions of the circle * when projected on screen coordinates. F just sets the * minimum number of subdivisions, while a smaller F * would allow to have more detailed circles. * N = MIN_POINT_ACCURACY * M = MAX_POINT_ACCURACY * F = POINT_ACCURACY_FACTOR */ final static protected int MIN_POINT_ACCURACY = 20; final static protected int MAX_POINT_ACCURACY = 200; final static protected float POINT_ACCURACY_FACTOR = 10.0f; /** Used in quad point tessellation. */ final static protected float[][] QUAD_POINT_SIGNS = { {-1, +1}, {-1, -1}, {+1, -1}, {+1, +1} }; /** To get data from OpenGL. */ static protected IntBuffer intBuffer; static protected FloatBuffer floatBuffer; // ........................................................ // Error strings: static final String OPENGL_THREAD_ERROR = "Cannot run the OpenGL renderer outside the main thread, change your code" + "\nso the drawing calls are all inside the main thread, " + "\nor use the default renderer instead."; static final String BLEND_DRIVER_ERROR = "blendMode(%1$s) is not supported by this hardware (or driver)"; static final String BLEND_RENDERER_ERROR = "blendMode(%1$s) is not supported by this renderer"; static final String ALREADY_BEGAN_CONTOUR_ERROR = "Already called beginContour()"; static final String NO_BEGIN_CONTOUR_ERROR = "Need to call beginContour() first"; static final String UNSUPPORTED_SMOOTH_LEVEL_ERROR = "Smooth level %1$s is not available. Using %2$s instead"; static final String UNSUPPORTED_SMOOTH_ERROR = "Smooth is not supported by this hardware (or driver)"; static final String TOO_MANY_SMOOTH_CALLS_ERROR = "The smooth/noSmooth functions are being called too often.\n" + "This results in screen flickering, so they will be disabled\n" + "for the rest of the sketch's execution"; static final String UNSUPPORTED_SHAPE_FORMAT_ERROR = "Unsupported shape format"; static final String MISSING_UV_TEXCOORDS_ERROR = "No uv texture coordinates supplied with vertex() call"; static final String INVALID_FILTER_SHADER_ERROR = "Your shader cannot be used as a filter because is of type POINT or LINES"; static final String INCONSISTENT_SHADER_TYPES = "The vertex and fragment shaders have different types"; static final String WRONG_SHADER_TYPE_ERROR = "shader() called with a wrong shader"; static final String SHADER_NEED_LIGHT_ATTRIBS = "The provided shader needs light attributes (ambient, diffuse, etc.), but " + "the current scene is unlit, so the default shader will be used instead"; static final String MISSING_FRAGMENT_SHADER = "The fragment shader is missing, cannot create shader object"; static final String MISSING_VERTEX_SHADER = "The vertex shader is missing, cannot create shader object"; static final String UNKNOWN_SHADER_KIND_ERROR = "Unknown shader kind"; static final String NO_TEXLIGHT_SHADER_ERROR = "Your shader needs to be of TEXLIGHT type " + "to render this geometry properly, using default shader instead."; static final String NO_LIGHT_SHADER_ERROR = "Your shader needs to be of LIGHT type " + "to render this geometry properly, using default shader instead."; static final String NO_TEXTURE_SHADER_ERROR = "Your shader needs to be of TEXTURE type " + "to render this geometry properly, using default shader instead."; static final String NO_COLOR_SHADER_ERROR = "Your shader needs to be of COLOR type " + "to render this geometry properly, using default shader instead."; static final String TESSELLATION_ERROR = "Tessellation Error: %1$s"; static final String GL_THREAD_NOT_CURRENT = "You are trying to draw outside OpenGL's animation thread.\n" + "Place all drawing commands in the draw() function, or inside\n" + "your own functions as long as they are called from draw(),\n" + "but not in event handling functions such as keyPressed()\n" + "or mousePressed()."; ////////////////////////////////////////////////////////////// // INIT/ALLOCATE/FINISH public PGraphicsOpenGL() { pgl = createPGL(this); if (intBuffer == null) { intBuffer = PGL.allocateIntBuffer(2); floatBuffer = PGL.allocateFloatBuffer(2); } viewport = PGL.allocateIntBuffer(4); PGL.bufferUsageRetained = PGL.DYNAMIC_DRAW; PGL.bufferUsageImmediate = PGL.STATIC_DRAW; PGL.bufferMapAccess = PGL.READ_WRITE; polyAttribs = newAttributeMap(); inGeo = newInGeometry(this, polyAttribs, IMMEDIATE); tessGeo = newTessGeometry(this, polyAttribs, IMMEDIATE, PGL.bufferStreamingImmediate); texCache = newTexCache(this); projection = new PMatrix3D(); camera = new PMatrix3D(); cameraInv = new PMatrix3D(); modelview = new PMatrix3D(); modelviewInv = new PMatrix3D(); projmodelview = new PMatrix3D(); lightType = new int[PGL.MAX_LIGHTS]; lightPosition = new float[4 * PGL.MAX_LIGHTS]; lightNormal = new float[3 * PGL.MAX_LIGHTS]; lightAmbient = new float[3 * PGL.MAX_LIGHTS]; lightDiffuse = new float[3 * PGL.MAX_LIGHTS]; lightSpecular = new float[3 * PGL.MAX_LIGHTS]; lightFalloffCoefficients = new float[3 * PGL.MAX_LIGHTS]; lightSpotParameters = new float[2 * PGL.MAX_LIGHTS]; currentLightSpecular = new float[3]; initialized = false; } @Override public void setParent(PApplet parent) { super.setParent(parent); if (pgl != null) { pgl.sketch = parent; } } @Override public void setPrimary(boolean primary) { super.setPrimary(primary); pgl.setPrimary(primary); format = ARGB; if (primary) { fbStack = new FrameBuffer[FB_STACK_DEPTH]; fontMap = new WeakHashMap<>(); tessellator = new Tessellator(); } else { tessellator = getPrimaryPG().tessellator; } } //public void setPath(String path) // PGraphics //public void setAntiAlias(int samples) // PGraphics @Override public void setSize(int iwidth, int iheight) { width = iwidth; height = iheight; updatePixelSize(); texture = null; ptexture = null; // init perspective projection based on new dimensions defCameraFOV = 60 * DEG_TO_RAD; // at least for now defCameraX = width / 2.0f; defCameraY = height / 2.0f; defCameraZ = defCameraY / ((float) Math.tan(defCameraFOV / 2.0f)); defCameraNear = defCameraZ / 10.0f; defCameraFar = defCameraZ * 10.0f; defCameraAspect = (float) width / (float) height; cameraFOV = defCameraFOV; cameraX = defCameraX; cameraY = defCameraY; cameraZ = defCameraZ; cameraNear = defCameraNear; cameraFar = defCameraFar; cameraAspect = defCameraAspect; sized = true; } @Override public void dispose() { // PGraphics if (asyncPixelReader != null) { asyncPixelReader.dispose(); asyncPixelReader = null; } if (!primaryGraphics) { deleteSurfaceTextures(); FrameBuffer ofb = offscreenFramebuffer; FrameBuffer mfb = multisampleFramebuffer; if (ofb != null) { ofb.dispose(); } if (mfb != null) { mfb.dispose(); } } pgl.dispose(); super.dispose(); } protected void setFlushMode(int mode) { flushMode = mode; } protected void updatePixelSize() { float f = pgl.getPixelScale(); pixelWidth = (int)(width * f); pixelHeight = (int)(height * f); if (primaryGraphics) { parent.pixelWidth = pixelWidth; parent.pixelHeight = pixelHeight; } } ////////////////////////////////////////////////////////////// // PLATFORM-SPECIFIC CODE (Java, Android, etc.). Needs to be manually edited. // Factory method protected PGL createPGL(PGraphicsOpenGL pg) { return new PJOGL(pg); // return new PGLES(pg); } /* @Override // Android only public void setFrameRate(float frameRate) { pgl.setFrameRate(frameRate); } @Override // Android only public boolean canDraw() { return pgl.canDraw(); } @Override // Android only public void requestDraw() { if (primaryGraphics) { if (initialized) { if (sized) pgl.reinitSurface(); if (parent.canDraw()) pgl.requestDraw(); } else { initPrimary(); } } } */ @Override // Java only public PSurface createSurface() { // ignore return surface = new PSurfaceJOGL(this); } @Override public boolean saveImpl(String filename) { // ASYNC save frame using PBOs not yet available on Android //return super.save(filename); // In 4.0 beta 5, the loadPixels() call is moved into saveImpl(), // otherwise it undermines part of the point to having optimized // image writing methods in subclasses (which presumably might be // able to write directly from frame buffer to file). loadPixels(); if (getHint(DISABLE_ASYNC_SAVEFRAME)) { if (primaryGraphics) { // Act as an opaque surface while saving int prevFormat = format; format = RGB; if (pixels == null) { // Workaround for an NPE caused by resize events: // https://github.com/processing/processing4/issues/162 // But there's a larger problem at play here: // https://github.com/processing/processing4/issues/385 System.err.println("Not saving image because pixels not ready."); return false; } boolean result = super.saveImpl(filename); format = prevFormat; return result; } return super.saveImpl(filename); } if (asyncImageSaver == null) { asyncImageSaver = new AsyncImageSaver(); } if (!asyncPixelReaderInitialized) { // First call! Get this guy initialized if (pgl.hasPBOs() && pgl.hasSynchronization()) { asyncPixelReader = new AsyncPixelReader(); } asyncPixelReaderInitialized = true; } if (asyncPixelReader != null && !loaded) { boolean needEndDraw = false; if (!drawing) { beginDraw(); needEndDraw = true; } flush(); updatePixelSize(); // get the whole async package asyncPixelReader.readAndSaveAsync(parent.sketchFile(filename)); if (needEndDraw) endDraw(); } else { // async transfer is not supported or // pixels are already in memory, just do async save if (!loaded) loadPixels(); int format = primaryGraphics ? RGB : ARGB; PImage target = asyncImageSaver.getAvailableTarget(pixelWidth, pixelHeight, format); if (target == null) return false; int count = PApplet.min(pixels.length, target.pixels.length); System.arraycopy(pixels, 0, target.pixels, 0, count); asyncImageSaver.saveTargetAsync(this, target, parent.sketchFile(filename)); } return true; } ////////////////////////////////////////////////////////////// // IMAGE METADATA FOR THIS RENDERER @Override public void setCache(PImage image, Object storage) { if (image instanceof PGraphicsOpenGL) { // Prevent strong reference to the key from the value by wrapping // the Texture into WeakReference (proposed solution by WeakHashMap docs) getPrimaryPG().cacheMap.put(image, new WeakReference<>(storage)); return; } getPrimaryPG().cacheMap.put(image, storage); } @Override @SuppressWarnings("rawtypes") public Object getCache(PImage image) { Object storage = getPrimaryPG().cacheMap.get(image); if (storage != null && storage.getClass() == WeakReference.class) { // Unwrap the value, use getClass() for fast check return ((WeakReference) storage).get(); } return storage; } @Override public void removeCache(PImage image) { getPrimaryPG().cacheMap.remove(image); } ////////////////////////////////////////////////////////////// protected void setFontTexture(PFont font, FontTexture fontTexture) { getPrimaryPG().fontMap.put(font, fontTexture); } protected FontTexture getFontTexture(PFont font) { return getPrimaryPG().fontMap.get(font); } protected void removeFontTexture(PFont font) { getPrimaryPG().fontMap.remove(font); } ////////////////////////////////////////////////////////////// protected static
Disposable
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/autoconfigure/WebMvcProperties.java
{ "start": 1435, "end": 5345 }
class ____ { /** * Formatting strategy for message codes. For instance, 'PREFIX_ERROR_CODE'. */ private DefaultMessageCodesResolver.@Nullable Format messageCodesResolverFormat; private final Format format = new Format(); /** * Whether to dispatch TRACE requests to the FrameworkServlet doService method. */ private boolean dispatchTraceRequest; /** * Whether to dispatch OPTIONS requests to the FrameworkServlet doService method. */ private boolean dispatchOptionsRequest = true; /** * Whether to publish a ServletRequestHandledEvent at the end of each request. */ private boolean publishRequestHandledEvents = true; /** * Whether logging of (potentially sensitive) request details at DEBUG and TRACE level * is allowed. */ private boolean logRequestDetails; /** * Whether to enable warn logging of exceptions resolved by a * "HandlerExceptionResolver", except for "DefaultHandlerExceptionResolver". */ private boolean logResolvedException; /** * Path pattern used for static resources. */ private String staticPathPattern = "/**"; /** * Path pattern used for WebJar assets. */ private String webjarsPathPattern = "/webjars/**"; private final Async async = new Async(); private final Servlet servlet = new Servlet(); private final View view = new View(); private final Contentnegotiation contentnegotiation = new Contentnegotiation(); private final Pathmatch pathmatch = new Pathmatch(); private final Problemdetails problemdetails = new Problemdetails(); private final Apiversion apiversion = new Apiversion(); public DefaultMessageCodesResolver.@Nullable Format getMessageCodesResolverFormat() { return this.messageCodesResolverFormat; } public void setMessageCodesResolverFormat(DefaultMessageCodesResolver.@Nullable Format messageCodesResolverFormat) { this.messageCodesResolverFormat = messageCodesResolverFormat; } public Format getFormat() { return this.format; } public boolean isPublishRequestHandledEvents() { return this.publishRequestHandledEvents; } public void setPublishRequestHandledEvents(boolean publishRequestHandledEvents) { this.publishRequestHandledEvents = publishRequestHandledEvents; } public boolean isLogRequestDetails() { return this.logRequestDetails; } public void setLogRequestDetails(boolean logRequestDetails) { this.logRequestDetails = logRequestDetails; } public boolean isLogResolvedException() { return this.logResolvedException; } public void setLogResolvedException(boolean logResolvedException) { this.logResolvedException = logResolvedException; } public boolean isDispatchOptionsRequest() { return this.dispatchOptionsRequest; } public void setDispatchOptionsRequest(boolean dispatchOptionsRequest) { this.dispatchOptionsRequest = dispatchOptionsRequest; } public boolean isDispatchTraceRequest() { return this.dispatchTraceRequest; } public void setDispatchTraceRequest(boolean dispatchTraceRequest) { this.dispatchTraceRequest = dispatchTraceRequest; } public String getStaticPathPattern() { return this.staticPathPattern; } public void setStaticPathPattern(String staticPathPattern) { this.staticPathPattern = staticPathPattern; } public String getWebjarsPathPattern() { return this.webjarsPathPattern; } public void setWebjarsPathPattern(String webjarsPathPattern) { this.webjarsPathPattern = webjarsPathPattern; } public Async getAsync() { return this.async; } public Servlet getServlet() { return this.servlet; } public View getView() { return this.view; } public Contentnegotiation getContentnegotiation() { return this.contentnegotiation; } public Pathmatch getPathmatch() { return this.pathmatch; } public Problemdetails getProblemdetails() { return this.problemdetails; } public Apiversion getApiversion() { return this.apiversion; } public static
WebMvcProperties
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/TestApplicationId.java
{ "start": 1191, "end": 2072 }
class ____ { @Test void testApplicationId() { ApplicationId a1 = ApplicationId.newInstance(10l, 1); ApplicationId a2 = ApplicationId.newInstance(10l, 2); ApplicationId a3 = ApplicationId.newInstance(10l, 1); ApplicationId a4 = ApplicationId.newInstance(8l, 3); assertNotEquals(a1, a2); assertNotEquals(a1, a4); assertEquals(a1, a3); assertTrue(a1.compareTo(a2) < 0); assertTrue(a1.compareTo(a3) == 0); assertTrue(a1.compareTo(a4) > 0); assertTrue(a1.hashCode() == a3.hashCode()); assertFalse(a1.hashCode() == a2.hashCode()); assertFalse(a2.hashCode() == a4.hashCode()); long ts = System.currentTimeMillis(); ApplicationId a5 = ApplicationId.newInstance(ts, 45436343); assertEquals("application_10_0001", a1.toString()); assertEquals("application_" + ts + "_45436343", a5.toString()); } }
TestApplicationId
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdatetime/LocalDateTimeAssert_hasDayOfMonth_Test.java
{ "start": 1062, "end": 1970 }
class ____ { @Test void should_fail_if_actual_is_null() { // GIVEN LocalDateTime actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasDayOfMonth(1)); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_pass_if_actual_is_on_given_day() { // GIVEN LocalDateTime actual = LocalDateTime.of(2022, 1, 1, 0, 0, 0); // WHEN/THEN then(actual).hasDayOfMonth(1); } @Test void should_fail_if_actual_is_not_on_given_day() { // GIVEN LocalDateTime actual = LocalDateTime.of(2022, 1, 1, 0, 0, 0); int expectedDay = 2; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasDayOfMonth(expectedDay)); // THEN then(assertionError).hasMessage(shouldHaveDateField(actual, "day of month", expectedDay).create()); } }
LocalDateTimeAssert_hasDayOfMonth_Test
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/workload/ConfigurableProducerSpec.java
{ "start": 4812, "end": 8734 }
class ____ extends TaskSpec { private final String producerNode; private final String bootstrapServers; private final Optional<FlushGenerator> flushGenerator; private final ThroughputGenerator throughputGenerator; private final PayloadGenerator keyGenerator; private final PayloadGenerator valueGenerator; private final Map<String, String> producerConf; private final Map<String, String> adminClientConf; private final Map<String, String> commonClientConf; private final TopicsSpec activeTopic; private final int activePartition; @JsonCreator public ConfigurableProducerSpec(@JsonProperty("startMs") long startMs, @JsonProperty("durationMs") long durationMs, @JsonProperty("producerNode") String producerNode, @JsonProperty("bootstrapServers") String bootstrapServers, @JsonProperty("flushGenerator") Optional<FlushGenerator> flushGenerator, @JsonProperty("throughputGenerator") ThroughputGenerator throughputGenerator, @JsonProperty("keyGenerator") PayloadGenerator keyGenerator, @JsonProperty("valueGenerator") PayloadGenerator valueGenerator, @JsonProperty("producerConf") Map<String, String> producerConf, @JsonProperty("commonClientConf") Map<String, String> commonClientConf, @JsonProperty("adminClientConf") Map<String, String> adminClientConf, @JsonProperty("activeTopic") TopicsSpec activeTopic, @JsonProperty("activePartition") int activePartition) { super(startMs, durationMs); this.producerNode = (producerNode == null) ? "" : producerNode; this.bootstrapServers = (bootstrapServers == null) ? "" : bootstrapServers; this.flushGenerator = flushGenerator; this.keyGenerator = keyGenerator; this.valueGenerator = valueGenerator; this.throughputGenerator = throughputGenerator; this.producerConf = configOrEmptyMap(producerConf); this.commonClientConf = configOrEmptyMap(commonClientConf); this.adminClientConf = configOrEmptyMap(adminClientConf); this.activeTopic = activeTopic.immutableCopy(); this.activePartition = activePartition; } @JsonProperty public String producerNode() { return producerNode; } @JsonProperty public String bootstrapServers() { return bootstrapServers; } @JsonProperty public Optional<FlushGenerator> flushGenerator() { return flushGenerator; } @JsonProperty public PayloadGenerator keyGenerator() { return keyGenerator; } @JsonProperty public PayloadGenerator valueGenerator() { return valueGenerator; } @JsonProperty public ThroughputGenerator throughputGenerator() { return throughputGenerator; } @JsonProperty public Map<String, String> producerConf() { return producerConf; } @JsonProperty public Map<String, String> commonClientConf() { return commonClientConf; } @JsonProperty public Map<String, String> adminClientConf() { return adminClientConf; } @JsonProperty public TopicsSpec activeTopic() { return activeTopic; } @JsonProperty public int activePartition() { return activePartition; } @Override public TaskController newController(String id) { return topology -> Set.of(producerNode); } @Override public TaskWorker newTaskWorker(String id) { return new ConfigurableProducerWorker(id, this); } }
ConfigurableProducerSpec
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/GetJobModelSnapshotsUpgradeStatsActionResponseTests.java
{ "start": 862, "end": 2349 }
class ____ extends AbstractWireSerializingTestCase<Response> { @Override protected Response createTestInstance() { int listSize = randomInt(10); List<Response.JobModelSnapshotUpgradeStats> statsList = new ArrayList<>(listSize); for (int j = 0; j < listSize; j++) { statsList.add(createRandomizedStat()); } return new Response(new QueryPage<>(statsList, statsList.size(), GetJobModelSnapshotsUpgradeStatsAction.RESULTS_FIELD)); } @Override protected Response mutateInstance(Response instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Response> instanceReader() { return Response::new; } public static Response.JobModelSnapshotUpgradeStats createRandomizedStat() { Response.JobModelSnapshotUpgradeStats.Builder builder = Response.JobModelSnapshotUpgradeStats.builder( randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20) ).setUpgradeState(randomFrom(SnapshotUpgradeState.values())); if (randomBoolean()) { builder.setNode(DiscoveryNodeUtils.create("_id", new TransportAddress(InetAddress.getLoopbackAddress(), 9300))); } else { builder.setAssignmentExplanation(randomAlphaOfLengthBetween(20, 50)); } return builder.build(); } }
GetJobModelSnapshotsUpgradeStatsActionResponseTests
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/serde/RexNodeJsonSerdeTest.java
{ "start": 27687, "end": 44604 }
class ____ { private final CatalogPlanRestore restore = CatalogPlanRestore.ALL; @Test void withConstantCatalogFunction() throws Exception { final SerdeContext ctx = serdeContextWithPermanentFunction(compilation, restore); final JsonNode json = serializePermanentFunction(ctx); assertThatJsonContains(json, FIELD_NAME_CLASS); final ContextResolvedFunction actual = deserialize(ctx, json); // The serde is symmetric, because the function is still present in the catalog assertThat(actual).isEqualTo(PERMANENT_FUNCTION); } @Test void withDroppedCatalogFunction() throws Exception { final SerdeContext ctx = serdeContextWithPermanentFunction(compilation, restore); final JsonNode json = serializePermanentFunction(ctx); assertThatJsonContains(json, FIELD_NAME_CLASS); dropPermanentFunction(ctx); final ContextResolvedFunction actual = deserialize(ctx, json); assertThat(actual) .isEqualTo( ContextResolvedFunction.permanent(FUNCTION_CAT_ID, SER_UDF_IMPL)); } @Test void withShadowingTemporaryFunction() throws Exception { final SerdeContext ctx = serdeContextWithPermanentFunction(compilation, restore); final JsonNode json = serializePermanentFunction(ctx); assertThatJsonContains(json, FIELD_NAME_CLASS); registerTemporaryFunction(ctx); final ContextResolvedFunction actual = deserialize(ctx, json); // The serde is not symmetric, the function is temporary after restore assertThat(actual) .isEqualTo( ContextResolvedFunction.temporary( FUNCTION_CAT_ID, NON_SER_FUNCTION_DEF_IMPL, new FunctionCatalog.InlineCatalogFunction( NON_SER_FUNCTION_DEF_IMPL))); } } } // -------------------------------------------------------------------------------------------- // Test data // -------------------------------------------------------------------------------------------- @SuppressWarnings("UnstableApiUsage") private static Stream<RexNode> testRexNodeSerde() { final RexBuilder rexBuilder = new RexBuilder(FACTORY); final RelDataType inputType = FACTORY.createStructType( StructKind.PEEK_FIELDS_NO_EXPAND, Arrays.asList( FACTORY.createSqlType(SqlTypeName.INTEGER), FACTORY.createSqlType(SqlTypeName.BIGINT), FACTORY.createStructType( StructKind.PEEK_FIELDS_NO_EXPAND, Arrays.asList( FACTORY.createSqlType(SqlTypeName.VARCHAR), FACTORY.createSqlType(SqlTypeName.VARCHAR)), Arrays.asList("n1", "n2"))), Arrays.asList("f1", "f2", "f3")); return Stream.of( rexBuilder.makeNullLiteral(FACTORY.createSqlType(SqlTypeName.VARCHAR)), rexBuilder.makeLiteral(true), rexBuilder.makeExactLiteral( new BigDecimal(Byte.MAX_VALUE), FACTORY.createSqlType(SqlTypeName.TINYINT)), rexBuilder.makeExactLiteral( new BigDecimal(Short.MAX_VALUE), FACTORY.createSqlType(SqlTypeName.SMALLINT)), rexBuilder.makeExactLiteral( new BigDecimal(Integer.MAX_VALUE), FACTORY.createSqlType(SqlTypeName.INTEGER)), rexBuilder.makeExactLiteral( new BigDecimal(Long.MAX_VALUE), FACTORY.createSqlType(SqlTypeName.BIGINT)), rexBuilder.makeExactLiteral( BigDecimal.valueOf(Double.MAX_VALUE), FACTORY.createSqlType(SqlTypeName.DOUBLE)), rexBuilder.makeApproxLiteral( BigDecimal.valueOf(Float.MAX_VALUE), FACTORY.createSqlType(SqlTypeName.FLOAT)), rexBuilder.makeExactLiteral(new BigDecimal("23.1234567890123456789012345678")), rexBuilder.makeIntervalLiteral( BigDecimal.valueOf(100), new SqlIntervalQualifier( TimeUnit.YEAR, 4, TimeUnit.YEAR, RelDataType.PRECISION_NOT_SPECIFIED, SqlParserPos.ZERO)), rexBuilder.makeIntervalLiteral( BigDecimal.valueOf(3), new SqlIntervalQualifier( TimeUnit.YEAR, 2, TimeUnit.MONTH, RelDataType.PRECISION_NOT_SPECIFIED, SqlParserPos.ZERO)), rexBuilder.makeIntervalLiteral( BigDecimal.valueOf(3), new SqlIntervalQualifier( TimeUnit.DAY, 2, TimeUnit.SECOND, 6, SqlParserPos.ZERO)), rexBuilder.makeIntervalLiteral( BigDecimal.valueOf(3), new SqlIntervalQualifier( TimeUnit.SECOND, 2, TimeUnit.SECOND, 6, SqlParserPos.ZERO)), rexBuilder.makeDateLiteral(DateString.fromDaysSinceEpoch(10)), rexBuilder.makeDateLiteral(new DateString("2000-12-12")), rexBuilder.makeTimeLiteral(TimeString.fromMillisOfDay(1234), 3), rexBuilder.makeTimeLiteral(TimeString.fromMillisOfDay(123456), 6), rexBuilder.makeTimeLiteral(new TimeString("01:01:01.000000001"), 9), rexBuilder.makeTimestampLiteral(TimestampString.fromMillisSinceEpoch(1234), 3), rexBuilder.makeTimestampLiteral(TimestampString.fromMillisSinceEpoch(123456789), 9), rexBuilder.makeTimestampLiteral( new TimestampString("0001-01-01 01:01:01.000000001"), 9), rexBuilder.makeTimestampLiteral(new TimestampString("2000-12-12 12:30:57.1234"), 4), rexBuilder.makeBinaryLiteral(ByteString.EMPTY), rexBuilder.makeBinaryLiteral(ByteString.ofBase64("SGVsbG8gV29ybGQh")), rexBuilder.makeLiteral(""), rexBuilder.makeLiteral("abc"), rexBuilder.makeFlag(SqlTrimFunction.Flag.BOTH), rexBuilder.makeFlag(TimeUnitRange.DAY), rexBuilder.makeSearchArgumentLiteral( Sarg.of( false, ImmutableRangeSet.of( Range.closed( BigDecimal.valueOf(1), BigDecimal.valueOf(10)))), FACTORY.createSqlType(SqlTypeName.INTEGER)), rexBuilder.makeSearchArgumentLiteral( Sarg.of( false, ImmutableRangeSet.of( Range.range( BigDecimal.valueOf(1), BoundType.OPEN, BigDecimal.valueOf(10), BoundType.CLOSED))), FACTORY.createSqlType(SqlTypeName.INTEGER)), rexBuilder.makeSearchArgumentLiteral( Sarg.of( false, TreeRangeSet.create( Arrays.asList( Range.closed( BigDecimal.valueOf(1), BigDecimal.valueOf(1)), Range.closed( BigDecimal.valueOf(3), BigDecimal.valueOf(3)), Range.closed( BigDecimal.valueOf(6), BigDecimal.valueOf(6))))), FACTORY.createSqlType(SqlTypeName.INTEGER)), rexBuilder.makeInputRef(FACTORY.createSqlType(SqlTypeName.BIGINT), 0), rexBuilder.makeCorrel(inputType, new CorrelationId("$cor1")), rexBuilder.makeFieldAccess( rexBuilder.makeCorrel(inputType, new CorrelationId("$cor2")), "f2", true), // cast($1 as smallint) rexBuilder.makeCast( FACTORY.createSqlType(SqlTypeName.SMALLINT), rexBuilder.makeInputRef(FACTORY.createSqlType(SqlTypeName.INTEGER), 1)), // $1 in (1, 3, 5) rexBuilder.makeIn( rexBuilder.makeInputRef(FACTORY.createSqlType(SqlTypeName.INTEGER), 1), Arrays.asList( rexBuilder.makeExactLiteral(new BigDecimal(1)), rexBuilder.makeExactLiteral(new BigDecimal(3)), rexBuilder.makeExactLiteral(new BigDecimal(5)))), // null or $1 is null rexBuilder.makeCall( SqlStdOperatorTable.OR, rexBuilder.makeNullLiteral(FACTORY.createSqlType(SqlTypeName.INTEGER)), rexBuilder.makeCall( SqlStdOperatorTable.IS_NOT_NULL, rexBuilder.makeInputRef( FACTORY.createSqlType(SqlTypeName.INTEGER), 1))), // $1 >= 10 rexBuilder.makeCall( SqlStdOperatorTable.GREATER_THAN_OR_EQUAL, rexBuilder.makeInputRef(FACTORY.createSqlType(SqlTypeName.INTEGER), 1), rexBuilder.makeExactLiteral(new BigDecimal(10))), // hash_code($1) rexBuilder.makeCall( FlinkSqlOperatorTable.HASH_CODE, rexBuilder.makeInputRef(FACTORY.createSqlType(SqlTypeName.INTEGER), 1)), rexBuilder.makePatternFieldRef( "test", FACTORY.createSqlType(SqlTypeName.INTEGER), 0), new RexTableArgCall( FACTORY.createStructType( StructKind.PEEK_FIELDS_NO_EXPAND, Arrays.asList( FACTORY.createSqlType(SqlTypeName.VARCHAR), FACTORY.createSqlType(SqlTypeName.INTEGER)), Arrays.asList("f1", "f2")), 0, new int[] {1}, new int[] {0})); } // -------------------------------------------------------------------------------------------- // Helper methods / classes // -------------------------------------------------------------------------------------------- private static RexNode createFunctionCall( SerdeContext serdeContext, ContextResolvedFunction resolvedFunction) { final BridgingSqlFunction nonSerializableFunction = BridgingSqlFunction.of( serdeContext.getFlinkContext(), serdeContext.getTypeFactory(), resolvedFunction); return createFunctionCall(serdeContext, nonSerializableFunction); } private static RexNode createFunctionCall(SerdeContext serdeContext, SqlFunction sqlFunction) { return serdeContext .getRexBuilder() .makeCall( sqlFunction, serdeContext .getRexBuilder() .makeLiteral( 12, serdeContext .getTypeFactory() .createSqlType(SqlTypeName.INTEGER), false)); } private static SerdeContext serdeContext( CatalogPlanCompilation planCompilationOption, CatalogPlanRestore planRestoreOption) { final Configuration configuration = new Configuration(); configuration.set(TableConfigOptions.PLAN_RESTORE_CATALOG_OBJECTS, planRestoreOption); configuration.set(TableConfigOptions.PLAN_COMPILE_CATALOG_OBJECTS, planCompilationOption); return JsonSerdeTestUtil.configuredSerdeContext(configuration); } private static SerdeContext serdeContextWithPermanentFunction( CatalogPlanCompilation planCompilationOption, CatalogPlanRestore planRestoreOption) { final SerdeContext serdeContext = serdeContext(planCompilationOption, planRestoreOption); serdeContext .getFlinkContext() .getFunctionCatalog() .registerCatalogFunction( UNRESOLVED_FUNCTION_CAT_ID, FunctionDescriptor.forFunctionClass(SER_UDF_CLASS).build(), false); serdeContext .getFlinkContext() .getFunctionCatalog() .registerCatalogFunction( UNRESOLVED_ASYNC_FUNCTION_CAT_ID, FunctionDescriptor.forFunctionClass(SER_ASYNC_UDF_CLASS).build(), false); return serdeContext; } private static void dropPermanentFunction(SerdeContext serdeContext) { serdeContext .getFlinkContext() .getFunctionCatalog() .dropCatalogFunction(UNRESOLVED_FUNCTION_CAT_ID, false); } private static void modifyPermanentFunction(SerdeContext serdeContext) { dropPermanentFunction(serdeContext); serdeContext .getFlinkContext() .getFunctionCatalog() .registerCatalogFunction( UNRESOLVED_FUNCTION_CAT_ID, FunctionDescriptor.forFunctionClass(SER_UDF_CLASS_OTHER).build(), false); } private static void registerTemporaryFunction(SerdeContext serdeContext) { serdeContext .getFlinkContext() .getFunctionCatalog() .registerTemporaryCatalogFunction( UNRESOLVED_FUNCTION_CAT_ID, NON_SER_FUNCTION_DEF_IMPL, false); } private static void registerTemporarySystemFunction(SerdeContext serdeContext) { serdeContext .getFlinkContext() .getFunctionCatalog() .registerTemporarySystemFunction(FUNCTION_NAME, NON_SER_FUNCTION_DEF_IMPL, false); } private JsonNode serializePermanentFunction(SerdeContext serdeContext) throws Exception { final byte[] actualSerialized = createJsonObjectWriter(serdeContext) .writeValueAsBytes(createFunctionCall(serdeContext, PERMANENT_FUNCTION)); return createJsonObjectReader(serdeContext).readTree(actualSerialized); } private ContextResolvedFunction deserialize(SerdeContext serdeContext, JsonNode node) throws IOException { final RexNode actualDeserialized = createJsonObjectReader(serdeContext).readValue(node, RexNode.class); return ((BridgingSqlFunction) ((RexCall) actualDeserialized).getOperator()) .getResolvedFunction(); } private static SerdeContext contradictingSerdeContext() { // these contradicting options should not have an impact on temporary or anonymous functions return serdeContext(CatalogPlanCompilation.IDENTIFIER, CatalogPlanRestore.ALL_ENFORCED); } private static
TestRestoreAll
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/domain/userguide/Image.java
{ "start": 366, "end": 686 }
class ____ { @Id private Long id; @Lob @Basic( fetch = FetchType.LAZY ) private byte[] content; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } }
Image
java
elastic__elasticsearch
modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/TLSConfig.java
{ "start": 1021, "end": 1106 }
interface ____ { SSLEngine create(String host, int port); } }
EngineProvider
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/proxy/MethodProxy.java
{ "start": 1501, "end": 3284 }
class ____ { private Signature sig1; private Signature sig2; private CreateInfo createInfo; private final Object initLock = new Object(); private volatile FastClassInfo fastClassInfo; /** * For internal use by {@link Enhancer} only; see the {@link org.springframework.cglib.reflect.FastMethod} class * for similar functionality. */ public static MethodProxy create(Class c1, Class c2, String desc, String name1, String name2) { MethodProxy proxy = new MethodProxy(); proxy.sig1 = new Signature(name1, desc); proxy.sig2 = new Signature(name2, desc); proxy.createInfo = new CreateInfo(c1, c2); // SPRING PATCH BEGIN if (c1 != Object.class && c1.isAssignableFrom(c2.getSuperclass()) && !Factory.class.isAssignableFrom(c2)) { // Try early initialization for overridden methods on specifically purposed subclasses try { proxy.init(); } catch (CodeGenerationException ignored) { // to be retried when actually needed later on (possibly not at all) } } // SPRING PATCH END return proxy; } private void init() { /* * Using a volatile invariant allows us to initialize the FastClass and * method index pairs atomically. * * Double-checked locking is safe with volatile in Java 5. Before 1.5 this * code could allow fastClassInfo to be instantiated more than once, which * appears to be benign. */ if (fastClassInfo == null) { synchronized (initLock) { if (fastClassInfo == null) { CreateInfo ci = createInfo; FastClassInfo fci = new FastClassInfo(); fci.f1 = helper(ci, ci.c1); fci.f2 = helper(ci, ci.c2); fci.i1 = fci.f1.getIndex(sig1); fci.i2 = fci.f2.getIndex(sig2); fastClassInfo = fci; createInfo = null; } } } } private static
MethodProxy
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/ApplicationHistoryManagerOnTimelineStore.java
{ "start": 32468, "end": 32610 }
enum ____ { ALL, // retrieve all the fields USER_AND_ACLS // retrieve user and ACLs info only } private static
ApplicationReportField
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DebeziumSqlserverComponentBuilderFactory.java
{ "start": 5996, "end": 6702 }
class ____ should be used to serialize and deserialize * value data for offsets. The default is JSON converter. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: org.apache.kafka.connect.json.JsonConverter * Group: consumer * * @param internalValueConverter the value to set * @return the dsl builder */ default DebeziumSqlserverComponentBuilder internalValueConverter(java.lang.String internalValueConverter) { doSetProperty("internalValueConverter", internalValueConverter); return this; } /** * The name of the Java
that
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/awt/PointDeserializerTest.java
{ "start": 267, "end": 1492 }
class ____ extends TestCase { public void test_0 () throws Exception { new AwtCodec().getFastMatchToken(); } public void test_error() throws Exception { Exception error = null; try { JSON.parseObject("[]", Point.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_1() throws Exception { Exception error = null; try { JSON.parseObject("{33:44}", Point.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_2() throws Exception { Exception error = null; try { JSON.parseObject("{\"r\":44.}", Point.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { Exception error = null; try { JSON.parseObject("{\"x\":\"aaa\"}", Point.class); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } }
PointDeserializerTest
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/instrumentation/VertxEventBusInstrumentationDisabledTest.java
{ "start": 1275, "end": 2963 }
class ____ { @RegisterExtension static final QuarkusUnitTest unitTest = new QuarkusUnitTest() .withApplicationRoot(root -> root .addClasses(Events.class, TestUtil.class, TestSpanExporter.class, TestSpanExporterProvider.class) .addAsResource(new StringAsset(TestSpanExporterProvider.class.getCanonicalName()), "META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider")) .overrideConfigKey("quarkus.otel.traces.exporter", "test-span-exporter") .overrideConfigKey("quarkus.otel.metrics.exporter", "none") .overrideConfigKey("quarkus.otel.logs.exporter", "none") .overrideConfigKey("quarkus.otel.bsp.schedule.delay", "200") .overrideConfigKey("quarkus.otel.instrument.vertx-event-bus", "false"); @Inject TestSpanExporter spanExporter; @AfterEach void tearDown() { spanExporter.reset(); } @Test void testTracingDisabled() throws Exception { RestAssured.when().get("/hello/event") .then() .statusCode(HTTP_OK) .body(equalTo("BAR")); // http request and dummy List<SpanData> spans = spanExporter.getFinishedSpanItems(2); assertEquals(2, spans.size()); SpanData internal = getSpanByKindAndParentId(spans, INTERNAL, "0000000000000000"); assertEquals("io.quarkus.vertx.opentelemetry", internal.getName()); assertEquals("dummy", internal.getAttributes().get(stringKey("test.message"))); } @Singleton public static
VertxEventBusInstrumentationDisabledTest
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/EndpointAware.java
{ "start": 840, "end": 959 }
interface ____ represent an object such as a {@link org.apache.camel.Processor} that uses an {@link Endpoint} */ public
to
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/namesuggestion/erroneous/PersonAgeMapper.java
{ "start": 425, "end": 618 }
interface ____ { PersonAgeMapper MAPPER = Mappers.getMapper( PersonAgeMapper.class ); @Mapping(target = "fullAge", source = "agee") Person mapPerson(PersonDto dto); }
PersonAgeMapper
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultModelXmlFactory.java
{ "start": 7935, "end": 14040 }
class ____ { static final XMLInputFactory XML_INPUT_FACTORY; static { XMLInputFactory factory = XMLInputFactory.newFactory(); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true); factory.setProperty(XMLInputFactory.IS_COALESCING, true); XML_INPUT_FACTORY = factory; } } /** * Extracts the modelId (groupId:artifactId:version) from a POM XML stream * by parsing just enough XML to get the GAV coordinates. * * @param inputStream the input stream to read from * @return the modelId in format "groupId:artifactId:version" or null if not determinable */ private String extractModelId(InputStream inputStream) { try { XMLStreamReader reader = InputFactoryHolder.XML_INPUT_FACTORY.createXMLStreamReader(inputStream); try { return extractModelId(reader); } finally { reader.close(); } } catch (Exception e) { // If extraction fails, return null and let the normal parsing handle it // This is not a critical failure return null; } } private String extractModelId(Reader reader) { try { // Use a buffered stream to allow efficient reading XMLStreamReader xmlReader = InputFactoryHolder.XML_INPUT_FACTORY.createXMLStreamReader(reader); try { return extractModelId(xmlReader); } finally { xmlReader.close(); } } catch (Exception e) { // If extraction fails, return null and let the normal parsing handle it // This is not a critical failure return null; } } private static String extractModelId(XMLStreamReader reader) throws XMLStreamException { String groupId = null; String artifactId = null; String version = null; String parentGroupId = null; String parentVersion = null; boolean inProject = false; boolean inParent = false; String currentElement = null; while (reader.hasNext()) { int event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { String localName = reader.getLocalName(); if ("project".equals(localName)) { inProject = true; } else if ("parent".equals(localName) && inProject) { inParent = true; } else if (inProject && ("groupId".equals(localName) || "artifactId".equals(localName) || "version".equals(localName))) { currentElement = localName; } } else if (event == XMLStreamConstants.END_ELEMENT) { String localName = reader.getLocalName(); if ("parent".equals(localName)) { inParent = false; } else if ("project".equals(localName)) { break; // We've processed the main project element } currentElement = null; } else if (event == XMLStreamConstants.CHARACTERS && currentElement != null) { String text = reader.getText().trim(); if (!text.isEmpty()) { if (inParent) { switch (currentElement) { case "groupId": parentGroupId = text; break; case "version": parentVersion = text; break; default: // Ignore other elements break; } } else { switch (currentElement) { case "groupId": groupId = text; break; case "artifactId": artifactId = text; break; case "version": version = text; break; default: // Ignore other elements break; } } } } // Early exit if we have enough information if (artifactId != null && groupId != null && version != null) { break; } } // Use parent values as fallback if (groupId == null) { groupId = parentGroupId; } if (version == null) { version = parentVersion; } // Return modelId if we have all required components if (groupId != null && artifactId != null && version != null) { return groupId + ":" + artifactId + ":" + version; } return null; } /** * Simply parse the given xml string. * * @param xml the input XML string * @return the parsed object * @throws XmlReaderException if an error occurs during the parsing * @see #toXmlString(Object) */ public static Model fromXml(@Nonnull String xml) throws XmlReaderException { return new DefaultModelXmlFactory().fromXmlString(xml); } /** * Simply converts the given content to an XML string. * * @param content the object to convert * @return the XML string representation * @throws XmlWriterException if an error occurs during the transformation * @see #fromXmlString(String) */ public static String toXml(@Nonnull Model content) throws XmlWriterException { return new DefaultModelXmlFactory().toXmlString(content); } }
InputFactoryHolder
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/sql/FunctionITCase.java
{ "start": 82715, "end": 83043 }
class ____ extends TableFunction<StructuredUser> { public void eval(String name, int age) { if (name == null) { collect(null); } collect(new StructuredUser(name, age)); } } /** Example POJO for structured type. */ public static
StructuredTableFunction
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/dynamic/ReactiveTypeAdapters.java
{ "start": 8306, "end": 8681 }
enum ____ implements Function<Publisher<?>, Observable<?>> { INSTANCE; @Override public Observable<?> apply(Publisher<?> source) { return RxReactiveStreams.toObservable(source); } } /** * An adapter {@link Function} to adopt a {@link Single} to {@link Publisher}. */ public
PublisherToRxJava1ObservableAdapter
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/util/concurrent/PrioritizedThrottledTaskRunnerTests.java
{ "start": 1235, "end": 1996 }
class ____ extends ESTestCase { private static final ThreadFactory threadFactory = TestEsExecutors.testOnlyDaemonThreadFactory("test"); private static final ThreadContext threadContext = new ThreadContext(Settings.EMPTY); private ExecutorService executor; private int maxThreads; @Override public void setUp() throws Exception { super.setUp(); maxThreads = between(1, 10); executor = EsExecutors.newScaling("test", maxThreads, maxThreads, 0, TimeUnit.NANOSECONDS, false, threadFactory, threadContext); } @Override public void tearDown() throws Exception { super.tearDown(); TestThreadPool.terminate(executor, 30, TimeUnit.SECONDS); } static
PrioritizedThrottledTaskRunnerTests
java
apache__camel
components/camel-weather/src/main/java/org/apache/camel/component/weather/geolocation/GeoLocation.java
{ "start": 867, "end": 1231 }
class ____ { private final String longitude; private final String latitude; public GeoLocation(String longitude, String latitude) { this.longitude = longitude; this.latitude = latitude; } public String getLongitude() { return longitude; } public String getLatitude() { return latitude; } }
GeoLocation
java
elastic__elasticsearch
x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/Protocol.java
{ "start": 700, "end": 1310 }
class ____ extends CoreProtocol { /** * Global choice for the default fetch size. */ public static final TimeValue REQUEST_TIMEOUT = fromProto(CoreProtocol.REQUEST_TIMEOUT); public static final TimeValue PAGE_TIMEOUT = fromProto(CoreProtocol.PAGE_TIMEOUT); public static final TimeValue DEFAULT_KEEP_ALIVE = fromProto(CoreProtocol.DEFAULT_KEEP_ALIVE); public static final TimeValue DEFAULT_WAIT_FOR_COMPLETION_TIMEOUT = fromProto(CoreProtocol.DEFAULT_WAIT_FOR_COMPLETION_TIMEOUT); public static final TimeValue MIN_KEEP_ALIVE = fromProto(CoreProtocol.MIN_KEEP_ALIVE); }
Protocol
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/CommonClientConfigs.java
{ "start": 1524, "end": 10812 }
class ____ { private static final Logger log = LoggerFactory.getLogger(CommonClientConfigs.class); /* * NOTE: DO NOT CHANGE EITHER CONFIG NAMES AS THESE ARE PART OF THE PUBLIC API AND CHANGE WILL BREAK USER CODE. */ public static final String BOOTSTRAP_SERVERS_CONFIG = "bootstrap.servers"; public static final String BOOTSTRAP_SERVERS_DOC = "A list of host/port pairs used to establish the initial connection to the Kafka cluster. " + "Clients use this list to bootstrap and discover the full set of Kafka brokers. " + "While the order of servers in the list does not matter, we recommend including more than one server to ensure resilience if any servers are down. " + "This list does not need to contain the entire set of brokers, as Kafka clients automatically manage and update connections to the cluster efficiently. " + "This list must be in the form <code>host1:port1,host2:port2,...</code>."; public static final String CLIENT_DNS_LOOKUP_CONFIG = "client.dns.lookup"; public static final String CLIENT_DNS_LOOKUP_DOC = "Controls how the client uses DNS lookups. " + "If set to <code>use_all_dns_ips</code>, connect to each returned IP " + "address in sequence until a successful connection is established. " + "After a disconnection, the next IP is used. Once all IPs have been " + "used once, the client resolves the IP(s) from the hostname again " + "(both the JVM and the OS cache DNS name lookups, however). " + "If set to <code>resolve_canonical_bootstrap_servers_only</code>, " + "resolve each bootstrap address into a list of canonical names. After " + "the bootstrap phase, this behaves the same as <code>use_all_dns_ips</code>."; public static final String METADATA_MAX_AGE_CONFIG = "metadata.max.age.ms"; public static final String METADATA_MAX_AGE_DOC = "The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions."; public static final String SEND_BUFFER_CONFIG = "send.buffer.bytes"; public static final String SEND_BUFFER_DOC = "The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used."; public static final int SEND_BUFFER_LOWER_BOUND = -1; public static final String RECEIVE_BUFFER_CONFIG = "receive.buffer.bytes"; public static final String RECEIVE_BUFFER_DOC = "The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used."; public static final int RECEIVE_BUFFER_LOWER_BOUND = -1; public static final String CLIENT_ID_CONFIG = "client.id"; public static final String CLIENT_ID_DOC = "An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging."; public static final String CLIENT_RACK_CONFIG = "client.rack"; public static final String CLIENT_RACK_DOC = "A rack identifier for this client. This can be any string value which indicates where this client is physically located. It corresponds with the broker config 'broker.rack'"; public static final String DEFAULT_CLIENT_RACK = ""; public static final String RECONNECT_BACKOFF_MS_CONFIG = "reconnect.backoff.ms"; public static final String RECONNECT_BACKOFF_MS_DOC = "The base amount of time to wait before attempting to reconnect to a given host. " + "This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker. " + "This value is the initial backoff value and will increase exponentially for each consecutive connection failure, up to the <code>reconnect.backoff.max.ms</code> value."; public static final String RECONNECT_BACKOFF_MAX_MS_CONFIG = "reconnect.backoff.max.ms"; public static final String RECONNECT_BACKOFF_MAX_MS_DOC = "The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. " + "If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms."; public static final String RETRIES_CONFIG = "retries"; public static final String RETRIES_DOC = "It is recommended to set the value to either <code>MAX_VALUE</code> or zero, and use corresponding timeout parameters to control how long a client should retry a request." + " Setting a value greater than zero will cause the client to resend any request that fails with a potentially transient error." + " Setting a value of zero will lead to transient errors not being retried, and they will be propagated to the application to be handled."; public static final String RETRY_BACKOFF_MS_CONFIG = "retry.backoff.ms"; public static final String RETRY_BACKOFF_MS_DOC = "The amount of time to wait before attempting to retry a failed request to a given topic partition. " + "This avoids repeatedly sending requests in a tight loop under some failure scenarios. This value is the initial backoff value and will increase exponentially for each failed request, " + "up to the <code>retry.backoff.max.ms</code> value."; public static final Long DEFAULT_RETRY_BACKOFF_MS = 100L; public static final String RETRY_BACKOFF_MAX_MS_CONFIG = "retry.backoff.max.ms"; public static final String RETRY_BACKOFF_MAX_MS_DOC = "The maximum amount of time in milliseconds to wait when retrying a request to the broker that has repeatedly failed. " + "If provided, the backoff per client will increase exponentially for each failed request, up to this maximum. To prevent all clients from being synchronized upon retry, " + "a randomized jitter with a factor of 0.2 will be applied to the backoff, resulting in the backoff falling within a range between 20% below and 20% above the computed value. " + "If <code>retry.backoff.ms</code> is set to be higher than <code>retry.backoff.max.ms</code>, then <code>retry.backoff.max.ms</code> will be used as a constant backoff from the beginning without any exponential increase"; public static final Long DEFAULT_RETRY_BACKOFF_MAX_MS = 1000L; public static final int RETRY_BACKOFF_EXP_BASE = 2; public static final double RETRY_BACKOFF_JITTER = 0.2; public static final String ENABLE_METRICS_PUSH_CONFIG = "enable.metrics.push"; public static final String ENABLE_METRICS_PUSH_DOC = "Whether to enable pushing of client metrics to the cluster, if the cluster has a client metrics subscription which matches this client."; public static final String METRICS_SAMPLE_WINDOW_MS_CONFIG = "metrics.sample.window.ms"; public static final String METRICS_SAMPLE_WINDOW_MS_DOC = "The window of time a metrics sample is computed over."; public static final String METRICS_NUM_SAMPLES_CONFIG = "metrics.num.samples"; public static final String METRICS_NUM_SAMPLES_DOC = "The number of samples maintained to compute metrics."; public static final String METRICS_RECORDING_LEVEL_CONFIG = "metrics.recording.level"; public static final String METRICS_RECORDING_LEVEL_DOC = "The highest recording level for metrics. It has three levels for recording metrics - info, debug, and trace.\n" + " \n" + "INFO level records only essential metrics necessary for monitoring system performance and health. It collects vital data without gathering too much detail, making it suitable for production environments where minimal overhead is desired.\n" + "\n" + "DEBUG level records most metrics, providing more detailed information about the system's operation. It's useful for development and testing environments where you need deeper insights to debug and fine-tune the application.\n" + "\n" + "TRACE level records all possible metrics, capturing every detail about the system's performance and operation. It's best for controlled environments where in-depth analysis is required, though it can introduce significant overhead."; public static final String METRIC_REPORTER_CLASSES_CONFIG = "metric.reporters"; public static final String METRIC_REPORTER_CLASSES_DOC = "A list of classes to use as metrics reporters. " + "Implementing the <code>org.apache.kafka.common.metrics.MetricsReporter</code>
CommonClientConfigs
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/uuid/random/Book.java
{ "start": 478, "end": 988 }
class ____ { @Id @GeneratedValue @UuidGenerator private UUID id; @Basic private String name; //end::example-identifiers-generators-uuid-implicit[] protected Book() { // for Hibernate use } public Book(String name) { this.name = name; } public UUID getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } //tag::example-identifiers-generators-uuid-implicit[] } //end::example-identifiers-generators-uuid-implicit[]
Book
java
apache__spark
sql/core/src/main/java/org/apache/spark/sql/execution/datasources/HadoopLineRecordReader.java
{ "start": 2767, "end": 12000 }
class ____ extends RecordReader<LongWritable, Text> { public static final String MAX_LINE_LENGTH = "mapreduce.input.linerecordreader.line.maxlength"; private static final SparkLogger LOG = SparkLoggerFactory.getLogger(HadoopLineRecordReader.class); private long start; private long pos; private long end; private SplitLineReader in; private FSDataInputStream fileIn; private Seekable filePosition; private int maxLineLength; private LongWritable key; private Text value; private boolean isCompressedInput; private Decompressor decompressor; private byte[] recordDelimiterBytes; public HadoopLineRecordReader() { } public HadoopLineRecordReader(byte[] recordDelimiter) { this.recordDelimiterBytes = recordDelimiter; } public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException { FileSplit split = (FileSplit) genericSplit; Configuration job = context.getConfiguration(); this.maxLineLength = job.getInt(MAX_LINE_LENGTH, Integer.MAX_VALUE); start = split.getStart(); end = start + split.getLength(); final Path file = split.getPath(); // open the file and seek to the start of the split final FutureDataInputStreamBuilder builder = file.getFileSystem(job).openFile(file); // the start and end of the split may be used to build // an input strategy. builder.optLong(FS_OPTION_OPENFILE_SPLIT_START, start); builder.optLong(FS_OPTION_OPENFILE_SPLIT_END, end); FutureIO.propagateOptions(builder, job, MRJobConfig.INPUT_FILE_OPTION_PREFIX, MRJobConfig.INPUT_FILE_MANDATORY_PREFIX); fileIn = FutureIO.awaitFuture(builder.build()); try { Option<CompressionCodec> codecOpt = HadoopCodecStreams.getDecompressionCodec(job, file); if (codecOpt.isDefined()) { CompressionCodec codec = codecOpt.get(); isCompressedInput = true; try { decompressor = CodecPool.getDecompressor(codec); if (codec instanceof SplittableCompressionCodec) { final SplitCompressionInputStream cIn = ((SplittableCompressionCodec) codec).createInputStream( fileIn, decompressor, start, end, SplittableCompressionCodec.READ_MODE.BYBLOCK); in = new CompressedSplitLineReader(cIn, job, this.recordDelimiterBytes); start = cIn.getAdjustedStart(); end = cIn.getAdjustedEnd(); filePosition = cIn; } else { if (start != 0) { // So we have a split that is only part of a file stored using // a Compression codec that cannot be split. throw new IOException("Cannot seek in " + codec.getClass().getSimpleName() + " compressed stream"); } in = new SplitLineReader(codec.createInputStream(fileIn, decompressor), job, this.recordDelimiterBytes); filePosition = fileIn; } } catch (RuntimeException e) { // Try Spark's ZSTD decompression support. This is not available in Hadoop's // version of LineRecordReader. Option<InputStream> decompressedStreamOpt = HadoopCodecStreams.createZstdInputStream(file, fileIn); if (decompressedStreamOpt.isEmpty()) { // File is either not ZSTD compressed or ZSTD codec is not available. throw e; } InputStream decompressedStream = decompressedStreamOpt.get(); if (start != 0) { decompressedStream.close(); throw new IOException("Cannot seek in "+ file.getName() + " compressed stream"); } isCompressedInput = true; in = new SplitLineReader(decompressedStream, job, this.recordDelimiterBytes); filePosition = fileIn; } } else { fileIn.seek(start); in = new UncompressedSplitLineReader( fileIn, job, this.recordDelimiterBytes, split.getLength()); filePosition = fileIn; } // If this is not the first split, we always throw away first record // because we always (except the last split) read one extra line in // next() method. if (start != 0) { start += in.readLine(new Text(), 0, maxBytesToConsume(start)); } this.pos = start; } catch (Exception e) { fileIn.close(); throw e; } } private int maxBytesToConsume(long pos) { return isCompressedInput ? Integer.MAX_VALUE : (int) Math.max(Math.min(Integer.MAX_VALUE, end - pos), maxLineLength); } private long getFilePosition() throws IOException { long retVal; if (isCompressedInput && null != filePosition) { retVal = filePosition.getPos(); } else { retVal = pos; } return retVal; } private int skipUtfByteOrderMark() throws IOException { // Strip BOM(Byte Order Mark) // Text only support UTF-8, we only need to check UTF-8 BOM // (0xEF,0xBB,0xBF) at the start of the text stream. int newMaxLineLength = (int) Math.min(3L + (long) maxLineLength, Integer.MAX_VALUE); int newSize = in.readLine(value, newMaxLineLength, maxBytesToConsume(pos)); // Even we read 3 extra bytes for the first line, // we won't alter existing behavior (no backwards incompat issue). // Because the newSize is less than maxLineLength and // the number of bytes copied to Text is always no more than newSize. // If the return size from readLine is not less than maxLineLength, // we will discard the current line and read the next line. pos += newSize; int textLength = value.getLength(); byte[] textBytes = value.getBytes(); if ((textLength >= 3) && (textBytes[0] == (byte)0xEF) && (textBytes[1] == (byte)0xBB) && (textBytes[2] == (byte)0xBF)) { // find UTF-8 BOM, strip it. LOG.info("Found UTF-8 BOM and skipped it"); textLength -= 3; newSize -= 3; if (textLength > 0) { // It may work to use the same buffer and not do the copyBytes textBytes = value.copyBytes(); value.set(textBytes, 3, textLength); } else { value.clear(); } } return newSize; } public boolean nextKeyValue() throws IOException { if (key == null) { key = new LongWritable(); } key.set(pos); if (value == null) { value = new Text(); } int newSize = 0; // We always read one extra line, which lies outside the upper // split limit i.e. (end - 1) while (getFilePosition() <= end || in.needAdditionalRecordAfterSplit()) { if (pos == 0) { newSize = skipUtfByteOrderMark(); } else { newSize = in.readLine(value, maxLineLength, maxBytesToConsume(pos)); pos += newSize; } if ((newSize == 0) || (newSize < maxLineLength)) { break; } // line too long. try again LOG.info("Skipped line of size " + newSize + " at pos " + (pos - newSize)); } if (newSize == 0) { key = null; value = null; return false; } else { return true; } } @Override public LongWritable getCurrentKey() { return key; } @Override public Text getCurrentValue() { return value; } /** * Get the progress within the split */ public float getProgress() throws IOException { if (start == end) { return 0.0f; } else { return Math.min(1.0f, (getFilePosition() - start) / (float)(end - start)); } } public synchronized void close() throws IOException { try { if (in != null) { in.close(); } } finally { if (decompressor != null) { CodecPool.returnDecompressor(decompressor); decompressor = null; } } } }
HadoopLineRecordReader
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/querydsl/container/QueryContainer.java
{ "start": 1654, "end": 6462 }
class ____ { private final FieldExtractorRegistry extractorRegistry = new FieldExtractorRegistry(); private final Query query; // attributes found in the tree private final AttributeMap<Expression> attributes; // list of fields available in the output private final List<Tuple<FieldExtraction, String>> fields; private final Map<String, Sort> sort; private final boolean trackHits; private final boolean includeFrozen; private final Limit limit; public QueryContainer() { this(null, emptyList(), AttributeMap.emptyAttributeMap(), emptyMap(), false, false, null); } private QueryContainer( Query query, List<Tuple<FieldExtraction, String>> fields, AttributeMap<Expression> attributes, Map<String, Sort> sort, boolean trackHits, boolean includeFrozen, Limit limit ) { this.query = query; this.fields = fields; this.sort = sort; this.attributes = attributes; this.trackHits = trackHits; this.includeFrozen = includeFrozen; this.limit = limit; } public QueryContainer withFrozen() { throw new UnsupportedOperationException(); } public Query query() { return query; } public List<Tuple<FieldExtraction, String>> fields() { return fields; } public Map<String, Sort> sort() { return sort; } public boolean shouldTrackHits() { return trackHits; } public Limit limit() { return limit; } public QueryContainer with(Query q) { return new QueryContainer(q, fields, attributes, sort, trackHits, includeFrozen, limit); } public QueryContainer with(Limit limit) { return new QueryContainer(query, fields, attributes, sort, trackHits, includeFrozen, limit); } public QueryContainer addColumn(Attribute attr) { Expression expression = attributes.getOrDefault(attr, attr); Tuple<QueryContainer, FieldExtraction> tuple = asFieldExtraction(attr); return tuple.v1().addColumn(tuple.v2(), Expressions.id(expression)); } private Tuple<QueryContainer, FieldExtraction> asFieldExtraction(Attribute attr) { // resolve it Expression Expression expression = attributes.getOrDefault(attr, attr); if (expression instanceof FieldAttribute fa) { if (fa.isNested()) { throw new UnsupportedOperationException("Nested not yet supported"); } return new Tuple<>(this, extractorRegistry.fieldExtraction(expression)); } if (expression instanceof OptionalMissingAttribute) { return new Tuple<>(this, new ComputedRef(new ConstantInput(expression.source(), expression, null))); } if (expression.foldable()) { return new Tuple<>(this, new ComputedRef(new ConstantInput(expression.source(), expression, expression.fold()))); } throw new EqlIllegalArgumentException("Unknown output attribute {}", attr); } public QueryContainer addSort(String expressionId, Sort sortable) { Map<String, Sort> newSort = new LinkedHashMap<>(this.sort); newSort.put(expressionId, sortable); return new QueryContainer(query, fields, attributes, newSort, trackHits, includeFrozen, limit); } // // reference methods // public QueryContainer addColumn(FieldExtraction ref, String id) { return new QueryContainer(query, combine(fields, new Tuple<>(ref, id)), attributes, sort, trackHits, includeFrozen, limit); } @Override public int hashCode() { return Objects.hash(query, attributes, fields, trackHits, includeFrozen, limit); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } QueryContainer other = (QueryContainer) obj; return Objects.equals(query, other.query) && Objects.equals(attributes, other.attributes) && Objects.equals(fields, other.fields) && trackHits == other.trackHits && includeFrozen == other.includeFrozen && Objects.equals(limit, other.limit); } @Override public String toString() { try (XContentBuilder builder = JsonXContent.contentBuilder()) { builder.humanReadable(true).prettyPrint(); SourceGenerator.sourceBuilder(this, null, null, null).toXContent(builder, ToXContent.EMPTY_PARAMS); return Strings.toString(builder); } catch (IOException e) { throw new EqlIllegalArgumentException("error rendering", e); } } }
QueryContainer
java
spring-projects__spring-boot
module/spring-boot-data-redis/src/main/java/org/springframework/boot/data/redis/autoconfigure/LettuceConnectionConfiguration.java
{ "start": 11994, "end": 12071 }
class ____ allow optional commons-pool2 dependency. */ private static final
to
java
apache__camel
components/camel-ai/camel-djl/src/main/java/org/apache/camel/component/djl/ImageNetUtil.java
{ "start": 1304, "end": 2366 }
class ____ { public ImageNetUtil() { } public void extractClassName(Exchange exchange) { Classifications body = exchange.getMessage().getBody(Classifications.class); String className = body.best().getClassName().split(",")[0].split(" ", 2)[1]; exchange.getMessage().setBody(className); } public void addHypernym(Exchange exchange) throws Exception { String className = exchange.getMessage().getBody(String.class); Dictionary dic = Dictionary.getDefaultResourceInstance(); IndexWord word = dic.getIndexWord(POS.NOUN, className); if (word == null) { throw new RuntimeCamelException("Word not found: " + className); } PointerTargetNodeList hypernyms = PointerUtils.getDirectHypernyms(word.getSenses().get(0)); String hypernym = hypernyms.stream() .map(h -> h.getSynset().getWords().get(0).getLemma()) .findFirst().orElse(className); exchange.getMessage().setBody(List.of(className, hypernym)); } }
ImageNetUtil
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 63599, "end": 63802 }
class ____ { @Bean public ExtendedFoo foo() { return new ExtendedFoo(); } @Bean public Bar bar() { return new Bar(foo()); } } } @Configuration static
OverridingSingletonBeanConfig
java
apache__logging-log4j2
log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/LogManagerLoggerContextFactoryRule.java
{ "start": 1250, "end": 1916 }
class ____ extends ExternalResource { private final LoggerContextFactory loggerContextFactory; private LoggerContextFactory restoreLoggerContextFactory; public LogManagerLoggerContextFactoryRule(final LoggerContextFactory loggerContextFactory) { this.loggerContextFactory = loggerContextFactory; } @Override protected void after() { LogManager.setFactory(this.restoreLoggerContextFactory); } @Override protected void before() throws Throwable { this.restoreLoggerContextFactory = LogManager.getFactory(); LogManager.setFactory(this.loggerContextFactory); } }
LogManagerLoggerContextFactoryRule
java
apache__camel
components/camel-opentelemetry-metrics/src/generated/java/org/apache/camel/opentelemetry/metrics/OpenTelemetryEndpointUriFactory.java
{ "start": 521, "end": 2622 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":metricType:metricName"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(10); props.add("action"); props.add("attributes"); props.add("decrement"); props.add("increment"); props.add("lazyStartProducer"); props.add("metricName"); props.add("metricType"); props.add("metricsDescription"); props.add("unit"); props.add("value"); PROPERTY_NAMES = Collections.unmodifiableSet(props); SECRET_PROPERTY_NAMES = Collections.emptySet(); Map<String, String> prefixes = new HashMap<>(1); prefixes.put("attributes", "attributes."); MULTI_VALUE_PREFIXES = Collections.unmodifiableMap(prefixes); } @Override public boolean isEnabled(String scheme) { return "opentelemetry-metrics".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "metricType", null, true, copy); uri = buildPathParameter(syntax, uri, "metricName", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
OpenTelemetryEndpointUriFactory
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/SlivePartitioner.java
{ "start": 1161, "end": 1537 }
class ____ implements Partitioner<Text, Text> { @Override // JobConfigurable public void configure(JobConf conf) {} @Override // Partitioner public int getPartition(Text key, Text value, int numPartitions) { OperationOutput oo = new OperationOutput(key, value); return (oo.getOperationType().hashCode() & Integer.MAX_VALUE) % numPartitions; } }
SlivePartitioner
java
micronaut-projects__micronaut-core
inject-java-test/src/test/groovy/io/micronaut/inject/visitor/beans/reflection/PrivateMethodsBean.java
{ "start": 207, "end": 393 }
class ____ { private String name; private String getName() { return name; } private void setName(String name) { this.name = name; } }
PrivateMethodsBean
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/util/UtfTextUtilsTest.java
{ "start": 1245, "end": 4632 }
class ____ { @Test void validateCharsetDetectionWithBOM() { assertEquals("UTF-32", testDetection("0000FEFF").name()); assertEquals("UTF-32", testDetection("FFFE0000").name()); assertEquals("UTF-16", testDetection("FEFF0041").name()); assertEquals("UTF-16", testDetection("FFFE4100").name()); assertEquals("UTF-8", testDetection("EFBBBF41").name()); // Invalid UCS-4 encodings: these we're certain we cannot handle. assertThrows(IllegalArgumentException.class, () -> testDetection("0000FFFE")); assertThrows(IllegalArgumentException.class, () -> testDetection("FEFF0000")); } @Test void validateCharsetDetectionWithoutBOM() { assertEquals("UTF-32BE", testDetection("00000041").name()); assertEquals("UTF-32LE", testDetection("41000000").name()); assertEquals("UTF-16BE", testDetection("00410042").name()); assertEquals("UTF-16LE", testDetection("41004200").name()); assertEquals("UTF-8", testDetection("41424344").name()); assertEquals("UTF-8", testDetection("414243").name()); assertEquals("UTF-16BE", testDetection("0041").name()); assertEquals("UTF-16LE", testDetection("4100").name()); assertEquals("UTF-8", testDetection("4142").name()); assertEquals("UTF-8", testDetection("41").name()); assertEquals("UTF-8", testDetection("").name()); // Invalid UCS-4 encodings: these we're fairly certain we cannot handle. assertThrows(IllegalArgumentException.class, () -> testDetection("00004100")); assertThrows(IllegalArgumentException.class, () -> testDetection("00410000")); } private Charset testDetection(String hexBytes) { return UtfTextUtils.detectUtfCharset(hexBytes(hexBytes)); } private static byte[] hexBytes(String hexBytes) { byte[] bytes = new byte[hexBytes.length() / 2]; for (int i = 0; i < bytes.length; i++) { int index = i * 2; bytes[i] = (byte) Integer.parseUnsignedInt(hexBytes.substring(index, index + 2), 16); } return bytes; } @Test void validateTextConversionFromBytes() { assertEquals("A", UtfTextUtils.asString(hexBytes("EFBBBF41"), StandardCharsets.UTF_8)); assertEquals("A", UtfTextUtils.asString(hexBytes("EFBBBF41"), null)); assertEquals("A", UtfTextUtils.asString(hexBytes("41"), StandardCharsets.UTF_8)); assertEquals("A", UtfTextUtils.asString(hexBytes("41"), null)); } @Test void validateTextConversionFromStreams() throws IOException { assertEquals("A", UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("EFBBBF41")), StandardCharsets.UTF_8)); assertEquals("A", UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("EFBBBF41")), null)); assertEquals("A", UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("41")), StandardCharsets.UTF_8)); assertEquals("A", UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("41")), null)); // Invalid UCS-4 encoding should throw an IOException instead of an // IllegalArgumentException. assertThrows(IOException.class, () -> UtfTextUtils.readAllBytes(new ByteArrayInputStream(hexBytes("0000FFFE")), null)); } @Test void validateSupportForUnmarkableStreams() throws IOException { assertEquals("ABCD", UtfTextUtils.readAllBytes(new UnmarkableInputStream(new ByteArrayInputStream(hexBytes("41424344"))), null)); } private static
UtfTextUtilsTest
java
google__guava
android/guava-tests/test/com/google/common/collect/RangeNonGwtTest.java
{ "start": 907, "end": 1265 }
class ____ extends TestCase { public void testNullPointers() { NullPointerTester tester = new NullPointerTester(); tester.testAllPublicStaticMethods(Range.class); tester.testAllPublicStaticMethods(Range.class); tester.testAllPublicInstanceMethods(Range.all()); tester.testAllPublicInstanceMethods(Range.open(1, 3)); } }
RangeNonGwtTest
java
apache__spark
sql/core/src/test/gen-java/org/apache/spark/sql/execution/datasources/parquet/test/avro/ParquetEnum.java
{ "start": 3411, "end": 5889 }
class ____ extends org.apache.avro.specific.SpecificRecordBuilderBase<ParquetEnum> implements org.apache.avro.data.RecordBuilder<ParquetEnum> { private org.apache.spark.sql.execution.datasources.parquet.test.avro.Suit suit; /** Creates a new Builder */ private Builder() { super(org.apache.spark.sql.execution.datasources.parquet.test.avro.ParquetEnum.SCHEMA$); } /** Creates a Builder by copying an existing Builder */ private Builder(org.apache.spark.sql.execution.datasources.parquet.test.avro.ParquetEnum.Builder other) { super(other); if (isValidValue(fields()[0], other.suit)) { this.suit = data().deepCopy(fields()[0].schema(), other.suit); fieldSetFlags()[0] = true; } } /** Creates a Builder by copying an existing ParquetEnum instance */ private Builder(org.apache.spark.sql.execution.datasources.parquet.test.avro.ParquetEnum other) { super(org.apache.spark.sql.execution.datasources.parquet.test.avro.ParquetEnum.SCHEMA$); if (isValidValue(fields()[0], other.suit)) { this.suit = data().deepCopy(fields()[0].schema(), other.suit); fieldSetFlags()[0] = true; } } /** Gets the value of the 'suit' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.Suit getSuit() { return suit; } /** Sets the value of the 'suit' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.ParquetEnum.Builder setSuit(org.apache.spark.sql.execution.datasources.parquet.test.avro.Suit value) { validate(fields()[0], value); this.suit = value; fieldSetFlags()[0] = true; return this; } /** Checks whether the 'suit' field has been set */ public boolean hasSuit() { return fieldSetFlags()[0]; } /** Clears the value of the 'suit' field */ public org.apache.spark.sql.execution.datasources.parquet.test.avro.ParquetEnum.Builder clearSuit() { suit = null; fieldSetFlags()[0] = false; return this; } @Override public ParquetEnum build() { try { ParquetEnum record = new ParquetEnum(); record.suit = fieldSetFlags()[0] ? this.suit : (org.apache.spark.sql.execution.datasources.parquet.test.avro.Suit) defaultValue(fields()[0]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } }
Builder
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxConcatMap.java
{ "start": 1600, "end": 1917 }
class ____<T, R> extends InternalFluxOperator<T, R> { final Function<? super T, ? extends Publisher<? extends R>> mapper; final Supplier<? extends Queue<T>> queueSupplier; final int prefetch; final ErrorMode errorMode; /** * Indicates when an error from the main source should be reported. */
FluxConcatMap
java
quarkusio__quarkus
integration-tests/awt/src/test/java/io/quarkus/awt/it/ImageDecodersTest.java
{ "start": 1186, "end": 8787 }
class ____ { /** * When comparing pixel colour values, how much difference * from the expected value is allowed. * 0 means no difference is tolerated. */ private static final int[] PIXEL_DIFFERENCE_THRESHOLD_RGBA_VEC = new int[] { 0, 0, 0, 0 }; /** * Exercises decoders on ordinary, valid images. * Mostly GIMP or ImageMagic generated. * * We want to make sure native-image compiled Java libs * can read files generated by different programs, * not just images also generated with Java... * * @param testData valid image filename █ RGBA pixel to test */ @ParameterizedTest // @formatter:off @ValueSource(strings = { // File name █Sanity check pixel x 100 y 100 "test_anim.gif █13,0,0,0", "test.bmp █14,3,23,0", "test_bmp3.bmp █14,3,23,0", "test_comp.jp2 █14,3,23,0", "test_deflate.tiff █182,104,180,255", "test.gif █4,0,0,0", "test_gray.jpg █12,0,0,0", "test_hsl.jpg █21,21,23,0", "test_hsl.png █14,3,23,0", "test.jp2 █14,3,23,0", "test.jpg █19,0,24,0", "test_lossless.jpg █15,3,23,0", "test_lzw.tiff █14,3,23,0", "test_none.tiff █182,104,180,255", "test_packbits.tiff█182,104,180,255", "test.png █14,3,23,0", "test_rgb.png █1,0,2,0", "test_srgb.png █14,3,23,0", "test.tiff █14,3,23,0", "test.wbmp █0,0,0,0", "test_zip.png █14,3,23,0", }) // @formatter:on public void testDecoders(String testData) throws IOException { final String[] filePixel = testData.split("█"); final String fileName = filePixel[0].trim(); final byte[] imgBytes = given() .multiPart("image", new File(ImageDecodersTest.class.getResource("/ordinary/" + fileName).getFile())) .when() .post("/topng/" + fileName) .asByteArray(); final BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgBytes)); assertNotNull(image, fileName + ": The image returned is not a valid PNG."); assertTrue(image.getWidth() == 237 && image.getHeight() == 296, String.format("%s image's expected dimension is %d x %d, but was %d x %d.", fileName, 237, 296, image.getWidth(), image.getHeight())); final int[] expected = decodeArray4(filePixel[1].trim()); final int[] actual = new int[4]; //4BYTE RGBA image.getData().getPixel(100, 100, actual); assertTrue(compareArrays(expected, actual, PIXEL_DIFFERENCE_THRESHOLD_RGBA_VEC), String.format("%s: Wrong pixel. Expected: [%d,%d,%d,%d] Actual: [%d,%d,%d,%d]", fileName, expected[0], expected[1], expected[2], expected[3], actual[0], actual[1], actual[2], actual[3])); } // @formatter:off /** * Suite of either specifically invalid images, to trigger exceptions * during parsing, or more exotic images, utilizing e.g. colour profiles * or specific metadata. * * Notes on selected images: * * weird_230.bmp: Triggers an error that is supposed to have a text * in src/java.desktop/share/classes/com/sun/imageio/plugins/common/iio-plugin.properties * associated with it. If the native image works right, the expected text should be captured * in the log. * * See the test data spreadsheet below for more: * * OK - must produce a readable BufferedImage, metadata could be checked with a regexp * NOK - must not produce any readable image, i.e. must fail, Quarkus log is checked with a regexp * NA - undefined, e.g. JDK inconsistent across versions, we just want no JNI/static init errors, * e.g. https://mail.openjdk.java.net/pipermail/client-libs-dev/2022-May/004780.html */ @ParameterizedTest @ValueSource(strings = { // File name █OK/NOK/NA█ Optionally a regexp to look for in the log or image toString() "weird_1000.jpg █NOK█.*weird_1000.jpg.*Bogus Huffman table definition.*" , // Affects javax/imageio/IIOException "test_a98.jpg █OK █.*type = 5 .* #pixelBits = 24 .*", // Affects sun.java2d.cmm.lcms.LCMSTransform "test_gray_to_k.tiff █OK █.*type = 5 .* #pixelBits = 24 .*", // Affects java.awt.color.ICC_Profile "test_gray_to_k.jpg █NOK█.*test_gray_to_k.jpg.*(Can not access.*profile|LUT is not suitable).*", // Affects java.awt.color.ICC_Profile "test_ps_gray.tiff █OK █.*type = 5 .* #pixelBits = 24 .*", // Affects java.awt.color.ICC_ProfileGray "test_sRGB_ICC_Miss.tiff█OK █.*type = 5 .* #pixelBits = 24 .*", // Affects java.awt.color.CMMException "weird_488-1.tif █OK █.*type = 11 .* #pixelBits = 16 .*", // Affects sun.awt.image.*Raster "test_hyperstack.tiff █OK █.*type = 5 .* #pixelBits = 24 numComponents = 3 .*", // Affects tiff plugin "test_lut_3c_fiji.tiff █OK █.*type = 5 .* #pixelBits = 24 numComponents = 3 .*", // Life sciences imagery, Fiji used to edit colour Lookup Table (LUT) "test_jpeg.tiff █NA █(?i:.*(type = 6 .* #pixelBits = 32 numComponents = 4 |test_jpeg.tiff.*Unsupported Image Type).*)", // JPEG compression TIFF by GIMP, bogus, inconsistent in JDK "test_jpeg_2.tiff █NOK█.*test_jpeg_2.tiff.*Unsupported Image Type.*", // JPEG compression TIFF by GIMP, Transparent pixels color saved "weird_230.bmp █NOK█.*weird_230.bmp.*New BMP version not implemented yet.*" // Tested with a custom iio-plugin.properties too }) // @formatter:on public void testComplexImages(String testData) throws IOException { final String[] imgExpectations = testData.split("█"); final String fileName = imgExpectations[0].trim(); final String okNoKNA = imgExpectations[1].trim(); final Pattern pattern = (imgExpectations.length > 2) ? Pattern.compile(imgExpectations[2].trim()) : null; final byte[] imgBytes = given() .multiPart("image", new File(ImageDecodersTest.class.getResource("/complex/" + fileName).getFile())) .when() .post("/topng/" + fileName) .asByteArray(); final BufferedImage image = ImageIO.read(new ByteArrayInputStream(imgBytes)); switch (okNoKNA) { case "OK": assertNotNull(image, "The image " + fileName + " should have been converted to a valid PNG."); if (pattern != null) { assertTrue(pattern.matcher(image.toString()).matches(), "Image description should have matched " + pattern); } break; case "NOK": assertNull(image, "The image " + fileName + " should have triggered a parsing error."); if (pattern != null) { checkLog(pattern, fileName); } break; case "NA": if (pattern != null) { if (image == null) { checkLog(pattern, fileName); } else { assertTrue(pattern.matcher(image.toString()).matches(), "Image description should have matched " + pattern); } } break; default: fail("Bogus test data: unknown condition: " + okNoKNA); break; } } }
ImageDecodersTest
java
processing__processing4
java/libraries/svg/src/processing/svg/PGraphicsSVG.java
{ "start": 1191, "end": 15254 }
class ____ extends PGraphicsJava2D { /** File being written, if it's a file. */ protected File file; /** OutputStream being written to, if using an OutputStream. */ protected OutputStream output; // protected Writer writer; public PGraphicsSVG() { } public void setPath(String path) { this.path = path; if (path != null) { file = new File(path); if (!file.isAbsolute()) { file = null; } } if (file == null) { throw new RuntimeException("PGraphicsSVG requires an absolute path " + "for the location of the output file."); } } /** * Set the library to write to an output stream instead of a file. */ public void setOutput(OutputStream output) { this.output = output; } @Override public PSurface createSurface() { return surface = new PSurfaceNone(this); } public void beginDraw() { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document. String ns = "http://www.w3.org/2000/svg"; Document document = domImpl.createDocument(ns, "svg", null); // Create an instance of the SVG Generator. g2 = new SVGGraphics2D(document); ((SVGGraphics2D) g2).setSVGCanvasSize(new Dimension(width, height)); //set the extension handler to allow linear and radial gradients to be exported as svg GradientExtensionHandler gradH = new GradientExtensionHandler(); ((SVGGraphics2D) g2).setExtensionHandler(gradH); // Done with our work, let's check on defaults and the rest //super.beginDraw(); // Can't call super.beginDraw() because it'll nuke our g2 checkSettings(); resetMatrix(); // reset model matrix vertexCount = 0; // Also need to push the matrix since the matrix doesn't reset on each run // https://download.processing.org/bugzilla/1227.html pushMatrix(); } public void endDraw() { // Also need to pop the matrix since the matrix doesn't reset on each run // https://download.processing.org/bugzilla/1227.html popMatrix(); // Figure out where the output goes. If the sketch is calling setOutput() // inside draw(), then that OutputStream will be used, otherwise the // path for rendering is expected to have ### inside it so that the frame // can be inserted, because SVG doesn't support multiple pages. if (output == null) { if (path == null) { throw new RuntimeException("setOutput() or setPath() must be " + "used with the SVG renderer"); } else { // insert the frame number and create intermediate directories File file = parent.saveFile(parent.insertFrame(path)); try { output = new FileOutputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } } // This needs to be overridden so that the endDraw() from PGraphicsJava2D // is not inherited (it calls loadPixels). // https://download.processing.org/bugzilla/1169.html // Finally, stream out SVG to the standard output using UTF-8 encoding. boolean useCSS = true; // we want to use CSS style attributes Writer writer = PApplet.createWriter(output); // Writer out = new OutputStreamWriter(System.out, "UTF-8"); try { ((SVGGraphics2D) g2).stream(writer, useCSS); } catch (SVGGraphics2DIOException e) { e.printStackTrace(); } try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { output = null; } } // /** // * Call to explicitly go to the next page from within a single draw(). // */ // public void nextPage() { // PStyle savedStyle = getStyle(); // endDraw(); // g2.dispose(); // // try { //// writer.setPageEmpty(false); // maybe useful later // document.newPage(); // is this bad if no addl pages are made? // } catch (Exception e) { // e.printStackTrace(); // } // g2 = createGraphics(); // beginDraw(); // style(savedStyle); // } // protected Graphics2D createGraphics() { // if (textMode == SHAPE) { // return content.createGraphicsShapes(width, height); // } else if (textMode == MODEL) { // return content.createGraphics(width, height, getMapper()); // } // // Should not be reachable... // throw new RuntimeException("Invalid textMode() selected for PDF."); // } // nothing to be done in dispose(), since essentially disposed on each frame public void dispose() { // if (document != null) { // g2.dispose(); // document.close(); // can't be done in finalize, not always called // document = null; // } // //new Exception().printStackTrace(System.out); } /** * Don't open a window for this renderer, it won't be used. */ @Override public boolean displayable() { return false; } /* protected void finalize() throws Throwable { System.out.println("calling finalize"); //document.close(); // do this in dispose instead? } */ ////////////////////////////////////////////////////////////// /* public void endRecord() { super.endRecord(); dispose(); } public void endRaw() { System.out.println("ending raw"); super.endRaw(); System.out.println("disposing"); dispose(); System.out.println("done"); } */ ////////////////////////////////////////////////////////////// /* protected void rectImpl(float x1, float y1, float x2, float y2) { //rect.setFrame(x1, y1, x2-x1, y2-y1); //draw_shape(rect); System.out.println("rect implements"); g2.fillRect((int)x1, (int)y1, (int) (x2-x1), (int) (y2-y1)); } * /* public void clear() { g2.setColor(Color.red); g2.fillRect(0, 0, width, height); } */ ////////////////////////////////////////////////////////////// /* protected void imageImplAWT(java.awt.Image awtImage, float x1, float y1, float x2, float y2, int u1, int v1, int u2, int v2) { pushMatrix(); translate(x1, y1); int awtImageWidth = awtImage.getWidth(null); int awtImageHeight = awtImage.getHeight(null); scale((x2 - x1) / (float)awtImageWidth, (y2 - y1) / (float)awtImageHeight); g2.drawImage(awtImage, 0, 0, awtImageWidth, awtImageHeight, u1, v1, u2, v2, null); popMatrix(); } */ ////////////////////////////////////////////////////////////// // public void textFont(PFont which) { // super.textFont(which); // checkFont(); // // Make sure a native version of the font is available. //// if (textFont.getFont() == null) { //// throw new RuntimeException("Use createFont() instead of loadFont() " + //// "when drawing text using the PDF library."); //// } // // Make sure that this is a font that the PDF library can deal with. //// if ((textMode != SHAPE) && !checkFont(which.getName())) { //// System.err.println("Use PGraphicsPDF.listFonts() to get a list of available fonts."); //// throw new RuntimeException("The font “" + which.getName() + "” cannot be used with PDF Export."); //// } // } // /** // * Change the textMode() to either SHAPE or MODEL. // * <br/> // * This resets all renderer settings, and therefore must // * be called <EM>before</EM> any other commands that set the fill() // * or the textFont() or anything. Unlike other renderers, // * use textMode() directly after the size() command. // */ // public void textMode(int mode) { // if (textMode != mode) { // if (mode == SHAPE) { // textMode = SHAPE; // g2.dispose(); //// g2 = content.createGraphicsShapes(width, height); // g2 = createGraphics(); // } else if (mode == MODEL) { // textMode = MODEL; // g2.dispose(); //// g2 = content.createGraphics(width, height, mapper); // g2 = createGraphics(); //// g2 = template.createGraphics(width, height, mapper); // } else if (mode == SCREEN) { // throw new RuntimeException("textMode(SCREEN) not supported with PDF"); // } else { // throw new RuntimeException("That textMode() does not exist"); // } // } // } // protected void textLineImpl(char buffer[], int start, int stop, // float x, float y) { // checkFont(); // super.textLineImpl(buffer, start, stop, x, y); // } ////////////////////////////////////////////////////////////// public void loadPixels() { nope("loadPixels"); } public void updatePixels() { nope("updatePixels"); } public void updatePixels(int x, int y, int c, int d) { nope("updatePixels"); } // public int get(int x, int y) { nope("get"); return 0; // not reached } public PImage get(int x, int y, int c, int d) { nope("get"); return null; // not reached } public PImage get() { nope("get"); return null; // not reached } public void set(int x, int y, int argb) { nope("set"); } public void set(int x, int y, PImage image) { nope("set"); } // public void mask(int alpha[]) { nope("mask"); } public void mask(PImage alpha) { nope("mask"); } // public void filter(int kind) { nope("filter"); } public void filter(int kind, float param) { nope("filter"); } // public void copy(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { nope("copy"); } public void copy(PImage src, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { nope("copy"); } // public void blend(int sx, int sy, int dx, int dy, int mode) { nope("blend"); } public void blend(PImage src, int sx, int sy, int dx, int dy, int mode) { nope("blend"); } public void blend(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, int mode) { nope("blend"); } public void blend(PImage src, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, int mode) { nope("blend"); } // public boolean save(String filename) { nope("save"); return false; } ////////////////////////////////////////////////////////////// // /** // * Add a directory that should be searched for font data. // * <br/> // * On Mac OS X, the following directories are added by default: // * <UL> // * <LI>/System/Library/Fonts // * <LI>/Library/Fonts // * <LI>~/Library/Fonts // * </UL> // * On Windows, all drive letters are searched for WINDOWS\Fonts // * or WINNT\Fonts, any that exists is added. // * <br/><br/> // * On Linux or any other platform, you'll need to add the // * directories by hand. (If there are actual standards here that we // * can use as a starting point, please file a bug to make a note of it) // */ // public void addFonts(String directory) { // mapper.insertDirectory(directory); // } // /** // * Check whether the specified font can be used with the PDF library. // * @param name name of the font // * @return true if it's ok // */ // protected void checkFont() { // Font awtFont = textFont.getFont(); // if (awtFont == null) { // always need a native font or reference to it // throw new RuntimeException("Use createFont() instead of loadFont() " + // "when drawing text using the PDF library."); // } else if (textMode != SHAPE) { // if (textFont.isStream()) { // throw new RuntimeException("Use textMode(SHAPE) with PDF when loading " + // ".ttf and .otf files with createFont()."); // } else if (mapper.getAliases().get(textFont.getName()) == null) { // //System.out.println("alias for " + name + " = " + mapper.getAliases().get(name)); //// System.err.println("Use PGraphicsPDF.listFonts() to get a list of " + //// "fonts that can be used with PDF."); //// throw new RuntimeException("The font “" + textFont.getName() + "” " + //// "cannot be used with PDF Export."); // if (textFont.getName().equals("Lucida Sans")) { // throw new RuntimeException("Use textMode(SHAPE) with the default " + // "font when exporting to PDF."); // } else { // throw new RuntimeException("Use textMode(SHAPE) with " + // "“" + textFont.getName() + "” " + // "when exporting to PDF."); // } // } // } // } // /** // * List the fonts known to the PDF renderer. This is like PFont.list(), // * however not all those fonts are available by default. // */ // static public String[] listFonts() { // if (fontList == null) { // HashMap<?, ?> map = getMapper().getAliases(); //// Set entries = map.entrySet(); //// fontList = new String[entries.size()]; // fontList = new String[map.size()]; // int count = 0; // for (Object entry : map.entrySet()) { // fontList[count++] = (String) ((Map.Entry) entry).getKey(); // } //// Iterator it = entries.iterator(); //// int count = 0; //// while (it.hasNext()) { //// Map.Entry entry = (Map.Entry) it.next(); //// //System.out.println(entry.getKey() + "-->" + entry.getValue()); //// fontList[count++] = (String) entry.getKey(); //// } // fontList = PApplet.sort(fontList); // } // return fontList; // } ////////////////////////////////////////////////////////////// protected void nope(String function) { throw new RuntimeException("No " + function + "() for PGraphicsSVG"); } }
PGraphicsSVG
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/main/java/org/springframework/boot/webmvc/test/autoconfigure/WebDriverScope.java
{ "start": 1604, "end": 4627 }
class ____ implements Scope { /** * WebDriver bean scope name. */ public static final String NAME = "webDriver"; private static final String WEB_DRIVER_CLASS = "org.openqa.selenium.WebDriver"; private static final String[] BEAN_CLASSES = { WEB_DRIVER_CLASS, "org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder" }; private final Map<String, Object> instances = new HashMap<>(); @Override public Object get(String name, ObjectFactory<?> objectFactory) { synchronized (this.instances) { Object instance = this.instances.get(name); if (instance == null) { instance = objectFactory.getObject(); this.instances.put(name, instance); } return instance; } } @Override public Object remove(String name) { synchronized (this.instances) { return this.instances.remove(name); } } @Override public void registerDestructionCallback(String name, Runnable callback) { } @Override public @Nullable Object resolveContextualObject(String key) { return null; } @Override public @Nullable String getConversationId() { return null; } /** * Reset all instances in the scope. * @return {@code true} if items were reset */ boolean reset() { boolean reset = false; synchronized (this.instances) { for (Object instance : this.instances.values()) { reset = true; if (instance instanceof WebDriver webDriver) { webDriver.quit(); } } this.instances.clear(); } return reset; } /** * Register this scope with the specified context and reassign appropriate bean * definitions to use it. * @param context the application context */ static void registerWith(ConfigurableApplicationContext context) { if (!ClassUtils.isPresent(WEB_DRIVER_CLASS, null)) { return; } ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); if (beanFactory.getRegisteredScope(NAME) == null) { beanFactory.registerScope(NAME, new WebDriverScope()); } context.addBeanFactoryPostProcessor(WebDriverScope::postProcessBeanFactory); } private static void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { for (String beanClass : BEAN_CLASSES) { for (String beanName : beanFactory.getBeanNamesForType(ClassUtils.resolveClassName(beanClass, null))) { BeanDefinition definition = beanFactory.getBeanDefinition(beanName); if (!StringUtils.hasLength(definition.getScope())) { definition.setScope(NAME); } } } } /** * Return the {@link WebDriverScope} being used by the specified context (if any). * @param context the application context * @return the web driver scope or {@code null} */ static @Nullable WebDriverScope getFrom(ApplicationContext context) { if (context instanceof ConfigurableApplicationContext configurableContext) { Scope scope = configurableContext.getBeanFactory().getRegisteredScope(NAME); return (scope instanceof WebDriverScope webDriverScope) ? webDriverScope : null; } return null; } }
WebDriverScope
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java
{ "start": 8247, "end": 8724 }
class ____ definition, * as set by {@link #checkConfigurationClassCandidate}. * @param beanDef the bean definition to check * @return the {@link Order @Order} annotation value on the configuration class, * or {@link Ordered#LOWEST_PRECEDENCE} if none declared * @since 4.2 */ public static int getOrder(BeanDefinition beanDef) { Integer order = (Integer) beanDef.getAttribute(ORDER_ATTRIBUTE); return (order != null ? order : Ordered.LOWEST_PRECEDENCE); } }
bean
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java
{ "start": 834, "end": 1356 }
class ____ { /** * The bean name of the internally managed transaction advisor (used when mode == PROXY). */ public static final String TRANSACTION_ADVISOR_BEAN_NAME = "org.springframework.transaction.config.internalTransactionAdvisor"; /** * The bean name of the internally managed transaction aspect (used when mode == ASPECTJ). */ public static final String TRANSACTION_ASPECT_BEAN_NAME = "org.springframework.transaction.config.internalTransactionAspect"; /** * The
TransactionManagementConfigUtils
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/engine/CallbackException.java
{ "start": 306, "end": 540 }
class ____ extends RuntimeException { private static final long serialVersionUID = -7530898992688511851L; CallbackException(Throwable cause) { super("Unexpected exception thrown by non-Glide code", cause); } }
CallbackException
java
apache__flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/nfa/NotPatternITCase.java
{ "start": 1845, "end": 18223 }
class ____ extends TestLogger { @Test public void testNotNext() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event c1 = new Event(41, "c", 2.0); Event b1 = new Event(42, "b", 3.0); Event c2 = new Event(43, "c", 4.0); Event d = new Event(43, "d", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(c2, 4)); inputEvents.add(new StreamRecord<>(d, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notNext("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns( matches, Lists.<List<Event>>newArrayList( Lists.newArrayList(a1, c1, d), Lists.newArrayList(a1, c2, d))); } @Test public void testNotNextNoMatches() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event b1 = new Event(42, "b", 3.0); Event c1 = new Event(41, "c", 2.0); Event c2 = new Event(43, "c", 4.0); Event d = new Event(43, "d", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(b1, 2)); inputEvents.add(new StreamRecord<>(c1, 3)); inputEvents.add(new StreamRecord<>(c2, 4)); inputEvents.add(new StreamRecord<>(d, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notNext("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedBy("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); assertEquals(0, matches.size()); } @Test public void testNotNextNoMatchesAtTheEnd() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event c1 = new Event(41, "c", 2.0); Event c2 = new Event(43, "c", 4.0); Event d = new Event(43, "d", 4.0); Event b1 = new Event(42, "b", 3.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(c2, 3)); inputEvents.add(new StreamRecord<>(d, 4)); inputEvents.add(new StreamRecord<>(b1, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedByAny("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))) .notNext("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); assertEquals(0, matches.size()); } @Test public void testNotFollowedBy() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event c1 = new Event(41, "c", 2.0); Event b1 = new Event(42, "b", 3.0); Event c2 = new Event(43, "c", 4.0); Event d = new Event(43, "d", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(c2, 4)); inputEvents.add(new StreamRecord<>(d, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns(matches, Lists.<List<Event>>newArrayList(Lists.newArrayList(a1, c1, d))); } @Test public void testNotFollowedByBeforeOptional() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event c1 = new Event(41, "c", 2.0); Event b1 = new Event(42, "b", 3.0); Event c2 = new Event(43, "c", 4.0); Event d = new Event(43, "d", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(c2, 4)); inputEvents.add(new StreamRecord<>(d, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .optional() .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns(matches, Lists.<List<Event>>newArrayList(Lists.newArrayList(a1, c1, d))); } @Test public void testTimesWithNotFollowedBy() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event b1 = new Event(41, "b", 2.0); Event c = new Event(42, "c", 3.0); Event b2 = new Event(43, "b", 4.0); Event d = new Event(43, "d", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(b1, 2)); inputEvents.add(new StreamRecord<>(c, 3)); inputEvents.add(new StreamRecord<>(b2, 4)); inputEvents.add(new StreamRecord<>(d, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .times(2) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns(matches, Lists.<List<Event>>newArrayList()); } @Test public void testIgnoreStateOfTimesWithNotFollowedBy() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event e = new Event(41, "e", 2.0); Event c1 = new Event(42, "c", 3.0); Event b1 = new Event(43, "b", 4.0); Event c2 = new Event(44, "c", 5.0); Event d1 = new Event(45, "d", 6.0); Event d2 = new Event(46, "d", 7.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(d1, 2)); inputEvents.add(new StreamRecord<>(e, 1)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(c2, 4)); inputEvents.add(new StreamRecord<>(d2, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .times(2) .optional() .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns(matches, Lists.<List<Event>>newArrayList(Lists.newArrayList(a1, d1))); } @Test public void testTimesWithNotFollowedByAfter() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event e = new Event(41, "e", 2.0); Event c1 = new Event(42, "c", 3.0); Event b1 = new Event(43, "b", 4.0); Event b2 = new Event(44, "b", 5.0); Event d1 = new Event(46, "d", 7.0); Event d2 = new Event(47, "d", 8.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(d1, 2)); inputEvents.add(new StreamRecord<>(e, 1)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(b2, 3)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(d2, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .times(2) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns(matches, Lists.<List<Event>>newArrayList()); } @Test public void testNotFollowedByBeforeOptionalAtTheEnd() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event c1 = new Event(41, "c", 2.0); Event b1 = new Event(42, "b", 3.0); Event c2 = new Event(43, "c", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(c2, 4)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedByAny("end") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .optional(); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns( matches, Lists.<List<Event>>newArrayList( Lists.newArrayList(a1, c1), Lists.newArrayList(a1))); } @Test public void testNotFollowedByBeforeOptionalTimes() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event c1 = new Event(41, "c", 2.0); Event b1 = new Event(42, "b", 3.0); Event c2 = new Event(43, "c", 4.0); Event d = new Event(43, "d", 4.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(c1, 2)); inputEvents.add(new StreamRecord<>(b1, 3)); inputEvents.add(new StreamRecord<>(c2, 4)); inputEvents.add(new StreamRecord<>(d, 5)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedByAny("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .times(2) .optional() .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns( matches, Lists.<List<Event>>newArrayList(Lists.newArrayList(a1, c1, c2, d))); } @Test public void testNotFollowedByWithBranchingAtStart() throws Exception { List<StreamRecord<Event>> inputEvents = new ArrayList<>(); Event a1 = new Event(40, "a", 1.0); Event b1 = new Event(42, "b", 3.0); Event c1 = new Event(41, "c", 2.0); Event a2 = new Event(41, "a", 4.0); Event c2 = new Event(43, "c", 5.0); Event d = new Event(43, "d", 6.0); inputEvents.add(new StreamRecord<>(a1, 1)); inputEvents.add(new StreamRecord<>(b1, 2)); inputEvents.add(new StreamRecord<>(c1, 3)); inputEvents.add(new StreamRecord<>(a2, 4)); inputEvents.add(new StreamRecord<>(c2, 5)); inputEvents.add(new StreamRecord<>(d, 6)); Pattern<Event, ?> pattern = Pattern.<Event>begin("start") .where(SimpleCondition.of(value -> value.getName().equals("a"))) .notFollowedBy("notPattern") .where(SimpleCondition.of(value -> value.getName().equals("b"))) .followedBy("middle") .where(SimpleCondition.of(value -> value.getName().equals("c"))) .followedBy("end") .where(SimpleCondition.of(value -> value.getName().equals("d"))); NFA<Event> nfa = compile(pattern, false); final List<List<Event>> matches = feedNFA(inputEvents, nfa); comparePatterns(matches, Lists.<List<Event>>newArrayList(Lists.newArrayList(a2, c2, d))); } private static
NotPatternITCase
java
quarkusio__quarkus
extensions/devui/deployment/src/test/java/io/quarkus/devui/testrunner/params/Setup.java
{ "start": 200, "end": 396 }
class ____ { public void route(@Observes Router router) { router.route("/hello").handler(new HelloResource()); router.route("/odd/:num").handler(new OddResource()); } }
Setup
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/BrokerController.java
{ "start": 10598, "end": 115769 }
class ____ { protected static final Logger LOG = LoggerFactory.getLogger(LoggerName.BROKER_LOGGER_NAME); private static final Logger LOG_PROTECTION = LoggerFactory.getLogger(LoggerName.PROTECTION_LOGGER_NAME); private static final Logger LOG_WATER_MARK = LoggerFactory.getLogger(LoggerName.WATER_MARK_LOGGER_NAME); protected static final int HA_ADDRESS_MIN_LENGTH = 6; protected final BrokerConfig brokerConfig; private final NettyServerConfig nettyServerConfig; private final NettyClientConfig nettyClientConfig; protected final MessageStoreConfig messageStoreConfig; private final AuthConfig authConfig; protected ConsumerOffsetManager consumerOffsetManager; protected final BroadcastOffsetManager broadcastOffsetManager; protected final ConsumerManager consumerManager; protected final ConsumerFilterManager consumerFilterManager; protected final ConsumerOrderInfoManager consumerOrderInfoManager; protected final PopInflightMessageCounter popInflightMessageCounter; protected final PopConsumerService popConsumerService; protected final ProducerManager producerManager; protected final ScheduleMessageService scheduleMessageService; protected final ClientHousekeepingService clientHousekeepingService; protected final PullMessageProcessor pullMessageProcessor; protected final PeekMessageProcessor peekMessageProcessor; protected final PopMessageProcessor popMessageProcessor; protected final AckMessageProcessor ackMessageProcessor; protected final ChangeInvisibleTimeProcessor changeInvisibleTimeProcessor; protected final NotificationProcessor notificationProcessor; protected final PollingInfoProcessor pollingInfoProcessor; protected final QueryAssignmentProcessor queryAssignmentProcessor; protected final ClientManageProcessor clientManageProcessor; protected final SendMessageProcessor sendMessageProcessor; protected final RecallMessageProcessor recallMessageProcessor; protected final ReplyMessageProcessor replyMessageProcessor; protected final PullRequestHoldService pullRequestHoldService; protected final MessageArrivingListener messageArrivingListener; protected final Broker2Client broker2Client; protected final ConsumerIdsChangeListener consumerIdsChangeListener; protected final EndTransactionProcessor endTransactionProcessor; private final RebalanceLockManager rebalanceLockManager = new RebalanceLockManager(); private final TopicRouteInfoManager topicRouteInfoManager; protected BrokerOuterAPI brokerOuterAPI; protected ScheduledExecutorService scheduledExecutorService; protected ScheduledExecutorService syncBrokerMemberGroupExecutorService; protected ScheduledExecutorService brokerHeartbeatExecutorService; protected final SlaveSynchronize slaveSynchronize; protected final BlockingQueue<Runnable> sendThreadPoolQueue; protected final BlockingQueue<Runnable> putThreadPoolQueue; protected final BlockingQueue<Runnable> ackThreadPoolQueue; protected final BlockingQueue<Runnable> pullThreadPoolQueue; protected final BlockingQueue<Runnable> litePullThreadPoolQueue; protected final BlockingQueue<Runnable> replyThreadPoolQueue; protected final BlockingQueue<Runnable> queryThreadPoolQueue; protected final BlockingQueue<Runnable> clientManagerThreadPoolQueue; protected final BlockingQueue<Runnable> heartbeatThreadPoolQueue; protected final BlockingQueue<Runnable> consumerManagerThreadPoolQueue; protected final BlockingQueue<Runnable> endTransactionThreadPoolQueue; protected final BlockingQueue<Runnable> adminBrokerThreadPoolQueue; protected final BlockingQueue<Runnable> loadBalanceThreadPoolQueue; protected BrokerStatsManager brokerStatsManager; protected final List<SendMessageHook> sendMessageHookList = new ArrayList<>(); protected final List<ConsumeMessageHook> consumeMessageHookList = new ArrayList<>(); protected MessageStore messageStore; protected static final String TCP_REMOTING_SERVER = "TCP_REMOTING_SERVER"; protected static final String FAST_REMOTING_SERVER = "FAST_REMOTING_SERVER"; protected final Map<String, RemotingServer> remotingServerMap = new ConcurrentHashMap<>(); protected CountDownLatch remotingServerStartLatch; /** * If {Topic, SubscriptionGroup, Offset}ManagerV2 are used, config entries are stored in RocksDB. */ protected ConfigStorage configStorage; protected TopicConfigManager topicConfigManager; protected SubscriptionGroupManager subscriptionGroupManager; protected TopicQueueMappingManager topicQueueMappingManager; protected ExecutorService sendMessageExecutor; protected ExecutorService pullMessageExecutor; protected ExecutorService litePullMessageExecutor; protected ExecutorService putMessageFutureExecutor; protected ExecutorService ackMessageExecutor; protected ExecutorService replyMessageExecutor; protected ExecutorService queryMessageExecutor; protected ExecutorService adminBrokerExecutor; protected ExecutorService clientManageExecutor; protected ExecutorService heartbeatExecutor; protected ExecutorService consumerManageExecutor; protected ExecutorService loadBalanceExecutor; protected ExecutorService endTransactionExecutor; protected boolean updateMasterHAServerAddrPeriodically = false; private BrokerStats brokerStats; private InetSocketAddress storeHost; private TimerMessageStore timerMessageStore; private TimerCheckpoint timerCheckpoint; protected BrokerFastFailure brokerFastFailure; private Configuration configuration; protected TopicQueueMappingCleanService topicQueueMappingCleanService; protected FileWatchService fileWatchService; protected TransactionalMessageCheckService transactionalMessageCheckService; protected TransactionalMessageService transactionalMessageService; protected AbstractTransactionalMessageCheckListener transactionalMessageCheckListener; protected volatile boolean shutdown = false; protected ShutdownHook shutdownHook; private volatile boolean isScheduleServiceStart = false; private volatile boolean isTransactionCheckServiceStart = false; protected volatile BrokerMemberGroup brokerMemberGroup; protected EscapeBridge escapeBridge; protected List<BrokerAttachedPlugin> brokerAttachedPlugins = new ArrayList<>(); protected volatile long shouldStartTime; private BrokerPreOnlineService brokerPreOnlineService; protected volatile boolean isIsolated = false; protected volatile long minBrokerIdInGroup = 0; protected volatile String minBrokerAddrInGroup = null; private final Lock lock = new ReentrantLock(); protected final List<ScheduledFuture<?>> scheduledFutures = new ArrayList<>(); protected ReplicasManager replicasManager; private long lastSyncTimeMs = System.currentTimeMillis(); protected BrokerMetricsManager brokerMetricsManager; private ColdDataPullRequestHoldService coldDataPullRequestHoldService; private ColdDataCgCtrService coldDataCgCtrService; private TransactionMetricsFlushService transactionMetricsFlushService; private AuthenticationMetadataManager authenticationMetadataManager; private AuthorizationMetadataManager authorizationMetadataManager; private ConfigContext configContext; public BrokerController( final BrokerConfig brokerConfig, final NettyServerConfig nettyServerConfig, final NettyClientConfig nettyClientConfig, final MessageStoreConfig messageStoreConfig, final AuthConfig authConfig, final ShutdownHook shutdownHook ) { this(brokerConfig, nettyServerConfig, nettyClientConfig, messageStoreConfig, authConfig); this.shutdownHook = shutdownHook; } public BrokerController( final BrokerConfig brokerConfig, final MessageStoreConfig messageStoreConfig ) { this(brokerConfig, null, null, messageStoreConfig, null); } public BrokerController( final BrokerConfig brokerConfig, final MessageStoreConfig messageStoreConfig, final AuthConfig authConfig ) { this(brokerConfig, null, null, messageStoreConfig, authConfig); } public BrokerController( final BrokerConfig brokerConfig, final NettyServerConfig nettyServerConfig, final NettyClientConfig nettyClientConfig, final MessageStoreConfig messageStoreConfig ) { this(brokerConfig, nettyServerConfig, nettyClientConfig, messageStoreConfig, null); } public BrokerController( final BrokerConfig brokerConfig, final NettyServerConfig nettyServerConfig, final NettyClientConfig nettyClientConfig, final MessageStoreConfig messageStoreConfig, final AuthConfig authConfig ) { this.brokerConfig = brokerConfig; this.nettyServerConfig = nettyServerConfig; this.nettyClientConfig = nettyClientConfig; this.messageStoreConfig = messageStoreConfig; this.authConfig = authConfig; this.setStoreHost(new InetSocketAddress(this.getBrokerConfig().getBrokerIP1(), getListenPort())); this.brokerStatsManager = messageStoreConfig.isEnableLmq() ? new LmqBrokerStatsManager(this.brokerConfig) : new BrokerStatsManager(this.brokerConfig.getBrokerClusterName(), this.brokerConfig.isEnableDetailStat()); this.broadcastOffsetManager = new BroadcastOffsetManager(this); if (ConfigManagerVersion.V2.getVersion().equals(brokerConfig.getConfigManagerVersion())) { this.configStorage = new ConfigStorage(messageStoreConfig); this.topicConfigManager = new TopicConfigManagerV2(this, configStorage); this.subscriptionGroupManager = new SubscriptionGroupManagerV2(this, configStorage); this.consumerOffsetManager = new ConsumerOffsetManagerV2(this, configStorage); } else if (this.messageStoreConfig.isEnableRocksDBStore()) { this.topicConfigManager = messageStoreConfig.isEnableLmq() ? new RocksDBLmqTopicConfigManager(this) : new RocksDBTopicConfigManager(this); this.subscriptionGroupManager = messageStoreConfig.isEnableLmq() ? new RocksDBLmqSubscriptionGroupManager(this) : new RocksDBSubscriptionGroupManager(this); this.consumerOffsetManager = new RocksDBConsumerOffsetManager(this); } else { this.topicConfigManager = messageStoreConfig.isEnableLmq() ? new LmqTopicConfigManager(this) : new TopicConfigManager(this); this.subscriptionGroupManager = messageStoreConfig.isEnableLmq() ? new LmqSubscriptionGroupManager(this) : new SubscriptionGroupManager(this); this.consumerOffsetManager = messageStoreConfig.isEnableLmq() ? new LmqConsumerOffsetManager(this) : new ConsumerOffsetManager(this); } this.topicQueueMappingManager = new TopicQueueMappingManager(this); this.authenticationMetadataManager = AuthenticationFactory.getMetadataManager(this.authConfig); this.authorizationMetadataManager = AuthorizationFactory.getMetadataManager(this.authConfig); this.pullMessageProcessor = new PullMessageProcessor(this); this.peekMessageProcessor = new PeekMessageProcessor(this); this.pullRequestHoldService = messageStoreConfig.isEnableLmq() ? new LmqPullRequestHoldService(this) : new PullRequestHoldService(this); this.popMessageProcessor = new PopMessageProcessor(this); this.notificationProcessor = new NotificationProcessor(this); this.pollingInfoProcessor = new PollingInfoProcessor(this); this.ackMessageProcessor = new AckMessageProcessor(this); this.changeInvisibleTimeProcessor = new ChangeInvisibleTimeProcessor(this); this.sendMessageProcessor = new SendMessageProcessor(this); this.recallMessageProcessor = new RecallMessageProcessor(this); this.replyMessageProcessor = new ReplyMessageProcessor(this); this.messageArrivingListener = new NotifyMessageArrivingListener(this.pullRequestHoldService, this.popMessageProcessor, this.notificationProcessor); this.consumerIdsChangeListener = new DefaultConsumerIdsChangeListener(this); this.consumerManager = new ConsumerManager(this.consumerIdsChangeListener, this.brokerStatsManager, this.brokerConfig); this.producerManager = new ProducerManager(this.brokerStatsManager); this.consumerFilterManager = new ConsumerFilterManager(this); this.consumerOrderInfoManager = new ConsumerOrderInfoManager(this); this.popInflightMessageCounter = new PopInflightMessageCounter(this); this.popConsumerService = brokerConfig.isPopConsumerKVServiceInit() ? new PopConsumerService(this) : null; this.clientHousekeepingService = new ClientHousekeepingService(this); this.broker2Client = new Broker2Client(this); this.scheduleMessageService = new ScheduleMessageService(this); this.coldDataPullRequestHoldService = new ColdDataPullRequestHoldService(this); this.coldDataCgCtrService = new ColdDataCgCtrService(this); if (nettyClientConfig != null) { this.brokerOuterAPI = new BrokerOuterAPI(nettyClientConfig, authConfig); } this.queryAssignmentProcessor = new QueryAssignmentProcessor(this); this.clientManageProcessor = new ClientManageProcessor(this); this.slaveSynchronize = new SlaveSynchronize(this); this.endTransactionProcessor = new EndTransactionProcessor(this); this.sendThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getSendThreadPoolQueueCapacity()); this.putThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getPutThreadPoolQueueCapacity()); this.pullThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getPullThreadPoolQueueCapacity()); this.litePullThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getLitePullThreadPoolQueueCapacity()); this.ackThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getAckThreadPoolQueueCapacity()); this.replyThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getReplyThreadPoolQueueCapacity()); this.queryThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getQueryThreadPoolQueueCapacity()); this.clientManagerThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getClientManagerThreadPoolQueueCapacity()); this.consumerManagerThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getConsumerManagerThreadPoolQueueCapacity()); this.heartbeatThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getHeartbeatThreadPoolQueueCapacity()); this.endTransactionThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getEndTransactionPoolQueueCapacity()); this.adminBrokerThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getAdminBrokerThreadPoolQueueCapacity()); this.loadBalanceThreadPoolQueue = new LinkedBlockingQueue<>(this.brokerConfig.getLoadBalanceThreadPoolQueueCapacity()); this.brokerFastFailure = new BrokerFastFailure(this); String brokerConfigPath; if (brokerConfig.getBrokerConfigPath() != null && !brokerConfig.getBrokerConfigPath().isEmpty()) { brokerConfigPath = brokerConfig.getBrokerConfigPath(); } else { brokerConfigPath = BrokerPathConfigHelper.getBrokerConfigPath(); } this.configuration = new Configuration( LOG, brokerConfigPath, this.brokerConfig, this.nettyServerConfig, this.nettyClientConfig, this.messageStoreConfig ); this.brokerStatsManager.setProducerStateGetter(new BrokerStatsManager.StateGetter() { @Override public boolean online(String instanceId, String group, String topic) { if (getTopicConfigManager().getTopicConfigTable().containsKey(NamespaceUtil.wrapNamespace(instanceId, topic))) { return getProducerManager().groupOnline(NamespaceUtil.wrapNamespace(instanceId, group)); } else { return getProducerManager().groupOnline(group); } } }); this.brokerStatsManager.setConsumerStateGetter(new BrokerStatsManager.StateGetter() { @Override public boolean online(String instanceId, String group, String topic) { String topicFullName = NamespaceUtil.wrapNamespace(instanceId, topic); if (getTopicConfigManager().getTopicConfigTable().containsKey(topicFullName)) { return getConsumerManager().findSubscriptionData(NamespaceUtil.wrapNamespace(instanceId, group), topicFullName) != null; } else { return getConsumerManager().findSubscriptionData(group, topic) != null; } } }); this.brokerMemberGroup = new BrokerMemberGroup(this.brokerConfig.getBrokerClusterName(), this.brokerConfig.getBrokerName()); this.brokerMemberGroup.getBrokerAddrs().put(this.brokerConfig.getBrokerId(), this.getBrokerAddr()); this.escapeBridge = new EscapeBridge(this); this.topicRouteInfoManager = new TopicRouteInfoManager(this); if (this.brokerConfig.isEnableSlaveActingMaster() && !this.brokerConfig.isSkipPreOnline()) { this.brokerPreOnlineService = new BrokerPreOnlineService(this); } if (this.authConfig != null && this.authConfig.isMigrateAuthFromV1Enabled()) { new AuthMigrator(this.authConfig).migrate(); } } public AuthConfig getAuthConfig() { return authConfig; } public BrokerConfig getBrokerConfig() { return brokerConfig; } public NettyServerConfig getNettyServerConfig() { return nettyServerConfig; } public NettyClientConfig getNettyClientConfig() { return nettyClientConfig; } public BlockingQueue<Runnable> getPullThreadPoolQueue() { return pullThreadPoolQueue; } public BlockingQueue<Runnable> getQueryThreadPoolQueue() { return queryThreadPoolQueue; } public BrokerMetricsManager getBrokerMetricsManager() { return brokerMetricsManager; } public void setBrokerMetricsManager(BrokerMetricsManager brokerMetricsManager) { this.brokerMetricsManager = brokerMetricsManager; } protected void initializeRemotingServer() throws CloneNotSupportedException { NettyRemotingServer tcpRemotingServer = new NettyRemotingServer(this.nettyServerConfig, this.clientHousekeepingService); NettyServerConfig fastConfig = (NettyServerConfig) this.nettyServerConfig.clone(); int listeningPort = nettyServerConfig.getListenPort() - 2; if (listeningPort < 0) { listeningPort = 0; } fastConfig.setListenPort(listeningPort); NettyRemotingServer fastRemotingServer = new NettyRemotingServer(fastConfig, this.clientHousekeepingService); // Set RemotingMetricsManager on both remoting servers if (this.brokerMetricsManager != null) { tcpRemotingServer.setRemotingMetricsManager(this.brokerMetricsManager.getRemotingMetricsManager()); fastRemotingServer.setRemotingMetricsManager(this.brokerMetricsManager.getRemotingMetricsManager()); } remotingServerMap.put(TCP_REMOTING_SERVER, tcpRemotingServer); remotingServerMap.put(FAST_REMOTING_SERVER, fastRemotingServer); } /** * Initialize resources including remoting server and thread executors. */ protected void initializeResources() { this.scheduledExecutorService = ThreadUtils.newScheduledThreadPool(1, new ThreadFactoryImpl("BrokerControllerScheduledThread", true, getBrokerIdentity())); this.sendMessageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getSendMessageThreadPoolNums(), this.brokerConfig.getSendMessageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.sendThreadPoolQueue, new ThreadFactoryImpl("SendMessageThread_", getBrokerIdentity())); this.pullMessageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getPullMessageThreadPoolNums(), this.brokerConfig.getPullMessageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.pullThreadPoolQueue, new ThreadFactoryImpl("PullMessageThread_", getBrokerIdentity())); this.litePullMessageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getLitePullMessageThreadPoolNums(), this.brokerConfig.getLitePullMessageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.litePullThreadPoolQueue, new ThreadFactoryImpl("LitePullMessageThread_", getBrokerIdentity())); this.putMessageFutureExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getPutMessageFutureThreadPoolNums(), this.brokerConfig.getPutMessageFutureThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.putThreadPoolQueue, new ThreadFactoryImpl("PutMessageThread_", getBrokerIdentity())); this.ackMessageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getAckMessageThreadPoolNums(), this.brokerConfig.getAckMessageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.ackThreadPoolQueue, new ThreadFactoryImpl("AckMessageThread_", getBrokerIdentity())); this.queryMessageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getQueryMessageThreadPoolNums(), this.brokerConfig.getQueryMessageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.queryThreadPoolQueue, new ThreadFactoryImpl("QueryMessageThread_", getBrokerIdentity())); this.adminBrokerExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getAdminBrokerThreadPoolNums(), this.brokerConfig.getAdminBrokerThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.adminBrokerThreadPoolQueue, new ThreadFactoryImpl("AdminBrokerThread_", getBrokerIdentity())); this.clientManageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getClientManageThreadPoolNums(), this.brokerConfig.getClientManageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.clientManagerThreadPoolQueue, new ThreadFactoryImpl("ClientManageThread_", getBrokerIdentity())); this.heartbeatExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getHeartbeatThreadPoolNums(), this.brokerConfig.getHeartbeatThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.heartbeatThreadPoolQueue, new ThreadFactoryImpl("HeartbeatThread_", true, getBrokerIdentity())); this.consumerManageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getConsumerManageThreadPoolNums(), this.brokerConfig.getConsumerManageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.consumerManagerThreadPoolQueue, new ThreadFactoryImpl("ConsumerManageThread_", true, getBrokerIdentity())); this.replyMessageExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getProcessReplyMessageThreadPoolNums(), this.brokerConfig.getProcessReplyMessageThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.replyThreadPoolQueue, new ThreadFactoryImpl("ProcessReplyMessageThread_", getBrokerIdentity())); this.endTransactionExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getEndTransactionThreadPoolNums(), this.brokerConfig.getEndTransactionThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.endTransactionThreadPoolQueue, new ThreadFactoryImpl("EndTransactionThread_", getBrokerIdentity())); this.loadBalanceExecutor = ThreadUtils.newThreadPoolExecutor( this.brokerConfig.getLoadBalanceProcessorThreadPoolNums(), this.brokerConfig.getLoadBalanceProcessorThreadPoolNums(), 1000 * 60, TimeUnit.MILLISECONDS, this.loadBalanceThreadPoolQueue, new ThreadFactoryImpl("LoadBalanceProcessorThread_", getBrokerIdentity())); this.syncBrokerMemberGroupExecutorService = ThreadUtils.newScheduledThreadPool(1, new ThreadFactoryImpl("BrokerControllerSyncBrokerScheduledThread", getBrokerIdentity())); this.brokerHeartbeatExecutorService = ThreadUtils.newScheduledThreadPool(1, new ThreadFactoryImpl("BrokerControllerHeartbeatScheduledThread", getBrokerIdentity())); this.topicQueueMappingCleanService = new TopicQueueMappingCleanService(this); } protected void initializeBrokerScheduledTasks() { final long initialDelay = UtilAll.computeNextMorningTimeMillis() - System.currentTimeMillis(); final long period = TimeUnit.DAYS.toMillis(1); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.getBrokerStats().record(); } catch (Throwable e) { LOG.error("BrokerController: failed to record broker stats", e); } } }, initialDelay, period, TimeUnit.MILLISECONDS); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.consumerOffsetManager.persist(); } catch (Throwable e) { LOG.error( "BrokerController: failed to persist config file of consumerOffset", e); } } }, 1000 * 10, this.brokerConfig.getFlushConsumerOffsetInterval(), TimeUnit.MILLISECONDS); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.consumerFilterManager.persist(); BrokerController.this.consumerOrderInfoManager.persist(); } catch (Throwable e) { LOG.error( "BrokerController: failed to persist config file of consumerFilter or consumerOrderInfo", e); } } }, 1000 * 10, 1000 * 10, TimeUnit.MILLISECONDS); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.protectBroker(); } catch (Throwable e) { LOG.error("BrokerController: failed to protectBroker", e); } } }, 3, 3, TimeUnit.MINUTES); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.printWaterMark(); } catch (Throwable e) { LOG.error("BrokerController: failed to print broker watermark", e); } } }, 10, 1, TimeUnit.SECONDS); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.messageStore.getTimerMessageStore().getTimerMetrics() .cleanMetrics(BrokerController.this.topicConfigManager.getTopicConfigTable().keySet()); } catch (Throwable e) { LOG.error("BrokerController: failed to clean unused timer metrics.", e); } } }, 3, 3, TimeUnit.MINUTES); this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { LOG.info("Dispatch task fall behind commit log {}bytes", BrokerController.this.getMessageStore().dispatchBehindBytes()); } catch (Throwable e) { LOG.error("Failed to print dispatchBehindBytes", e); } } }, 1000 * 10, 1000 * 60, TimeUnit.MILLISECONDS); if (!messageStoreConfig.isEnableDLegerCommitLog() && !messageStoreConfig.isDuplicationEnable() && !brokerConfig.isEnableControllerMode()) { if (BrokerRole.SLAVE == this.messageStoreConfig.getBrokerRole()) { if (this.messageStoreConfig.getHaMasterAddress() != null && this.messageStoreConfig.getHaMasterAddress().length() >= HA_ADDRESS_MIN_LENGTH) { this.messageStore.updateHaMasterAddress(this.messageStoreConfig.getHaMasterAddress()); this.updateMasterHAServerAddrPeriodically = false; } else { this.updateMasterHAServerAddrPeriodically = true; } this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { if (System.currentTimeMillis() - lastSyncTimeMs > 60 * 1000) { BrokerController.this.getSlaveSynchronize().syncAll(); lastSyncTimeMs = System.currentTimeMillis(); } //timer checkpoint, latency-sensitive, so sync it more frequently if (messageStoreConfig.isTimerWheelEnable()) { BrokerController.this.getSlaveSynchronize().syncTimerCheckPoint(); } } catch (Throwable e) { LOG.error("Failed to sync all config for slave.", e); } } }, 1000 * 10, 3 * 1000, TimeUnit.MILLISECONDS); } else { this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.printMasterAndSlaveDiff(); } catch (Throwable e) { LOG.error("Failed to print diff of master and slave.", e); } } }, 1000 * 10, 1000 * 60, TimeUnit.MILLISECONDS); } } if (this.brokerConfig.isEnableControllerMode()) { this.updateMasterHAServerAddrPeriodically = true; } } protected void initializeScheduledTasks() { initializeBrokerScheduledTasks(); if (this.brokerConfig.getNamesrvAddr() != null) { this.updateNamesrvAddr(); LOG.info("Set user specified name server address: {}", this.brokerConfig.getNamesrvAddr()); // also auto update namesrv if specify this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.updateNamesrvAddr(); } catch (Throwable e) { LOG.error("Failed to update nameServer address list", e); } } }, 1000 * 10, this.brokerConfig.getUpdateNameServerAddrPeriod(), TimeUnit.MILLISECONDS); } else if (this.brokerConfig.isFetchNamesrvAddrByAddressServer()) { this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.brokerOuterAPI.fetchNameServerAddr(); } catch (Throwable e) { LOG.error("Failed to fetch nameServer address", e); } } }, 1000 * 10, this.brokerConfig.getFetchNamesrvAddrInterval(), TimeUnit.MILLISECONDS); } } private void updateNamesrvAddr() { if (this.brokerConfig.isFetchNameSrvAddrByDnsLookup()) { this.brokerOuterAPI.updateNameServerAddressListByDnsLookup(this.brokerConfig.getNamesrvAddr()); } else { this.brokerOuterAPI.updateNameServerAddressList(this.brokerConfig.getNamesrvAddr()); } } public boolean initializeMetadata() { boolean result = true; if (null != configStorage) { result = configStorage.start(); } result = result && this.topicConfigManager.load(); result = result && this.topicQueueMappingManager.load(); result = result && this.consumerOffsetManager.load(); result = result && this.subscriptionGroupManager.load(); result = result && this.consumerFilterManager.load(); result = result && this.consumerOrderInfoManager.load(); return result; } public boolean initializeMessageStore() { boolean result = true; try { DefaultMessageStore defaultMessageStore; if (this.messageStoreConfig.isEnableRocksDBStore()) { defaultMessageStore = new RocksDBMessageStore(this.messageStoreConfig, this.brokerStatsManager, this.messageArrivingListener, this.brokerConfig, topicConfigManager.getTopicConfigTable()); } else { defaultMessageStore = new DefaultMessageStore(this.messageStoreConfig, this.brokerStatsManager, this.messageArrivingListener, this.brokerConfig, topicConfigManager.getTopicConfigTable()); } if (messageStoreConfig.isEnableDLegerCommitLog()) { DLedgerRoleChangeHandler roleChangeHandler = new DLedgerRoleChangeHandler(this, defaultMessageStore); ((DLedgerCommitLog) defaultMessageStore.getCommitLog()) .getdLedgerServer().getDLedgerLeaderElector().addRoleChangeHandler(roleChangeHandler); } this.brokerStats = new BrokerStats(defaultMessageStore); // Load store plugin MessageStorePluginContext context = new MessageStorePluginContext( messageStoreConfig, brokerStatsManager, messageArrivingListener, brokerConfig, configuration); this.messageStore = MessageStoreFactory.build(context, defaultMessageStore); this.messageStore.getDispatcherList().addFirst(new CommitLogDispatcherCalcBitMap(this.brokerConfig, this.consumerFilterManager)); if (messageStoreConfig.isTimerWheelEnable()) { this.timerCheckpoint = new TimerCheckpoint(BrokerPathConfigHelper.getTimerCheckPath(messageStoreConfig.getStorePathRootDir())); TimerMetrics timerMetrics = new TimerMetrics(BrokerPathConfigHelper.getTimerMetricsPath(messageStoreConfig.getStorePathRootDir())); this.timerMessageStore = new TimerMessageStore(messageStore, messageStoreConfig, timerCheckpoint, timerMetrics, brokerStatsManager); this.timerMessageStore.registerEscapeBridgeHook(msg -> escapeBridge.putMessage(msg)); this.messageStore.setTimerMessageStore(this.timerMessageStore); } } catch (Exception e) { result = false; LOG.error("BrokerController#initialize: unexpected error occurs", e); } return result; } public boolean initialize() throws CloneNotSupportedException { boolean result = this.initializeMetadata(); if (!result) { return false; } result = this.initializeMessageStore(); if (!result) { return false; } return this.recoverAndInitService(); } public boolean recoverAndInitService() throws CloneNotSupportedException { boolean result = true; if (this.brokerConfig.isEnableControllerMode()) { this.replicasManager = new ReplicasManager(this); this.replicasManager.setFenced(true); } if (messageStore != null) { registerMessageStoreHook(); result = this.messageStore.load(); } if (messageStoreConfig.isTimerWheelEnable()) { result = result && this.timerMessageStore.load(); } //scheduleMessageService load after messageStore load success result = result && this.scheduleMessageService.load(); for (BrokerAttachedPlugin brokerAttachedPlugin : brokerAttachedPlugins) { if (brokerAttachedPlugin != null) { result = result && brokerAttachedPlugin.load(); } } this.brokerMetricsManager = new BrokerMetricsManager(this); if (result) { initializeRemotingServer(); initializeResources(); registerProcessor(); initializeScheduledTasks(); initialTransaction(); initialRpcHooks(); initialRequestPipeline(); if (TlsSystemConfig.tlsMode != TlsMode.DISABLED) { // Register a listener to reload SslContext try { fileWatchService = new FileWatchService( new String[] { TlsSystemConfig.tlsServerCertPath, TlsSystemConfig.tlsServerKeyPath, TlsSystemConfig.tlsServerTrustCertPath }, new FileWatchService.Listener() { boolean certChanged, keyChanged = false; @Override public void onChanged(String path) { if (path.equals(TlsSystemConfig.tlsServerTrustCertPath)) { LOG.info("The trust certificate changed, reload the ssl context"); reloadServerSslContext(); } if (path.equals(TlsSystemConfig.tlsServerCertPath)) { certChanged = true; } if (path.equals(TlsSystemConfig.tlsServerKeyPath)) { keyChanged = true; } if (certChanged && keyChanged) { LOG.info("The certificate and private key changed, reload the ssl context"); certChanged = keyChanged = false; reloadServerSslContext(); } } private void reloadServerSslContext() { for (Map.Entry<String, RemotingServer> entry : remotingServerMap.entrySet()) { RemotingServer remotingServer = entry.getValue(); if (remotingServer instanceof NettyRemotingServer) { ((NettyRemotingServer) remotingServer).loadSslContext(); } } } }); } catch (Exception e) { result = false; LOG.warn("FileWatchService created error, can't load the certificate dynamically"); } } } return result; } public void registerMessageStoreHook() { List<PutMessageHook> putMessageHookList = messageStore.getPutMessageHookList(); putMessageHookList.add(new PutMessageHook() { @Override public String hookName() { return "checkBeforePutMessage"; } @Override public PutMessageResult executeBeforePutMessage(MessageExt msg) { return HookUtils.checkBeforePutMessage(BrokerController.this, msg); } }); putMessageHookList.add(new PutMessageHook() { @Override public String hookName() { return "innerBatchChecker"; } @Override public PutMessageResult executeBeforePutMessage(MessageExt msg) { if (msg instanceof MessageExtBrokerInner) { return HookUtils.checkInnerBatch(BrokerController.this, msg); } return null; } }); putMessageHookList.add(new PutMessageHook() { @Override public String hookName() { return "handleScheduleMessage"; } @Override public PutMessageResult executeBeforePutMessage(MessageExt msg) { if (msg instanceof MessageExtBrokerInner) { return HookUtils.handleScheduleMessage(BrokerController.this, (MessageExtBrokerInner) msg); } return null; } }); SendMessageBackHook sendMessageBackHook = new SendMessageBackHook() { @Override public boolean executeSendMessageBack(List<MessageExt> msgList, String brokerName, String brokerAddr) { return HookUtils.sendMessageBack(BrokerController.this, msgList, brokerName, brokerAddr); } }; if (messageStore != null) { messageStore.setSendMessageBackHook(sendMessageBackHook); } } private void initialTransaction() { this.transactionalMessageService = ServiceProvider.loadClass(TransactionalMessageService.class); if (null == this.transactionalMessageService) { this.transactionalMessageService = new TransactionalMessageServiceImpl( new TransactionalMessageBridge(this, this.getMessageStore())); LOG.warn("Load default transaction message hook service: {}", TransactionalMessageServiceImpl.class.getSimpleName()); } this.transactionalMessageCheckListener = ServiceProvider.loadClass( AbstractTransactionalMessageCheckListener.class); if (null == this.transactionalMessageCheckListener) { this.transactionalMessageCheckListener = new DefaultTransactionalMessageCheckListener(); LOG.warn("Load default discard message hook service: {}", DefaultTransactionalMessageCheckListener.class.getSimpleName()); } this.transactionalMessageCheckListener.setBrokerController(this); this.transactionalMessageCheckService = new TransactionalMessageCheckService(this); this.transactionMetricsFlushService = new TransactionMetricsFlushService(this); this.transactionMetricsFlushService.start(); } private void initialRpcHooks() { List<RPCHook> rpcHooks = ServiceProvider.load(RPCHook.class); if (rpcHooks == null || rpcHooks.isEmpty()) { return; } for (RPCHook rpcHook : rpcHooks) { this.registerServerRPCHook(rpcHook); } } private void initialRequestPipeline() { if (this.authConfig == null) { return; } RequestPipeline pipeline = (ctx, request) -> { }; // add pipeline // the last pipe add will execute at the first try { pipeline = pipeline.pipe(new AuthorizationPipeline(authConfig)) .pipe(new AuthenticationPipeline(authConfig)); this.setRequestPipeline(pipeline); } catch (Exception e) { throw new RuntimeException(e); } } public void registerProcessor() { RemotingServer remotingServer = remotingServerMap.get(TCP_REMOTING_SERVER); RemotingServer fastRemotingServer = remotingServerMap.get(FAST_REMOTING_SERVER); /* * SendMessageProcessor */ sendMessageProcessor.registerSendMessageHook(sendMessageHookList); sendMessageProcessor.registerConsumeMessageHook(consumeMessageHookList); remotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendMessageProcessor, this.sendMessageExecutor); remotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendMessageProcessor, this.sendMessageExecutor); remotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendMessageProcessor, this.sendMessageExecutor); remotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendMessageProcessor, this.sendMessageExecutor); remotingServer.registerProcessor(RequestCode.RECALL_MESSAGE, recallMessageProcessor, this.sendMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.SEND_MESSAGE, sendMessageProcessor, this.sendMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.SEND_MESSAGE_V2, sendMessageProcessor, this.sendMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.SEND_BATCH_MESSAGE, sendMessageProcessor, this.sendMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.CONSUMER_SEND_MSG_BACK, sendMessageProcessor, this.sendMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.RECALL_MESSAGE, recallMessageProcessor, this.sendMessageExecutor); /** * PullMessageProcessor */ remotingServer.registerProcessor(RequestCode.PULL_MESSAGE, this.pullMessageProcessor, this.pullMessageExecutor); remotingServer.registerProcessor(RequestCode.LITE_PULL_MESSAGE, this.pullMessageProcessor, this.litePullMessageExecutor); this.pullMessageProcessor.registerConsumeMessageHook(consumeMessageHookList); /** * PeekMessageProcessor */ remotingServer.registerProcessor(RequestCode.PEEK_MESSAGE, this.peekMessageProcessor, this.pullMessageExecutor); /** * PopMessageProcessor */ remotingServer.registerProcessor(RequestCode.POP_MESSAGE, this.popMessageProcessor, this.pullMessageExecutor); /** * AckMessageProcessor */ remotingServer.registerProcessor(RequestCode.ACK_MESSAGE, this.ackMessageProcessor, this.ackMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.ACK_MESSAGE, this.ackMessageProcessor, this.ackMessageExecutor); remotingServer.registerProcessor(RequestCode.BATCH_ACK_MESSAGE, this.ackMessageProcessor, this.ackMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.BATCH_ACK_MESSAGE, this.ackMessageProcessor, this.ackMessageExecutor); /** * ChangeInvisibleTimeProcessor */ remotingServer.registerProcessor(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, this.changeInvisibleTimeProcessor, this.ackMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, this.changeInvisibleTimeProcessor, this.ackMessageExecutor); /** * notificationProcessor */ remotingServer.registerProcessor(RequestCode.NOTIFICATION, this.notificationProcessor, this.pullMessageExecutor); /** * pollingInfoProcessor */ remotingServer.registerProcessor(RequestCode.POLLING_INFO, this.pollingInfoProcessor, this.pullMessageExecutor); /** * ReplyMessageProcessor */ replyMessageProcessor.registerSendMessageHook(sendMessageHookList); remotingServer.registerProcessor(RequestCode.SEND_REPLY_MESSAGE, replyMessageProcessor, replyMessageExecutor); remotingServer.registerProcessor(RequestCode.SEND_REPLY_MESSAGE_V2, replyMessageProcessor, replyMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.SEND_REPLY_MESSAGE, replyMessageProcessor, replyMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.SEND_REPLY_MESSAGE_V2, replyMessageProcessor, replyMessageExecutor); /** * QueryMessageProcessor */ NettyRequestProcessor queryProcessor = new QueryMessageProcessor(this); remotingServer.registerProcessor(RequestCode.QUERY_MESSAGE, queryProcessor, this.queryMessageExecutor); remotingServer.registerProcessor(RequestCode.VIEW_MESSAGE_BY_ID, queryProcessor, this.queryMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.QUERY_MESSAGE, queryProcessor, this.queryMessageExecutor); fastRemotingServer.registerProcessor(RequestCode.VIEW_MESSAGE_BY_ID, queryProcessor, this.queryMessageExecutor); /** * ClientManageProcessor */ remotingServer.registerProcessor(RequestCode.HEART_BEAT, clientManageProcessor, this.heartbeatExecutor); remotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientManageProcessor, this.clientManageExecutor); remotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientManageProcessor, this.clientManageExecutor); fastRemotingServer.registerProcessor(RequestCode.HEART_BEAT, clientManageProcessor, this.heartbeatExecutor); fastRemotingServer.registerProcessor(RequestCode.UNREGISTER_CLIENT, clientManageProcessor, this.clientManageExecutor); fastRemotingServer.registerProcessor(RequestCode.CHECK_CLIENT_CONFIG, clientManageProcessor, this.clientManageExecutor); /** * ConsumerManageProcessor */ ConsumerManageProcessor consumerManageProcessor = new ConsumerManageProcessor(this); remotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, this.consumerManageExecutor); remotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor); remotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor); fastRemotingServer.registerProcessor(RequestCode.GET_CONSUMER_LIST_BY_GROUP, consumerManageProcessor, this.consumerManageExecutor); fastRemotingServer.registerProcessor(RequestCode.UPDATE_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor); fastRemotingServer.registerProcessor(RequestCode.QUERY_CONSUMER_OFFSET, consumerManageProcessor, this.consumerManageExecutor); /** * QueryAssignmentProcessor */ remotingServer.registerProcessor(RequestCode.QUERY_ASSIGNMENT, queryAssignmentProcessor, loadBalanceExecutor); fastRemotingServer.registerProcessor(RequestCode.QUERY_ASSIGNMENT, queryAssignmentProcessor, loadBalanceExecutor); remotingServer.registerProcessor(RequestCode.SET_MESSAGE_REQUEST_MODE, queryAssignmentProcessor, loadBalanceExecutor); fastRemotingServer.registerProcessor(RequestCode.SET_MESSAGE_REQUEST_MODE, queryAssignmentProcessor, loadBalanceExecutor); /** * EndTransactionProcessor */ remotingServer.registerProcessor(RequestCode.END_TRANSACTION, endTransactionProcessor, this.endTransactionExecutor); fastRemotingServer.registerProcessor(RequestCode.END_TRANSACTION, endTransactionProcessor, this.endTransactionExecutor); /* * Default */ AdminBrokerProcessor adminProcessor = new AdminBrokerProcessor(this); remotingServer.registerDefaultProcessor(adminProcessor, this.adminBrokerExecutor); fastRemotingServer.registerDefaultProcessor(adminProcessor, this.adminBrokerExecutor); /* * Initialize the mapping of request codes to request headers. */ RequestHeaderRegistry.getInstance().initialize(); } public BrokerStats getBrokerStats() { return brokerStats; } public void setBrokerStats(BrokerStats brokerStats) { this.brokerStats = brokerStats; } public void protectBroker() { if (this.brokerConfig.isDisableConsumeIfConsumerReadSlowly()) { for (Map.Entry<String, MomentStatsItem> next : this.brokerStatsManager.getMomentStatsItemSetFallSize().getStatsItemTable().entrySet()) { final long fallBehindBytes = next.getValue().getValue().get(); if (fallBehindBytes > this.brokerConfig.getConsumerFallbehindThreshold()) { final String[] split = next.getValue().getStatsKey().split("@"); final String group = split[2]; LOG_PROTECTION.info("[PROTECT_BROKER] the consumer[{}] consume slowly, {} bytes, disable it", group, fallBehindBytes); this.subscriptionGroupManager.disableConsume(group); } } } } public long headSlowTimeMills(BlockingQueue<Runnable> q) { long slowTimeMills = 0; final Runnable peek = q.peek(); if (peek != null) { RequestTask rt = BrokerFastFailure.castRunnable(peek); slowTimeMills = rt == null ? 0 : this.messageStore.now() - rt.getCreateTimestamp(); } if (slowTimeMills < 0) { slowTimeMills = 0; } return slowTimeMills; } public long headSlowTimeMills4SendThreadPoolQueue() { return this.headSlowTimeMills(this.sendThreadPoolQueue); } public long headSlowTimeMills4PullThreadPoolQueue() { return this.headSlowTimeMills(this.pullThreadPoolQueue); } public long headSlowTimeMills4LitePullThreadPoolQueue() { return this.headSlowTimeMills(this.litePullThreadPoolQueue); } public long headSlowTimeMills4QueryThreadPoolQueue() { return this.headSlowTimeMills(this.queryThreadPoolQueue); } public long headSlowTimeMills4AckThreadPoolQueue() { return this.headSlowTimeMills(this.ackThreadPoolQueue); } public long headSlowTimeMills4EndTransactionThreadPoolQueue() { return this.headSlowTimeMills(this.endTransactionThreadPoolQueue); } public long headSlowTimeMills4ClientManagerThreadPoolQueue() { return this.headSlowTimeMills(this.clientManagerThreadPoolQueue); } public long headSlowTimeMills4HeartbeatThreadPoolQueue() { return this.headSlowTimeMills(this.heartbeatThreadPoolQueue); } public long headSlowTimeMills4AdminBrokerThreadPoolQueue() { return this.headSlowTimeMills(this.adminBrokerThreadPoolQueue); } public void printWaterMark() { logWaterMarkQueueInfo("Send", this.sendThreadPoolQueue, this::headSlowTimeMills4SendThreadPoolQueue); logWaterMarkQueueInfo("Pull", this.pullThreadPoolQueue, this::headSlowTimeMills4PullThreadPoolQueue); logWaterMarkQueueInfo("Query", this.queryThreadPoolQueue, this::headSlowTimeMills4QueryThreadPoolQueue); logWaterMarkQueueInfo("Lite Pull", this.litePullThreadPoolQueue, this::headSlowTimeMills4LitePullThreadPoolQueue); logWaterMarkQueueInfo("Transaction", this.endTransactionThreadPoolQueue, this::headSlowTimeMills4EndTransactionThreadPoolQueue); logWaterMarkQueueInfo("ClientManager", this.clientManagerThreadPoolQueue, this::headSlowTimeMills4ClientManagerThreadPoolQueue); logWaterMarkQueueInfo("Heartbeat", this.heartbeatThreadPoolQueue, this::headSlowTimeMills4HeartbeatThreadPoolQueue); logWaterMarkQueueInfo("Ack", this.ackThreadPoolQueue, this::headSlowTimeMills4AckThreadPoolQueue); logWaterMarkQueueInfo("Admin", this.adminBrokerThreadPoolQueue, this::headSlowTimeMills4AdminBrokerThreadPoolQueue); } private void logWaterMarkQueueInfo(String queueName, BlockingQueue<?> queue, Supplier<Long> slowTimeSupplier) { LOG_WATER_MARK.info("[WATERMARK] {} Queue Size: {} SlowTimeMills: {}", queueName, queue.size(), slowTimeSupplier.get()); } public MessageStore getMessageStore() { return messageStore; } public void setMessageStore(MessageStore messageStore) { this.messageStore = messageStore; } protected void printMasterAndSlaveDiff() { if (messageStore.getHaService() != null && messageStore.getHaService().getConnectionCount().get() > 0) { long diff = this.messageStore.slaveFallBehindMuch(); LOG.info("CommitLog: slave fall behind master {}bytes", diff); } } public Broker2Client getBroker2Client() { return broker2Client; } public ConsumerManager getConsumerManager() { return consumerManager; } public ConsumerFilterManager getConsumerFilterManager() { return consumerFilterManager; } public ConsumerOrderInfoManager getConsumerOrderInfoManager() { return consumerOrderInfoManager; } public PopInflightMessageCounter getPopInflightMessageCounter() { return popInflightMessageCounter; } public PopConsumerService getPopConsumerService() { return popConsumerService; } public ConsumerOffsetManager getConsumerOffsetManager() { return consumerOffsetManager; } public void setConsumerOffsetManager(ConsumerOffsetManager consumerOffsetManager) { this.consumerOffsetManager = consumerOffsetManager; } public BroadcastOffsetManager getBroadcastOffsetManager() { return broadcastOffsetManager; } public MessageStoreConfig getMessageStoreConfig() { return messageStoreConfig; } public ProducerManager getProducerManager() { return producerManager; } public PullMessageProcessor getPullMessageProcessor() { return pullMessageProcessor; } public PullRequestHoldService getPullRequestHoldService() { return pullRequestHoldService; } public void setSubscriptionGroupManager(SubscriptionGroupManager subscriptionGroupManager) { this.subscriptionGroupManager = subscriptionGroupManager; } public SubscriptionGroupManager getSubscriptionGroupManager() { return subscriptionGroupManager; } public PopMessageProcessor getPopMessageProcessor() { return popMessageProcessor; } public NotificationProcessor getNotificationProcessor() { return notificationProcessor; } public TimerMessageStore getTimerMessageStore() { return timerMessageStore; } public void setTimerMessageStore(TimerMessageStore timerMessageStore) { this.timerMessageStore = timerMessageStore; } public AckMessageProcessor getAckMessageProcessor() { return ackMessageProcessor; } public ChangeInvisibleTimeProcessor getChangeInvisibleTimeProcessor() { return changeInvisibleTimeProcessor; } protected void shutdownBasicService() { shutdown = true; this.unregisterBrokerAll(); if (this.shutdownHook != null) { this.shutdownHook.beforeShutdown(this); } for (Map.Entry<String, RemotingServer> entry : remotingServerMap.entrySet()) { RemotingServer remotingServer = entry.getValue(); if (remotingServer != null) { remotingServer.shutdown(); } } if (this.brokerMetricsManager != null) { this.brokerMetricsManager.shutdown(); } if (this.brokerStatsManager != null) { this.brokerStatsManager.shutdown(); } if (this.clientHousekeepingService != null) { this.clientHousekeepingService.shutdown(); } if (this.pullRequestHoldService != null) { this.pullRequestHoldService.shutdown(); } if (this.popConsumerService != null) { this.popConsumerService.shutdown(); } if (this.popMessageProcessor.getPopLongPollingService() != null) { this.popMessageProcessor.getPopLongPollingService().shutdown(); } if (this.popMessageProcessor.getQueueLockManager() != null) { this.popMessageProcessor.getQueueLockManager().shutdown(); } if (this.popMessageProcessor.getPopBufferMergeService() != null) { this.popMessageProcessor.getPopBufferMergeService().shutdown(); } if (this.ackMessageProcessor.getPopReviveServices() != null) { this.ackMessageProcessor.shutdownPopReviveService(); } if (this.transactionalMessageService != null) { this.transactionalMessageService.close(); } if (this.transactionalMessageCheckListener != null) { this.transactionalMessageCheckListener.shutdown(); } if (transactionalMessageCheckService != null) { this.transactionalMessageCheckService.shutdown(); } if (transactionMetricsFlushService != null) { this.transactionMetricsFlushService.shutdown(); } if (this.notificationProcessor != null) { this.notificationProcessor.getPopLongPollingService().shutdown(); } if (this.consumerIdsChangeListener != null) { this.consumerIdsChangeListener.shutdown(); } if (this.topicQueueMappingCleanService != null) { this.topicQueueMappingCleanService.shutdown(); } //it is better to make sure the timerMessageStore shutdown firstly if (this.timerMessageStore != null) { this.timerMessageStore.shutdown(); } if (this.fileWatchService != null) { this.fileWatchService.shutdown(); } if (this.broadcastOffsetManager != null) { this.broadcastOffsetManager.shutdown(); } if (this.replicasManager != null) { this.replicasManager.shutdown(); } shutdownScheduledExecutorService(this.scheduledExecutorService); if (this.sendMessageExecutor != null) { this.sendMessageExecutor.shutdown(); } if (this.litePullMessageExecutor != null) { this.litePullMessageExecutor.shutdown(); } if (this.pullMessageExecutor != null) { this.pullMessageExecutor.shutdown(); } if (this.replyMessageExecutor != null) { this.replyMessageExecutor.shutdown(); } if (this.putMessageFutureExecutor != null) { this.putMessageFutureExecutor.shutdown(); } if (this.ackMessageExecutor != null) { this.ackMessageExecutor.shutdown(); } if (this.adminBrokerExecutor != null) { this.adminBrokerExecutor.shutdown(); } if (this.brokerFastFailure != null) { this.brokerFastFailure.shutdown(); } if (this.consumerFilterManager != null) { this.consumerFilterManager.persist(); } if (this.scheduleMessageService != null) { this.scheduleMessageService.persist(); this.scheduleMessageService.shutdown(); } if (this.clientManageExecutor != null) { this.clientManageExecutor.shutdown(); } if (this.queryMessageExecutor != null) { this.queryMessageExecutor.shutdown(); } if (this.heartbeatExecutor != null) { this.heartbeatExecutor.shutdown(); } if (this.consumerManageExecutor != null) { this.consumerManageExecutor.shutdown(); } if (this.transactionalMessageCheckService != null) { this.transactionalMessageCheckService.shutdown(false); } if (this.loadBalanceExecutor != null) { this.loadBalanceExecutor.shutdown(); } if (this.endTransactionExecutor != null) { this.endTransactionExecutor.shutdown(); } if (this.transactionMetricsFlushService != null) { this.transactionMetricsFlushService.shutdown(); } if (this.escapeBridge != null) { this.escapeBridge.shutdown(); } if (this.topicRouteInfoManager != null) { this.topicRouteInfoManager.shutdown(); } if (this.brokerPreOnlineService != null && !this.brokerPreOnlineService.isStopped()) { this.brokerPreOnlineService.shutdown(); } if (this.coldDataPullRequestHoldService != null) { this.coldDataPullRequestHoldService.shutdown(); } if (this.coldDataCgCtrService != null) { this.coldDataCgCtrService.shutdown(); } shutdownScheduledExecutorService(this.syncBrokerMemberGroupExecutorService); shutdownScheduledExecutorService(this.brokerHeartbeatExecutorService); if (this.topicConfigManager != null) { this.topicConfigManager.persist(); this.topicConfigManager.stop(); } if (this.subscriptionGroupManager != null) { this.subscriptionGroupManager.persist(); this.subscriptionGroupManager.stop(); } if (this.consumerOffsetManager != null) { this.consumerOffsetManager.persist(); this.consumerOffsetManager.stop(); } if (this.consumerOrderInfoManager != null) { this.consumerOrderInfoManager.persist(); this.consumerOrderInfoManager.shutdown(); } if (this.configStorage != null) { this.configStorage.shutdown(); } if (this.authenticationMetadataManager != null) { this.authenticationMetadataManager.shutdown(); } if (this.authorizationMetadataManager != null) { this.authorizationMetadataManager.shutdown(); } for (BrokerAttachedPlugin brokerAttachedPlugin : brokerAttachedPlugins) { if (brokerAttachedPlugin != null) { brokerAttachedPlugin.shutdown(); } } if (this.messageStore != null) { this.messageStore.shutdown(); } } public void shutdown() { shutdownBasicService(); for (ScheduledFuture<?> scheduledFuture : scheduledFutures) { scheduledFuture.cancel(true); } if (this.brokerOuterAPI != null) { this.brokerOuterAPI.shutdown(); } } protected void shutdownScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { if (scheduledExecutorService == null) { return; } scheduledExecutorService.shutdown(); try { scheduledExecutorService.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { BrokerController.LOG.warn("shutdown ScheduledExecutorService was Interrupted! ", ignore); Thread.currentThread().interrupt(); } } protected void unregisterBrokerAll() { this.brokerOuterAPI.unregisterBrokerAll( this.brokerConfig.getBrokerClusterName(), this.getBrokerAddr(), this.brokerConfig.getBrokerName(), this.brokerConfig.getBrokerId()); } public String getBrokerAddr() { return this.brokerConfig.getBrokerIP1() + ":" + this.nettyServerConfig.getListenPort(); } protected void startBasicService() throws Exception { if (this.messageStore != null) { this.messageStore.start(); } if (this.timerMessageStore != null) { this.timerMessageStore.start(); } if (this.replicasManager != null) { this.replicasManager.start(); } if (remotingServerStartLatch != null) { remotingServerStartLatch.await(); } for (Map.Entry<String, RemotingServer> entry : remotingServerMap.entrySet()) { RemotingServer remotingServer = entry.getValue(); if (remotingServer != null) { remotingServer.start(); if (TCP_REMOTING_SERVER.equals(entry.getKey())) { // In test scenarios where it is up to OS to pick up an available port, set the listening port back to config if (null != nettyServerConfig && 0 == nettyServerConfig.getListenPort()) { nettyServerConfig.setListenPort(remotingServer.localListenPort()); } } } } this.storeHost = new InetSocketAddress(this.getBrokerConfig().getBrokerIP1(), this.getNettyServerConfig().getListenPort()); for (BrokerAttachedPlugin brokerAttachedPlugin : brokerAttachedPlugins) { if (brokerAttachedPlugin != null) { brokerAttachedPlugin.start(); } } if (this.popMessageProcessor != null) { this.popMessageProcessor.getPopLongPollingService().start(); if (brokerConfig.isPopConsumerFSServiceInit()) { this.popMessageProcessor.getPopBufferMergeService().start(); } this.popMessageProcessor.getQueueLockManager().start(); } if (this.ackMessageProcessor != null) { if (brokerConfig.isPopConsumerFSServiceInit()) { this.ackMessageProcessor.startPopReviveService(); } } if (this.notificationProcessor != null) { this.notificationProcessor.getPopLongPollingService().start(); } if (this.popConsumerService != null) { this.popConsumerService.start(); } if (this.topicQueueMappingCleanService != null) { this.topicQueueMappingCleanService.start(); } if (this.fileWatchService != null) { this.fileWatchService.start(); } if (this.pullRequestHoldService != null) { this.pullRequestHoldService.start(); } if (this.clientHousekeepingService != null) { this.clientHousekeepingService.start(); } if (this.brokerStatsManager != null) { this.brokerStatsManager.start(); } if (this.brokerFastFailure != null) { this.brokerFastFailure.start(); } if (this.broadcastOffsetManager != null) { this.broadcastOffsetManager.start(); } if (this.escapeBridge != null) { this.escapeBridge.start(); } if (this.topicRouteInfoManager != null) { this.topicRouteInfoManager.start(); } if (this.brokerPreOnlineService != null) { this.brokerPreOnlineService.start(); } if (this.coldDataPullRequestHoldService != null) { this.coldDataPullRequestHoldService.start(); } if (this.coldDataCgCtrService != null) { this.coldDataCgCtrService.start(); } } public void start() throws Exception { this.shouldStartTime = System.currentTimeMillis() + messageStoreConfig.getDisappearTimeAfterStart(); if (messageStoreConfig.getTotalReplicas() > 1 && this.brokerConfig.isEnableSlaveActingMaster()) { isIsolated = true; } if (this.brokerOuterAPI != null) { this.brokerOuterAPI.start(); } startBasicService(); if (!isIsolated && !this.messageStoreConfig.isEnableDLegerCommitLog() && !this.messageStoreConfig.isDuplicationEnable()) { changeSpecialServiceStatus(this.brokerConfig.getBrokerId() == MixAll.MASTER_ID); this.registerBrokerAll(true, false, true); } scheduledFutures.add(this.scheduledExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { try { if (System.currentTimeMillis() < shouldStartTime) { BrokerController.LOG.info("Register to namesrv after {}", shouldStartTime); return; } if (isIsolated) { BrokerController.LOG.info("Skip register for broker is isolated"); return; } BrokerController.this.registerBrokerAll(true, false, brokerConfig.isForceRegister()); } catch (Throwable e) { BrokerController.LOG.error("registerBrokerAll Exception", e); } } }, 1000 * 10, Math.max(10000, Math.min(brokerConfig.getRegisterNameServerPeriod(), 60000)), TimeUnit.MILLISECONDS)); if (this.brokerConfig.isEnableSlaveActingMaster()) { scheduleSendHeartbeat(); scheduledFutures.add(this.syncBrokerMemberGroupExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { try { BrokerController.this.syncBrokerMemberGroup(); } catch (Throwable e) { BrokerController.LOG.error("sync BrokerMemberGroup error. ", e); } } }, 1000, this.brokerConfig.getSyncBrokerMemberGroupPeriod(), TimeUnit.MILLISECONDS)); } if (this.brokerConfig.isEnableControllerMode()) { scheduleSendHeartbeat(); } if (brokerConfig.isSkipPreOnline()) { startServiceWithoutCondition(); } this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { BrokerController.this.brokerOuterAPI.refreshMetadata(); } catch (Exception e) { LOG.error("ScheduledTask refresh metadata exception", e); } } }, 10, 5, TimeUnit.SECONDS); } protected void scheduleSendHeartbeat() { scheduledFutures.add(this.brokerHeartbeatExecutorService.scheduleAtFixedRate(new AbstractBrokerRunnable(this.getBrokerIdentity()) { @Override public void run0() { if (isIsolated) { return; } try { BrokerController.this.sendHeartbeat(); } catch (Exception e) { BrokerController.LOG.error("sendHeartbeat Exception", e); } } }, 1000, brokerConfig.getBrokerHeartbeatInterval(), TimeUnit.MILLISECONDS)); } public synchronized void registerSingleTopicAll(final TopicConfig topicConfig) { TopicConfig tmpTopic = topicConfig; if (!PermName.isWriteable(this.getBrokerConfig().getBrokerPermission()) || !PermName.isReadable(this.getBrokerConfig().getBrokerPermission())) { // Copy the topic config and modify the perm tmpTopic = new TopicConfig(topicConfig); tmpTopic.setPerm(topicConfig.getPerm() & this.brokerConfig.getBrokerPermission()); } this.brokerOuterAPI.registerSingleTopicAll(this.brokerConfig.getBrokerName(), tmpTopic, 3000); } public synchronized void registerIncrementBrokerData(TopicConfig topicConfig, DataVersion dataVersion) { this.registerIncrementBrokerData(Collections.singletonList(topicConfig), dataVersion); } public synchronized void registerIncrementBrokerData(List<TopicConfig> topicConfigList, DataVersion dataVersion) { if (topicConfigList == null || topicConfigList.isEmpty()) { return; } TopicConfigAndMappingSerializeWrapper topicConfigSerializeWrapper = new TopicConfigAndMappingSerializeWrapper(); topicConfigSerializeWrapper.setDataVersion(dataVersion); ConcurrentMap<String, TopicConfig> topicConfigTable = topicConfigList.stream() .map(topicConfig -> { TopicConfig registerTopicConfig; if (!PermName.isWriteable(this.getBrokerConfig().getBrokerPermission()) || !PermName.isReadable(this.getBrokerConfig().getBrokerPermission())) { registerTopicConfig = new TopicConfig(topicConfig.getTopicName(), topicConfig.getReadQueueNums(), topicConfig.getWriteQueueNums(), topicConfig.getPerm() & this.brokerConfig.getBrokerPermission(), topicConfig.getTopicSysFlag()); } else { registerTopicConfig = new TopicConfig(topicConfig); } return registerTopicConfig; }) .collect(Collectors.toConcurrentMap(TopicConfig::getTopicName, Function.identity())); topicConfigSerializeWrapper.setTopicConfigTable(topicConfigTable); Map<String, TopicQueueMappingInfo> topicQueueMappingInfoMap = topicConfigList.stream() .map(TopicConfig::getTopicName) .map(topicName -> Optional.ofNullable(this.topicQueueMappingManager.getTopicQueueMapping(topicName)) .map(info -> new AbstractMap.SimpleImmutableEntry<>(topicName, TopicQueueMappingDetail.cloneAsMappingInfo(info))) .orElse(null)) .filter(Objects::nonNull) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (!topicQueueMappingInfoMap.isEmpty()) { topicConfigSerializeWrapper.setTopicQueueMappingInfoMap(topicQueueMappingInfoMap); } doRegisterBrokerAll(true, false, topicConfigSerializeWrapper); } public synchronized void registerBrokerAll(final boolean checkOrderConfig, boolean oneway, boolean forceRegister) { ConcurrentMap<String, TopicConfig> topicConfigMap = this.getTopicConfigManager().getTopicConfigTable(); ConcurrentHashMap<String, TopicConfig> topicConfigTable = new ConcurrentHashMap<>(); for (TopicConfig topicConfig : topicConfigMap.values()) { if (!PermName.isWriteable(this.getBrokerConfig().getBrokerPermission()) || !PermName.isReadable(this.getBrokerConfig().getBrokerPermission())) { topicConfigTable.put(topicConfig.getTopicName(), new TopicConfig(topicConfig.getTopicName(), topicConfig.getReadQueueNums(), topicConfig.getWriteQueueNums(), topicConfig.getPerm() & getBrokerConfig().getBrokerPermission())); } else { topicConfigTable.put(topicConfig.getTopicName(), topicConfig); } if (this.brokerConfig.isEnableSplitRegistration() && topicConfigTable.size() >= this.brokerConfig.getSplitRegistrationSize()) { TopicConfigAndMappingSerializeWrapper topicConfigWrapper = this.getTopicConfigManager().buildSerializeWrapper(topicConfigTable); doRegisterBrokerAll(checkOrderConfig, oneway, topicConfigWrapper); topicConfigTable.clear(); } } Map<String, TopicQueueMappingInfo> topicQueueMappingInfoMap = this.getTopicQueueMappingManager().getTopicQueueMappingTable().entrySet().stream() .map(entry -> new AbstractMap.SimpleImmutableEntry<>(entry.getKey(), TopicQueueMappingDetail.cloneAsMappingInfo(entry.getValue()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); TopicConfigAndMappingSerializeWrapper topicConfigWrapper = this.getTopicConfigManager(). buildSerializeWrapper(topicConfigTable, topicQueueMappingInfoMap); if (this.brokerConfig.isEnableSplitRegistration() || forceRegister || needRegister(this.brokerConfig.getBrokerClusterName(), this.getBrokerAddr(), this.brokerConfig.getBrokerName(), this.brokerConfig.getBrokerId(), this.brokerConfig.getRegisterBrokerTimeoutMills(), this.brokerConfig.isInBrokerContainer())) { doRegisterBrokerAll(checkOrderConfig, oneway, topicConfigWrapper); } } protected void doRegisterBrokerAll(boolean checkOrderConfig, boolean oneway, TopicConfigSerializeWrapper topicConfigWrapper) { if (shutdown) { BrokerController.LOG.info("BrokerController#doRegisterBrokerAll: broker has shutdown, no need to register any more."); return; } List<RegisterBrokerResult> registerBrokerResultList = this.brokerOuterAPI.registerBrokerAll( this.brokerConfig.getBrokerClusterName(), this.getBrokerAddr(), this.brokerConfig.getBrokerName(), this.brokerConfig.getBrokerId(), this.getHAServerAddr(), topicConfigWrapper, Lists.newArrayList(), oneway, this.brokerConfig.getRegisterBrokerTimeoutMills(), this.brokerConfig.isEnableSlaveActingMaster(), this.brokerConfig.isCompressedRegister(), this.brokerConfig.isEnableSlaveActingMaster() ? this.brokerConfig.getBrokerNotActiveTimeoutMillis() : null, this.getBrokerIdentity()); handleRegisterBrokerResult(registerBrokerResultList, checkOrderConfig); } protected void sendHeartbeat() { if (this.brokerConfig.isEnableControllerMode()) { this.replicasManager.sendHeartbeatToController(); } if (this.brokerConfig.isEnableSlaveActingMaster()) { if (this.brokerConfig.isCompatibleWithOldNameSrv()) { this.brokerOuterAPI.sendHeartbeatViaDataVersion( this.brokerConfig.getBrokerClusterName(), this.getBrokerAddr(), this.brokerConfig.getBrokerName(), this.brokerConfig.getBrokerId(), this.brokerConfig.getSendHeartbeatTimeoutMillis(), this.getTopicConfigManager().getDataVersion(), this.brokerConfig.isInBrokerContainer()); } else { this.brokerOuterAPI.sendHeartbeat( this.brokerConfig.getBrokerClusterName(), this.getBrokerAddr(), this.brokerConfig.getBrokerName(), this.brokerConfig.getBrokerId(), this.brokerConfig.getSendHeartbeatTimeoutMillis(), this.brokerConfig.isInBrokerContainer()); } } } protected void syncBrokerMemberGroup() { try { brokerMemberGroup = this.getBrokerOuterAPI() .syncBrokerMemberGroup(this.brokerConfig.getBrokerClusterName(), this.brokerConfig.getBrokerName(), this.brokerConfig.isCompatibleWithOldNameSrv()); } catch (Exception e) { BrokerController.LOG.error("syncBrokerMemberGroup from namesrv failed, ", e); return; } if (brokerMemberGroup == null || brokerMemberGroup.getBrokerAddrs().size() == 0) { BrokerController.LOG.warn("Couldn't find any broker member from namesrv in {}/{}", this.brokerConfig.getBrokerClusterName(), this.brokerConfig.getBrokerName()); return; } this.messageStore.setAliveReplicaNumInGroup(calcAliveBrokerNumInGroup(brokerMemberGroup.getBrokerAddrs())); if (!this.isIsolated) { long minBrokerId = brokerMemberGroup.minimumBrokerId(); this.updateMinBroker(minBrokerId, brokerMemberGroup.getBrokerAddrs().get(minBrokerId)); } } private int calcAliveBrokerNumInGroup(Map<Long, String> brokerAddrTable) { if (brokerAddrTable.containsKey(this.brokerConfig.getBrokerId())) { return brokerAddrTable.size(); } else { return brokerAddrTable.size() + 1; } } protected void handleRegisterBrokerResult(List<RegisterBrokerResult> registerBrokerResultList, boolean checkOrderConfig) { for (RegisterBrokerResult registerBrokerResult : registerBrokerResultList) { if (registerBrokerResult != null) { if (this.updateMasterHAServerAddrPeriodically && registerBrokerResult.getHaServerAddr() != null) { this.messageStore.updateHaMasterAddress(registerBrokerResult.getHaServerAddr()); this.messageStore.updateMasterAddress(registerBrokerResult.getMasterAddr()); } this.slaveSynchronize.setMasterAddr(registerBrokerResult.getMasterAddr()); if (checkOrderConfig) { this.getTopicConfigManager().updateOrderTopicConfig(registerBrokerResult.getKvTable()); } break; } } } private boolean needRegister(final String clusterName, final String brokerAddr, final String brokerName, final long brokerId, final int timeoutMills, final boolean isInBrokerContainer) { TopicConfigSerializeWrapper topicConfigWrapper = this.getTopicConfigManager().buildTopicConfigSerializeWrapper(); List<Boolean> changeList = brokerOuterAPI.needRegister(clusterName, brokerAddr, brokerName, brokerId, topicConfigWrapper, timeoutMills, isInBrokerContainer); boolean needRegister = false; for (Boolean changed : changeList) { if (changed) { needRegister = true; break; } } return needRegister; } public void startService(long minBrokerId, String minBrokerAddr) { BrokerController.LOG.info("{} start service, min broker id is {}, min broker addr: {}", this.brokerConfig.getCanonicalName(), minBrokerId, minBrokerAddr); this.minBrokerIdInGroup = minBrokerId; this.minBrokerAddrInGroup = minBrokerAddr; this.changeSpecialServiceStatus(this.brokerConfig.getBrokerId() == minBrokerId); this.registerBrokerAll(true, false, brokerConfig.isForceRegister()); isIsolated = false; } public void startServiceWithoutCondition() { BrokerController.LOG.info("{} start service", this.brokerConfig.getCanonicalName()); this.changeSpecialServiceStatus(this.brokerConfig.getBrokerId() == MixAll.MASTER_ID); this.registerBrokerAll(true, false, brokerConfig.isForceRegister()); isIsolated = false; } public void stopService() { BrokerController.LOG.info("{} stop service", this.getBrokerConfig().getCanonicalName()); isIsolated = true; this.changeSpecialServiceStatus(false); } public boolean isSpecialServiceRunning() { if (isScheduleServiceStart() && isTransactionCheckServiceStart()) { return true; } return this.ackMessageProcessor != null && this.ackMessageProcessor.isPopReviveServiceRunning(); } private void onMasterOffline() { // close channels with master broker String masterAddr = this.slaveSynchronize.getMasterAddr(); if (masterAddr != null) { this.brokerOuterAPI.getRemotingClient().closeChannels( Arrays.asList(masterAddr, MixAll.brokerVIPChannel(true, masterAddr))); } // master not available, stop sync this.slaveSynchronize.setMasterAddr(null); this.messageStore.updateHaMasterAddress(null); } private void onMasterOnline(String masterAddr, String masterHaAddr) { boolean needSyncMasterFlushOffset = this.messageStore.getMasterFlushedOffset() == 0 && this.messageStoreConfig.isSyncMasterFlushOffsetWhenStartup(); if (masterHaAddr == null || needSyncMasterFlushOffset) { try { BrokerSyncInfo brokerSyncInfo = this.brokerOuterAPI.retrieveBrokerHaInfo(masterAddr); if (needSyncMasterFlushOffset) { LOG.info("Set master flush offset in slave to {}", brokerSyncInfo.getMasterFlushOffset()); this.messageStore.setMasterFlushedOffset(brokerSyncInfo.getMasterFlushOffset()); } if (masterHaAddr == null) { this.messageStore.updateHaMasterAddress(brokerSyncInfo.getMasterHaAddress()); this.messageStore.updateMasterAddress(brokerSyncInfo.getMasterAddress()); } } catch (Exception e) { LOG.error("retrieve master ha info exception, {}", e); } } // set master HA address. if (masterHaAddr != null) { this.messageStore.updateHaMasterAddress(masterHaAddr); } // wakeup HAClient this.messageStore.wakeupHAClient(); } private void onMinBrokerChange(long minBrokerId, String minBrokerAddr, String offlineBrokerAddr, String masterHaAddr) { LOG.info("Min broker changed, old: {}-{}, new {}-{}", this.minBrokerIdInGroup, this.minBrokerAddrInGroup, minBrokerId, minBrokerAddr); this.minBrokerIdInGroup = minBrokerId; this.minBrokerAddrInGroup = minBrokerAddr; this.changeSpecialServiceStatus(this.brokerConfig.getBrokerId() == this.minBrokerIdInGroup); if (offlineBrokerAddr != null && offlineBrokerAddr.equals(this.slaveSynchronize.getMasterAddr())) { // master offline onMasterOffline(); } if (minBrokerId == MixAll.MASTER_ID && minBrokerAddr != null) { // master online onMasterOnline(minBrokerAddr, masterHaAddr); } // notify PullRequest on hold to pull from master. if (this.minBrokerIdInGroup == MixAll.MASTER_ID) { this.pullRequestHoldService.notifyMasterOnline(); } } public void updateMinBroker(long minBrokerId, String minBrokerAddr) { if (brokerConfig.isEnableSlaveActingMaster() && brokerConfig.getBrokerId() != MixAll.MASTER_ID) { if (lock.tryLock()) { try { if (minBrokerId != this.minBrokerIdInGroup) { String offlineBrokerAddr = null; if (minBrokerId > this.minBrokerIdInGroup) { offlineBrokerAddr = this.minBrokerAddrInGroup; } onMinBrokerChange(minBrokerId, minBrokerAddr, offlineBrokerAddr, null); } } finally { lock.unlock(); } } } } public void updateMinBroker(long minBrokerId, String minBrokerAddr, String offlineBrokerAddr, String masterHaAddr) { if (brokerConfig.isEnableSlaveActingMaster() && brokerConfig.getBrokerId() != MixAll.MASTER_ID) { try { if (lock.tryLock(3000, TimeUnit.MILLISECONDS)) { try { if (minBrokerId != this.minBrokerIdInGroup) { onMinBrokerChange(minBrokerId, minBrokerAddr, offlineBrokerAddr, masterHaAddr); } } finally { lock.unlock(); } } } catch (InterruptedException e) { LOG.error("Update min broker error, {}", e); } } } public void changeSpecialServiceStatus(boolean shouldStart) { for (BrokerAttachedPlugin brokerAttachedPlugin : brokerAttachedPlugins) { if (brokerAttachedPlugin != null) { brokerAttachedPlugin.statusChanged(shouldStart); } } changeScheduleServiceStatus(shouldStart); changeTransactionCheckServiceStatus(shouldStart); if (this.ackMessageProcessor != null) { LOG.info("Set PopReviveService Status to {}", shouldStart); this.ackMessageProcessor.setPopReviveServiceStatus(shouldStart); } } private synchronized void changeTransactionCheckServiceStatus(boolean shouldStart) { if (isTransactionCheckServiceStart != shouldStart) { LOG.info("TransactionCheckService status changed to {}", shouldStart); if (shouldStart) { this.transactionalMessageCheckService.start(); } else { this.transactionalMessageCheckService.shutdown(true); } isTransactionCheckServiceStart = shouldStart; } } public synchronized void changeScheduleServiceStatus(boolean shouldStart) { if (isScheduleServiceStart != shouldStart) { LOG.info("ScheduleServiceStatus changed to {}", shouldStart); if (shouldStart) { this.scheduleMessageService.start(); } else { this.scheduleMessageService.stop(); } isScheduleServiceStart = shouldStart; if (timerMessageStore != null) { timerMessageStore.syncLastReadTimeMs(); timerMessageStore.setShouldRunningDequeue(shouldStart); } } } public MessageStore getMessageStoreByBrokerName(String brokerName) { if (this.brokerConfig.getBrokerName().equals(brokerName)) { return this.getMessageStore(); } return null; } public BrokerIdentity getBrokerIdentity() { if (messageStoreConfig.isEnableDLegerCommitLog()) { return new BrokerIdentity( brokerConfig.getBrokerClusterName(), brokerConfig.getBrokerName(), Integer.parseInt(messageStoreConfig.getdLegerSelfId().substring(1)), brokerConfig.isInBrokerContainer()); } else { return new BrokerIdentity( brokerConfig.getBrokerClusterName(), brokerConfig.getBrokerName(), brokerConfig.getBrokerId(), brokerConfig.isInBrokerContainer()); } } public TopicConfigManager getTopicConfigManager() { return topicConfigManager; } public void setTopicConfigManager(TopicConfigManager topicConfigManager) { this.topicConfigManager = topicConfigManager; } public TopicQueueMappingManager getTopicQueueMappingManager() { return topicQueueMappingManager; } public AuthenticationMetadataManager getAuthenticationMetadataManager() { return authenticationMetadataManager; } @VisibleForTesting public void setAuthenticationMetadataManager( AuthenticationMetadataManager authenticationMetadataManager) { this.authenticationMetadataManager = authenticationMetadataManager; } public AuthorizationMetadataManager getAuthorizationMetadataManager() { return authorizationMetadataManager; } @VisibleForTesting public void setAuthorizationMetadataManager( AuthorizationMetadataManager authorizationMetadataManager) { this.authorizationMetadataManager = authorizationMetadataManager; } public String getHAServerAddr() { return this.brokerConfig.getBrokerIP2() + ":" + this.messageStoreConfig.getHaListenPort(); } public RebalanceLockManager getRebalanceLockManager() { return rebalanceLockManager; } public SlaveSynchronize getSlaveSynchronize() { return slaveSynchronize; } public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } public ExecutorService getPullMessageExecutor() { return pullMessageExecutor; } public ExecutorService getPutMessageFutureExecutor() { return putMessageFutureExecutor; } public void setPullMessageExecutor(ExecutorService pullMessageExecutor) { this.pullMessageExecutor = pullMessageExecutor; } public BlockingQueue<Runnable> getSendThreadPoolQueue() { return sendThreadPoolQueue; } public BlockingQueue<Runnable> getAckThreadPoolQueue() { return ackThreadPoolQueue; } public BrokerStatsManager getBrokerStatsManager() { return brokerStatsManager; } public void setBrokerStatsManager(BrokerStatsManager brokerStatsManager) { this.brokerStatsManager = brokerStatsManager; } public List<SendMessageHook> getSendMessageHookList() { return sendMessageHookList; } public void registerSendMessageHook(final SendMessageHook hook) { this.sendMessageHookList.add(hook); LOG.info("register SendMessageHook Hook, {}", hook.hookName()); } public List<ConsumeMessageHook> getConsumeMessageHookList() { return consumeMessageHookList; } public void registerConsumeMessageHook(final ConsumeMessageHook hook) { this.consumeMessageHookList.add(hook); LOG.info("register ConsumeMessageHook Hook, {}", hook.hookName()); } public void registerServerRPCHook(RPCHook rpcHook) { for (Map.Entry<String, RemotingServer> entry : remotingServerMap.entrySet()) { RemotingServer remotingServer = entry.getValue(); if (remotingServer != null) { remotingServer.registerRPCHook(rpcHook); } } } public void setRequestPipeline(RequestPipeline pipeline) { for (Map.Entry<String, RemotingServer> entry : remotingServerMap.entrySet()) { RemotingServer remotingServer = entry.getValue(); if (remotingServer != null) { remotingServer.setRequestPipeline(pipeline); } } } public RemotingServer getRemotingServer() { return remotingServerMap.get(TCP_REMOTING_SERVER); } public void setRemotingServer(RemotingServer remotingServer) { remotingServerMap.put(TCP_REMOTING_SERVER, remotingServer); } public RemotingServer getFastRemotingServer() { return remotingServerMap.get(FAST_REMOTING_SERVER); } public void setFastRemotingServer(RemotingServer fastRemotingServer) { remotingServerMap.put(FAST_REMOTING_SERVER, fastRemotingServer); } public RemotingServer getRemotingServerByName(String name) { return remotingServerMap.get(name); } public void setRemotingServerByName(String name, RemotingServer remotingServer) { remotingServerMap.put(name, remotingServer); } public ClientHousekeepingService getClientHousekeepingService() { return clientHousekeepingService; } public CountDownLatch getRemotingServerStartLatch() { return remotingServerStartLatch; } public void setRemotingServerStartLatch(CountDownLatch remotingServerStartLatch) { this.remotingServerStartLatch = remotingServerStartLatch; } public void registerClientRPCHook(RPCHook rpcHook) { this.getBrokerOuterAPI().registerRPCHook(rpcHook); } public BrokerOuterAPI getBrokerOuterAPI() { return brokerOuterAPI; } public InetSocketAddress getStoreHost() { return storeHost; } public void setStoreHost(InetSocketAddress storeHost) { this.storeHost = storeHost; } public Configuration getConfiguration() { return this.configuration; } public BlockingQueue<Runnable> getHeartbeatThreadPoolQueue() { return heartbeatThreadPoolQueue; } public TransactionalMessageCheckService getTransactionalMessageCheckService() { return transactionalMessageCheckService; } public void setTransactionalMessageCheckService( TransactionalMessageCheckService transactionalMessageCheckService) { this.transactionalMessageCheckService = transactionalMessageCheckService; } public TransactionalMessageService getTransactionalMessageService() { return transactionalMessageService; } public void setTransactionalMessageService(TransactionalMessageService transactionalMessageService) { this.transactionalMessageService = transactionalMessageService; } public AbstractTransactionalMessageCheckListener getTransactionalMessageCheckListener() { return transactionalMessageCheckListener; } public void setTransactionalMessageCheckListener( AbstractTransactionalMessageCheckListener transactionalMessageCheckListener) { this.transactionalMessageCheckListener = transactionalMessageCheckListener; } public BlockingQueue<Runnable> getEndTransactionThreadPoolQueue() { return endTransactionThreadPoolQueue; } public ExecutorService getSendMessageExecutor() { return sendMessageExecutor; } public SendMessageProcessor getSendMessageProcessor() { return sendMessageProcessor; } public RecallMessageProcessor getRecallMessageProcessor() { return recallMessageProcessor; } public QueryAssignmentProcessor getQueryAssignmentProcessor() { return queryAssignmentProcessor; } public TopicQueueMappingCleanService getTopicQueueMappingCleanService() { return topicQueueMappingCleanService; } public ExecutorService getAdminBrokerExecutor() { return adminBrokerExecutor; } public BlockingQueue<Runnable> getLitePullThreadPoolQueue() { return litePullThreadPoolQueue; } public ShutdownHook getShutdownHook() { return shutdownHook; } public void setShutdownHook(ShutdownHook shutdownHook) { this.shutdownHook = shutdownHook; } public long getMinBrokerIdInGroup() { return this.brokerConfig.getBrokerId(); } public BrokerController peekMasterBroker() { return brokerConfig.getBrokerId() == MixAll.MASTER_ID ? this : null; } public BrokerMemberGroup getBrokerMemberGroup() { return this.brokerMemberGroup; } public int getListenPort() { return this.nettyServerConfig.getListenPort(); } public List<BrokerAttachedPlugin> getBrokerAttachedPlugins() { return brokerAttachedPlugins; } public EscapeBridge getEscapeBridge() { return escapeBridge; } public long getShouldStartTime() { return shouldStartTime; } public BrokerPreOnlineService getBrokerPreOnlineService() { return brokerPreOnlineService; } public EndTransactionProcessor getEndTransactionProcessor() { return endTransactionProcessor; } public boolean isScheduleServiceStart() { return isScheduleServiceStart; } public boolean isTransactionCheckServiceStart() { return isTransactionCheckServiceStart; } public ScheduleMessageService getScheduleMessageService() { return scheduleMessageService; } public ReplicasManager getReplicasManager() { return replicasManager; } public void setIsolated(boolean isolated) { isIsolated = isolated; } public boolean isIsolated() { return this.isIsolated; } public TimerCheckpoint getTimerCheckpoint() { return timerCheckpoint; } public TopicRouteInfoManager getTopicRouteInfoManager() { return this.topicRouteInfoManager; } public BlockingQueue<Runnable> getClientManagerThreadPoolQueue() { return clientManagerThreadPoolQueue; } public BlockingQueue<Runnable> getConsumerManagerThreadPoolQueue() { return consumerManagerThreadPoolQueue; } public BlockingQueue<Runnable> getAsyncPutThreadPoolQueue() { return putThreadPoolQueue; } public BlockingQueue<Runnable> getReplyThreadPoolQueue() { return replyThreadPoolQueue; } public BlockingQueue<Runnable> getAdminBrokerThreadPoolQueue() { return adminBrokerThreadPoolQueue; } public ColdDataPullRequestHoldService getColdDataPullRequestHoldService() { return coldDataPullRequestHoldService; } public void setColdDataPullRequestHoldService( ColdDataPullRequestHoldService coldDataPullRequestHoldService) { this.coldDataPullRequestHoldService = coldDataPullRequestHoldService; } public ColdDataCgCtrService getColdDataCgCtrService() { return coldDataCgCtrService; } public void setColdDataCgCtrService(ColdDataCgCtrService coldDataCgCtrService) { this.coldDataCgCtrService = coldDataCgCtrService; } public ConfigContext getConfigContext() { return configContext; } public void setConfigContext(ConfigContext configContext) { this.configContext = configContext; } }
BrokerController
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/NetworkClientTest.java
{ "start": 69692, "end": 70072 }
class ____ implements RequestCompletionHandler { public boolean executed = false; public ClientResponse response; public void onComplete(ClientResponse response) { this.executed = true; this.response = response; } } // ManualMetadataUpdater with ability to keep track of failures private static
TestCallbackHandler
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/delegation/Planner.java
{ "start": 2546, "end": 4645 }
interface ____ { /** * Retrieves a {@link Parser} that provides methods for parsing a SQL string. * * @return initialized {@link Parser} */ Parser getParser(); /** * Converts a relational tree of {@link ModifyOperation}s into a set of runnable {@link * Transformation}s. * * <p>This method accepts a list of {@link ModifyOperation}s to allow reusing common subtrees of * multiple relational queries. Each query's top node should be a {@link ModifyOperation} in * order to pass the expected properties of the output {@link Transformation} such as output * mode (append, retract, upsert) or the expected output type. * * @param modifyOperations list of relational operations to plan, optimize and convert in a * single run. * @return list of corresponding {@link Transformation}s. */ List<Transformation<?>> translate(List<ModifyOperation> modifyOperations); /** * Returns the AST of the specified Table API and SQL queries and the execution plan to compute * the result of the given collection of {@link QueryOperation}s. * * @param operations The collection of relational queries for which the AST and execution plan * will be returned. * @param format The output format of explained statement. See more details at {@link * ExplainFormat}. * @param extraDetails The extra explain details which the explain result should include, e.g. * estimated cost, changelog mode for streaming, displaying execution plan in json format */ String explain(List<Operation> operations, ExplainFormat format, ExplainDetail... extraDetails); // --- Plan compilation and restore @Experimental InternalPlan loadPlan(PlanReference planReference) throws IOException; @Experimental InternalPlan compilePlan(List<ModifyOperation> modifyOperations); @Experimental List<Transformation<?>> translatePlan(InternalPlan plan); @Experimental String explainPlan(InternalPlan plan, ExplainDetail... extraDetails); }
Planner
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/grouping/GroupingFunction.java
{ "start": 1825, "end": 2130 }
class ____ grouping functions that cannot be evaluated outside the context of an aggregation. * They will have their evaluation implemented part of an aggregation, which may keep state for their execution, making them "stateful" * grouping functions. */ public abstract static non-sealed
of
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/RequestType.java
{ "start": 858, "end": 1300 }
enum ____ { STREAM((byte) 0); private final byte code; RequestType(byte code) { this.code = code; } public static RequestType valueOf(byte code) { for (RequestType requestType : RequestType.values()) { if (requestType.getCode() == code) { return requestType; } } return null; } public byte getCode() { return code; } }
RequestType
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/meta_data/FieldMetaData.java
{ "start": 3355, "end": 3858 }
class ____ possible. */ public static <T extends TBase<T, F>, F extends TFieldIdEnum> Map<F, FieldMetaData> getStructMetaDataMap(Class<T> sClass) { // Note: Do not use synchronized on this method declaration - it leads to a deadlock. // Similarly, do not trigger sClass.newInstance() while holding a lock on structMap, // it will lead to the same deadlock. // See: https://issues.apache.org/jira/browse/THRIFT-5430 for details. if (!structMap.containsKey(sClass)) { // Load
is
java
google__dagger
javatests/dagger/hilt/android/processor/internal/GeneratorsTest.java
{ "start": 25910, "end": 26582 }
class ____ extends Application implements" + " GeneratedComponentManagerHolder {")); }); } @Test public void copySuppressWarningsAnnotation_onFragment_annotationCopied() { Source myApplication = HiltCompilerTests.javaSource( "test.MyFragment", "package test;", "", "import android.annotation.TargetApi;", "import androidx.fragment.app.Fragment;", "import dagger.hilt.android.AndroidEntryPoint;", "", "@SuppressWarnings(\"rawtypes\")", "@AndroidEntryPoint(Fragment.class)", "public
Hilt_MyApplication
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IdentityHashMapUsageTest.java
{ "start": 4716, "end": 4997 }
class ____ { private final Map<String, Integer> m = new IdentityHashMap<>(); } """) .addOutputLines( "Test.java", """ import java.util.IdentityHashMap; import java.util.Map;
Test
java
apache__camel
components/camel-iec60870/src/generated/java/org/apache/camel/component/iec60870/client/ClientEndpointConfigurer.java
{ "start": 742, "end": 9602 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { ClientEndpoint target = (ClientEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "acknowledgewindow": case "acknowledgeWindow": target.getConnectionOptions().setAcknowledgeWindow(property(camelContext, short.class, value)); return true; case "adsuaddresstype": case "adsuAddressType": target.getConnectionOptions().setAdsuAddressType(property(camelContext, org.eclipse.neoscada.protocol.iec60870.ASDUAddressType.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "causeoftransmissiontype": case "causeOfTransmissionType": target.getConnectionOptions().setCauseOfTransmissionType(property(camelContext, org.eclipse.neoscada.protocol.iec60870.CauseOfTransmissionType.class, value)); return true; case "causesourceaddress": case "causeSourceAddress": target.getConnectionOptions().setCauseSourceAddress(property(camelContext, byte.class, value)); return true; case "connectionid": case "connectionId": target.setConnectionId(property(camelContext, java.lang.String.class, value)); return true; case "connectiontimeout": case "connectionTimeout": target.getConnectionOptions().setConnectionTimeout(property(camelContext, int.class, value)); return true; case "datamoduleoptions": case "dataModuleOptions": target.getConnectionOptions().setDataModuleOptions(property(camelContext, org.eclipse.neoscada.protocol.iec60870.client.data.DataModuleOptions.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "ignorebackgroundscan": case "ignoreBackgroundScan": target.getConnectionOptions().setIgnoreBackgroundScan(property(camelContext, boolean.class, value)); return true; case "ignoredaylightsavingtime": case "ignoreDaylightSavingTime": target.getConnectionOptions().setIgnoreDaylightSavingTime(property(camelContext, boolean.class, value)); return true; case "informationobjectaddresstype": case "informationObjectAddressType": target.getConnectionOptions().setInformationObjectAddressType(property(camelContext, org.eclipse.neoscada.protocol.iec60870.InformationObjectAddressType.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxunacknowledged": case "maxUnacknowledged": target.getConnectionOptions().setMaxUnacknowledged(property(camelContext, short.class, value)); return true; case "protocoloptions": case "protocolOptions": target.getConnectionOptions().setProtocolOptions(property(camelContext, org.eclipse.neoscada.protocol.iec60870.ProtocolOptions.class, value)); return true; case "timezone": case "timeZone": target.getConnectionOptions().setTimeZone(property(camelContext, java.util.TimeZone.class, value)); return true; case "timeout1": target.getConnectionOptions().setTimeout1(property(camelContext, int.class, value)); return true; case "timeout2": target.getConnectionOptions().setTimeout2(property(camelContext, int.class, value)); return true; case "timeout3": target.getConnectionOptions().setTimeout3(property(camelContext, int.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "acknowledgewindow": case "acknowledgeWindow": return short.class; case "adsuaddresstype": case "adsuAddressType": return org.eclipse.neoscada.protocol.iec60870.ASDUAddressType.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "causeoftransmissiontype": case "causeOfTransmissionType": return org.eclipse.neoscada.protocol.iec60870.CauseOfTransmissionType.class; case "causesourceaddress": case "causeSourceAddress": return byte.class; case "connectionid": case "connectionId": return java.lang.String.class; case "connectiontimeout": case "connectionTimeout": return int.class; case "datamoduleoptions": case "dataModuleOptions": return org.eclipse.neoscada.protocol.iec60870.client.data.DataModuleOptions.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "ignorebackgroundscan": case "ignoreBackgroundScan": return boolean.class; case "ignoredaylightsavingtime": case "ignoreDaylightSavingTime": return boolean.class; case "informationobjectaddresstype": case "informationObjectAddressType": return org.eclipse.neoscada.protocol.iec60870.InformationObjectAddressType.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "maxunacknowledged": case "maxUnacknowledged": return short.class; case "protocoloptions": case "protocolOptions": return org.eclipse.neoscada.protocol.iec60870.ProtocolOptions.class; case "timezone": case "timeZone": return java.util.TimeZone.class; case "timeout1": return int.class; case "timeout2": return int.class; case "timeout3": return int.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { ClientEndpoint target = (ClientEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "acknowledgewindow": case "acknowledgeWindow": return target.getConnectionOptions().getAcknowledgeWindow(); case "adsuaddresstype": case "adsuAddressType": return target.getConnectionOptions().getAdsuAddressType(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "causeoftransmissiontype": case "causeOfTransmissionType": return target.getConnectionOptions().getCauseOfTransmissionType(); case "causesourceaddress": case "causeSourceAddress": return target.getConnectionOptions().getCauseSourceAddress(); case "connectionid": case "connectionId": return target.getConnectionId(); case "connectiontimeout": case "connectionTimeout": return target.getConnectionOptions().getConnectionTimeout(); case "datamoduleoptions": case "dataModuleOptions": return target.getConnectionOptions().getDataModuleOptions(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "ignorebackgroundscan": case "ignoreBackgroundScan": return target.getConnectionOptions().isIgnoreBackgroundScan(); case "ignoredaylightsavingtime": case "ignoreDaylightSavingTime": return target.getConnectionOptions().isIgnoreDaylightSavingTime(); case "informationobjectaddresstype": case "informationObjectAddressType": return target.getConnectionOptions().getInformationObjectAddressType(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxunacknowledged": case "maxUnacknowledged": return target.getConnectionOptions().getMaxUnacknowledged(); case "protocoloptions": case "protocolOptions": return target.getConnectionOptions().getProtocolOptions(); case "timezone": case "timeZone": return target.getConnectionOptions().getTimeZone(); case "timeout1": return target.getConnectionOptions().getTimeout1(); case "timeout2": return target.getConnectionOptions().getTimeout2(); case "timeout3": return target.getConnectionOptions().getTimeout3(); default: return null; } } }
ClientEndpointConfigurer
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateExpressionTimeoutFallbackTest.java
{ "start": 1094, "end": 2150 }
class ____ extends ContextTestSupport { @Test public void testAggregateExpressionTimeoutFallback() throws Exception { getMockEndpoint("mock:aggregated").expectedBodiesReceived("A+B+C"); Map<String, Object> headers = new HashMap<>(); headers.put("id", 123); template.sendBodyAndHeaders("direct:start", "A", headers); template.sendBodyAndHeaders("direct:start", "B", headers); template.sendBodyAndHeaders("direct:start", "C", headers); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").aggregate(header("id"), new BodyInAggregatingStrategy()) // if no timeout header it will fallback to the 2000 seconds .completionTimeout(header("timeout")).completionTimeout(2000).to("mock:aggregated"); } }; } }
AggregateExpressionTimeoutFallbackTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/SequenceGeneratorTest.java
{ "start": 920, "end": 1957 }
class ____ { /** * This seems a little trivial, but we need to guarantee that all Dialects start their sequences on a non-0 value. */ @Test @JiraKey(value = "HHH-8814") @RequiresDialectFeature(feature = DialectFeatureChecks.SupportsSequences.class) @SkipForDialect( dialectClass = SQLServerDialect.class, majorVersion = 11, reason = "SQLServer2012Dialect initializes sequence to minimum value (e.g., Long.MIN_VALUE; Hibernate assumes it is uninitialized.", versionMatchMode = VersionMatchMode.SAME_OR_OLDER ) public void testStartOfSequence(SessionFactoryScope scope) { final Person person = new Person(); scope.inTransaction( session -> { session.persist( person ); } ); assertTrue( person.getId() > 0 ); final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); assertTrue( statementInspector.getSqlQueries() .stream() .filter( sql -> sql.contains( "product_sequence" ) ) .findFirst() .isPresent() ); } }
SequenceGeneratorTest
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/lifecycle/PreDestroyBeanSpec.java
{ "start": 784, "end": 1235 }
class ____ { @Test void testBeanClosingOnContextClose() { // tag::start[] ApplicationContext ctx = ApplicationContext.run(); PreDestroyBean preDestroyBean = ctx.getBean(PreDestroyBean.class); Connection connection = ctx.getBean(Connection.class); ctx.stop(); // end::start[] assertTrue(preDestroyBean.stopped.get()); assertTrue(connection.stopped.get()); } }
PreDestroyBeanSpec
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/execution/ExecutionService.java
{ "start": 31573, "end": 32004 }
class ____ { private final WatchExecutionContext context; private final Thread executionThread; WatchExecution(WatchExecutionContext context, Thread executionThread) { this.context = context; this.executionThread = executionThread; } WatchExecutionSnapshot createSnapshot() { return context.createSnapshot(executionThread); } } }
WatchExecution