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
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/hologres/HoloKeywordsTest.java
{ "start": 463, "end": 1723 }
class ____ extends TestCase { public void test_keywords() { DbType dbType = DbType.hologres; String sql = "select 1 as default"; SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, SQLParserFeature.IgnoreNameQuotes); SQLStatement stmt = parser.parseStatement(); assertEquals(Token.EOF, parser.getLexer().token()); String result = SQLUtils.toSQLString(stmt, dbType, null, VisitorFeature.OutputNameQuote).trim(); String expectedSql = "SELECT 1 AS \"default\""; assertEquals(expectedSql, result); } public void test_keywords2() { DbType dbType = DbType.hologres; String sql = "select a from default.test"; SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, SQLParserFeature.IgnoreNameQuotes); SQLStatement stmt = parser.parseStatement(); assertEquals(Token.EOF, parser.getLexer().token()); String result = SQLUtils.toSQLString(stmt, dbType, null, VisitorFeature.OutputNameQuote).trim(); String expectedSql = "SELECT a\n" + "FROM \"DEFAULT\".test"; assertEquals(expectedSql, result); } }
HoloKeywordsTest
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalPythonGroupTableAggregateRule.java
{ "start": 1887, "end": 5229 }
class ____ extends ConverterRule { public static final RelOptRule INSTANCE = new StreamPhysicalPythonGroupTableAggregateRule( Config.INSTANCE .withConversion( FlinkLogicalTableAggregate.class, FlinkConventions.LOGICAL(), FlinkConventions.STREAM_PHYSICAL(), "StreamPhysicalPythonGroupTableAggregateRule") .withRuleFactory(StreamPhysicalPythonGroupTableAggregateRule::new)); public StreamPhysicalPythonGroupTableAggregateRule(Config config) { super(config); } @Override public boolean matches(RelOptRuleCall call) { FlinkLogicalTableAggregate agg = call.rel(0); List<AggregateCall> aggCalls = agg.getAggCallList(); boolean existGeneralPythonFunction = aggCalls.stream() .anyMatch(x -> PythonUtil.isPythonAggregate(x, PythonFunctionKind.GENERAL)); boolean existPandasFunction = aggCalls.stream() .anyMatch(x -> PythonUtil.isPythonAggregate(x, PythonFunctionKind.PANDAS)); boolean existJavaUserDefinedFunction = aggCalls.stream() .anyMatch( x -> !PythonUtil.isPythonAggregate(x, null) && !PythonUtil.isBuiltInAggregate(x)); if (existPandasFunction || existGeneralPythonFunction) { if (existPandasFunction) { throw new TableException( "Pandas UDAFs are not supported in streaming mode currently."); } if (existJavaUserDefinedFunction) { throw new TableException( "Python UDAF and Java/Scala UDAF cannot be used together."); } return true; } else { return false; } } @Override public RelNode convert(RelNode rel) { FlinkLogicalTableAggregate agg = (FlinkLogicalTableAggregate) rel; FlinkRelDistribution requiredDistribution; if (agg.getGroupSet().cardinality() != 0) { requiredDistribution = FlinkRelDistribution.hash(agg.getGroupSet().asList(), true); } else { requiredDistribution = FlinkRelDistribution.SINGLETON(); } RelTraitSet requiredTraitSet = rel.getCluster() .getPlanner() .emptyTraitSet() .replace(requiredDistribution) .replace(FlinkConventions.STREAM_PHYSICAL()); RelTraitSet providedTraitSet = rel.getTraitSet().replace(FlinkConventions.STREAM_PHYSICAL()); RelNode newInput = RelOptRule.convert(agg.getInput(), requiredTraitSet); return new StreamPhysicalPythonGroupTableAggregate( rel.getCluster(), providedTraitSet, newInput, rel.getRowType(), agg.getGroupSet().toArray(), JavaScalaConversionUtil.toScala(agg.getAggCallList())); } }
StreamPhysicalPythonGroupTableAggregateRule
java
elastic__elasticsearch
libs/x-content/src/main/java/org/elasticsearch/xcontent/ConstructingObjectParser.java
{ "start": 10374, "end": 11178 }
interface ____. public static <Value, FieldT> BiConsumer<Value, FieldT> constructorArg() { return (BiConsumer<Value, FieldT>) REQUIRED_CONSTRUCTOR_ARG_MARKER; } /** * Pass the {@linkplain BiConsumer} this returns the declare methods to declare an optional constructor argument. See this class's * javadoc for an example. The order in which these are declared matters: it is the order that they come in the array passed to * {@link #builder} and the order that missing arguments are reported to the user if any are missing. When all of these parameters are * parsed from the {@linkplain XContentParser} the target object is immediately built. */ @SuppressWarnings("unchecked") // Safe because we never call the method. This is just trickery to make the
pretty
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/AutoFactoryAtInjectTest.java
{ "start": 2785, "end": 2937 }
class ____ { @Inject AutoFactoryOnInnerType() {} @AutoFactory static
AutoFactoryOnInnerType
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ParameterTest.java
{ "start": 5210, "end": 5699 }
class ____ { abstract void target(Object o); void test() { // BUG: Diagnostic contains: String target(new String()); } } """) .doTest(); } @Test public void getName_stripsPrefix_fromMethodWithGetPrefix() { CompilationTestHelper.newInstance(PrintNameOfFirstArgument.class, getClass()) .addSourceLines( "Test.java", """ abstract
Test
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/json/JsonContentAssert.java
{ "start": 11971, "end": 15462 }
class ____ to load the resource * @param compareMode the compare mode used when checking * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isEqualToJson(String path, Class<?> resourceLoadClass, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(path, resourceLoadClass); return assertNotFailed(compare(expectedJson, compareMode)); } /** * Verifies that the actual value is equal to the specified JSON bytes. * @param expected the expected JSON bytes * @param compareMode the compare mode used when checking * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isEqualToJson(byte[] expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, compareMode)); } /** * Verifies that the actual value is equal to the specified JSON file. * @param expected a file containing the expected JSON * @param compareMode the compare mode used when checking * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isEqualToJson(File expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, compareMode)); } /** * Verifies that the actual value is equal to the specified JSON input stream. * @param expected an input stream containing the expected JSON * @param compareMode the compare mode used when checking * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isEqualToJson(InputStream expected, JSONCompareMode compareMode) { return assertNotFailed(compare(this.loader.getJson(expected), compareMode)); } /** * Verifies that the actual value is equal to the specified JSON resource. * @param expected a resource containing the expected JSON * @param compareMode the compare mode used when checking * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isEqualToJson(Resource expected, JSONCompareMode compareMode) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, compareMode)); } /** * Verifies that the actual value is equal to the specified JSON. The {@code expected} * value can contain the JSON itself or, if it ends with {@code .json}, the name of a * resource to be loaded using {@code resourceLoadClass}. * @param expected the expected JSON or the name of a resource containing the expected * JSON * @param comparator the comparator used when checking * @return {@code this} assertion object * @throws AssertionError if the actual JSON value is not equal to the given one */ public JsonContentAssert isEqualToJson(CharSequence expected, JSONComparator comparator) { String expectedJson = this.loader.getJson(expected); return assertNotFailed(compare(expectedJson, comparator)); } /** * Verifies that the actual value is equal to the specified JSON resource. * @param path the name of a resource containing the expected JSON * @param resourceLoadClass the source
used
java
google__guava
android/guava/src/com/google/common/collect/Sets.java
{ "start": 64482, "end": 72573 }
class ____<E> extends AbstractSet<Set<E>> { final ImmutableMap<E, Integer> inputSet; PowerSet(Set<E> input) { checkArgument( input.size() <= 30, "Too many elements to create power set: %s > 30", input.size()); this.inputSet = Maps.indexMap(input); } @Override public int size() { return 1 << inputSet.size(); } @Override public boolean isEmpty() { return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIndexedListIterator<Set<E>>(size()) { @Override protected Set<E> get(int setBits) { return new SubSet<>(inputSet, setBits); } }; } @Override public boolean contains(@Nullable Object obj) { if (obj instanceof Set) { Set<?> set = (Set<?>) obj; return inputSet.keySet().containsAll(set); } return false; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof PowerSet) { PowerSet<?> that = (PowerSet<?>) obj; return inputSet.keySet().equals(that.inputSet.keySet()); } return super.equals(obj); } @Override public int hashCode() { /* * The sum of the sums of the hash codes in each subset is just the sum of * each input element's hash code times the number of sets that element * appears in. Each element appears in exactly half of the 2^n sets, so: */ return inputSet.keySet().hashCode() << (inputSet.size() - 1); } @Override public String toString() { return "powerSet(" + inputSet + ")"; } } /** * Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code * combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}. * * <p>Elements appear in these subsets in the same iteration order as they appeared in the input * set. The order in which these subsets appear in the outer set is undefined. * * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements * are identical, even if the input set uses a different concept of equivalence. * * <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When * the result set is constructed, the input set is merely copied. Only as the result set is * iterated are the individual subsets created. Each of these subsets occupies an additional O(n) * memory but only for as long as the user retains a reference to it. That is, the set returned by * {@code combinations} does not retain the individual subsets. * * @param set the set of elements to take combinations of * @param size the number of elements per combination * @return the set of all combinations of {@code size} elements from {@code set} * @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()} * inclusive * @throws NullPointerException if {@code set} is or contains {@code null} * @since 23.0 */ public static <E> Set<Set<E>> combinations(Set<E> set, int size) { ImmutableMap<E, Integer> index = Maps.indexMap(set); checkNonnegative(size, "size"); checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size()); if (size == 0) { return ImmutableSet.of(ImmutableSet.of()); } else if (size == index.size()) { return ImmutableSet.of(index.keySet()); } return new AbstractSet<Set<E>>() { @Override public boolean contains(@Nullable Object o) { if (o instanceof Set) { Set<?> s = (Set<?>) o; return s.size() == size && index.keySet().containsAll(s); } return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIterator<Set<E>>() { final BitSet bits = new BitSet(index.size()); @Override protected @Nullable Set<E> computeNext() { if (bits.isEmpty()) { bits.set(0, size); } else { int firstSetBit = bits.nextSetBit(0); int bitToFlip = bits.nextClearBit(firstSetBit); if (bitToFlip == index.size()) { return endOfData(); } /* * The current set in sorted order looks like * {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...} * where it does *not* contain bitToFlip. * * The next combination is * * {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...} * * This is lexicographically next if you look at the combinations in descending order * e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}... */ bits.set(0, bitToFlip - firstSetBit - 1); bits.clear(bitToFlip - firstSetBit - 1, bitToFlip); bits.set(bitToFlip); } BitSet copy = (BitSet) bits.clone(); return new AbstractSet<E>() { @Override public boolean contains(@Nullable Object o) { Integer i = index.get(o); return i != null && copy.get(i); } @Override public Iterator<E> iterator() { return new AbstractIterator<E>() { int i = -1; @Override protected @Nullable E computeNext() { i = copy.nextSetBit(i + 1); if (i == -1) { return endOfData(); } return index.keySet().asList().get(i); } }; } @Override public int size() { return size; } }; } }; } @Override public int size() { return IntMath.binomial(index.size(), size); } @Override public String toString() { return "Sets.combinations(" + index.keySet() + ", " + size + ")"; } }; } /** An implementation for {@link Set#hashCode()}. */ static int hashCodeImpl(Set<?> s) { int hashCode = 0; for (Object o : s) { hashCode += o != null ? o.hashCode() : 0; hashCode = ~~hashCode; // Needed to deal with unusual integer overflow in GWT. } return hashCode; } /** An implementation for {@link Set#equals(Object)}. */ static boolean equalsImpl(Set<?> s, @Nullable Object object) { if (s == object) { return true; } if (object instanceof Set) { Set<?> o = (Set<?>) object; try { return s.size() == o.size() && s.containsAll(o); } catch (NullPointerException | ClassCastException ignored) { return false; } } return false; } /** * Returns an unmodifiable view of the specified navigable set. This method allows modules to * provide users with "read-only" access to internal navigable sets. Query operations on the * returned set "read through" to the specified set, and attempts to modify the returned set, * whether direct or via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned navigable set will be serializable if the specified navigable set is * serializable. * * <p><b>Java 8+ users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}. * * @param set the navigable set for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified navigable set * @since 12.0 */ public static <E extends @Nullable Object> NavigableSet<E> unmodifiableNavigableSet( NavigableSet<E> set) { if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) { return set; } return new UnmodifiableNavigableSet<>(set); } static final
PowerSet
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/JobVertexFlameGraphHeaders.java
{ "start": 1223, "end": 2669 }
class ____ implements RuntimeMessageHeaders< EmptyRequestBody, VertexFlameGraph, JobVertexFlameGraphParameters> { private static final JobVertexFlameGraphHeaders INSTANCE = new JobVertexFlameGraphHeaders(); private static final String URL = "/jobs/:" + JobIDPathParameter.KEY + "/vertices/:" + JobVertexIdPathParameter.KEY + "/flamegraph"; @Override public Class<EmptyRequestBody> getRequestClass() { return EmptyRequestBody.class; } @Override public Class<VertexFlameGraph> getResponseClass() { return VertexFlameGraph.class; } @Override public HttpResponseStatus getResponseStatusCode() { return HttpResponseStatus.OK; } @Override public JobVertexFlameGraphParameters getUnresolvedMessageParameters() { return new JobVertexFlameGraphParameters(); } @Override public HttpMethodWrapper getHttpMethod() { return HttpMethodWrapper.GET; } @Override public String getTargetRestEndpointURL() { return URL; } public static JobVertexFlameGraphHeaders getInstance() { return INSTANCE; } @Override public String getDescription() { return "Returns flame graph information for a vertex, and may initiate flame graph sampling if necessary."; } }
JobVertexFlameGraphHeaders
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/mapping/Fetchable.java
{ "start": 242, "end": 384 }
interface ____ { FetchMode getFetchMode(); void setFetchMode(FetchMode joinedFetch); boolean isLazy(); void setLazy(boolean lazy); }
Fetchable
java
apache__logging-log4j2
log4j-slf4j2-impl/src/test/java/org/apache/logging/slf4j/LoggerTest.java
{ "start": 1830, "end": 8010 }
class ____ { private final Logger logger; private final LoggerContext ctx; @Test void debug() { logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{}" + Strings.LINE_SEPARATOR); } public LoggerTest(final LoggerContext context) { this.ctx = context; this.logger = LoggerFactory.getLogger("LoggerTest"); } @Test void debugNoParms() { logger.debug("Debug message {}"); verify("o.a.l.s.LoggerTest Debug message {} MDC{}" + Strings.LINE_SEPARATOR); logger.debug("Debug message {}", (Object[]) null); verify("o.a.l.s.LoggerTest Debug message {} MDC{}" + Strings.LINE_SEPARATOR); ((LocationAwareLogger) logger) .log(null, Log4jLogger.class.getName(), LocationAwareLogger.DEBUG_INT, "Debug message {}", null, null); verify("o.a.l.s.LoggerTest Debug message {} MDC{}" + Strings.LINE_SEPARATOR); } @Test void debugWithParms() { logger.debug("Hello, {}", "World"); verify("o.a.l.s.LoggerTest Hello, World MDC{}" + Strings.LINE_SEPARATOR); } @Test void mdc() { MDC.put("TestYear", "2010"); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{TestYear=2010}" + Strings.LINE_SEPARATOR); MDC.clear(); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{}" + Strings.LINE_SEPARATOR); } @Test void mdcStack() { MDC.pushByKey("TestYear", "2010"); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{TestYear=2010}" + Strings.LINE_SEPARATOR); MDC.pushByKey("TestYear", "2011"); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{TestYear=2011}" + Strings.LINE_SEPARATOR); MDC.popByKey("TestYear"); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{TestYear=2010}" + Strings.LINE_SEPARATOR); MDC.clear(); logger.debug("Debug message"); verify("o.a.l.s.LoggerTest Debug message MDC{}" + Strings.LINE_SEPARATOR); } /** * @see <a href="https://issues.apache.org/jira/browse/LOG4J2-793">LOG4J2-793</a> */ @Test void supportsCustomSLF4JMarkers() { final Marker marker = new CustomFlatMarker("TEST"); logger.debug(marker, "Test"); verify("o.a.l.s.LoggerTest Test MDC{}" + Strings.LINE_SEPARATOR); } @Test void testRootLogger() { final Logger l = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); assertNotNull(l, "No Root Logger"); assertEquals(Logger.ROOT_LOGGER_NAME, l.getName()); } @Test void doubleSubst() { logger.debug("Hello, {}", "Log4j {}"); verify("o.a.l.s.LoggerTest Hello, Log4j {} MDC{}" + Strings.LINE_SEPARATOR); } @Test void testThrowable() { final Throwable expected = new RuntimeException(); logger.debug("Hello {}", expected); verifyThrowable(expected); logger.debug("Hello {}", (Object) expected); verifyThrowable(null); logger.debug("Hello", expected); verifyThrowable(expected); logger.debug("Hello {}! {}", "World!", expected); verifyThrowable(null); logger.debug("Hello {}!", "World!", expected); verifyThrowable(expected); final LocationAwareLogger lal = (LocationAwareLogger) logger; lal.log(null, LoggerTest.class.getName(), LocationAwareLogger.DEBUG_INT, "Hello {}", null, expected); verifyThrowable(expected); lal.log( null, LoggerTest.class.getName(), LocationAwareLogger.DEBUG_INT, "Hello {}", new Object[] {expected}, null); verifyThrowable(null); lal.log( null, LoggerTest.class.getName(), LocationAwareLogger.DEBUG_INT, "Hello {}", new Object[] {"World!", expected}, null); verifyThrowable(expected); } @Test void testLazyLoggingEventBuilder() { final ListAppender appender = ctx.getConfiguration().getAppender("UnformattedList"); final Level oldLevel = ctx.getRootLogger().getLevel(); try { Configurator.setRootLevel(Level.ERROR); final LoggingEventBuilder builder = logger.makeLoggingEventBuilder(org.slf4j.event.Level.DEBUG); Configurator.setRootLevel(Level.DEBUG); builder.log(); assertThat(appender.getEvents()).hasSize(1).map(LogEvent::getLevel).containsExactly(Level.DEBUG); } finally { Configurator.setRootLevel(oldLevel); } } private ListAppender getAppenderByName(final String name) { final ListAppender listApp = ctx.getConfiguration().getAppender(name); assertNotNull(listApp, "Missing Appender"); return listApp; } private void verify(final String expected) { final ListAppender listApp = getAppenderByName("List"); final List<String> events = listApp.getMessages(); assertEquals(1, events.size(), "Incorrect number of messages. Expected 1 Actual " + events.size()); final String actual = events.get(0); assertEquals(expected, actual, "Incorrect message. Expected \" + expected + \". Actual \" + actual"); listApp.clear(); } private void verifyThrowable(final Throwable expected) { final ListAppender listApp = getAppenderByName("UnformattedList"); final List<LogEvent> events = listApp.getEvents(); assertEquals(1, events.size(), "Incorrect number of messages"); final LogEvent actual = events.get(0); assertEquals(expected, actual.getThrown(), "Incorrect throwable."); listApp.clear(); } @BeforeEach @AfterEach void cleanup(@Named("List") final ListAppender list, @Named("UnformattedList") final ListAppender unformattedList) { MDC.clear(); list.clear(); unformattedList.clear(); } }
LoggerTest
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedManualFlush.java
{ "start": 1274, "end": 2653 }
class ____ extends AbstractModifiedFlagsEntityTest { private Integer id = null; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { // Revision 1 em.getTransaction().begin(); BasicTestEntity1 entity = new BasicTestEntity1( "str1", 1 ); em.persist( entity ); em.getTransaction().commit(); id = entity.getId(); // Revision 2 - both properties (str1 and long1) should be marked as modified. em.getTransaction().begin(); BasicTestEntity1 entity2 = em.find( BasicTestEntity1.class, entity.getId() ); entity2.setStr1( "str2" ); entity2 = em.merge( entity2 ); em.flush(); entity2.setLong1( 2 ); entity2 = em.merge( entity2 ); em.flush(); em.getTransaction().commit(); } ); } @Test public void testHasChangedOnDoubleFlush(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); List list = queryForPropertyHasChanged( auditReader, BasicTestEntity1.class, id, "str1" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( auditReader, BasicTestEntity1.class, id, "long1" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); } ); } }
HasChangedManualFlush
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/util/diff/PatchTest.java
{ "start": 829, "end": 1857 }
class ____ { @Test void testPatch_Insert() { List<String> insertTest_from = newArrayList("hhh"); List<String> insertTest_to = newArrayList("hhh", "jjj", "kkk", "lll"); Patch<String> patch = DiffUtils.diff(insertTest_from, insertTest_to); assertThat(DiffUtils.patch(insertTest_from, patch)).isEqualTo(insertTest_to); } @Test void testPatch_Delete() { List<String> deleteTest_from = newArrayList("ddd", "fff", "ggg", "hhh"); List<String> deleteTest_to = newArrayList("ggg"); Patch<String> patch = DiffUtils.diff(deleteTest_from, deleteTest_to); assertThat(DiffUtils.patch(deleteTest_from, patch)).isEqualTo(deleteTest_to); } @Test void testPatch_Change() { List<String> changeTest_from = newArrayList("aaa", "bbb", "ccc", "ddd"); List<String> changeTest_to = newArrayList("aaa", "bxb", "cxc", "ddd"); Patch<String> patch = DiffUtils.diff(changeTest_from, changeTest_to); assertThat(DiffUtils.patch(changeTest_from, patch)).isEqualTo(changeTest_to); } }
PatchTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest138.java
{ "start": 804, "end": 1572 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); String sql = "INSERT INTO T01_CHECKIN_CUSTOMER" + "(WEB_USER_ID,NAME,COUNTRY,PROVINCE,CITY" + ",POSTCODE,PHONE,FAX,EMAIL,ADDRESS,FIRST_NAME,LAST_NAME,sex) " + "select 2,null,'4225',null,'beijing','','1','','1223@123.com','beijing','booking','test',null "// + "from dual " + "where not exists ("// + " select EMAIL" + " from T01_CHECKIN_CUSTOMER" + " where WEB_USER_ID=2 and EMAIL='1223@123.com'" + ")"; assertTrue(provider.checkValid(sql)); } }
MySqlWallTest138
java
mockito__mockito
mockito-extensions/mockito-errorprone/src/test/java/org/mockito/errorprone/bugpatterns/MockitoAnyClassWithPrimitiveTypeTest.java
{ "start": 583, "end": 1539 }
class ____ { private CompilationTestHelper compilationHelper; private BugCheckerRefactoringTestHelper refactoringHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance( MockitoAnyClassWithPrimitiveType.class, getClass()); refactoringHelper = BugCheckerRefactoringTestHelper.newInstance( new MockitoAnyClassWithPrimitiveType(), getClass()); } @Test public void testPositiveCases() { compilationHelper .addSourceLines( "Test.java", "package org.mockito;", "import static org.mockito.Mockito.mock;", "import static org.mockito.Mockito.when;", "import static org.mockito.ArgumentMatchers.any;", "
MockitoAnyClassWithPrimitiveTypeTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bulkid/GlobalQuotedIdentifiersBulkIdTest.java
{ "start": 3422, "end": 4132 }
class ____ { @Id @GeneratedValue private Long id; private String name; private boolean employed; @Temporal(TemporalType.TIMESTAMP) private Date employedOn; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getEmployedOn() { return employedOn; } public void setEmployedOn(Date employedOn) { this.employedOn = employedOn; } public boolean isEmployed() { return employed; } public void setEmployed(boolean employed) { this.employed = employed; } } @Entity(name = "Doctor") public static
Person
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
{ "start": 73417, "end": 73510 }
class ____ extends ArrayList<CharSequence> { } @SuppressWarnings("serial") static
ExtendsList
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/matching/PreMatchContentTypeInHeaderTest.java
{ "start": 2556, "end": 2986 }
class ____ { @POST @Consumes(MediaType.TEXT_PLAIN) public String fromText(String input) { return "text-" + input; } @POST @Consumes(MediaType.APPLICATION_JSON) public String fromJson(String input) { return "json-" + input; } } public record Result(String message) { } @Provider @PreMatching public static
TestResource
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ElasticsearchEndpointBuilderFactory.java
{ "start": 29962, "end": 30314 }
class ____ extends AbstractEndpointBuilder implements ElasticsearchEndpointBuilder, AdvancedElasticsearchEndpointBuilder { public ElasticsearchEndpointBuilderImpl(String path) { super(componentName, path); } } return new ElasticsearchEndpointBuilderImpl(path); } }
ElasticsearchEndpointBuilderImpl
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/RoutingSlipNotStopErrorHandlerTest.java
{ "start": 1008, "end": 1234 }
class ____ extends ContextTestSupport { private static final String DIRECT_START = "direct:start"; private static final String THROWING_ROUTE = "direct:throwingRoute"; public static
RoutingSlipNotStopErrorHandlerTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsSelectTest_over_rows_5.java
{ "start": 909, "end": 2279 }
class ____ extends TestCase { public void test_select() throws Exception { String sql = "SELECT sum(c) over(order by ds rows UNBOUNDED following) s, ds FROM t1"; assertEquals("SELECT sum(c) OVER (ORDER BY ds ROWS UNBOUNDED FOLLOWING) AS s, ds\n" + "FROM t1", SQLUtils.formatOdps(sql)); assertEquals("select sum(c) over (order by ds rows unbounded following) as s, ds\n" + "from t1", SQLUtils.formatOdps(sql, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ODPS); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ODPS); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(2, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); // assertTrue(visitor.getColumns().contains(new Column("abc", "name"))); } }
OdpsSelectTest_over_rows_5
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/error/JMXTXUseOriginalBodyIT.java
{ "start": 3092, "end": 3239 }
class ____ { @Handler public String process(@Body String body) { return "oh no"; } } public static
FooBean
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/NaturalIdDereferenceTest.java
{ "start": 1419, "end": 12722 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { Book book = new Book(); book.isbn = "abcd"; session.persist( book ); BookRef bookRef = new BookRef(); bookRef.naturalBook = bookRef.normalBook = book; session.persist( bookRef ); session.flush(); session.clear(); } ); } @AfterEach public void deleteData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void naturalIdDereferenceTest(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r.normalBook.isbn FROM BookRef r" ); List resultList = query.getResultList(); assertFalse( resultList.isEmpty() ); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 1, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test public void normalIdDereferenceFromAlias(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r.normalBook.id FROM BookRef r" ); List resultList = query.getResultList(); assertFalse( resultList.isEmpty() ); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 0, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test public void naturalIdDereferenceFromAlias(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r.naturalBook.isbn FROM BookRef r" ); List resultList = query.getResultList(); assertFalse( resultList.isEmpty() ); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 0, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test public void normalIdDereferenceFromImplicitJoin(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.normalBookRef.normalBook.id FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 1, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test public void naturalIdDereferenceFromImplicitJoin(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.normalBookRef.naturalBook.isbn FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 1, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * Due to the construction of the mapping for {@link BookRefRef#naturalBookRef}, the {@code isbn} column maps * to both the referenced {@link BookRef} and {@link Book}. As such, {@code r2.naturalBookRef.naturalBook.isbn} * can be dereferenced without a single join. */ @Test public void nestedNaturalIdDereferenceFromImplicitJoin(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.naturalBookRef.naturalBook.isbn FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 0, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * Adjustment of {@link #nestedNaturalIdDereferenceFromImplicitJoin(SessionFactoryScope)}, that instead selects the {@code id} property, * which requires a single join to {@code Book}. */ @Test public void nestedNaturalIdDereferenceFromImplicitJoin2(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.naturalBookRef.naturalBook.id FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 1, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test public void doNotDereferenceNaturalIdIfIsReferenceToPrimaryKey(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.normalBookRef.normalBook.isbn FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 2, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test public void selectedEntityIsNotDereferencedForPrimaryKey(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.normalBookRef.normalBook FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 2, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * BookRefRef can be joined directly with Book due to the construction of the isbn key. * <p> * I.e. * <p> * BookRefRef{isbn=abcd} enforces BookRef{isbn=abc} (FK) enforces BookRef{isbn=abc} (FK), * so bookRefRef.naturalBookRef.naturalBook = Book{isbn=abc}. * <p> * BookRefRef{isbn=null}, i.e. no BookRef for this BookRefRef, and as such no book, * so bookRefRef.naturalBookRef.naturalBook yields null which is expected. */ @Test public void selectedEntityIsNotDereferencedForNaturalId(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.naturalBookRef.naturalBook FROM BookRefRef r2" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 1, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * {@code r2.normalBookRef.normalBook.id} requires 1 join as seen in {@link #normalIdDereferenceFromImplicitJoin}. * {@code r3.naturalBookRef.naturalBook.isbn} requires 1 join as seen in {@link #selectedEntityIsNotDereferencedForNaturalId(SessionFactoryScope)} . * An additional join is added to join BookRef once more on {@code r2.normalBookRef.normalBook.isbn = r3.naturalBookRef.naturalBook.isbn}. * This results in three joins in total. */ @Test public void dereferenceNaturalIdInJoin(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r2.normalBookRef.normalBook.id, r3.naturalBookRef.naturalBook.isbn " + "FROM BookRefRef r2 JOIN BookRefRef r3 ON r2.normalBookRef.normalBook.isbn = r3.naturalBookRef.naturalBook.isbn" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); // r2.normalBookRef.normalBook.id requires assertEquals( 3, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * {@code BookRefRef} is joined with {@code BookRef} on {@code b.naturalBook.isbn = a.naturalBookRef.naturalBook.isbn}. * {@code b.naturalBook.isbn} can be dereferenced without any join ({@link #naturalIdDereferenceFromAlias(SessionFactoryScope)} . * {@code a.naturalBookRef.naturalBook.isbn} can be dereferenced without any join ({@link #nestedNaturalIdDereferenceFromImplicitJoin(SessionFactoryScope)} . * We finally select all properties of {@code b.normalBook}, which requires {@code Book} to be joined. * This results in two joins in total. */ @Test public void dereferenceNaturalIdInJoin2(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT b.normalBook FROM BookRefRef a " + "JOIN BookRef b ON b.naturalBook.isbn = a.naturalBookRef.naturalBook.isbn" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 2, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * The {@link BookRef#normalBook} is joined with {@code BookRef} on {@code join.isbn = from.normalBook.isbn}. * {@code join.isbn = from.normalBook.isbn} both dereference to {@code join.isbn}. * {@code r.normalBook.isbn} dereferences to {@code join.isbn}. * As a result, only a single join is required. */ @Test public void dereferenceNaturalIdInJoin3(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r.normalBook.isbn FROM BookRef r JOIN r.normalBook b ON b.isbn = r.normalBook.isbn" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 1, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } /** * The {@link Book} is joined with {@link BookRef} on {@code book.isbn = ref.normalBook.isbn}. * {@code book.isbn} can be dereferenced from the {@code Book} table. * {@code ref.normalBook.isbn} requires an implicit join with book. * {@code ref.normalBook.isbn} in the final selection is available due to the aforementioned join. * As a result, 2 joins are required. */ @Test public void dereferenceNaturalIdInJoin4(SessionFactoryScope scope) { SQLStatementInspector sqlStatementInterceptor = scope.getCollectingStatementInspector(); sqlStatementInterceptor.clear(); scope.inTransaction( session -> { Query query = session.createQuery( "SELECT r.normalBook.isbn FROM BookRef r JOIN Book b ON b.isbn = r.normalBook.isbn" ); query.getResultList(); sqlStatementInterceptor.assertExecutedCount( 1 ); assertEquals( 2, sqlStatementInterceptor.getNumberOfJoins( 0 ) ); } ); } @Test @JiraKey(value = "HHH-13752") public void deleteWithNaturalIdBasedJoinTable(SessionFactoryScope scope) { scope.inTransaction( session -> { Query query = session.createQuery( "DELETE FROM Book b WHERE 1=0" ); query.executeUpdate(); } ); } @Entity(name = "Book") @Table(name = "book") public static
NaturalIdDereferenceTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/xml/XmlPiFunction.java
{ "start": 1172, "end": 2260 }
class ____ extends AbstractSqmSelfRenderingFunctionDescriptor { public XmlPiFunction(TypeConfiguration typeConfiguration) { super( "xmlpi", FunctionKind.NORMAL, StandardArgumentsValidators.composite( new ArgumentTypesValidator( StandardArgumentsValidators.between( 1, 2 ), STRING, STRING ) ), StandardFunctionReturnTypeResolvers.invariant( typeConfiguration.getBasicTypeRegistry().resolve( String.class, SqlTypes.SQLXML ) ), StandardFunctionArgumentTypeResolvers.invariant( typeConfiguration, ANY, STRING ) ); } @Override public void render( SqlAppender sqlAppender, List<? extends SqlAstNode> sqlAstArguments, ReturnableType<?> returnType, SqlAstTranslator<?> walker) { sqlAppender.appendSql( "xmlpi(name " ); final Literal literal = (Literal) sqlAstArguments.get( 0 ); sqlAppender.appendDoubleQuoteEscapedString( (String) literal.getLiteralValue() ); if ( sqlAstArguments.size() > 1 ) { sqlAppender.appendSql( ',' ); sqlAstArguments.get( 1 ).accept( walker ); } sqlAppender.appendSql( ')' ); } }
XmlPiFunction
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/PreemptionContract.java
{ "start": 1601, "end": 3379 }
class ____ { @Private @Unstable public static PreemptionContract newInstance( List<PreemptionResourceRequest> req, Set<PreemptionContainer> containers) { PreemptionContract contract = Records.newRecord(PreemptionContract.class); contract.setResourceRequest(req); contract.setContainers(containers); return contract; } /** * If the AM releases resources matching these requests, then the {@link * PreemptionContainer}s enumerated in {@link #getContainers()} should not be * evicted from the cluster. Due to delays in propagating cluster state and * sending these messages, there are conditions where satisfied contracts may * not prevent the platform from killing containers. * @return List of {@link PreemptionResourceRequest} to update the * <code>ApplicationMaster</code> about resources requested back by the * <code>ResourceManager</code>. * @see AllocateRequest#setAskList(List) */ @Public @Evolving public abstract List<PreemptionResourceRequest> getResourceRequest(); @Private @Unstable public abstract void setResourceRequest(List<PreemptionResourceRequest> req); /** * Assign the set of {@link PreemptionContainer} specifying which containers * owned by the <code>ApplicationMaster</code> that may be reclaimed by the * <code>ResourceManager</code>. If the AM prefers a different set of * containers, then it may checkpoint or kill containers matching the * description in {@link #getResourceRequest}. * @return Set of containers at risk if the contract is not met. */ @Public @Evolving public abstract Set<PreemptionContainer> getContainers(); @Private @Unstable public abstract void setContainers(Set<PreemptionContainer> containers); }
PreemptionContract
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/function/scalar/string/Between.java
{ "start": 2141, "end": 6325 }
class ____ extends CaseInsensitiveScalarFunction implements OptionalArgument { private final Expression input, left, right, greedy; public Between(Source source, Expression input, Expression left, Expression right, Expression greedy, boolean caseInsensitive) { super(source, Arrays.asList(input, left, right, defaultGreedy(greedy)), caseInsensitive); this.input = input; this.left = left; this.right = right; this.greedy = arguments().get(3); } private static Expression defaultGreedy(Expression exp) { return exp != null ? exp : Literal.FALSE; } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } TypeResolution resolution = isStringAndExact(input, sourceText(), FIRST); if (resolution.unresolved()) { return resolution; } resolution = isStringAndExact(left, sourceText(), SECOND); if (resolution.unresolved()) { return resolution; } resolution = isStringAndExact(right, sourceText(), THIRD); if (resolution.unresolved()) { return resolution; } return isBoolean(greedy, sourceText(), FOURTH); } public Expression input() { return input; } public Expression left() { return left; } public Expression right() { return right; } public Expression greedy() { return greedy; } @Override protected Pipe makePipe() { return new BetweenFunctionPipe( source(), this, Expressions.pipe(input), Expressions.pipe(left), Expressions.pipe(right), Expressions.pipe(greedy), isCaseInsensitive() ); } @Override public boolean foldable() { return input.foldable() && left.foldable() && right.foldable() && greedy.foldable(); } @Override public Object fold() { return doProcess(input.fold(), left.fold(), right.fold(), greedy.fold(), isCaseInsensitive()); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, Between::new, input, left, right, greedy, isCaseInsensitive()); } @Override public ScriptTemplate asScript() { ScriptTemplate inputScript = asScript(input); ScriptTemplate leftScript = asScript(left); ScriptTemplate rightScript = asScript(right); ScriptTemplate greedyScript = asScript(greedy); return asScriptFrom(inputScript, leftScript, rightScript, greedyScript); } private ScriptTemplate asScriptFrom( ScriptTemplate inputScript, ScriptTemplate leftScript, ScriptTemplate rightScript, ScriptTemplate greedyScript ) { return new ScriptTemplate( format( Locale.ROOT, formatTemplate("{eql}.%s(%s,%s,%s,%s,%s)"), "between", inputScript.template(), leftScript.template(), rightScript.template(), greedyScript.template(), "{}" ), paramsBuilder().script(inputScript.params()) .script(leftScript.params()) .script(rightScript.params()) .script(greedyScript.params()) .variable(isCaseInsensitive()) .build(), dataType() ); } @Override public ScriptTemplate scriptWithField(FieldAttribute field) { return new ScriptTemplate( processScript(Scripts.DOC_VALUE), paramsBuilder().variable(field.exactAttribute().name()).build(), dataType() ); } @Override public DataType dataType() { return DataTypes.KEYWORD; } @Override public Expression replaceChildren(List<Expression> newChildren) { return new Between(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2), newChildren.get(3), isCaseInsensitive()); } }
Between
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/TypeFactoryTest.java
{ "start": 19678, "end": 25092 }
class ____ superType = subtype.getSuperClass(); assertNotNull(superType); assertEquals(HashMap.class, superType.getRawClass()); // which also should have proper typing assertEquals(String.class, superType.getKeyType().getRawClass()); assertEquals(List.class, superType.getContentType().getRawClass()); assertEquals(Integer.class, superType.getContentType().getContentType().getRawClass()); } @Test public void testTypeGeneralization() { TypeFactory tf = newTypeFactory(); MapType t = tf.constructMapType(HashMap.class, String.class, Long.class); JavaType superT = tf.constructGeneralizedType(t, Map.class); assertEquals(String.class, superT.getKeyType().getRawClass()); assertEquals(Long.class, superT.getContentType().getRawClass()); assertSame(t, tf.constructGeneralizedType(t, HashMap.class)); // plus check there is super/sub relationship try { tf.constructGeneralizedType(t, TreeMap.class); fail("Should not pass"); } catch (IllegalArgumentException e) { verifyException(e, "not a super-type of"); } } @Test public void testMapTypesRaw() { JavaType type = TF.constructType(HashMap.class); assertEquals(MapType.class, type.getClass()); MapType mapType = (MapType) type; assertEquals(TF.constructType(Object.class), mapType.getKeyType()); assertEquals(TF.constructType(Object.class), mapType.getContentType()); } @Test public void testMapTypesAdvanced() { JavaType type = TF.constructType(MyMap.class); assertEquals(MapType.class, type.getClass()); MapType mapType = (MapType) type; assertEquals(TF.constructType(String.class), mapType.getKeyType()); assertEquals(TF.constructType(Long.class), mapType.getContentType()); type = TF.constructType(MapInterface.class); mapType = (MapType) type; assertEquals(TF.constructType(String.class), mapType.getKeyType()); assertEquals(TF.constructType(Integer.class), mapType.getContentType()); type = TF.constructType(MyStringIntMap.class); mapType = (MapType) type; assertEquals(TF.constructType(String.class), mapType.getKeyType()); assertEquals(TF.constructType(Integer.class), mapType.getContentType()); } /** * Specific test to verify that complicate name mangling schemes * do not fool type resolver */ @Test public void testMapTypesSneaky() { JavaType type = TF.constructType(IntLongMap.class); assertEquals(MapType.class, type.getClass()); MapType mapType = (MapType) type; assertEquals(TF.constructType(Integer.class), mapType.getKeyType()); assertEquals(TF.constructType(Long.class), mapType.getContentType()); } /** * Plus sneaky types may be found via introspection as well. */ @Test public void testSneakyFieldTypes() throws Exception { Field field = SneakyBean.class.getDeclaredField("intMap"); JavaType type = TF.constructType(field.getGenericType()); assertEquals(MapType.class, type.getClass()); MapType mapType = (MapType) type; assertEquals(TF.constructType(Integer.class), mapType.getKeyType()); assertEquals(TF.constructType(Long.class), mapType.getContentType()); field = SneakyBean.class.getDeclaredField("longList"); type = TF.constructType(field.getGenericType()); assertTrue(type instanceof CollectionType); CollectionType collectionType = (CollectionType) type; assertEquals(TF.constructType(Long.class), collectionType.getContentType()); } /** * Looks like type handling actually differs for properties, too. */ @Test public void testSneakyBeanProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); StringLongMapBean bean = mapper.readValue("{\"value\":{\"a\":123}}", StringLongMapBean.class); assertNotNull(bean); Map<String,Long> map = bean.value; assertEquals(1, map.size()); assertEquals(Long.valueOf(123), map.get("a")); StringListBean bean2 = mapper.readValue("{\"value\":[\"...\"]}", StringListBean.class); assertNotNull(bean2); List<String> list = bean2.value; assertSame(GenericList.class, list.getClass()); assertEquals(1, list.size()); assertEquals("...", list.get(0)); } @Test public void testSneakySelfRefs() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(new SneakyBean2()); assertEquals("{\"foobar\":null}", json); } /* /********************************************************** /* Unit tests: handling of specific JDK types /********************************************************** */ @Test public void testAtomicArrayRefParameters() { JavaType type = TF.constructType(new TypeReference<AtomicReference<long[]>>() { }); JavaType[] params = TF.findTypeParameters(type, AtomicReference.class); assertNotNull(params); assertEquals(1, params.length); assertEquals(TF.constructType(long[].class), params[0]); } static abstract
JavaType
java
apache__camel
test-infra/camel-test-infra-ollama/src/main/java/org/apache/camel/test/infra/ollama/services/OllamaRemoteInfraService.java
{ "start": 1015, "end": 2488 }
class ____ implements OllamaServiceConfiguration { @Override public String modelName() { return System.getProperty(OllamaProperties.MODEL); } @Override public String apiKey() { return System.getProperty(OllamaProperties.API_KEY); } } private final OllamaServiceConfiguration configuration; public OllamaRemoteInfraService() { configuration = new DefaultServiceConfiguration(); } public OllamaRemoteInfraService(OllamaServiceConfiguration serviceConfiguration) { configuration = serviceConfiguration; } @Override public void registerProperties() { // NO-OP } @Override public void initialize() { registerProperties(); } @Override public void shutdown() { // NO-OP } @Override public String getEndpoint() { return baseUrl(); } @Override public String getModel() { return modelName(); } @Override public String modelName() { return configuration.modelName(); } @Override public String baseUrl() { return System.getProperty(OllamaProperties.ENDPOINT); } @Override public String baseUrlV1() { return System.getProperty(OllamaProperties.ENDPOINT) + "v1"; } @Override public String apiKey() { return System.getProperty(OllamaProperties.API_KEY); } }
DefaultServiceConfiguration
java
jhy__jsoup
src/test/java/org/jsoup/select/QueryParserTest.java
{ "start": 462, "end": 10250 }
class ____ { @Test public void testConsumeSubQuery() { Document doc = Jsoup.parse("<html><head>h</head><body>" + "<li><strong>l1</strong></li>" + "<a><li><strong>l2</strong></li></a>" + "<p><strong>yes</strong></p>" + "</body></html>"); assertEquals("l1 yes", doc.body().select(">p>strong,>li>strong").text()); // selecting immediate from body assertEquals("l1 yes", doc.body().select(" > p > strong , > li > strong").text()); // space variants assertEquals("l2 yes", doc.select("body>p>strong,body>*>li>strong").text()); assertEquals("l2 yes", doc.select("body>*>li>strong,body>p>strong").text()); assertEquals("l2 yes", doc.select("body>p>strong,body>*>li>strong").text()); } @Test public void testImmediateParentRun() { String query = "div > p > bold.brass"; assertEquals("(ImmediateParentRun (Tag 'div')(Tag 'p')(And (Tag 'bold')(Class '.brass')))", sexpr(query)); /* <ImmediateParentRun css="div > p > bold.brass" cost="11"> <Tag css="div" cost="1"></Tag> <Tag css="p" cost="1"></Tag> <And css="bold.brass" cost="7"> <Tag css="bold" cost="1"></Tag> <Class css=".brass" cost="6"></Class> </And> </ImmediateParentRun> */ } @Test public void testOrGetsCorrectPrecedence() { // tests that a selector "a b, c d, e f" evals to (a AND b) OR (c AND d) OR (e AND f)" // top level or, three child ands String query = "a b, c d, e f"; String parsed = sexpr(query); assertEquals("(Or (And (Tag 'b')(Ancestor (Tag 'a')))(And (Tag 'd')(Ancestor (Tag 'c')))(And (Tag 'f')(Ancestor (Tag 'e'))))", parsed); /* <Or css="a b, c d, e f" cost="9"> <And css="a b" cost="3"> <Tag css="b" cost="1"></Tag> <Parent css="a " cost="2"> <Tag css="a" cost="1"></Tag> </Parent> </And> <And css="c d" cost="3"> <Tag css="d" cost="1"></Tag> <Parent css="c " cost="2"> <Tag css="c" cost="1"></Tag> </Parent> </And> <And css="e f" cost="3"> <Tag css="f" cost="1"></Tag> <Parent css="e " cost="2"> <Tag css="e" cost="1"></Tag> </Parent> </And> </Or> */ } @Test public void testParsesMultiCorrectly() { String query = ".foo.qux[attr=bar] > ol.bar, ol > li + li"; String parsed = sexpr(query); assertEquals("(Or (And (Tag 'li')(ImmediatePreviousSibling (ImmediateParentRun (Tag 'ol')(Tag 'li'))))(ImmediateParentRun (And (AttributeWithValue '[attr=bar]')(Class '.foo')(Class '.qux'))(And (Tag 'ol')(Class '.bar'))))", parsed); /* <Or css=".foo.qux[attr=bar] > ol.bar, ol > li + li" cost="31"> <And css="ol > li + li" cost="7"> <Tag css="li" cost="1"></Tag> <ImmediatePreviousSibling css="ol > li + " cost="6"> <ImmediateParentRun css="ol > li" cost="4"> <Tag css="ol" cost="1"></Tag> <Tag css="li" cost="1"></Tag> </ImmediateParentRun> </ImmediatePreviousSibling> </And> <ImmediateParentRun css=".foo.qux[attr=bar] > ol.bar" cost="24"> <And css=".foo.qux[attr=bar]" cost="15"> <AttributeWithValue css="[attr=bar]" cost="3"></AttributeWithValue> <Class css=".foo" cost="6"></Class> <Class css=".qux" cost="6"></Class> </And> <And css="ol.bar" cost="7"> <Tag css="ol" cost="1"></Tag> <Class css=".bar" cost="6"></Class> </And> </ImmediateParentRun> </Or> */ } @Test void idDescenderClassOrder() { // https://github.com/jhy/jsoup/issues/2254 // '#id .class' cost String query = "#id .class"; String parsed = sexpr(query); assertEquals("(And (Class '.class')(Ancestor (Id '#id')))", parsed); /* <And css="#id .class" cost="22"> <Class css=".class" cost="6"></Class> <Ancestor css="#id " cost="16"> <Id css="#id" cost="2"></Id> </Ancestor> </And> */ } @Test public void exceptionOnUncloseAttribute() { Selector.SelectorParseException exception = assertThrows(Selector.SelectorParseException.class, () -> QueryParser.parse("section > a[href=\"]")); assertEquals( "Did not find balanced marker at 'href=\"]'", exception.getMessage()); } @Test public void testParsesSingleQuoteInContains() { Selector.SelectorParseException exception = assertThrows(Selector.SelectorParseException.class, () -> QueryParser.parse("p:contains(One \" One)")); assertEquals("Did not find balanced marker at 'One \" One)'", exception.getMessage()); } @Test public void exceptOnEmptySelector() { SelectorParseException exception = assertThrows(SelectorParseException.class, () -> QueryParser.parse("")); assertEquals("String must not be empty", exception.getMessage()); } @Test public void exceptOnNullSelector() { SelectorParseException exception = assertThrows(SelectorParseException.class, () -> QueryParser.parse(null)); assertEquals("String must not be empty", exception.getMessage()); } @Test public void exceptOnUnhandledEvaluator() { SelectorParseException exception = assertThrows(SelectorParseException.class, () -> QueryParser.parse("div / foo")); assertEquals("Could not parse query 'div / foo': unexpected token at '/ foo'", exception.getMessage()); } @Test public void okOnSpacesForeAndAft() { Evaluator parse = QueryParser.parse(" span div "); assertEquals("span div", parse.toString()); } @Test public void structuralEvaluatorsToString() { String q = "a:not(:has(span.foo)) b d > e + f ~ g"; Evaluator parse = QueryParser.parse(q); assertEquals(q, parse.toString()); String parsed = sexpr(q); assertEquals("(And (Tag 'g')(PreviousSibling (And (Tag 'f')(ImmediatePreviousSibling (ImmediateParentRun (And (Tag 'd')(Ancestor (And (Tag 'b')(Ancestor (And (Tag 'a')(Not (Has (And (Tag 'span')(Class '.foo')))))))))(Tag 'e'))))))", parsed); } @Test public void parsesOrAfterAttribute() { // https://github.com/jhy/jsoup/issues/2073 String q = "#parent [class*=child], .some-other-selector .nested"; String parsed = sexpr(q); assertEquals("(Or (And (AttributeWithValueContaining '[class*=child]')(Ancestor (Id '#parent')))(And (Class '.nested')(Ancestor (Class '.some-other-selector'))))", parsed); assertEquals("(Or (Class '.some-other-selector')(And (AttributeWithValueContaining '[class*=child]')(Ancestor (Id '#parent'))))", sexpr("#parent [class*=child], .some-other-selector")); assertEquals("(Or (And (Id '#el')(AttributeWithValueContaining '[class*=child]'))(Class '.some-other-selector'))", sexpr("#el[class*=child], .some-other-selector")); assertEquals("(Or (And (AttributeWithValueContaining '[class*=child]')(Ancestor (Id '#parent')))(And (Class '.nested')(Ancestor (Class '.some-other-selector'))))", sexpr("#parent [class*=child], .some-other-selector .nested")); } @Test void parsesEscapedSubqueries() { String html = "<div class='-4a'>One</div> <div id='-4a'>Two</div>"; Document doc = Jsoup.parse(html); String classQ = "div.-\\34 a"; Element div1 = doc.expectFirst(classQ); assertEquals("One", div1.wholeText()); String idQ = "#-\\34 a"; Element div2 = doc.expectFirst(idQ); assertEquals("Two", div2.wholeText()); String genClassQ = "html > body > div.-\\34 a"; assertEquals(genClassQ, div1.cssSelector()); assertSame(div1, doc.expectFirst(genClassQ)); String deepIdQ = "html > body > #-\\34 a"; assertEquals(idQ, div2.cssSelector()); assertSame(div2, doc.expectFirst(deepIdQ)); assertEquals("(ImmediateParentRun (Tag 'html')(Tag 'body')(And (Tag 'div')(Class '.-4a')))", sexpr(genClassQ)); assertEquals("(ImmediateParentRun (Tag 'html')(Tag 'body')(Id '#-4a'))", sexpr(deepIdQ)); } @Test void trailingParens() { SelectorParseException exception = assertThrows(SelectorParseException.class, () -> QueryParser.parse("div:has(p))")); assertEquals("Could not parse query 'div:has(p))': unexpected token at ')'", exception.getMessage()); } @Test void consecutiveCombinators() { Selector.SelectorParseException exception1 = assertThrows(Selector.SelectorParseException.class, () -> QueryParser.parse("div>>p")); assertEquals( "Could not parse query 'div>>p': unexpected token at '>p'", exception1.getMessage()); Selector.SelectorParseException exception2 = assertThrows(Selector.SelectorParseException.class, () -> QueryParser.parse("+ + div")); assertEquals( "Could not parse query '+ + div': unexpected token at '+ div'", exception2.getMessage()); } @Test void hasNodeSelector() { String q = "p:has(::comment:contains(some text))"; Evaluator e = QueryParser.parse(q); assertEquals("(And (Tag 'p')(Has (And (InstanceType '::comment')(ContainsValue ':contains(some text)'))))", sexpr(e)); assertEquals(q, e.toString()); } }
QueryParserTest
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java
{ "start": 2861, "end": 11192 }
class ____ extends MyTestBean { } public static Pointcut myTestBeanSubclassGetterPointcut = new StaticMethodMatcherPointcut() { @Override public ClassFilter getClassFilter() { return new RootClassFilter(MyTestBeanSubclass.class); } @Override public boolean matches(Method m, @Nullable Class<?> targetClass) { return m.getName().startsWith("get"); } }; public static Pointcut allClassGetterPointcut = Pointcuts.GETTERS; public static Pointcut allClassGetAgePointcut = new NameMatchMethodPointcut().addMethodName("getAge"); public static Pointcut allClassGetNamePointcut = new NameMatchMethodPointcut().addMethodName("getName"); @Test void testTrue() { assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_SET_AGE, TestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(Pointcut.TRUE, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); } @Test void testMatches() { assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(allClassSetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, 6)).isFalse(); assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(allClassGetterPointcut, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); } /** * Should match all setters and getters on any class */ @Test void testUnionOfSettersAndGetters() { Pointcut union = Pointcuts.union(allClassGetterPointcut, allClassSetterPointcut); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); } @Test void testUnionOfSpecificGetters() { Pointcut union = Pointcuts.union(allClassGetAgePointcut, allClassGetNamePointcut); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, 6)).isFalse(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); // Union with all setters union = Pointcuts.union(union, allClassSetterPointcut); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, 6)).isTrue(); } /** * Tests vertical composition. First pointcut matches all setters. * Second one matches all getters in the MyTestBean class. TestBean getters shouldn't pass. */ @Test void testUnionOfAllSettersAndSubclassSetters() { assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, TestBean.class, 6)).isFalse(); assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_SET_AGE, MyTestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(myTestBeanSetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); Pointcut union = Pointcuts.union(myTestBeanSetterPointcut, allClassGetterPointcut); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); // Still doesn't match superclass setter assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, MyTestBean.class, 6)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_SET_AGE, TestBean.class, 6)).isFalse(); } /** * Intersection should be MyTestBean getAge() only: * it's the union of allClassGetAge and subclass getters */ @Test void testIntersectionOfSpecificGettersAndSubclassGetters() { assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(allClassGetAgePointcut, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_NAME, MyTestBean.class)).isTrue(); assertThat(Pointcuts.matches(myTestBeanGetterPointcut, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); Pointcut intersection = Pointcuts.intersection(allClassGetAgePointcut, myTestBeanGetterPointcut); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)).isTrue(); // Matches subclass of MyTestBean assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue(); // Now intersection with MyTestBeanSubclass getters should eliminate MyTestBean target intersection = Pointcuts.intersection(intersection, myTestBeanSubclassGetterPointcut); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBean.class)).isFalse(); // Still matches subclass of MyTestBean assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue(); // Now union with all TestBean methods Pointcut union = Pointcuts.union(intersection, allTestBeanMethodsPointcut); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBean.class)).isFalse(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBean.class)).isFalse(); // Still matches subclass of MyTestBean assertThat(Pointcuts.matches(union, TEST_BEAN_GET_NAME, MyTestBeanSubclass.class)).isFalse(); assertThat(Pointcuts.matches(union, TEST_BEAN_GET_AGE, MyTestBeanSubclass.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, TestBean.class)).isTrue(); assertThat(Pointcuts.matches(union, TEST_BEAN_ABSQUATULATE, MyTestBean.class)).isFalse(); } /** * The intersection of these two pointcuts leaves nothing. */ @Test void testSimpleIntersection() { Pointcut intersection = Pointcuts.intersection(allClassGetterPointcut, allClassSetterPointcut); assertThat(Pointcuts.matches(intersection, TEST_BEAN_SET_AGE, TestBean.class, 6)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_GET_AGE, TestBean.class)).isFalse(); assertThat(Pointcuts.matches(intersection, TEST_BEAN_ABSQUATULATE, TestBean.class)).isFalse(); } }
MyTestBeanSubclass
java
quarkusio__quarkus
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/examples/funqy-knative-events-example/java/src/main/java/org/acme/funqy/cloudevent/CloudEventGreeting.java
{ "start": 107, "end": 334 }
class ____ { private static final Logger log = Logger.getLogger(CloudEventGreeting.class); @Funq public void myCloudEventGreeting(Person input) { log.info("Hello " + input.getName()); } }
CloudEventGreeting
java
apache__camel
components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsConfiguration.java
{ "start": 1610, "end": 13743 }
class ____ implements Cloneable { @UriPath private String namespace; @UriPath private String eventHubName; @UriParam(label = "security") private String sharedAccessName; @UriParam(label = "security", secret = true) private String sharedAccessKey; @UriParam(label = "security", secret = true) private String connectionString; @UriParam(label = "security", secret = true) @Metadata(autowired = true) private TokenCredential tokenCredential; @UriParam(label = "common", defaultValue = "AMQP") private AmqpTransportType amqpTransportType = AmqpTransportType.AMQP; @UriParam(label = "common") private AmqpRetryOptions amqpRetryOptions; @UriParam(label = "consumer", defaultValue = "$Default") private String consumerGroupName = "$Default"; @UriParam(label = "consumer", defaultValue = "500") private int prefetchCount = 500; @UriParam(label = "consumer", defaultValue = "BlobCheckpointStore") private CheckpointStore checkpointStore; @UriParam(label = "consumer") private String blobAccountName; @UriParam(label = "consumer", secret = true) private String blobAccessKey; @UriParam(label = "consumer") private String blobContainerName; @UriParam(label = "consumer", secret = true) private StorageSharedKeyCredential blobStorageSharedKeyCredential; @UriParam(label = "consumer") private Map<String, EventPosition> eventPosition = new HashMap<>(); @UriParam(label = "consumer", defaultValue = "500") private int checkpointBatchSize = 500; @UriParam(label = "consumer", defaultValue = "5000") private int checkpointBatchTimeout = 5000; @UriParam(label = "producer") @Metadata(autowired = true) private EventHubProducerAsyncClient producerAsyncClient; @UriParam(label = "producer") private String partitionKey; @UriParam(label = "producer") private String partitionId; @UriParam(label = "security", enums = "AZURE_IDENTITY,CONNECTION_STRING,TOKEN_CREDENTIAL", defaultValue = "CONNECTION_STRING") private CredentialType credentialType; /** * EventHubs namespace created in Azure Portal. */ public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } /** * EventHubs name under a specific namespace. */ public String getEventHubName() { return eventHubName; } public void setEventHubName(String eventHubName) { this.eventHubName = eventHubName; } /** * The name you chose for your EventHubs SAS keys. */ public String getSharedAccessName() { return sharedAccessName; } public void setSharedAccessName(String sharedAccessName) { this.sharedAccessName = sharedAccessName; } /** * The generated value for the SharedAccessName. */ public String getSharedAccessKey() { return sharedAccessKey; } public void setSharedAccessKey(String sharedAccessKey) { this.sharedAccessKey = sharedAccessKey; } /** * Instead of supplying namespace, sharedAccessKey, sharedAccessName, etc. you can supply the connection string for * your eventHub. The connection string for EventHubs already includes all the necessary information to connect to * your EventHub. To learn how to generate the connection string, take a look at this documentation: * https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-get-connection-string */ public String getConnectionString() { return connectionString; } public void setConnectionString(String connectionString) { this.connectionString = connectionString; } /** * Provide custom authentication credentials using an implementation of {@link TokenCredential}. */ public TokenCredential getTokenCredential() { return tokenCredential; } public void setTokenCredential(TokenCredential tokenCredential) { this.tokenCredential = tokenCredential; } /** * Sets the transport type by which all the communication with Azure Event Hubs occurs. */ public AmqpTransportType getAmqpTransportType() { return amqpTransportType; } public void setAmqpTransportType(AmqpTransportType amqpTransportType) { this.amqpTransportType = amqpTransportType; } /** * Sets the retry policy for {@link EventHubProducerAsyncClient}. If not specified, the default retry options are * used. */ public AmqpRetryOptions getAmqpRetryOptions() { return amqpRetryOptions; } public void setAmqpRetryOptions(AmqpRetryOptions amqpRetryOptions) { this.amqpRetryOptions = amqpRetryOptions; } /** * Sets the name of the consumer group this consumer is associated with. Events are read in the context of this * group. The name of the consumer group that is created by default is $Default. */ public String getConsumerGroupName() { return consumerGroupName; } public void setConsumerGroupName(String consumerGroupName) { this.consumerGroupName = consumerGroupName; } /** * Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive * and queue locally without regard to whether a receive operation is currently active. */ public int getPrefetchCount() { return prefetchCount; } public void setPrefetchCount(int prefetchCount) { this.prefetchCount = prefetchCount; } /** * Sets the {@link EventHubProducerAsyncClient}.An asynchronous producer responsible for transmitting * {@link EventData} to a specific Event Hub, grouped together in batches. Depending on the * {@link com.azure.messaging.eventhubs.models.CreateBatchOptions} options specified when creating an * {@link com.azure.messaging.eventhubs.EventDataBatch}, the events may be automatically routed to an available * partition or specific to a partition. Use by this component to produce the data in camel producer. */ public EventHubProducerAsyncClient getProducerAsyncClient() { return producerAsyncClient; } public void setProducerAsyncClient(EventHubProducerAsyncClient producerAsyncClient) { this.producerAsyncClient = producerAsyncClient; } /** * Sets the identifier of the Event Hub partition that the {@link EventData} events will be sent to. If the * identifier is not specified, the Event Hubs service will be responsible for routing events that are sent to an * available partition. */ public String getPartitionId() { return partitionId; } public void setPartitionId(String partitionId) { this.partitionId = partitionId; } /** * Sets a hashing key to be provided for the batch of events, which instructs the Event Hubs service to map this key * to a specific partition. * * The selection of a partition is stable for a given partition hashing key. Should any other batches of events be * sent using the same exact partition hashing key, the Event Hubs service will route them all to the same * partition. * * This should be specified only when there is a need to group events by partition, but there is flexibility into * which partition they are routed. If ensuring that a batch of events is sent only to a specific partition, it is * recommended that the identifier of the position be specified directly when sending the batch. */ public String getPartitionKey() { return partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } /** * Sets the {@link CheckpointStore} the {@link EventProcessorClient} will use for storing partition ownership and * checkpoint information. * * <p> * Users can, optionally, provide their own implementation of {@link CheckpointStore} which will store ownership and * checkpoint information. * </p> * * By default, it's set to use {@link com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore} which * stores all checkpoint offsets into Azure Blob Storage. */ public CheckpointStore getCheckpointStore() { return checkpointStore; } public void setCheckpointStore(CheckpointStore checkpointStore) { this.checkpointStore = checkpointStore; } /** * In case you chose the default BlobCheckpointStore, this sets Azure account name to be used for authentication * with azure blob services. */ public String getBlobAccountName() { return blobAccountName; } public void setBlobAccountName(String blobAccountName) { this.blobAccountName = blobAccountName; } /** * In case you chose the default BlobCheckpointStore, this sets access key for the associated azure account name to * be used for authentication with azure blob services. */ public String getBlobAccessKey() { return blobAccessKey; } public void setBlobAccessKey(String blobAccessKey) { this.blobAccessKey = blobAccessKey; } /** * In case you chose the default BlobCheckpointStore, this sets the blob container that shall be used by the * BlobCheckpointStore to store the checkpoint offsets. */ public String getBlobContainerName() { return blobContainerName; } public void setBlobContainerName(String blobContainerName) { this.blobContainerName = blobContainerName; } /** * In case you chose the default BlobCheckpointStore, StorageSharedKeyCredential can be injected to create the azure * client, this holds the important authentication information. */ public StorageSharedKeyCredential getBlobStorageSharedKeyCredential() { return blobStorageSharedKeyCredential; } public void setBlobStorageSharedKeyCredential(StorageSharedKeyCredential blobStorageSharedKeyCredential) { this.blobStorageSharedKeyCredential = blobStorageSharedKeyCredential; } /** * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not * exist in {@link CheckpointStore}. This map is keyed off of the partition id. If there is no checkpoint in * {@link CheckpointStore} and there is no entry in this map, the processing of the partition will start from * {@link EventPosition#latest()} position. */ public Map<String, EventPosition> getEventPosition() { return eventPosition; } public void setEventPosition(Map<String, EventPosition> eventPosition) { this.eventPosition = eventPosition; } public int getCheckpointBatchSize() { return checkpointBatchSize; } /** * Sets the batch size between each checkpoint update. Works jointly with {@link #checkpointBatchTimeout}. */ public void setCheckpointBatchSize(int checkpointBatchSize) { this.checkpointBatchSize = checkpointBatchSize; } public int getCheckpointBatchTimeout() { return checkpointBatchTimeout; } /** * Sets the batch timeout between each checkpoint update. Works jointly with {@link #checkpointBatchSize}. */ public void setCheckpointBatchTimeout(int checkpointBatchTimeout) { this.checkpointBatchTimeout = checkpointBatchTimeout; } public CredentialType getCredentialType() { return credentialType; } /** * Determines the credential strategy to adopt */ public void setCredentialType(CredentialType credentialType) { this.credentialType = credentialType; } public EventHubsConfiguration copy() { try { return (EventHubsConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
EventHubsConfiguration
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/CompoundProjectExecutionListener.java
{ "start": 1072, "end": 2400 }
class ____ implements ProjectExecutionListener { private final Collection<ProjectExecutionListener> listeners; public CompoundProjectExecutionListener(Collection<ProjectExecutionListener> listeners) { this.listeners = listeners; // NB this is live injected collection } @Override public void beforeProjectExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { for (ProjectExecutionListener listener : listeners) { listener.beforeProjectExecution(event); } } @Override public void beforeProjectLifecycleExecution(ProjectExecutionEvent event) throws LifecycleExecutionException { for (ProjectExecutionListener listener : listeners) { listener.beforeProjectLifecycleExecution(event); } } @Override public void afterProjectExecutionSuccess(ProjectExecutionEvent event) throws LifecycleExecutionException { for (ProjectExecutionListener listener : listeners) { listener.afterProjectExecutionSuccess(event); } } @Override public void afterProjectExecutionFailure(ProjectExecutionEvent event) { for (ProjectExecutionListener listener : listeners) { listener.afterProjectExecutionFailure(event); } } }
CompoundProjectExecutionListener
java
apache__camel
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaBreakOnFirstErrorOffUsingKafkaManualCommitIT.java
{ "start": 2298, "end": 6633 }
class ____ extends BaseKafkaTestSupport { public static final String ROUTE_ID = "breakOnFirstErrorOff"; public static final String TOPIC = "breakOnFirstErrorOff"; private static final Logger LOG = LoggerFactory.getLogger(KafkaBreakOnFirstErrorOffUsingKafkaManualCommitIT.class); @EndpointInject("mock:result") private MockEndpoint to; private org.apache.kafka.clients.producer.KafkaProducer<String, String> producer; @BeforeEach public void before() { Properties props = getDefaultProperties(); producer = new org.apache.kafka.clients.producer.KafkaProducer<>(props); MockConsumerInterceptor.recordsCaptured.clear(); } @AfterEach public void after() { if (producer != null) { producer.close(); } // clean all test topics kafkaAdminClient.deleteTopics(Collections.singletonList(TOPIC)).all(); } /** * will continue to retry the message that is in error */ @Test public void kafkaBreakOnFirstErrorBasicCapability() throws Exception { to.reset(); to.expectedMessageCount(4); // message-3 and message-4 were never committed // by the consumer route // but we moved past them anyway // because breakOnFirstError was false // then when we encounter a successful message // we commit that one and keep going to.expectedBodiesReceivedInAnyOrder("message-0", "message-1", "message-2", "message-5"); contextExtension.getContext().getRouteController().stopRoute(ROUTE_ID); this.publishMessagesToKafka(); contextExtension.getContext().getRouteController().startRoute(ROUTE_ID); Awaitility.await() .atMost(30, TimeUnit.SECONDS) // changed to 30 sec for CAMEL-20722 .until(() -> to.getExchanges().size() > 3); to.assertIsSatisfied(3000); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { fromF("kafka:%s" + "?groupId=breakOnFirstErrorOff" + "&autoOffsetReset=earliest" + "&autoCommitEnable=false" + "&allowManualCommit=true" // set BOFE to false + "&breakOnFirstError=false" + "&maxPollRecords=1" + "&pollTimeoutMs=1000" + "&keyDeserializer=org.apache.kafka.common.serialization.StringDeserializer" + "&valueDeserializer=org.apache.kafka.common.serialization.StringDeserializer" + "&interceptorClasses=org.apache.camel.component.kafka.MockConsumerInterceptor", TOPIC) .routeId(ROUTE_ID) .process(exchange -> { LOG.debug(CamelKafkaUtil.buildKafkaLogMessage("Consuming", exchange, true)); }) .process(exchange -> { ifIsPayloadWithErrorThrowException(exchange); }) .to(to) .process(exchange -> { doCommitOffset(exchange); }); } }; } private void publishMessagesToKafka() { for (int i = 0; i < 6; i++) { String msg = "message-" + i; ProducerRecord<String, String> data = new ProducerRecord<>(TOPIC, null, msg); producer.send(data); } } private void doCommitOffset(Exchange exchange) { LOG.debug(CamelKafkaUtil.buildKafkaLogMessage("Committing", exchange, true)); KafkaManualCommit manual = exchange.getMessage() .getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); assertNotNull(manual); manual.commit(); } private void ifIsPayloadWithErrorThrowException(Exchange exchange) { String payload = exchange.getMessage().getBody(String.class); if (payload.equals("message-3") || payload.equals("message-4")) { throw new RuntimeException("ERROR TRIGGERED BY TEST"); } } }
KafkaBreakOnFirstErrorOffUsingKafkaManualCommitIT
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/support/ExecutorSubscribableChannelTests.java
{ "start": 8042, "end": 8311 }
class ____ extends AbstractTestInterceptor { @Override public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { super.beforeHandle(message, channel, handler); return null; } } }
NullReturningBeforeHandleInterceptor
java
quarkusio__quarkus
extensions/amazon-lambda/deployment/src/main/java/io/quarkus/amazon/lambda/deployment/AmazonLambdaProcessor.java
{ "start": 4878, "end": 12992 }
class ____ the " + providedLambda.get().getProvider() + " extension. Please remove one of them from your deployment.", List.of()); } AdditionalBeanBuildItem.Builder additionalBeansBuilder = AdditionalBeanBuildItem.builder().setUnremovable(); List<AmazonLambdaBuildItem> amazonLambdas = new ArrayList<>(); for (ClassInfo requestHandler : requestHandlers) { if (requestHandler.isAbstract()) { continue; } additionalBeansBuilder.addBeanClass(requestHandler.name().toString()); amazonLambdas.add(new AmazonLambdaBuildItem(requestHandler.name().toString(), getCdiName(requestHandler), false)); } for (ClassInfo streamHandler : streamHandlers) { if (streamHandler.isAbstract()) { continue; } additionalBeansBuilder.addBeanClass(streamHandler.name().toString()); amazonLambdas.add(new AmazonLambdaBuildItem(streamHandler.name().toString(), getCdiName(streamHandler), true)); } additionalBeanBuildItemBuildProducer.produce(additionalBeansBuilder.build()); reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(FunctionError.class).methods().fields() .reason(getClass().getName()) .build()); return amazonLambdas; } @BuildStep void processProvidedLambda(Optional<ProvidedAmazonLambdaHandlerBuildItem> providedLambda, BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer) { if (!providedLambda.isPresent()) return; AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable(); Class handlerClass = providedLambda.get().getHandlerClass(); builder.addBeanClass(handlerClass); additionalBeanBuildItemBuildProducer.produce(builder.build()); reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(handlerClass).methods().fields() .reason(getClass().getName()) .build()); // TODO // This really isn't good enough. We should recursively add reflection for all method and field types of the parameter // and return type. Otherwise Jackson won't work. In AWS Lambda HTTP extension, the whole jackson model is registered // for reflection. Shouldn't have to do this. for (Method method : handlerClass.getMethods()) { if (method.getName().equals("handleRequest") && method.getParameterCount() == 2) { Class<?>[] parameterTypes = method.getParameterTypes(); if (!parameterTypes[0].equals(Object.class)) { reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(parameterTypes[0].getName()) .reason(getClass().getName() + " > " + method.getName() + " first parameter type") .methods().fields().build()); reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(method.getReturnType().getName()) .reason(getClass().getName() + " > " + method.getName() + " return type") .methods().fields().build()); reflectiveClassBuildItemBuildProducer .produce(ReflectiveClassBuildItem.builder(DateTime.class) .reason(getClass().getName()) .methods().fields().build()); break; } } } } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void recordStaticInitHandlerClass(CombinedIndexBuildItem index, List<AmazonLambdaBuildItem> lambdas, LambdaObjectMapperInitializedBuildItem mapper, // ordering! Optional<ProvidedAmazonLambdaHandlerBuildItem> providedLambda, AmazonLambdaStaticRecorder recorder, RecorderContext context, BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchies) { // can set handler within static initialization if only one handler exists in deployment if (providedLambda.isPresent()) { boolean useStreamHandler = false; for (Class handleInterface : providedLambda.get().getHandlerClass().getInterfaces()) { if (handleInterface.getName().equals(RequestStreamHandler.class.getName())) { useStreamHandler = true; break; } } if (useStreamHandler) { Class<? extends RequestStreamHandler> handlerClass = (Class<? extends RequestStreamHandler>) context .classProxy(providedLambda.get().getHandlerClass().getName()); recorder.setStreamHandlerClass(handlerClass); } else { RequestHandlerJandexDefinition requestHandlerJandexDefinition = RequestHandlerJandexUtil .discoverHandlerMethod(providedLambda.get().getHandlerClass().getName(), index.getComputingIndex()); registerForReflection(requestHandlerJandexDefinition, reflectiveMethods, reflectiveHierarchies); recorder.setHandlerClass(toRequestHandlerDefinition(requestHandlerJandexDefinition, context)); } } else if (lambdas != null && lambdas.size() == 1) { AmazonLambdaBuildItem item = lambdas.get(0); if (item.isStreamHandler()) { Class<? extends RequestStreamHandler> handlerClass = (Class<? extends RequestStreamHandler>) context .classProxy(item.getHandlerClass()); recorder.setStreamHandlerClass(handlerClass); } else { RequestHandlerJandexDefinition requestHandlerJandexDefinition = RequestHandlerJandexUtil .discoverHandlerMethod(item.getHandlerClass(), index.getComputingIndex()); registerForReflection(requestHandlerJandexDefinition, reflectiveMethods, reflectiveHierarchies); recorder.setHandlerClass(toRequestHandlerDefinition(requestHandlerJandexDefinition, context)); } } else if (lambdas == null || lambdas.isEmpty()) { String errorMessage = "Unable to find handler class, make sure your deployment includes a single " + RequestHandler.class.getName() + " or " + RequestStreamHandler.class.getName() + " implementation"; throw new RuntimeException(errorMessage); } } @BuildStep @Record(ExecutionTime.RUNTIME_INIT) public void recordBeanContainer(BeanContainerBuildItem beanContainerBuildItem, AmazonLambdaRecorder recorder, // try to order this after service recorders List<ServiceStartBuildItem> orderServicesFirst) { recorder.setBeanContainer(beanContainerBuildItem.getValue()); } @BuildStep @Record(ExecutionTime.RUNTIME_INIT) public void recordHandlerClass(CombinedIndexBuildItem index, List<AmazonLambdaBuildItem> lambdas, Optional<ProvidedAmazonLambdaHandlerBuildItem> providedLambda, BeanContainerBuildItem beanContainerBuildItem, AmazonLambdaRecorder recorder, List<ServiceStartBuildItem> orderServicesFirst, // try to order this after service recorders RecorderContext context, BuildProducer<ReflectiveMethodBuildItem> reflectiveMethods, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchies) { // Have to set lambda
and
java
elastic__elasticsearch
x-pack/plugin/downsample/qa/rest/src/yamlRestTest/java/org/elasticsearch/xpack/downsample/DownsampleRestIT.java
{ "start": 601, "end": 1642 }
class ____ extends ESClientYamlSuiteTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local() .module("x-pack-downsample") .module("x-pack-ilm") .module("lang-painless") .module("aggregations") // for auto_date_histogram .module("mapper-extras") // for scaled_float .module("x-pack-analytics") // for histogram .module("data-streams") // for time series .module("ingest-common") .setting("xpack.license.self_generated.type", "trial") .setting("xpack.security.enabled", "false") .build(); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } public DownsampleRestIT(final ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return ESClientYamlSuiteTestCase.createParameters("downsample"); } }
DownsampleRestIT
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/ingest/GetPipelineResponse.java
{ "start": 1080, "end": 5499 }
class ____ extends ActionResponse implements ToXContentObject { private final List<PipelineConfiguration> pipelines; private final boolean summary; public GetPipelineResponse(List<PipelineConfiguration> pipelines, boolean summary) { this.pipelines = pipelines; this.summary = summary; } public GetPipelineResponse(List<PipelineConfiguration> pipelines) { this(pipelines, false); } /** * Get the list of pipelines that were a part of this response. * The pipeline id can be obtained using getId on the PipelineConfiguration object. * @return A list of {@link PipelineConfiguration} objects. */ public List<PipelineConfiguration> pipelines() { return Collections.unmodifiableList(pipelines); } /** * NB prior to 9.0 this was a TransportMasterNodeReadAction so for BwC we must remain able to read these requests until * we no longer need to support calling this action remotely. */ @UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) @Override public void writeTo(StreamOutput out) throws IOException { out.writeCollection(pipelines); out.writeBoolean(summary); } public boolean isFound() { return pipelines.isEmpty() == false; } public boolean isSummary() { return summary; } public RestStatus status() { return isFound() ? RestStatus.OK : RestStatus.NOT_FOUND; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); for (PipelineConfiguration pipeline : pipelines) { builder.startObject(pipeline.getId()); for (final Map.Entry<String, Object> configProperty : (summary ? Map.<String, Object>of() : pipeline.getConfig()).entrySet()) { if (Pipeline.CREATED_DATE_MILLIS.equals(configProperty.getKey())) { builder.timestampFieldsFromUnixEpochMillis( Pipeline.CREATED_DATE_MILLIS, Pipeline.CREATED_DATE, (Long) configProperty.getValue() ); } else if (Pipeline.MODIFIED_DATE_MILLIS.equals(configProperty.getKey())) { builder.timestampFieldsFromUnixEpochMillis( Pipeline.MODIFIED_DATE_MILLIS, Pipeline.MODIFIED_DATE, (Long) configProperty.getValue() ); } else { builder.field(configProperty.getKey(), configProperty.getValue()); } } builder.endObject(); } builder.endObject(); return builder; } @Override public boolean equals(Object other) { if (other == null) { return false; } else if (other instanceof GetPipelineResponse otherResponse) { if (pipelines == null) { return otherResponse.pipelines == null; } else { // We need a map here because order does not matter for equality Map<String, PipelineConfiguration> otherPipelineMap = new HashMap<>(); for (PipelineConfiguration pipeline : otherResponse.pipelines) { otherPipelineMap.put(pipeline.getId(), pipeline); } for (PipelineConfiguration pipeline : pipelines) { PipelineConfiguration otherPipeline = otherPipelineMap.get(pipeline.getId()); if (pipeline.equals(otherPipeline) == false) { return false; } otherPipelineMap.remove(pipeline.getId()); } if (otherPipelineMap.isEmpty() == false) { return false; } return true; } } else { return false; } } @Override public String toString() { return Strings.toString(this); } @Override public int hashCode() { int result = 1; for (PipelineConfiguration pipeline : pipelines) { // We only take the sum here to ensure that the order does not matter. result += (pipeline == null ? 0 : pipeline.hashCode()); } return result; } }
GetPipelineResponse
java
spring-projects__spring-boot
module/spring-boot-data-commons/src/test/java/org/springframework/boot/data/autoconfigure/metrics/DataRepositoryMetricsAutoConfigurationTests.java
{ "start": 7069, "end": 7233 }
class ____ { @Bean TestRepositoryTagsProvider tagsProvider() { return new TestRepositoryTagsProvider(); } } private static final
TagsProviderConfiguration
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/request/GoogleVertexAiRerankRequestTests.java
{ "start": 1099, "end": 6964 }
class ____ extends ESTestCase { private static final String AUTH_HEADER_VALUE = "foo"; public void testCreateRequest_WithMinimalFieldsSet() throws IOException { var input = "input"; var query = "query"; var request = createRequest(query, input, null, null, null, null); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is(AUTH_HEADER_VALUE)); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap, aMapWithSize(2)); assertThat(requestMap.get("records"), is(List.of(Map.of("id", "0", "content", input)))); assertThat(requestMap.get("query"), is(query)); } public void testCreateRequest_WithTopNSet() throws IOException { var input = "input"; var query = "query"; var topN = 1; var taskSettingsTopN = 3; var request = createRequest(query, input, null, topN, null, taskSettingsTopN); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is(AUTH_HEADER_VALUE)); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap, aMapWithSize(3)); assertThat(requestMap.get("records"), is(List.of(Map.of("id", "0", "content", input)))); assertThat(requestMap.get("query"), is(query)); assertThat(requestMap.get("topN"), is(topN)); } public void testCreateRequest_UsesTaskSettingsTopNWhenRootLevelIsNull() throws IOException { var input = "input"; var query = "query"; var topN = 1; var request = createRequest(query, input, null, null, null, topN); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is(AUTH_HEADER_VALUE)); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap, aMapWithSize(3)); assertThat(requestMap.get("records"), is(List.of(Map.of("id", "0", "content", input)))); assertThat(requestMap.get("query"), is(query)); assertThat(requestMap.get("topN"), is(topN)); } public void testCreateRequest_WithReturnDocumentsSet() throws IOException { var input = "input"; var query = "query"; var request = createRequest(query, input, null, null, Boolean.TRUE, null); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is(AUTH_HEADER_VALUE)); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap, aMapWithSize(3)); assertThat(requestMap.get("records"), is(List.of(Map.of("id", "0", "content", input)))); assertThat(requestMap.get("query"), is(query)); assertThat(requestMap.get("ignoreRecordDetailsInResponse"), is(Boolean.FALSE)); } public void testCreateRequest_WithModelSet() throws IOException { var input = "input"; var query = "query"; var modelId = "model"; var request = createRequest(query, input, modelId, null, null, null); var httpRequest = request.createHttpRequest(); assertThat(httpRequest.httpRequestBase(), instanceOf(HttpPost.class)); var httpPost = (HttpPost) httpRequest.httpRequestBase(); assertThat(httpPost.getLastHeader(HttpHeaders.CONTENT_TYPE).getValue(), is(XContentType.JSON.mediaType())); assertThat(httpPost.getLastHeader(HttpHeaders.AUTHORIZATION).getValue(), is(AUTH_HEADER_VALUE)); var requestMap = entityAsMap(httpPost.getEntity().getContent()); assertThat(requestMap, aMapWithSize(3)); assertThat(requestMap.get("records"), is(List.of(Map.of("id", "0", "content", input)))); assertThat(requestMap.get("query"), is(query)); assertThat(requestMap.get("model"), is(modelId)); } public void testTruncate_DoesNotTruncate() { var request = createRequest("query", "input", null, null, null, null); var truncatedRequest = request.truncate(); assertThat(truncatedRequest, sameInstance(request)); } private static GoogleVertexAiRerankRequest createRequest( String query, String input, @Nullable String modelId, @Nullable Integer topN, @Nullable Boolean returnDocuments, @Nullable Integer taskSettingsTopN ) { var rerankModel = GoogleVertexAiRerankModelTests.createModel(modelId, taskSettingsTopN); return new GoogleVertexAiRerankWithoutAuthRequest(query, List.of(input), rerankModel, topN, returnDocuments); } /** * We use this
GoogleVertexAiRerankRequestTests
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/dynamic/ReactiveTypeAdapters.java
{ "start": 15077, "end": 15469 }
enum ____ implements Function<io.reactivex.Completable, Publisher<?>> { INSTANCE; @Override public Publisher<?> apply(io.reactivex.Completable source) { return source.toFlowable(); } } /** * An adapter {@link Function} to adopt a {@link io.reactivex.Completable} to {@link Mono}. */ public
RxJava2CompletableToPublisherAdapter
java
apache__camel
components/camel-infinispan/camel-infinispan/src/main/java/org/apache/camel/component/infinispan/remote/transform/InfinispanEmbeddingsDataTypeTransformer.java
{ "start": 1847, "end": 4909 }
class ____ extends Transformer { private static final Set<InfinispanOperation> ALLOWED_EMBEDDING_OPERATIONS = Set.of(InfinispanOperation.PUT, InfinispanOperation.PUTASYNC, InfinispanOperation.PUTIFABSENT, InfinispanOperation.PUTIFABSENTASYNC, InfinispanOperation.REPLACE, InfinispanOperation.REPLACEASYNC, InfinispanOperation.QUERY); @Override public void transform(Message message, DataType from, DataType to) throws Exception { InfinispanOperation operation = message.getHeader(InfinispanConstants.OPERATION, InfinispanOperation.PUT, InfinispanOperation.class); Embedding embedding = message.getHeader(CamelLangchain4jAttributes.CAMEL_LANGCHAIN4J_EMBEDDING_VECTOR, Embedding.class); if (ALLOWED_EMBEDDING_OPERATIONS.contains(operation) && embedding != null) { if (operation.equals(InfinispanOperation.QUERY)) { InfinispanQueryBuilder builder = message.getHeader(InfinispanConstants.QUERY_BUILDER, InfinispanQueryBuilder.class); if (builder == null) { message.setHeader(InfinispanConstants.QUERY_BUILDER, new InfinispanVectorQueryBuilder(embedding.vector())); } } else { String text = null; List<String> metadataKeys = null; List<String> metadataValues = null; TextSegment textSegment = message.getHeader(CamelLangchain4jAttributes.CAMEL_LANGCHAIN4J_TEXT_SEGMENT, TextSegment.class); if (textSegment != null) { text = textSegment.text(); metadataKeys = new ArrayList<>(); metadataValues = new ArrayList<>(); Map<String, Object> metadata = textSegment.metadata().toMap(); for (Map.Entry<String, Object> entry : metadata.entrySet()) { metadataKeys.add(entry.getKey()); metadataValues.add(entry.getValue().toString()); } } InfinispanRemoteEmbedding item = new InfinispanRemoteEmbedding( message.getMessageId(), embedding.vector(), text, metadataKeys, metadataValues); if (operation.equals(InfinispanOperation.REPLACE) || operation.equals(InfinispanOperation.REPLACEASYNC)) { InfinispanRemoteEmbedding oldValue = message.getHeader(InfinispanConstants.OLD_VALUE, InfinispanRemoteEmbedding.class); if (oldValue != null) { message.setHeader(InfinispanConstants.KEY, oldValue.getId()); } } else { message.setHeader(InfinispanConstants.KEY, message.getMessageId()); } message.setHeader(InfinispanConstants.VALUE, item); } } } }
InfinispanEmbeddingsDataTypeTransformer
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/EmptyStateIndexRemover.java
{ "start": 1182, "end": 4629 }
class ____ implements MlDataRemover { private final OriginSettingClient client; private final TaskId parentTaskId; public EmptyStateIndexRemover(OriginSettingClient client, TaskId parentTaskId) { this.client = Objects.requireNonNull(client); this.parentTaskId = parentTaskId; } @Override public void remove(float requestsPerSec, ActionListener<Boolean> listener, BooleanSupplier isTimedOutSupplier) { try { if (isTimedOutSupplier.getAsBoolean()) { listener.onResponse(false); return; } getEmptyStateIndices(listener.delegateFailureAndWrap((delegate, emptyStateIndices) -> { if (emptyStateIndices.isEmpty()) { delegate.onResponse(true); return; } getCurrentStateIndices(delegate.delegateFailureAndWrap((l, currentStateIndices) -> { Set<String> stateIndicesToRemove = Sets.difference(emptyStateIndices, currentStateIndices); if (stateIndicesToRemove.isEmpty()) { l.onResponse(true); return; } executeDeleteEmptyStateIndices(stateIndicesToRemove, l); })); })); } catch (Exception e) { listener.onFailure(e); } } private void getEmptyStateIndices(ActionListener<Set<String>> listener) { IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest().indices(AnomalyDetectorsIndex.jobStateIndexPattern()); indicesStatsRequest.setParentTask(parentTaskId); client.admin() .indices() .stats( indicesStatsRequest, listener.delegateFailureAndWrap( (l, indicesStatsResponse) -> l.onResponse( indicesStatsResponse.getIndices() .values() .stream() .filter(stats -> stats.getTotal().getDocs() == null || stats.getTotal().getDocs().getCount() == 0) .map(IndexStats::getIndex) .collect(toSet()) ) ) ); } private void getCurrentStateIndices(ActionListener<Set<String>> listener) { GetIndexRequest getIndexRequest = new GetIndexRequest(MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT).indices( AnomalyDetectorsIndex.jobStateIndexWriteAlias() ); getIndexRequest.setParentTask(parentTaskId); client.admin() .indices() .getIndex( getIndexRequest, listener.delegateFailureAndWrap((l, getIndexResponse) -> l.onResponse(Set.of(getIndexResponse.getIndices()))) ); } private void executeDeleteEmptyStateIndices(Set<String> emptyStateIndices, ActionListener<Boolean> listener) { DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(emptyStateIndices.toArray(new String[0])); deleteIndexRequest.setParentTask(parentTaskId); client.admin() .indices() .delete( deleteIndexRequest, listener.delegateFailureAndWrap((l, deleteResponse) -> l.onResponse(deleteResponse.isAcknowledged())) ); } }
EmptyStateIndexRemover
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.java
{ "start": 3357, "end": 11318 }
class ____ implements ReactiveOAuth2AuthorizedClientManager { private static final ReactiveOAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = ReactiveOAuth2AuthorizedClientProviderBuilder .builder() .clientCredentials() .build(); private final ReactiveClientRegistrationRepository clientRegistrationRepository; private final ReactiveOAuth2AuthorizedClientService authorizedClientService; private ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER; private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper = new DefaultContextAttributesMapper(); private ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler; private ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler; /** * Constructs an {@code AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager} * using the provided parameters. * @param clientRegistrationRepository the repository of client registrations * @param authorizedClientService the authorized client service */ public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( ReactiveClientRegistrationRepository clientRegistrationRepository, ReactiveOAuth2AuthorizedClientService authorizedClientService) { Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); Assert.notNull(authorizedClientService, "authorizedClientService cannot be null"); this.clientRegistrationRepository = clientRegistrationRepository; this.authorizedClientService = authorizedClientService; this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientService .saveAuthorizedClient(authorizedClient, principal); this.authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler( (clientRegistrationId, principal, attributes) -> this.authorizedClientService .removeAuthorizedClient(clientRegistrationId, principal.getName())); } @Override public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) { Assert.notNull(authorizeRequest, "authorizeRequest cannot be null"); return createAuthorizationContext(authorizeRequest) .flatMap((authorizationContext) -> authorize(authorizationContext, authorizeRequest.getPrincipal())); } private Mono<OAuth2AuthorizationContext> createAuthorizationContext(OAuth2AuthorizeRequest authorizeRequest) { String clientRegistrationId = authorizeRequest.getClientRegistrationId(); Authentication principal = authorizeRequest.getPrincipal(); return Mono.justOrEmpty(authorizeRequest.getAuthorizedClient()) .map(OAuth2AuthorizationContext::withAuthorizedClient) .switchIfEmpty(Mono.defer(() -> this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId) .flatMap((clientRegistration) -> this.authorizedClientService .loadAuthorizedClient(clientRegistrationId, principal.getName()) .map(OAuth2AuthorizationContext::withAuthorizedClient) .switchIfEmpty(Mono .fromSupplier(() -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration)))) .switchIfEmpty(Mono.error(() -> new IllegalArgumentException( "Could not find ClientRegistration with id '" + clientRegistrationId + "'"))))) .flatMap((contextBuilder) -> this.contextAttributesMapper.apply(authorizeRequest) .defaultIfEmpty(Collections.emptyMap()) .map((contextAttributes) -> { OAuth2AuthorizationContext.Builder builder = contextBuilder.principal(principal); if (!contextAttributes.isEmpty()) { builder = builder.attributes((attributes) -> attributes.putAll(contextAttributes)); } return builder.build(); })); } /** * Performs authorization and then delegates to either the * {@link #authorizationSuccessHandler} or {@link #authorizationFailureHandler}, * depending on the authorization result. * @param authorizationContext the context to authorize * @param principal the principle to authorize * @return a {@link Mono} that emits the authorized client after the authorization * attempt succeeds and the {@link #authorizationSuccessHandler} has completed, or * completes with an exception after the authorization attempt fails and the * {@link #authorizationFailureHandler} has completed */ private Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext authorizationContext, Authentication principal) { return this.authorizedClientProvider.authorize(authorizationContext) // Delegate to the authorizationSuccessHandler of the successful // authorization .flatMap((authorizedClient) -> this.authorizationSuccessHandler .onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap()) .thenReturn(authorizedClient)) // Delegate to the authorizationFailureHandler of the failed authorization .onErrorResume(OAuth2AuthorizationException.class, (authorizationException) -> this.authorizationFailureHandler .onAuthorizationFailure(authorizationException, principal, Collections.emptyMap()) .then(Mono.error(authorizationException))) .switchIfEmpty(Mono.defer(() -> Mono.justOrEmpty(authorizationContext.getAuthorizedClient()))); } /** * Sets the {@link ReactiveOAuth2AuthorizedClientProvider} used for authorizing (or * re-authorizing) an OAuth 2.0 Client. * @param authorizedClientProvider the {@link ReactiveOAuth2AuthorizedClientProvider} * used for authorizing (or re-authorizing) an OAuth 2.0 Client */ public void setAuthorizedClientProvider(ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider) { Assert.notNull(authorizedClientProvider, "authorizedClientProvider cannot be null"); this.authorizedClientProvider = authorizedClientProvider; } /** * Sets the {@code Function} used for mapping attribute(s) from the * {@link OAuth2AuthorizeRequest} to a {@code Map} of attributes to be associated to * the {@link OAuth2AuthorizationContext#getAttributes() authorization context}. * @param contextAttributesMapper the {@code Function} used for supplying the * {@code Map} of attributes to the {@link OAuth2AuthorizationContext#getAttributes() * authorization context} */ public void setContextAttributesMapper( Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper) { Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null"); this.contextAttributesMapper = contextAttributesMapper; } /** * Sets the handler that handles successful authorizations. * * The default saves {@link OAuth2AuthorizedClient}s in the * {@link ReactiveOAuth2AuthorizedClientService}. * @param authorizationSuccessHandler the handler that handles successful * authorizations. * @since 5.3 */ public void setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler) { Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null"); this.authorizationSuccessHandler = authorizationSuccessHandler; } /** * Sets the handler that handles authorization failures. * * <p> * A {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} is used * by default. * </p> * @param authorizationFailureHandler the handler that handles authorization failures. * @since 5.3 * @see RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler */ public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) { Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null"); this.authorizationFailureHandler = authorizationFailureHandler; } /** * The default implementation of the {@link #setContextAttributesMapper(Function) * contextAttributesMapper}. */ public static
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
java
micronaut-projects__micronaut-core
http-netty/src/main/java/io/micronaut/http/netty/channel/loom/LoomCarrierGroup.java
{ "start": 23004, "end": 23300 }
class ____ extends Event { static final ContinuationScheduled INSTANCE = new ContinuationScheduled(); long hashCode; String virtualThreadName; int scheduleMode; int queueDepth; } @StackTrace(false) @Enabled(false) static
ContinuationScheduled
java
google__jimfs
jimfs/src/main/java/com/google/common/jimfs/SystemJimfsFileSystemProvider.java
{ "start": 3987, "end": 6659 }
class ____ only for use by Java itself. */ @Deprecated public SystemJimfsFileSystemProvider() {} // a public, no-arg constructor is required @Override public String getScheme() { return URI_SCHEME; } @Override public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException { checkArgument( uri.getScheme().equalsIgnoreCase(URI_SCHEME), "uri (%s) scheme must be '%s'", uri, URI_SCHEME); checkArgument( isValidFileSystemUri(uri), "uri (%s) may not have a path, query or fragment", uri); checkArgument( env.get(FILE_SYSTEM_KEY) instanceof FileSystem, "env map (%s) must contain key '%s' mapped to an instance of %s", env, FILE_SYSTEM_KEY, FileSystem.class); FileSystem fileSystem = (FileSystem) env.get(FILE_SYSTEM_KEY); if (fileSystems.putIfAbsent(uri, fileSystem) != null) { throw new FileSystemAlreadyExistsException(uri.toString()); } return fileSystem; } @Override public FileSystem getFileSystem(URI uri) { FileSystem fileSystem = fileSystems.get(uri); if (fileSystem == null) { throw new FileSystemNotFoundException(uri.toString()); } return fileSystem; } @Override public Path getPath(URI uri) { checkArgument( URI_SCHEME.equalsIgnoreCase(uri.getScheme()), "uri scheme does not match this provider: %s", uri); String path = uri.getPath(); checkArgument(!isNullOrEmpty(path), "uri must have a path: %s", uri); return toPath(getFileSystem(toFileSystemUri(uri)), uri); } /** * Returns whether or not the given URI is valid as a base file system URI. It must not have a * path, query or fragment. */ private static boolean isValidFileSystemUri(URI uri) { // would like to just check null, but fragment appears to be the empty string when not present return isNullOrEmpty(uri.getPath()) && isNullOrEmpty(uri.getQuery()) && isNullOrEmpty(uri.getFragment()); } /** Returns the given URI with any path, query or fragment stripped off. */ private static URI toFileSystemUri(URI uri) { try { return new URI( uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null); } catch (URISyntaxException e) { throw new AssertionError(e); } } /** Invokes the {@code toPath(URI)} method on the given {@code FileSystem}. */ private static Path toPath(FileSystem fileSystem, URI uri) { // We have to invoke this method by reflection because while the file system should be // an instance of JimfsFileSystem, it may be loaded by a different
is
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleFlashbackQueryTest4.java
{ "start": 882, "end": 1715 }
class ____ extends TestCase { public void test_isEmpty() throws Exception { String sql = "SELECT * FROM employees\n" + "AS OF TIMESTAMP\n" + "TO_TIMESTAMP('2004-04-04 09:30:00', 'YYYY-MM-DD HH:MI:SS')\n" + "WHERE last_name = 'Chung';"; String expect = "SELECT *\n" + "FROM employees\n" + "AS OF TIMESTAMP TO_TIMESTAMP('2004-04-04 09:30:00', 'YYYY-MM-DD HH:MI:SS')\n" + "WHERE last_name = 'Chung';"; OracleStatementParser parser = new OracleStatementParser(sql); SQLSelectStatement stmt = (SQLSelectStatement) parser.parseStatementList().get(0); String text = TestUtils.outputOracle(stmt); assertEquals(expect, text); System.out.println(text); } }
OracleFlashbackQueryTest4
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/state/MapStateDescriptorTest.java
{ "start": 1460, "end": 5775 }
class ____ { @Test void testMapStateDescriptor() throws Exception { TypeSerializer<Integer> keySerializer = new KryoSerializer<>(Integer.class, new SerializerConfigImpl()); TypeSerializer<String> valueSerializer = new KryoSerializer<>(String.class, new SerializerConfigImpl()); MapStateDescriptor<Integer, String> descr = new MapStateDescriptor<>("testName", keySerializer, valueSerializer); assertThat(descr.getName()).isEqualTo("testName"); assertThat(descr.getSerializer()).isNotNull(); assertThat(descr.getSerializer()).isInstanceOf(MapSerializer.class); assertThat(descr.getKeySerializer()).isNotNull(); assertThat(descr.getKeySerializer()).isEqualTo(keySerializer); assertThat(descr.getValueSerializer()).isNotNull(); assertThat(descr.getValueSerializer()).isEqualTo(valueSerializer); MapStateDescriptor<Integer, String> copy = CommonTestUtils.createCopySerializable(descr); assertThat(copy.getName()).isEqualTo("testName"); assertThat(copy.getSerializer()).isNotNull(); assertThat(copy.getSerializer()).isInstanceOf(MapSerializer.class); assertThat(copy.getKeySerializer()).isNotNull(); assertThat(copy.getKeySerializer()).isEqualTo(keySerializer); assertThat(copy.getValueSerializer()).isNotNull(); assertThat(copy.getValueSerializer()).isEqualTo(valueSerializer); } @Test void testHashCodeEquals() throws Exception { final String name = "testName"; MapStateDescriptor<String, String> original = new MapStateDescriptor<>(name, String.class, String.class); MapStateDescriptor<String, String> same = new MapStateDescriptor<>(name, String.class, String.class); MapStateDescriptor<String, String> sameBySerializer = new MapStateDescriptor<>( name, StringSerializer.INSTANCE, StringSerializer.INSTANCE); // test that hashCode() works on state descriptors with initialized and uninitialized // serializers assertThat(same).hasSameHashCodeAs(original); assertThat(sameBySerializer).hasSameHashCodeAs(original); assertThat(same).isEqualTo(original); assertThat(sameBySerializer).isEqualTo(original); // equality with a clone MapStateDescriptor<String, String> clone = CommonTestUtils.createCopySerializable(original); assertThat(clone).isEqualTo(original); // equality with an initialized clone.initializeSerializerUnlessSet(new ExecutionConfig()); assertThat(clone).isEqualTo(original); original.initializeSerializerUnlessSet(new ExecutionConfig()); assertThat(same).isEqualTo(original); } /** * FLINK-6775. * * <p>Tests that the returned serializer is duplicated. This allows to share the state * descriptor. */ @Test void testSerializerDuplication() { // we need a serializer that actually duplicates for testing (a stateful one) // we use Kryo here, because it meets these conditions TypeSerializer<String> keySerializer = new KryoSerializer<>(String.class, new SerializerConfigImpl()); TypeSerializer<Long> valueSerializer = new KryoSerializer<>(Long.class, new SerializerConfigImpl()); MapStateDescriptor<String, Long> descr = new MapStateDescriptor<>("foobar", keySerializer, valueSerializer); TypeSerializer<String> keySerializerA = descr.getKeySerializer(); TypeSerializer<String> keySerializerB = descr.getKeySerializer(); TypeSerializer<Long> valueSerializerA = descr.getValueSerializer(); TypeSerializer<Long> valueSerializerB = descr.getValueSerializer(); // check that we did not retrieve the same serializers assertThat(keySerializerB).isNotSameAs(keySerializerA); assertThat(valueSerializerB).isNotSameAs(valueSerializerA); TypeSerializer<Map<String, Long>> serializerA = descr.getSerializer(); TypeSerializer<Map<String, Long>> serializerB = descr.getSerializer(); assertThat(serializerB).isNotSameAs(serializerA); } }
MapStateDescriptorTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_doesNotContainSubsequence_List_Test.java
{ "start": 1299, "end": 2195 }
class ____ extends IterableAssertBaseTest { @Override protected ConcreteIterableAssert<Object> invoke_api_method() { // IterableAssertBaseTest is testing Iterable<Object>, so the List type needs to be Object // or the {@link AbstractIterableAssert#doesNotContainSubsequence(Object...)} method is called. return assertions.doesNotContainSubsequence(newLinkedHashSet((Object) "Luke", "Leia")); } @Override protected void verify_internal_effects() { verify(iterables).assertDoesNotContainSubsequence(getInfo(assertions), getActual(assertions), array("Luke", "Leia")); } @Test void should_throw_error_if_subsequence_is_null() { assertThatNullPointerException().isThrownBy(() -> { List<Object> nullList = null; assertions.doesNotContainSubsequence(nullList); }).withMessage(nullSubsequence()); } }
IterableAssert_doesNotContainSubsequence_List_Test
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/PrompterException.java
{ "start": 1013, "end": 1332 }
class ____ extends MavenException { public PrompterException(String message) { super(message); } /** * @param message the message to give * @param e the {@link Exception} */ public PrompterException(String message, Exception e) { super(message, e); } }
PrompterException
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/OtherFormData.java
{ "start": 114, "end": 300 }
class ____ extends OtherFormDataBase { public static String staticField = "static"; public final String finalField = "final"; @RestForm public String last; }
OtherFormData
java
netty__netty
codec-redis/src/main/java/io/netty/handler/codec/redis/DefaultBulkStringRedisContent.java
{ "start": 925, "end": 2552 }
class ____ extends DefaultByteBufHolder implements BulkStringRedisContent { /** * Creates a {@link DefaultBulkStringRedisContent} for the given {@code content}. * * @param content the content, can be {@code null}. */ public DefaultBulkStringRedisContent(ByteBuf content) { super(content); } @Override public BulkStringRedisContent copy() { return (BulkStringRedisContent) super.copy(); } @Override public BulkStringRedisContent duplicate() { return (BulkStringRedisContent) super.duplicate(); } @Override public BulkStringRedisContent retainedDuplicate() { return (BulkStringRedisContent) super.retainedDuplicate(); } @Override public BulkStringRedisContent replace(ByteBuf content) { return new DefaultBulkStringRedisContent(content); } @Override public BulkStringRedisContent retain() { super.retain(); return this; } @Override public BulkStringRedisContent retain(int increment) { super.retain(increment); return this; } @Override public BulkStringRedisContent touch() { super.touch(); return this; } @Override public BulkStringRedisContent touch(Object hint) { super.touch(hint); return this; } @Override public String toString() { return new StringBuilder(StringUtil.simpleClassName(this)) .append('[') .append("content=") .append(content()) .append(']').toString(); } }
DefaultBulkStringRedisContent
java
junit-team__junit5
junit-platform-launcher/src/main/java/org/junit/platform/launcher/jfr/FlightRecordingDiscoveryListener.java
{ "start": 3915, "end": 4225 }
class ____ extends DiscoveryEvent { @Label("Engine Id") @Nullable String engineId; @Label("Severity") @Nullable String severity; @Label("Message") @Nullable String message; @Label("Source") @Nullable String source; @Label("Cause") @Nullable String cause; } }
DiscoveryIssueEvent
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/control/http/NacosHttpTpsControlRegistration.java
{ "start": 1077, "end": 1816 }
class ____ { @Bean public FilterRegistrationBean<NacosHttpTpsFilter> tpsFilterRegistration(NacosHttpTpsFilter tpsFilter) { FilterRegistrationBean<NacosHttpTpsFilter> registration = new FilterRegistrationBean<>(); registration.setFilter(tpsFilter); //nacos naming registration.addUrlPatterns("/v1/ns/*", "/v2/ns/*"); //nacos config registration.addUrlPatterns("/v1/cs/*", "/v2/cs/*"); registration.setName("tpsFilter"); registration.setOrder(6); return registration; } @Bean public NacosHttpTpsFilter tpsFilter(ControllerMethodsCache methodsCache) { return new NacosHttpTpsFilter(methodsCache); } }
NacosHttpTpsControlRegistration
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/ai/model/a2a/SecurityScheme.java
{ "start": 821, "end": 1013 }
class ____ extends HashMap<String, Object> { private static final long serialVersionUID = -708604225878249736L; public SecurityScheme() { super(4); } }
SecurityScheme
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/test/java/org/springframework/boot/webmvc/autoconfigure/WebMvcAutoConfigurationTests.java
{ "start": 68385, "end": 68880 }
class ____ { @Bean @Order(-5) ServerHttpMessageConvertersCustomizer customizer1() { return mock(ServerHttpMessageConvertersCustomizer.class); } @Bean @Order(5) ServerHttpMessageConvertersCustomizer customizer2() { return mock(ServerHttpMessageConvertersCustomizer.class); } @Bean @Order(-10) ServerHttpMessageConvertersCustomizer customizer3() { return mock(ServerHttpMessageConvertersCustomizer.class); } } }
ServerHttpMessageConverterCustomizersConfiguration
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/snapshots/SystemResourceSnapshotIT.java
{ "start": 56774, "end": 57501 }
class ____ extends Plugin implements SystemIndexPlugin { public static final String SYSTEM_INDEX_NAME = ".test-system-idx"; @Override public Collection<SystemIndexDescriptor> getSystemIndexDescriptors(Settings settings) { return Collections.singletonList( SystemIndexDescriptorUtils.createUnmanaged(SYSTEM_INDEX_NAME + "*", "System indices for tests") ); } @Override public String getFeatureName() { return SystemIndexTestPlugin.class.getSimpleName(); } @Override public String getFeatureDescription() { return "A simple test plugin"; } } public static
SystemIndexTestPlugin
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
{ "start": 70501, "end": 71279 }
class ____ { private final Object actual = new AtomicStampedReference<>(0, 0); @Test void createAssert() { // WHEN AtomicStampedReferenceAssert<Integer> result = atomicStampedReference(Integer.class).createAssert(actual); // THEN result.hasReference(0); } @Test void createAssert_with_ValueProvider() { // GIVEN ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual); // WHEN AtomicStampedReferenceAssert<Integer> result = atomicStampedReference(Integer.class).createAssert(valueProvider); // THEN result.hasReference(0); verify(valueProvider).apply(parameterizedType(AtomicStampedReference.class, Integer.class)); } } @Nested
AtomicStampedReference_Typed_Factory
java
google__guice
core/src/com/google/inject/multibindings/OptionalBinderBinding.java
{ "start": 1606, "end": 3593 }
interface ____<T> { /** Returns the {@link Key} for this binding. */ Key<T> getKey(); /** * Returns the keys of other bindings that represent this OptionalBinder. This will return an * entry for {@code Optional<com.google.inject.Provider<V>>} and {@code * Optional<jakarta.inject.Provider<V>>}. * * @since 4.2.3 */ Set<Key<?>> getAlternateKeys(); /** * Returns the default binding (set by {@link OptionalBinder#setDefault}) if one exists or null if * no default binding is set. This will throw {@link UnsupportedOperationException} if it is * called on an element retrieved from {@link Elements#getElements}. * * <p>The Binding's type will always match the type Optional's generic type. For example, if * getKey returns a key of {@code Optional<String>}, then this will always return a {@code * Binding<String>}. */ Binding<?> getDefaultBinding(); /** * Returns the actual binding (set by {@link OptionalBinder#setBinding}) or null if not set. This * will throw {@link UnsupportedOperationException} if it is called on an element retrieved from * {@link Elements#getElements}. * * <p>The Binding's type will always match the type Optional's generic type. For example, if * getKey returns a key of {@code Optional<String>}, then this will always return a {@code * Binding<String>}. */ Binding<?> getActualBinding(); /** * Returns true if this OptionalBinder contains the given Element in order to build the optional * binding or uses the given Element in order to support building and injecting its data. This * will work for OptionalBinderBinding retrieved from an injector and {@link * Elements#getElements}. Usually this is only necessary if you are working with elements * retrieved from modules (without an Injector), otherwise {@link #getDefaultBinding} and {@link * #getActualBinding} are better options. */ boolean containsElement(Element element); }
OptionalBinderBinding
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/misc/IPhoneStyleProperty5335Test.java
{ "start": 566, "end": 678 }
class ____ extends DatabindTestUtil { @JsonPropertyOrder({ "aProp" }) static
IPhoneStyleProperty5335Test
java
netty__netty
common/src/main/java/io/netty/util/internal/logging/CommonsLoggerFactory.java
{ "start": 995, "end": 1406 }
class ____ extends InternalLoggerFactory { public static final InternalLoggerFactory INSTANCE = new CommonsLoggerFactory(); /** * @deprecated Use {@link #INSTANCE} instead. */ @Deprecated public CommonsLoggerFactory() { } @Override public InternalLogger newInstance(String name) { return new CommonsLogger(LogFactory.getLog(name), name); } }
CommonsLoggerFactory
java
quarkusio__quarkus
integration-tests/rest-client-reactive-http2/src/main/java/io/quarkus/it/rest/client/http2/multipart/MultipartClient.java
{ "start": 6617, "end": 6881 }
class ____ { @FormParam("file") @PartType(MediaType.APPLICATION_OCTET_STREAM) public Multi<Byte> file; @FormParam("fileName") @PartType(MediaType.TEXT_PLAIN) public String fileName; }
WithMultiByteAsBinaryFile
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/DefaultBeanContext.java
{ "start": 6836, "end": 11233 }
class ____ implements ConfigurableBeanContext permits DefaultApplicationContext { protected static final Logger LOG = LoggerFactory.getLogger(DefaultBeanContext.class); protected static final Logger LOG_LIFECYCLE = LoggerFactory.getLogger(DefaultBeanContext.class.getPackage().getName() + ".lifecycle"); private static final String SCOPED_PROXY_ANN = "io.micronaut.runtime.context.scope.ScopedProxy"; private static final String INTRODUCTION_TYPE = "io.micronaut.aop.Introduction"; private static final Predicate<BeanDefinition<?>> FILTER_OUT_ANY_PROVIDERS = new Predicate<BeanDefinition<?>>() { // Keep anonymous for hot path @Override public boolean test(BeanDefinition<?> candidate) { return candidate.getDeclaredQualifier() == null || !candidate.getDeclaredQualifier().equals(AnyQualifier.INSTANCE); } }; private static final String MSG_COULD_NOT_BE_LOADED = "] could not be loaded: "; public static final String MSG_BEAN_DEFINITION = "Bean definition ["; protected final AtomicBoolean running = new AtomicBoolean(false); protected final AtomicBoolean configured = new AtomicBoolean(false); protected final AtomicBoolean initializing = new AtomicBoolean(false); protected final AtomicBoolean terminating = new AtomicBoolean(false); final @NonNull BeanResolutionTraceMode traceMode; final @NonNull Set<String> tracePatterns; final Map<BeanIdentifier, BeanRegistration<?>> singlesInCreation = new ConcurrentHashMap<>(5); protected final SingletonScope singletonScope = new SingletonScope(); private final BeanContextConfiguration beanContextConfiguration; private final Map<String, List<String>> disabledConfigurations = new ConcurrentHashMap<>(5); private final Map<String, BeanConfiguration> beanConfigurations = new HashMap<>(10); private final Map<BeanKey, Boolean> containsBeanCache = new ConcurrentHashMap<>(30); private final Map<CharSequence, Object> attributes = Collections.synchronizedMap(new HashMap<>(5)); private final Map<BeanKey, CollectionHolder> singletonBeanRegistrations = new ConcurrentHashMap<>(50); private final Map<BeanCandidateKey, Optional<BeanDefinition>> beanConcreteCandidateCache = new ConcurrentLinkedHashMap.Builder<BeanCandidateKey, Optional<BeanDefinition>>().maximumWeightedCapacity(30).build(); private final Map<BeanCandidateKey, Optional<BeanDefinition>> beanProxyTargetCache = new ConcurrentLinkedHashMap.Builder<BeanCandidateKey, Optional<BeanDefinition>>().maximumWeightedCapacity(30).build(); private final Map<Argument, Collection<BeanDefinition>> beanCandidateCache = new ConcurrentLinkedHashMap.Builder<Argument, Collection<BeanDefinition>>().maximumWeightedCapacity(30).build(); private final ClassLoader classLoader; private final Set<Class<?>> thisInterfaces = CollectionUtils.setOf( BeanDefinitionRegistry.class, BeanContext.class, AnnotationMetadataResolver.class, BeanLocator.class, ExecutionHandleLocator.class, ApplicationContext.class, PropertyResolver.class, ValueResolver.class, PropertyPlaceholderResolver.class ); private final CustomScopeRegistry customScopeRegistry; private BeanDefinitionValidator beanValidator; private List<BeanConfiguration> beanConfigurationsList; List<Map.Entry<Class<?>, ListenersSupplier<BeanInitializedEventListener>>> beanInitializedEventListeners; private List<Map.Entry<Class<?>, ListenersSupplier<BeanCreatedEventListener>>> beanCreationEventListeners; private List<Map.Entry<Class<?>, ListenersSupplier<BeanPreDestroyEventListener>>> beanPreDestroyEventListeners; private List<Map.Entry<Class<?>, ListenersSupplier<BeanDestroyedEventListener>>> beanDestroyedEventListeners; private final boolean eventsEnabled; private final boolean eagerBeansEnabled; private ForkJoinTask<?> checkEnabledBeans; protected MutableConversionService conversionService; protected final BeanDefinitionService beanDefinitionProvider; /** * Construct a new bean context using the same classloader that loaded this DefaultBeanContext class. */ public DefaultBeanContext() { this(BeanContext.class.getClassLoader()); } /** * Construct a new bean context with the given
DefaultBeanContext
java
apache__kafka
connect/transforms/src/test/java/org/apache/kafka/connect/transforms/InsertFieldTest.java
{ "start": 1781, "end": 11560 }
class ____ { private final InsertField<SourceRecord> xformKey = new InsertField.Key<>(); private final InsertField<SourceRecord> xformValue = new InsertField.Value<>(); public static Stream<Arguments> data() { return Stream.of( Arguments.of(false, null), Arguments.of(true, 42L) ); } @AfterEach public void teardown() { xformValue.close(); } @Test public void topLevelStructRequired() { xformValue.configure(Map.of("topic.field", "topic_field")); assertThrows(DataException.class, () -> xformValue.apply(new SourceRecord(null, null, "", 0, Schema.INT32_SCHEMA, 42))); } @Test public void copySchemaAndInsertConfiguredFields() { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); xformValue.configure(props); final Schema simpleStructSchema = SchemaBuilder.struct().name("name").version(1).doc("doc").field("magic", Schema.OPTIONAL_INT64_SCHEMA).build(); final Struct simpleStruct = new Struct(simpleStructSchema).put("magic", 42L); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, simpleStructSchema, simpleStruct, 789L); final SourceRecord transformedRecord = xformValue.apply(record); assertEquals(simpleStructSchema.name(), transformedRecord.valueSchema().name()); assertEquals(simpleStructSchema.version(), transformedRecord.valueSchema().version()); assertEquals(simpleStructSchema.doc(), transformedRecord.valueSchema().doc()); assertEquals(Schema.OPTIONAL_INT64_SCHEMA, transformedRecord.valueSchema().field("magic").schema()); assertEquals(42L, ((Struct) transformedRecord.value()).getInt64("magic").longValue()); assertEquals(Schema.STRING_SCHEMA, transformedRecord.valueSchema().field("topic_field").schema()); assertEquals("test", ((Struct) transformedRecord.value()).getString("topic_field")); assertEquals(Schema.OPTIONAL_INT32_SCHEMA, transformedRecord.valueSchema().field("partition_field").schema()); assertEquals(0, ((Struct) transformedRecord.value()).getInt32("partition_field").intValue()); assertEquals(Timestamp.builder().optional().build(), transformedRecord.valueSchema().field("timestamp_field").schema()); assertEquals(789L, ((Date) ((Struct) transformedRecord.value()).get("timestamp_field")).getTime()); assertEquals(Schema.OPTIONAL_STRING_SCHEMA, transformedRecord.valueSchema().field("instance_id").schema()); assertEquals("my-instance-id", ((Struct) transformedRecord.value()).getString("instance_id")); // Exercise caching final SourceRecord transformedRecord2 = xformValue.apply( new SourceRecord(null, null, "test", 1, simpleStructSchema, new Struct(simpleStructSchema))); assertSame(transformedRecord.valueSchema(), transformedRecord2.valueSchema()); } @Test public void schemalessInsertConfiguredFields() { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); xformValue.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, null, Map.of("magic", 42L), 123L); final SourceRecord transformedRecord = xformValue.apply(record); assertEquals(42L, ((Map<?, ?>) transformedRecord.value()).get("magic")); assertEquals("test", ((Map<?, ?>) transformedRecord.value()).get("topic_field")); assertEquals(0, ((Map<?, ?>) transformedRecord.value()).get("partition_field")); assertEquals(123L, ((Map<?, ?>) transformedRecord.value()).get("timestamp_field")); assertEquals("my-instance-id", ((Map<?, ?>) transformedRecord.value()).get("instance_id")); } @Test public void insertConfiguredFieldsIntoTombstoneEventWithoutSchemaLeavesValueUnchanged() { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); xformValue.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null); final SourceRecord transformedRecord = xformValue.apply(record); assertNull(transformedRecord.value()); assertNull(transformedRecord.valueSchema()); } @Test public void insertConfiguredFieldsIntoTombstoneEventWithSchemaLeavesValueUnchanged() { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); xformValue.configure(props); final Schema simpleStructSchema = SchemaBuilder.struct().name("name").version(1).doc("doc").field("magic", Schema.OPTIONAL_INT64_SCHEMA).build(); final SourceRecord record = new SourceRecord(null, null, "test", 0, simpleStructSchema, null); final SourceRecord transformedRecord = xformValue.apply(record); assertNull(transformedRecord.value()); assertEquals(simpleStructSchema, transformedRecord.valueSchema()); } @Test public void insertKeyFieldsIntoTombstoneEvent() { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); xformKey.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, Map.of("magic", 42L), null, null); final SourceRecord transformedRecord = xformKey.apply(record); assertEquals(42L, ((Map<?, ?>) transformedRecord.key()).get("magic")); assertEquals("test", ((Map<?, ?>) transformedRecord.key()).get("topic_field")); assertEquals(0, ((Map<?, ?>) transformedRecord.key()).get("partition_field")); assertNull(((Map<?, ?>) transformedRecord.key()).get("timestamp_field")); assertEquals("my-instance-id", ((Map<?, ?>) transformedRecord.key()).get("instance_id")); assertNull(transformedRecord.value()); } @Test public void insertIntoNullKeyLeavesRecordUnchanged() { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); xformKey.configure(props); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, null, Map.of("magic", 42L)); final SourceRecord transformedRecord = xformKey.apply(record); assertSame(record, transformedRecord); } @Test public void testInsertFieldVersionRetrievedFromAppInfoParser() { assertEquals(AppInfoParser.getVersion(), xformKey.version()); assertEquals(AppInfoParser.getVersion(), xformValue.version()); assertEquals(xformKey.version(), xformValue.version()); } @ParameterizedTest @MethodSource("data") public void testUnsetOptionalField(boolean replaceNullWithDefault, Object expectedValue) { final Map<String, Object> props = new HashMap<>(); props.put("topic.field", "topic_field!"); props.put("partition.field", "partition_field"); props.put("timestamp.field", "timestamp_field?"); props.put("static.field", "instance_id"); props.put("static.value", "my-instance-id"); props.put("replace.null.with.default", replaceNullWithDefault); xformValue.configure(props); Schema magicFieldSchema = SchemaBuilder.int64().optional().defaultValue(42L).build(); final Schema simpleStructSchema = SchemaBuilder.struct().name("name").version(1).doc("doc").field("magic_with_default", magicFieldSchema).build(); final Struct simpleStruct = new Struct(simpleStructSchema).put("magic_with_default", null); final SourceRecord record = new SourceRecord(null, null, "test", 0, null, null, simpleStructSchema, simpleStruct, 789L); final SourceRecord transformedRecord = xformValue.apply(record); assertEquals(simpleStructSchema.name(), transformedRecord.valueSchema().name()); assertEquals(simpleStructSchema.version(), transformedRecord.valueSchema().version()); assertEquals(simpleStructSchema.doc(), transformedRecord.valueSchema().doc()); assertEquals(magicFieldSchema, transformedRecord.valueSchema().field("magic_with_default").schema()); assertEquals(expectedValue, ((Struct) transformedRecord.value()).getInt64("magic_with_default")); } }
InsertFieldTest
java
junit-team__junit5
documentation/src/test/java/example/exception/MultipleHandlersTestCase.java
{ "start": 1124, "end": 1341 }
class ____ implements TestExecutionExceptionHandler { @Override public void handleTestExecutionException(ExtensionContext context, Throwable ex) throws Throwable { throw ex; } } static
FirstExecutedHandler
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/SingletonScope.java
{ "start": 13276, "end": 13363 }
class ____ and attributes. * * @since 3.5.0 */ private static final
name
java
square__retrofit
retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java
{ "start": 53546, "end": 54068 }
class ____ { @GET Call<ResponseBody> method(@Url String url, @Path("hey") String hey) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessageThat() .isEqualTo( "@Path parameters may not be used with @Url. (parameter 'hey')\n" + " for method Example.method"); } } @Test public void getWithPathThenUrlThrows() {
Example
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batchfetch/DynamicBatchFetchTestCase.java
{ "start": 983, "end": 1872 }
class ____ { @Test @JiraKey(value = "HHH-12835") public void batchFetchTest(SessionFactoryScope scope) { scope.inTransaction( session -> { // Having DEFAULT_BATCH_FETCH_SIZE=15 // results in batchSizes = [15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] // Let's create 11 countries so batch size 15 will be used with padded values, // this causes to have to remove 4 elements from list int numberOfCountries = 11; IntStream.range( 0, numberOfCountries ).forEach( i -> { Country c = new Country( "Country " + i ); session.persist( c ); session.persist( new City( "City " + i, c ) ); } ); } ); scope.inTransaction( session -> { List<City> allCities = session.createQuery( "from City", City.class ).list(); // this triggers countries to be fetched in batch assertNotNull( allCities.get( 0 ).getCountry().getName() ); } ); } }
DynamicBatchFetchTestCase
java
elastic__elasticsearch
test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java
{ "start": 2508, "end": 37427 }
class ____ implements HttpHandler { private static final Logger logger = LogManager.getLogger(S3HttpHandler.class); private final String bucket; private final String basePath; private final String bucketAndBasePath; private final ConcurrentMap<String, BytesReference> blobs = new ConcurrentHashMap<>(); private final ConcurrentMap<String, MultipartUpload> uploads = new ConcurrentHashMap<>(); private final ConcurrentMap<String, AtomicInteger> completingUploads = new ConcurrentHashMap<>(); public S3HttpHandler(final String bucket) { this(bucket, null); } public S3HttpHandler(final String bucket, @Nullable final String basePath) { this.bucket = Objects.requireNonNull(bucket); this.basePath = Objects.requireNonNullElse(basePath, ""); this.bucketAndBasePath = bucket + (Strings.hasText(basePath) ? "/" + basePath : ""); } /** * Requests using these HTTP methods never have a request body (this is checked in the handler). */ private static final Set<String> METHODS_HAVING_NO_REQUEST_BODY = Set.of("GET", "HEAD", "DELETE"); private static final String SHA_256_ETAG_PREFIX = "es-test-sha-256-"; @Override public void handle(final HttpExchange exchange) throws IOException { // Remove custom query parameters before processing the request. This simulates how S3 ignores them. // https://docs.aws.amazon.com/AmazonS3/latest/userguide/LogFormat.html#LogFormatCustom final S3Request request = parseRequest(exchange); if (METHODS_HAVING_NO_REQUEST_BODY.contains(request.method())) { int read = exchange.getRequestBody().read(); assert read == -1 : "Request body should have been empty but saw [" + read + "]"; } try (exchange) { if (request.isHeadObjectRequest()) { final BytesReference blob = blobs.get(request.path()); if (blob == null) { exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1); } else { exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1); } } else if (request.isListMultipartUploadsRequest()) { final var prefix = request.getQueryParamOnce("prefix"); assert Objects.requireNonNullElse(prefix, "").contains(basePath) : basePath + " vs " + request; final var uploadsList = new StringBuilder(); uploadsList.append("<?xml version='1.0' encoding='UTF-8'?>"); uploadsList.append("<ListMultipartUploadsResult xmlns='http://s3.amazonaws.com/doc/2006-03-01/'>"); uploadsList.append("<Bucket>").append(bucket).append("</Bucket>"); uploadsList.append("<KeyMarker />"); uploadsList.append("<UploadIdMarker />"); uploadsList.append("<NextKeyMarker>--unused--</NextKeyMarker>"); uploadsList.append("<NextUploadIdMarker />"); uploadsList.append("<Delimiter />"); uploadsList.append("<Prefix>").append(prefix).append("</Prefix>"); uploadsList.append("<MaxUploads>10000</MaxUploads>"); uploadsList.append("<IsTruncated>false</IsTruncated>"); synchronized (uploads) { for (final var multipartUpload : uploads.values()) { if (multipartUpload.getPath().startsWith(prefix)) { multipartUpload.appendXml(uploadsList); } } } uploadsList.append("</ListMultipartUploadsResult>"); byte[] response = uploadsList.toString().getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } else if (request.isInitiateMultipartUploadRequest()) { final var upload = putUpload(request.path().substring(bucket.length() + 2)); final var uploadResult = new StringBuilder(); uploadResult.append("<?xml version='1.0' encoding='UTF-8'?>"); uploadResult.append("<InitiateMultipartUploadResult>"); uploadResult.append("<Bucket>").append(bucket).append("</Bucket>"); uploadResult.append("<Key>").append(upload.getPath()).append("</Key>"); uploadResult.append("<UploadId>").append(upload.getUploadId()).append("</UploadId>"); uploadResult.append("</InitiateMultipartUploadResult>"); byte[] response = uploadResult.toString().getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } else if (request.isUploadPartRequest()) { final var upload = getUpload(request.getQueryParamOnce("uploadId")); if (upload == null) { exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1); } else { // CopyPart is UploadPart with an x-amz-copy-source header final var copySource = copySourceName(exchange); if (copySource != null) { var sourceBlob = blobs.get(copySource); if (sourceBlob == null) { exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1); } else { var range = parsePartRange(exchange); int start = Math.toIntExact(range.start()); int len = Math.toIntExact(range.end() - range.start() + 1); var part = sourceBlob.slice(start, len); var etag = UUIDs.randomBase64UUID(); upload.addPart(etag, part); byte[] response = (""" <?xml version="1.0" encoding="UTF-8"?> <CopyPartResult> <ETag>%s</ETag> </CopyPartResult>""".formatted(etag)).getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } } else { final Tuple<String, BytesReference> blob = parseRequestBody(exchange); upload.addPart(blob.v1(), blob.v2()); exchange.getResponseHeaders().add("ETag", blob.v1()); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1); } } } else if (request.isCompleteMultipartUploadRequest()) { final var uploadId = request.getQueryParamOnce("uploadId"); final byte[] responseBody; final RestStatus responseCode; try (var ignoredCompletingUploadRef = setUploadCompleting(uploadId)) { synchronized (uploads) { final var upload = getUpload(request.getQueryParamOnce("uploadId")); if (upload == null) { if (Randomness.get().nextBoolean()) { responseCode = RestStatus.NOT_FOUND; responseBody = null; } else { responseCode = RestStatus.OK; responseBody = """ <?xml version="1.0" encoding="UTF-8"?> <Error> <Code>NoSuchUpload</Code> <Message>No such upload</Message> <RequestId>test-request-id</RequestId> <HostId>test-host-id</HostId> </Error>""".getBytes(StandardCharsets.UTF_8); } } else { final var blobContents = upload.complete(extractPartEtags(Streams.readFully(exchange.getRequestBody()))); responseCode = updateBlobContents(exchange, request.path(), blobContents); if (responseCode == RestStatus.OK) { responseBody = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<CompleteMultipartUploadResult>\n" + "<Bucket>" + bucket + "</Bucket>\n" + "<Key>" + request.path() + "</Key>\n" + "</CompleteMultipartUploadResult>").getBytes(StandardCharsets.UTF_8); } else { responseBody = null; } if (responseCode != RestStatus.PRECONDITION_FAILED) { removeUpload(upload.getUploadId()); } } } } if (responseCode == RestStatus.OK) { exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), responseBody.length); exchange.getResponseBody().write(responseBody); } else { exchange.sendResponseHeaders(responseCode.getStatus(), -1); } } else if (request.isAbortMultipartUploadRequest()) { final var uploadId = request.getQueryParamOnce("uploadId"); if (consistencyModel().hasStrongMultipartUploads() == false && completingUploads.containsKey(uploadId)) { // See AWS support case 176070774900712: aborts may sometimes return early if complete is already in progress exchange.sendResponseHeaders(RestStatus.NO_CONTENT.getStatus(), -1); } else { final var upload = removeUpload(request.getQueryParamOnce("uploadId")); exchange.sendResponseHeaders((upload == null ? RestStatus.NOT_FOUND : RestStatus.NO_CONTENT).getStatus(), -1); } } else if (request.isPutObjectRequest()) { // a copy request is a put request with an X-amz-copy-source header final var copySource = copySourceName(exchange); if (copySource != null) { if (isProtectOverwrite(exchange)) { throw new AssertionError("If-None-Match: * header is not supported here"); } if (getRequiredExistingETag(exchange) != null) { throw new AssertionError("If-Match: * header is not supported here"); } var sourceBlob = blobs.get(copySource); if (sourceBlob == null) { exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1); } else { blobs.put(request.path(), sourceBlob); byte[] response = (""" <?xml version="1.0" encoding="UTF-8"?> <CopyObjectResult></CopyObjectResult>""").getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } } else { final Tuple<String, BytesReference> blob = parseRequestBody(exchange); final var updateResponseCode = updateBlobContents(exchange, request.path(), blob.v2()); if (updateResponseCode == RestStatus.OK) { exchange.getResponseHeaders().add("ETag", blob.v1()); } exchange.sendResponseHeaders(updateResponseCode.getStatus(), -1); } } else if (request.isListObjectsRequest()) { final StringBuilder list = new StringBuilder(); list.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); list.append("<ListBucketResult>"); final String prefix = request.getOptionalQueryParam("prefix").orElse(null); if (prefix != null) { list.append("<Prefix>").append(prefix).append("</Prefix>"); } final Set<String> commonPrefixes = new HashSet<>(); final String delimiter = request.getOptionalQueryParam("delimiter").orElse(null); if (delimiter != null) { list.append("<Delimiter>").append(delimiter).append("</Delimiter>"); } // Would be good to test pagination here (the only real difference between ListObjects and ListObjectsV2) but for now // we return all the results at once. list.append("<IsTruncated>false</IsTruncated>"); for (Map.Entry<String, BytesReference> blob : blobs.entrySet()) { if (prefix != null && blob.getKey().startsWith("/" + bucket + "/" + prefix) == false) { continue; } String blobPath = blob.getKey().replace("/" + bucket + "/", ""); if (delimiter != null) { int fromIndex = (prefix != null ? prefix.length() : 0); int delimiterPosition = blobPath.indexOf(delimiter, fromIndex); if (delimiterPosition > 0) { commonPrefixes.add(blobPath.substring(0, delimiterPosition) + delimiter); continue; } } list.append("<Contents>"); list.append("<Key>").append(blobPath).append("</Key>"); list.append("<Size>").append(blob.getValue().length()).append("</Size>"); list.append("</Contents>"); } commonPrefixes.forEach( commonPrefix -> list.append("<CommonPrefixes><Prefix>").append(commonPrefix).append("</Prefix></CommonPrefixes>") ); list.append("</ListBucketResult>"); byte[] response = list.toString().getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } else if (request.isGetObjectRequest()) { final BytesReference blob = blobs.get(request.path()); if (blob == null) { exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1); return; } exchange.getResponseHeaders().add("ETag", getEtagFromContents(blob)); final String rangeHeader = exchange.getRequestHeaders().getFirst("Range"); if (rangeHeader == null) { exchange.getResponseHeaders().add("Content-Type", "application/octet-stream"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), blob.length()); blob.writeTo(exchange.getResponseBody()); return; } // S3 supports https://www.rfc-editor.org/rfc/rfc9110.html#name-range. The AWS SDK v1.x seems to always generate range // requests with a header value like "Range: bytes=start-end" where both {@code start} and {@code end} are always defined // (sometimes to very high value for {@code end}). It would be too tedious to fully support the RFC so S3HttpHandler only // supports when both {@code start} and {@code end} are defined to match the SDK behavior. final HttpHeaderParser.Range range = parseRangeHeader(rangeHeader); if (range == null) { throw new AssertionError("Bytes range does not match expected pattern: " + rangeHeader); } long start = range.start(); long end = range.end(); if (end < start) { exchange.getResponseHeaders().add("Content-Type", "application/octet-stream"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), blob.length()); blob.writeTo(exchange.getResponseBody()); return; } else if (blob.length() <= start) { exchange.getResponseHeaders().add("Content-Type", "application/octet-stream"); exchange.sendResponseHeaders(RestStatus.REQUESTED_RANGE_NOT_SATISFIED.getStatus(), -1); return; } var responseBlob = blob.slice(Math.toIntExact(start), Math.toIntExact(Math.min(end - start + 1, blob.length() - start))); end = start + responseBlob.length() - 1; exchange.getResponseHeaders().add("Content-Type", "application/octet-stream"); exchange.getResponseHeaders().add("Content-Range", String.format(Locale.ROOT, "bytes %d-%d/%d", start, end, blob.length())); exchange.sendResponseHeaders(RestStatus.PARTIAL_CONTENT.getStatus(), responseBlob.length()); responseBlob.writeTo(exchange.getResponseBody()); } else if (request.isDeleteObjectRequest()) { int deletions = 0; for (Iterator<Map.Entry<String, BytesReference>> iterator = blobs.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, BytesReference> blob = iterator.next(); if (blob.getKey().startsWith(request.path())) { iterator.remove(); deletions++; } } exchange.sendResponseHeaders((deletions > 0 ? RestStatus.OK : RestStatus.NO_CONTENT).getStatus(), -1); } else if (request.isMultiObjectDeleteRequest()) { final String requestBody = Streams.copyToString(new InputStreamReader(exchange.getRequestBody(), UTF_8)); final StringBuilder deletes = new StringBuilder(); deletes.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); deletes.append("<DeleteResult>"); for (Iterator<Map.Entry<String, BytesReference>> iterator = blobs.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, BytesReference> blob = iterator.next(); String key = blob.getKey().replace("/" + bucket + "/", ""); if (requestBody.contains("<Key>" + key + "</Key>")) { deletes.append("<Deleted><Key>").append(key).append("</Key></Deleted>"); iterator.remove(); } } deletes.append("</DeleteResult>"); byte[] response = deletes.toString().getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/xml"); exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length); exchange.getResponseBody().write(response); } else { logger.error("unknown request: {}", request); exchange.sendResponseHeaders(RestStatus.INTERNAL_SERVER_ERROR.getStatus(), -1); } } catch (Exception e) { logger.error("exception in request " + request, e); throw e; } } /** * Update the blob contents if and only if the preconditions in the request are satisfied. * * @return {@link RestStatus#OK} if the blob contents were updated, or else a different status code to indicate the error: possibly * {@link RestStatus#CONFLICT} in any case, but if not then either {@link RestStatus#PRECONDITION_FAILED} if the object exists * but doesn't match the specified precondition, or {@link RestStatus#NOT_FOUND} if the object doesn't exist but is required to * do so by the precondition. * * @see <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html#conditional-error-response">AWS docs</a> */ private RestStatus updateBlobContents(HttpExchange exchange, String path, BytesReference newContents) { if (consistencyModel().hasConditionalWrites()) { if (isProtectOverwrite(exchange)) { return blobs.putIfAbsent(path, newContents) == null ? RestStatus.OK : ESTestCase.randomFrom(RestStatus.PRECONDITION_FAILED, RestStatus.CONFLICT); } final var requireExistingETag = getRequiredExistingETag(exchange); if (requireExistingETag != null) { final var responseCode = new AtomicReference<>(RestStatus.OK); blobs.compute(path, (ignoredPath, existingContents) -> { if (existingContents != null && requireExistingETag.equals(getEtagFromContents(existingContents))) { return newContents; } responseCode.set( ESTestCase.randomFrom( existingContents == null ? RestStatus.NOT_FOUND : RestStatus.PRECONDITION_FAILED, RestStatus.CONFLICT ) ); return existingContents; }); return responseCode.get(); } } blobs.put(path, newContents); return RestStatus.OK; } /** * Etags are opaque identifiers for the contents of an object. * * @see <a href="https://en.wikipedia.org/wiki/HTTP_ETag">HTTP ETag on Wikipedia</a>. */ public static String getEtagFromContents(BytesReference blobContents) { return '"' + SHA_256_ETAG_PREFIX + MessageDigests.toHexString(MessageDigests.digest(blobContents, MessageDigests.sha256())) + '"'; } public Map<String, BytesReference> blobs() { return blobs; } private static final Pattern chunkSignaturePattern = Pattern.compile("^([0-9a-z]+);chunk-signature=([^\\r\\n]*)$"); private static Tuple<String, BytesReference> parseRequestBody(final HttpExchange exchange) throws IOException { try { final BytesReference bytesReference; final String headerDecodedContentLength = exchange.getRequestHeaders().getFirst("x-amz-decoded-content-length"); if (headerDecodedContentLength == null) { bytesReference = Streams.readFully(exchange.getRequestBody()); } else { BytesReference requestBody = Streams.readFully(exchange.getRequestBody()); int chunkIndex = 0; final List<BytesReference> chunks = new ArrayList<>(); while (true) { chunkIndex += 1; final int headerLength = requestBody.indexOf((byte) '\n', 0) + 1; // includes terminating \r\n if (headerLength == 0) { throw new IllegalStateException("header of chunk [" + chunkIndex + "] was not terminated"); } if (headerLength > 150) { throw new IllegalStateException( "header of chunk [" + chunkIndex + "] was too long at [" + headerLength + "] bytes" ); } if (headerLength < 3) { throw new IllegalStateException( "header of chunk [" + chunkIndex + "] was too short at [" + headerLength + "] bytes" ); } if (requestBody.get(headerLength - 1) != '\n' || requestBody.get(headerLength - 2) != '\r') { throw new IllegalStateException("header of chunk [" + chunkIndex + "] not terminated with [\\r\\n]"); } final String header = requestBody.slice(0, headerLength - 2).utf8ToString(); final Matcher matcher = chunkSignaturePattern.matcher(header); if (matcher.find() == false) { throw new IllegalStateException( "header of chunk [" + chunkIndex + "] did not match expected pattern: [" + header + "]" ); } final int chunkSize = Integer.parseUnsignedInt(matcher.group(1), 16); if (requestBody.get(headerLength + chunkSize) != '\r' || requestBody.get(headerLength + chunkSize + 1) != '\n') { throw new IllegalStateException("chunk [" + chunkIndex + "] not terminated with [\\r\\n]"); } if (chunkSize != 0) { chunks.add(requestBody.slice(headerLength, chunkSize)); } final int toSkip = headerLength + chunkSize + 2; requestBody = requestBody.slice(toSkip, requestBody.length() - toSkip); if (chunkSize == 0) { break; } } bytesReference = CompositeBytesReference.of(chunks.toArray(new BytesReference[0])); if (bytesReference.length() != Integer.parseInt(headerDecodedContentLength)) { throw new IllegalStateException( "Something went wrong when parsing the chunked request " + "[bytes read=" + bytesReference.length() + ", expected=" + headerDecodedContentLength + "]" ); } } return Tuple.tuple(getEtagFromContents(bytesReference), bytesReference); } catch (Exception e) { logger.error("exception in parseRequestBody", e); exchange.sendResponseHeaders(500, 0); try (PrintStream printStream = new PrintStream(exchange.getResponseBody())) { printStream.println(e); e.printStackTrace(printStream); } throw e; } } static List<String> extractPartEtags(BytesReference completeMultipartUploadBody) { try { final var document = XmlUtils.getHardenedBuilderFactory().newDocumentBuilder().parse(completeMultipartUploadBody.streamInput()); final var parts = document.getElementsByTagName("Part"); final var result = new ArrayList<String>(parts.getLength()); for (int partIndex = 0; partIndex < parts.getLength(); partIndex++) { final var part = parts.item(partIndex); String etag = null; int partNumber = -1; final var childNodes = part.getChildNodes(); for (int childIndex = 0; childIndex < childNodes.getLength(); childIndex++) { final var childNode = childNodes.item(childIndex); if (childNode.getNodeType() == ELEMENT_NODE) { if (childNode.getNodeName().equals("ETag")) { etag = childNode.getTextContent(); } else if (childNode.getNodeName().equals("PartNumber")) { partNumber = Integer.parseInt(childNode.getTextContent()) - 1; } } } if (etag == null || partNumber == -1) { throw new IllegalStateException("incomplete part details"); } while (result.size() <= partNumber) { result.add(null); } if (result.get(partNumber) != null) { throw new IllegalStateException("duplicate part found"); } result.set(partNumber, etag); } if (result.stream().anyMatch(Objects::isNull)) { throw new IllegalStateException("missing part"); } return result; } catch (Exception e) { throw ExceptionsHelper.convertToRuntime(e); } } @Nullable // if no X-amz-copy-source header present private static String copySourceName(final HttpExchange exchange) { final var copySources = exchange.getRequestHeaders().get("X-amz-copy-source"); if (copySources != null) { if (copySources.size() != 1) { throw new AssertionError("multiple X-amz-copy-source headers found: " + copySources); } final var copySource = copySources.get(0); // SDKv1 uses format /bucket/path/blob whereas SDKv2 omits the leading / so we must add it back in return copySource.length() > 0 && copySource.charAt(0) == '/' ? copySource : ("/" + copySource); } else { return null; } } private static HttpHeaderParser.Range parsePartRange(final HttpExchange exchange) { final var sourceRangeHeaders = exchange.getRequestHeaders().get("X-amz-copy-source-range"); if (sourceRangeHeaders == null) { throw new IllegalStateException("missing x-amz-copy-source-range header"); } if (sourceRangeHeaders.size() != 1) { throw new IllegalStateException("expected 1 x-amz-copy-source-range header, found " + sourceRangeHeaders.size()); } return parseRangeHeader(sourceRangeHeaders.getFirst()); } private static boolean isProtectOverwrite(final HttpExchange exchange) { final var ifNoneMatch = exchange.getRequestHeaders().get("If-None-Match"); if (ifNoneMatch == null) { return false; } if (exchange.getRequestHeaders().get("If-Match") != null) { throw new AssertionError("Handling both If-None-Match and If-Match headers is not supported"); } if (ifNoneMatch.size() != 1) { throw new AssertionError("multiple If-None-Match headers found: " + ifNoneMatch); } if (ifNoneMatch.getFirst().equals("*")) { return true; } throw new AssertionError("invalid If-None-Match header: " + ifNoneMatch); } @Nullable // if no If-Match header found private static String getRequiredExistingETag(final HttpExchange exchange) { final var ifMatch = exchange.getRequestHeaders().get("If-Match"); if (ifMatch == null) { return null; } if (exchange.getRequestHeaders().get("If-None-Match") != null) { throw new AssertionError("Handling both If-None-Match and If-Match headers is not supported"); } final var iterator = ifMatch.iterator(); if (iterator.hasNext()) { final var result = iterator.next(); if (iterator.hasNext() == false) { return result; } } throw new AssertionError("multiple If-Match headers found: " + ifMatch); } MultipartUpload putUpload(String path) { final var upload = new MultipartUpload(UUIDs.randomBase64UUID(), path); synchronized (uploads) { assertNull("upload " + upload.getUploadId() + " should not exist", uploads.put(upload.getUploadId(), upload)); return upload; } } MultipartUpload getUpload(String uploadId) { synchronized (uploads) { return uploads.get(uploadId); } } MultipartUpload removeUpload(String uploadId) { synchronized (uploads) { return uploads.remove(uploadId); } } private Releasable setUploadCompleting(String uploadId) { completingUploads.computeIfAbsent(uploadId, ignored -> new AtomicInteger()).incrementAndGet(); return () -> clearUploadCompleting(uploadId); } private void clearUploadCompleting(String uploadId) { completingUploads.compute(uploadId, (ignored, uploadCount) -> { if (uploadCount == null) { throw new AssertionError("upload [" + uploadId + "] not tracked"); } if (uploadCount.decrementAndGet() == 0) { return null; } else { return uploadCount; } }); } protected S3ConsistencyModel consistencyModel() { return S3ConsistencyModel.AWS_DEFAULT; } public S3Request parseRequest(HttpExchange exchange) { final String queryString = exchange.getRequestURI().getQuery(); final Map<String, List<String>> queryParameters; if (Strings.hasText(queryString)) { queryParameters = new HashMap<>(); for (final String queryPart : queryString.split("&")) { final String paramName, paramValue; final int equalsPos = queryPart.indexOf('='); if (equalsPos == -1) { paramName = queryPart; paramValue = null; } else { paramName = queryPart.substring(0, equalsPos); paramValue = queryPart.substring(equalsPos + 1); } queryParameters.computeIfAbsent(paramName, ignored -> new ArrayList<>()).add(paramValue); } } else { queryParameters = Map.of(); } return new S3Request(exchange.getRequestMethod(), exchange.getRequestURI().getPath(), queryParameters); } public
S3HttpHandler
java
quarkusio__quarkus
extensions/panache/hibernate-reactive-panache-kotlin/deployment/src/main/java/io/quarkus/hibernate/reactive/panache/kotlin/deployment/HibernateReactivePanacheKotlinProcessor.java
{ "start": 10058, "end": 11039 }
class ____.produce(new ReflectiveClassBuildItem(true, true, parameterType.name().toString())); } } @BuildStep public ValidationPhaseBuildItem.ValidationErrorBuildItem validate(ValidationPhaseBuildItem validationPhase, CombinedIndexBuildItem index) throws BuildException { // we verify that no ID fields are defined (via @Id) when extending PanacheEntity for (AnnotationInstance annotationInstance : index.getComputingIndex().getAnnotations(DOTNAME_ID)) { ClassInfo info = JandexUtil.getEnclosingClass(annotationInstance); if (JandexUtil.isSubclassOf(index.getComputingIndex(), info, TYPE_BUNDLE.entity().dotName())) { BuildException be = new BuildException( "You provide a JPA identifier via @Id inside '" + info.name() + "' but one is already provided by PanacheEntity, " + "your
reflectiveClass
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/type/H2DurationIntervalSecondJdbcType.java
{ "start": 826, "end": 3598 }
class ____ implements JdbcType { public static final H2DurationIntervalSecondJdbcType INSTANCE = new H2DurationIntervalSecondJdbcType(); @Override public int getJdbcTypeCode() { return Types.OTHER; } @Override public int getDefaultSqlTypeCode() { return SqlTypes.INTERVAL_SECOND; } @Override public Class<?> getPreferredJavaTypeClass(WrapperOptions options) { return Duration.class; } @Override public boolean isComparable() { return true; } @Override public <T> JdbcLiteralFormatter<T> getJdbcLiteralFormatter(JavaType<T> javaType) { return (appender, value, dialect, wrapperOptions) -> dialect.appendIntervalLiteral( appender, javaType.unwrap( value, Duration.class, wrapperOptions ) ); } @Override public <X> ValueBinder<X> getBinder(JavaType<X> javaType) { return new BasicBinder<>( javaType, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { st.setObject( index, javaType.unwrap( value, Duration.class, options ) ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { st.setObject( name, javaType.unwrap( value, Duration.class, options ) ); } }; } @Override public <X> ValueExtractor<X> getExtractor(JavaType<X> javaType) { return new BasicExtractor<>( javaType, this ) { @Override protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException { // Handle the fact that a duration could also come as number of nanoseconds final Object nativeValue = rs.getObject( paramIndex ); if ( nativeValue instanceof Number ) { return javaType.wrap( nativeValue, options ); } return javaType.wrap( rs.getObject( paramIndex, Duration.class ), options ); } @Override protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { // Handle the fact that a duration could also come as number of nanoseconds final Object nativeValue = statement.getObject( index ); return nativeValue instanceof Number ? javaType.wrap( nativeValue, options ) : javaType.wrap( statement.getObject( index, Duration.class ), options ); } @Override protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { // Handle the fact that a duration could also come as number of nanoseconds final Object nativeValue = statement.getObject( name ); return nativeValue instanceof Number ? javaType.wrap( nativeValue, options ) : javaType.wrap( statement.getObject( name, Duration.class ), options ); } }; } }
H2DurationIntervalSecondJdbcType
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/propertyref/component/complete/CompleteComponentPropertyRefTest.java
{ "start": 893, "end": 2535 }
class ____ { @Test public void testComponentPropertyRef(SessionFactoryScope scope) { scope.inTransaction( session -> { Person p = new Person(); p.setIdentity( new Identity() ); Account a = new Account(); a.setNumber( "123-12345-1236" ); a.setOwner( p ); p.getIdentity().setName( "Gavin" ); p.getIdentity().setSsn( "123-12-1234" ); session.persist( p ); session.persist( a ); } ); scope.inTransaction( session -> { Account a = (Account) session.createQuery( "from Account a left join fetch a.owner" ) .uniqueResult(); assertTrue( Hibernate.isInitialized( a.getOwner() ) ); assertNotNull( a.getOwner() ); assertEquals( "Gavin", a.getOwner().getIdentity().getName() ); session.clear(); a = session.get( Account.class, "123-12345-1236" ); assertFalse( Hibernate.isInitialized( a.getOwner() ) ); assertNotNull( a.getOwner() ); assertEquals( "Gavin", a.getOwner().getIdentity().getName() ); assertTrue( Hibernate.isInitialized( a.getOwner() ) ); session.clear(); final CacheImplementor cache = scope.getSessionFactory().getCache(); cache.evictEntityData( Account.class ); cache.evictEntityData( Person.class ); a = session.get( Account.class, "123-12345-1236" ); assertTrue( Hibernate.isInitialized( a.getOwner() ) ); assertNotNull( a.getOwner() ); assertEquals( "Gavin", a.getOwner().getIdentity().getName() ); assertTrue( Hibernate.isInitialized( a.getOwner() ) ); session.remove( a ); session.remove( a.getOwner() ); } ); } }
CompleteComponentPropertyRefTest
java
assertj__assertj-core
assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldBeClosedInTheLowerBound.java
{ "start": 807, "end": 1547 }
class ____ extends BasicErrorMessageFactory { public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveClosedLowerBound(final Range<T> actual) { return new RangeShouldBeClosedInTheLowerBound( "%nExpecting:%n %s%nto be closed in the lower bound but was opened", actual); } /** * Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>. * * @param format the format string. * @param arguments arguments referenced by the format specifiers in the format string. */ public RangeShouldBeClosedInTheLowerBound(final String format, final Object... arguments) { super(format, arguments); } }
RangeShouldBeClosedInTheLowerBound
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/NullableSerializerUpgradeTest.java
{ "start": 4436, "end": 4838 }
class ____ implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<Long> { @Override public TypeSerializer<Long> createPriorSerializer() { return NullableSerializer.wrap(LongSerializer.INSTANCE, false); } @Override public Long createTestData() { return null; } } /** * This
NullableNotPaddedSerializerSetup
java
quarkusio__quarkus
extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/NotifyingTransactionManager.java
{ "start": 1047, "end": 5122 }
class ____ extends TransactionScopedNotifier implements TransactionManager, Serializable { private static final long serialVersionUID = 1598L; private static final Logger LOG = Logger.getLogger(NotifyingTransactionManager.class); private transient com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple delegate; NotifyingTransactionManager() { delegate = (com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple) com.arjuna.ats.jta.TransactionManager .transactionManager(); } /** * Overrides {@link TransactionManager#begin()} to * additionally {@linkplain Event#fire(Object) fire} an {@link Object} * representing the {@linkplain Initialized initialization} * of the {@linkplain TransactionScoped transaction scope}. * * @see TransactionManager#begin() */ @Override public void begin() throws NotSupportedException, SystemException { delegate.begin(); initialized(getTransactionId()); } /** * Overrides {@link TransactionManager#commit()} to * additionally {@linkplain Event#fire(Object) fire} an {@link Object} * representing the {@linkplain BeforeDestroyed before destruction} and * the {@linkplain Destroyed destruction} * of the {@linkplain TransactionScoped transaction scope}. * * @see TransactionManager#commit() */ @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { TransactionId id = getTransactionId(); beforeDestroyed(id); try { delegate.commit(); } finally { destroyed(id); } } /** * Overrides {@link TransactionManager#rollback()} to * additionally {@linkplain Event#fire(Object) fire} an {@link Object} * representing the {@linkplain BeforeDestroyed before destruction} and * the {@linkplain Destroyed destruction} * of the {@linkplain TransactionScoped transaction scope}. * * @see TransactionManager#rollback() */ @Override public void rollback() throws IllegalStateException, SecurityException, SystemException { TransactionId id = getTransactionId(); try { beforeDestroyed(id); } catch (Throwable t) { LOG.error("Failed to fire @BeforeDestroyed(TransactionScoped.class)", t); } try { delegate.rollback(); } finally { //we don't need a catch block here, if this one fails we just let the exception propagate destroyed(id); } } /** * {@inheritDoc} */ @Override public int getStatus() throws SystemException { return delegate.getStatus(); } /** * {@inheritDoc} */ @Override public Transaction getTransaction() throws SystemException { return delegate.getTransaction(); } /** * {@inheritDoc} */ @Override public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException { delegate.resume(transaction); } /** * {@inheritDoc} */ @Override public void setRollbackOnly() throws IllegalStateException, SystemException { delegate.setRollbackOnly(); } /** * {@inheritDoc} */ @Override public void setTransactionTimeout(int seconds) throws SystemException { delegate.setTransactionTimeout(seconds); } /** * Returns transaction timeout in seconds. * * @return transaction timeout set currently * @throws SystemException on an undefined error */ public int getTransactionTimeout() throws SystemException { return delegate.getTimeout(); } /** * {@inheritDoc} */ @Override public Transaction suspend() throws SystemException { return delegate.suspend(); } }
NotifyingTransactionManager
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/StateSnapshotTransformers.java
{ "start": 6356, "end": 7127 }
class ____<S, T> implements StateSnapshotTransformFactory<T> { final StateSnapshotTransformFactory<S> originalSnapshotTransformFactory; StateSnapshotTransformFactoryWrapAdaptor( StateSnapshotTransformFactory<S> originalSnapshotTransformFactory) { this.originalSnapshotTransformFactory = originalSnapshotTransformFactory; } @Override public Optional<StateSnapshotTransformer<T>> createForDeserializedState() { throw new UnsupportedOperationException(); } @Override public Optional<StateSnapshotTransformer<byte[]>> createForSerializedState() { throw new UnsupportedOperationException(); } } }
StateSnapshotTransformFactoryWrapAdaptor
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/snapshots/SnapshotBrokenSettingsIT.java
{ "start": 1015, "end": 3314 }
class ____ extends AbstractSnapshotIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singletonList(BrokenSettingPlugin.class); } public void testExceptionWhenRestoringPersistentSettings() { logger.info("--> start 2 nodes"); internalCluster().startNodes(2); Client client = client(); Consumer<String> setSettingValue = value -> client.admin() .cluster() .prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(Settings.builder().put(BrokenSettingPlugin.BROKEN_SETTING.getKey(), value)) .get(); Consumer<String> assertSettingValue = value -> assertThat( client.admin() .cluster() .prepareState(TEST_REQUEST_TIMEOUT) .setRoutingTable(false) .setNodes(false) .get() .getState() .getMetadata() .persistentSettings() .get(BrokenSettingPlugin.BROKEN_SETTING.getKey()), equalTo(value) ); logger.info("--> set test persistent setting"); setSettingValue.accept("new value"); assertSettingValue.accept("new value"); createRepository("test-repo", "fs"); createFullSnapshot("test-repo", "test-snap"); assertThat(getSnapshot("test-repo", "test-snap").state(), equalTo(SnapshotState.SUCCESS)); logger.info("--> change the test persistent setting and break it"); setSettingValue.accept("new value 2"); assertSettingValue.accept("new value 2"); BrokenSettingPlugin.breakSetting(); logger.info("--> restore snapshot"); final IllegalArgumentException ex = expectThrows( IllegalArgumentException.class, client.admin() .cluster() .prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, "test-repo", "test-snap") .setRestoreGlobalState(true) .setWaitForCompletion(true) ); assertEquals(BrokenSettingPlugin.EXCEPTION.getMessage(), ex.getMessage()); assertSettingValue.accept("new value 2"); } public static
SnapshotBrokenSettingsIT
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-server-common/deployment/src/main/java/io/quarkus/resteasy/server/common/deployment/ResteasyServerCommonProcessor.java
{ "start": 25788, "end": 28621 }
class ____ with a request method designator Transformation transformation = context.transform() .add(resteasyConfig.singletonResources() ? BuiltinScope.SINGLETON.getName() : BuiltinScope.DEPENDENT.getName()); if (clazz.declaredAnnotation(DotNames.TYPED) == null) { // Add @Typed(MySubresource.class) transformation.add(createTypedAnnotationInstance(clazz)); } // Force constructors with arguments to also include @Inject, because sub-resources can be managed by the user if (!clazz.hasNoArgsConstructor()) { boolean hasInject = false; for (final MethodInfo constructor : clazz.constructors()) { if (constructor.hasAnnotation(DotNames.INJECT)) { hasInject = true; break; } } if (!hasInject) { transformation.add(DotNames.VETOED); } } transformation.done(); } } })); resteasyDeployment.produce(new ResteasyDeploymentBuildItem(path, deployment)); } @BuildStep List<AllowedJaxRsAnnotationPrefixBuildItem> registerCompatibleAnnotationPrefixes() { List<AllowedJaxRsAnnotationPrefixBuildItem> prefixes = new ArrayList<>(); prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem(packageName(ResteasyDotNames.PATH))); prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("kotlin")); // make sure the annotation that the Kotlin compiler adds don't interfere with creating a default constructor prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("lombok")); // same for lombok prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("io.quarkus.security")); // same for the security annotations prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("jakarta.annotation.security")); prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("jakarta.annotation.security")); prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("java.lang")); prefixes.add(new AllowedJaxRsAnnotationPrefixBuildItem("jakarta.inject")); return prefixes; } @BuildStep void processPathInterfaceImplementors(CombinedIndexBuildItem combinedIndexBuildItem, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, BuildProducer<AdditionalBeanBuildItem> additionalBeans, CustomScopeAnnotationsBuildItem scopes) { // NOTE: we cannot process @Path
annotated
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/JmsComponentBuilderFactory.java
{ "start": 1376, "end": 1812 }
interface ____ { /** * JMS (camel-jms) * Send and receive messages to/from JMS message brokers. * * Category: messaging * Since: 1.0 * Maven coordinates: org.apache.camel:camel-jms * * @return the dsl builder */ static JmsComponentBuilder jms() { return new JmsComponentBuilderImpl(); } /** * Builder for the JMS component. */
JmsComponentBuilderFactory
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/customized/QuarkusStrategySelectorBuilder.java
{ "start": 5245, "end": 11895 }
class ____ service used to (attempt to) resolve any un-registered * strategy implementations. * * @return The selector. */ public static StrategySelector buildRuntimeSelector(ClassLoaderService classLoaderService) { final StrategySelectorImpl strategySelector = new StrategySelectorImpl(classLoaderService); addImplicitNamingStrategies(strategySelector); return strategySelector; } private static <T> void applyFromStrategyRegistration(StrategySelectorImpl strategySelector, StrategyRegistration<T> strategyRegistration) { for (String name : strategyRegistration.getSelectorNames()) { strategySelector.registerStrategyImplementor( strategyRegistration.getStrategyRole(), name, strategyRegistration.getStrategyImplementation()); } } private static void addTransactionCoordinatorBuilders(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( TransactionCoordinatorBuilder.class, JdbcResourceLocalTransactionCoordinatorBuilderImpl.SHORT_NAME, JdbcResourceLocalTransactionCoordinatorBuilderImpl.class); strategySelector.registerStrategyImplementor( TransactionCoordinatorBuilder.class, JtaTransactionCoordinatorBuilderImpl.SHORT_NAME, JtaTransactionCoordinatorBuilderImpl.class); } private static void addSqmMultiTableInsertStrategies(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( SqmMultiTableInsertStrategy.class, CteInsertStrategy.SHORT_NAME, CteInsertStrategy.class); strategySelector.registerStrategyImplementor( SqmMultiTableInsertStrategy.class, GlobalTemporaryTableInsertStrategy.SHORT_NAME, GlobalTemporaryTableInsertStrategy.class); strategySelector.registerStrategyImplementor( SqmMultiTableInsertStrategy.class, LocalTemporaryTableInsertStrategy.SHORT_NAME, LocalTemporaryTableInsertStrategy.class); strategySelector.registerStrategyImplementor( SqmMultiTableInsertStrategy.class, PersistentTableInsertStrategy.SHORT_NAME, PersistentTableInsertStrategy.class); } private static void addSqmMultiTableMutationStrategies(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( SqmMultiTableMutationStrategy.class, CteMutationStrategy.SHORT_NAME, CteMutationStrategy.class); strategySelector.registerStrategyImplementor( SqmMultiTableMutationStrategy.class, GlobalTemporaryTableMutationStrategy.SHORT_NAME, GlobalTemporaryTableMutationStrategy.class); strategySelector.registerStrategyImplementor( SqmMultiTableMutationStrategy.class, LocalTemporaryTableMutationStrategy.SHORT_NAME, LocalTemporaryTableMutationStrategy.class); strategySelector.registerStrategyImplementor( SqmMultiTableMutationStrategy.class, PersistentTableMutationStrategy.SHORT_NAME, PersistentTableMutationStrategy.class); } private static void addImplicitNamingStrategies(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( ImplicitNamingStrategy.class, "default", ImplicitNamingStrategyJpaCompliantImpl.class); strategySelector.registerStrategyImplementor( ImplicitNamingStrategy.class, "jpa", ImplicitNamingStrategyJpaCompliantImpl.class); strategySelector.registerStrategyImplementor( ImplicitNamingStrategy.class, "component-path", ImplicitNamingStrategyComponentPathImpl.class); strategySelector.registerStrategyImplementor( ImplicitDatabaseObjectNamingStrategy.class, StandardNamingStrategy.STRATEGY_NAME, StandardNamingStrategy.class); strategySelector.registerStrategyImplementor( ImplicitDatabaseObjectNamingStrategy.class, SingleNamingStrategy.STRATEGY_NAME, SingleNamingStrategy.class); strategySelector.registerStrategyImplementor( ImplicitDatabaseObjectNamingStrategy.class, LegacyNamingStrategy.STRATEGY_NAME, LegacyNamingStrategy.class); } private static void addColumnOrderingStrategies(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( ColumnOrderingStrategy.class, "default", ColumnOrderingStrategyStandard.class); strategySelector.registerStrategyImplementor( ColumnOrderingStrategy.class, "legacy", ColumnOrderingStrategyLegacy.class); } private static void addCacheKeysFactories(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( CacheKeysFactory.class, DefaultCacheKeysFactory.SHORT_NAME, DefaultCacheKeysFactory.class); strategySelector.registerStrategyImplementor( CacheKeysFactory.class, SimpleCacheKeysFactory.SHORT_NAME, SimpleCacheKeysFactory.class); } private static void addJsonFormatMappers(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( FormatMapper.class, JacksonJsonFormatMapper.SHORT_NAME, JacksonJsonFormatMapper.class); strategySelector.registerStrategyImplementor( FormatMapper.class, JsonBJsonFormatMapper.SHORT_NAME, JsonBJsonFormatMapper.class); } private static void addXmlFormatMappers(StrategySelectorImpl strategySelector) { strategySelector.registerStrategyImplementor( FormatMapper.class, JacksonXmlFormatMapper.SHORT_NAME, JacksonXmlFormatMapper.class); strategySelector.registerStrategyImplementor( FormatMapper.class, JaxbXmlFormatMapper.SHORT_NAME, JaxbXmlFormatMapper.class); } }
loading
java
dropwizard__dropwizard
dropwizard-testing/src/test/java/io/dropwizard/testing/DropwizardTestSupportTest.java
{ "start": 4956, "end": 5349 }
class ____ extends Application<TestConfiguration> { @Override public void initialize(Bootstrap<TestConfiguration> bootstrap) { bootstrap.setConfigurationFactoryFactory(FailingConfigurationFactory::new); } @Override public void run(TestConfiguration configuration, Environment environment) { } } public static
FailingApplication
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/util/InMemoryResource.java
{ "start": 1130, "end": 2032 }
class ____ extends AbstractResource { private final byte[] source; private final String description; public InMemoryResource(String source) { this(source.getBytes()); } public InMemoryResource(byte[] source) { this(source, null); } public InMemoryResource(byte[] source, @Nullable String description) { Assert.notNull(source, "source cannot be null"); this.source = source; this.description = (description != null) ? description : ""; } @Override public String getDescription() { return this.description; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(this.source); } @Override public boolean equals(@Nullable Object res) { if (!(res instanceof InMemoryResource)) { return false; } return Arrays.equals(this.source, ((InMemoryResource) res).source); } @Override public int hashCode() { return 1; } }
InMemoryResource
java
apache__camel
components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
{ "start": 1212, "end": 3092 }
interface ____ extends Endpoint { /** * Creates a processor for the webhook that is responsible for receiving all messages sent to the webhook. * <p> * The processor should distinguish handshakes from standard calls and forward relevant data to the downstream * processor after transformation. Data forwarded to the downstream processor should be of the same type as data * generated by the corresponding polling consumer. * * @param next the downstream processor. * @return the webhook route processor */ Processor createWebhookHandler(Processor next); /** * Register the webhook at the remote site using endpoint specific instruction. * <p> * Additional configuration is injected into the endpoint using the setWebhookConfiguration method. * * @throws Exception if something goes wrong during the registration. */ void registerWebhook() throws Exception; /** * Unregister the webhook at the remote site using endpoint specific instruction. * <p> * Additional configuration is injected into the endpoint using the setWebhookConfiguration method. * * @throws Exception if something goes wrong during the un-registration. */ void unregisterWebhook() throws Exception; /** * Used by the workflow manager to inject webhook configuration options. * * @param webhookConfiguration the webhook configuration options. */ void setWebhookConfiguration(WebhookConfiguration webhookConfiguration); /** * Used by the endpoint to enlist the HTTP methods it's able to handle. Usually only "POST" is used, but some * webhook providers require multiple verbs in the handshake phase. * * @return the HTTP methods supported by the endpoint */ List<String> getWebhookMethods(); }
WebhookCapableEndpoint
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosStateMachine.java
{ "start": 2758, "end": 12556 }
class ____ extends StateMachineAdapter { protected final JRaftServer server; protected final RequestProcessor processor; private final AtomicBoolean isLeader = new AtomicBoolean(false); private final String groupId; private Collection<JSnapshotOperation> operations; private Node node; private volatile long term = -1; private volatile String leaderIp = "unknown"; NacosStateMachine(JRaftServer server, RequestProcessor4CP processor) { this.server = server; this.processor = processor; this.groupId = processor.group(); adapterToJraftSnapshot(processor.loadSnapshotOperate()); } @Override public void onApply(Iterator iter) { int index = 0; int applied = 0; Message message; NacosClosure closure = null; try { while (iter.hasNext()) { Status status = Status.OK(); try { if (iter.done() != null) { closure = (NacosClosure) iter.done(); message = closure.getMessage(); } else { final ByteBuffer data = iter.getData(); message = ProtoMessageUtil.parse(data.array()); if (message instanceof ReadRequest) { //'iter.done() == null' means current node is follower, ignore read operation applied++; index++; iter.next(); continue; } } LoggerUtils.printIfDebugEnabled(Loggers.RAFT, "receive log : {}", message); if (message instanceof WriteRequest) { Response response = processor.onApply((WriteRequest) message); postProcessor(response, closure); } if (message instanceof ReadRequest) { Response response = processor.onRequest((ReadRequest) message); postProcessor(response, closure); } } catch (Throwable e) { index++; status.setError(RaftError.UNKNOWN, e.toString()); Optional.ofNullable(closure).ifPresent(closure1 -> closure1.setThrowable(e)); throw e; } finally { Optional.ofNullable(closure).ifPresent(closure1 -> closure1.run(status)); } applied++; index++; iter.next(); } } catch (Throwable t) { Loggers.RAFT.error("processor : {}, stateMachine meet critical error: {}.", processor, t); iter.setErrorAndRollback(index - applied, new Status(RaftError.ESTATEMACHINE, "StateMachine meet critical error: %s.", ExceptionUtil.getStackTrace(t))); } } public void setNode(Node node) { this.node = node; } @Override public void onSnapshotSave(SnapshotWriter writer, Closure done) { for (JSnapshotOperation operation : operations) { try { operation.onSnapshotSave(writer, done); } catch (Throwable t) { Loggers.RAFT.error("There was an error saving the snapshot , error : {}, operation : {}", t, operation.info()); throw t; } } } @Override public boolean onSnapshotLoad(SnapshotReader reader) { for (JSnapshotOperation operation : operations) { try { if (!operation.onSnapshotLoad(reader)) { Loggers.RAFT.error("Snapshot load failed on : {}", operation.info()); return false; } } catch (Throwable t) { Loggers.RAFT.error("Snapshot load failed on : {}, has error : {}", operation.info(), t); return false; } } return true; } @Override public void onLeaderStart(final long term) { super.onLeaderStart(term); this.term = term; this.isLeader.set(true); this.leaderIp = node.getNodeId().getPeerId().getEndpoint().toString(); NotifyCenter.publishEvent( RaftEvent.builder().groupId(groupId).leader(leaderIp).term(term).raftClusterInfo(allPeers()).build()); } @Override public void onLeaderStop(final Status status) { super.onLeaderStop(status); this.isLeader.set(false); } @Override public void onStartFollowing(LeaderChangeContext ctx) { this.term = ctx.getTerm(); this.leaderIp = ctx.getLeaderId().getEndpoint().toString(); NotifyCenter.publishEvent( RaftEvent.builder().groupId(groupId).leader(leaderIp).term(ctx.getTerm()).raftClusterInfo(allPeers()) .build()); } @Override public void onConfigurationCommitted(Configuration conf) { NotifyCenter.publishEvent( RaftEvent.builder().groupId(groupId).raftClusterInfo(JRaftUtils.toStrings(conf.getPeers())).build()); } @Override public void onError(RaftException e) { super.onError(e); processor.onError(e); NotifyCenter.publishEvent( RaftEvent.builder().groupId(groupId).leader(leaderIp).term(term).raftClusterInfo(allPeers()) .errMsg(e.toString()) .build()); } public boolean isLeader() { return isLeader.get(); } private List<String> allPeers() { if (node == null) { return Collections.emptyList(); } if (node.isLeader()) { return JRaftUtils.toStrings(node.listPeers()); } return JRaftUtils.toStrings(RouteTable.getInstance().getConfiguration(node.getGroupId()).getPeers()); } private void postProcessor(Response data, NacosClosure closure) { if (Objects.nonNull(closure)) { closure.setResponse(data); } } public long getTerm() { return term; } private void adapterToJraftSnapshot(Collection<SnapshotOperation> userOperates) { List<JSnapshotOperation> tmp = new ArrayList<>(); for (SnapshotOperation item : userOperates) { if (item == null) { Loggers.RAFT.error("Existing SnapshotOperation for null"); continue; } tmp.add(new JSnapshotOperation() { @Override public void onSnapshotSave(SnapshotWriter writer, Closure done) { final Writer wCtx = new Writer(writer.getPath()); // Do a layer of proxy operation to shield different Raft // components from implementing snapshots final BiConsumer<Boolean, Throwable> callFinally = (result, t) -> { Boolean[] results = new Boolean[wCtx.listFiles().size()]; int[] index = new int[] {0}; wCtx.listFiles().forEach((file, meta) -> { try { results[index[0]++] = writer.addFile(file, buildMetadata(meta)); } catch (Exception e) { throw new ConsistencyException(e); } }); final Status status = result && Arrays.stream(results).allMatch(Boolean.TRUE::equals) ? Status.OK() : new Status(RaftError.EIO, "Fail to compress snapshot at %s, error is %s", writer.getPath(), t == null ? "" : t.getMessage()); done.run(status); }; item.onSnapshotSave(wCtx, callFinally); } @Override public boolean onSnapshotLoad(SnapshotReader reader) { final Map<String, LocalFileMeta> metaMap = new HashMap<>(reader.listFiles().size()); for (String fileName : reader.listFiles()) { final LocalFileMetaOutter.LocalFileMeta meta = (LocalFileMetaOutter.LocalFileMeta) reader .getFileMeta(fileName); byte[] bytes = meta.getUserMeta().toByteArray(); final LocalFileMeta fileMeta; if (bytes == null || bytes.length == 0) { fileMeta = new LocalFileMeta(); } else { fileMeta = JacksonUtils.toObj(bytes, LocalFileMeta.class); } metaMap.put(fileName, fileMeta); } final Reader rCtx = new Reader(reader.getPath(), metaMap); return item.onSnapshotLoad(rCtx); } @Override public String info() { return item.toString(); } }); } this.operations = Collections.unmodifiableList(tmp); } }
NacosStateMachine
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-project-interpolation/src/main/java/org/apache/maven/plugin/coreit/PropertyInterpolationMojo.java
{ "start": 1191, "end": 2022 }
class ____ extends AbstractMojo { /** * The current Maven project. */ @Parameter(defaultValue = "${project}") private MavenProject project; public void execute() throws MojoExecutionException { String value = normalize(project.getProperties().getProperty("myDirectory")); String targetValue = normalize(new File(project.getBuild().getDirectory(), "foo").getAbsolutePath()); if (!value.equals(targetValue)) { throw new MojoExecutionException("Property value of 'myDirectory': " + value + " should equal the 'foo' subpath of the project build directory: " + targetValue); } } private String normalize(String src) { return src.replace('/', File.separatorChar).replace('\\', File.separatorChar); } }
PropertyInterpolationMojo
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/test/ReflectionTestUtils.java
{ "start": 1883, "end": 2296 }
class ____ in search of the desired field. In addition, an attempt will be made to make * non-{@code public} fields <em>accessible</em>, thus allowing one to get {@code protected}, {@code private}, and * <em>package-private</em> fields. * * @param targetObject the target object from which to get the field; may be {@code null} if the field is static * @param targetClass the target
hierarchy
java
apache__flink
flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/table/SavepointConnectorOptions.java
{ "start": 1925, "end": 2854 }
enum ____ { VALUE, LIST, MAP } // -------------------------------------------------------------------------------------------- // Common options // -------------------------------------------------------------------------------------------- public static final ConfigOption<String> STATE_BACKEND_TYPE = ConfigOptions.key("state.backend.type") .stringType() .noDefaultValue() .withDescription( Description.builder() .text("The state backend to be used to read state.") .linebreak() .text( "The implementation can be specified either via their shortcut " + " name, or via the
StateType
java
grpc__grpc-java
testing/src/main/java/io/grpc/testing/GrpcServerRule.java
{ "start": 2215, "end": 4825 }
class ____ extends ExternalResource { private ManagedChannel channel; private Server server; private String serverName; private MutableHandlerRegistry serviceRegistry; private boolean useDirectExecutor; /** * Returns {@code this} configured to use a direct executor for the {@link ManagedChannel} and * {@link Server}. This can only be called at the rule instantiation. */ public final GrpcServerRule directExecutor() { checkState(serverName == null, "directExecutor() can only be called at the rule instantiation"); useDirectExecutor = true; return this; } /** * Returns a {@link ManagedChannel} connected to this service. */ public final ManagedChannel getChannel() { return channel; } /** * Returns the underlying gRPC {@link Server} for this service. */ public final Server getServer() { return server; } /** * Returns the randomly generated server name for this service. */ public final String getServerName() { return serverName; } /** * Returns the service registry for this service. The registry is used to add service instances * (e.g. {@link BindableService} or {@link ServerServiceDefinition} to the server. */ public final MutableHandlerRegistry getServiceRegistry() { return serviceRegistry; } /** * After the test has completed, clean up the channel and server. */ @Override protected void after() { serverName = null; serviceRegistry = null; channel.shutdown(); server.shutdown(); try { channel.awaitTermination(1, TimeUnit.MINUTES); server.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } finally { channel.shutdownNow(); channel = null; server.shutdownNow(); server = null; } } /** * Before the test has started, create the server and channel. */ @Override protected void before() throws Throwable { serverName = UUID.randomUUID().toString(); serviceRegistry = new MutableHandlerRegistry(); InProcessServerBuilder serverBuilder = InProcessServerBuilder.forName(serverName) .fallbackHandlerRegistry(serviceRegistry); if (useDirectExecutor) { serverBuilder.directExecutor(); } server = serverBuilder.build().start(); InProcessChannelBuilder channelBuilder = InProcessChannelBuilder.forName(serverName); if (useDirectExecutor) { channelBuilder.directExecutor(); } channel = channelBuilder.build(); } }
GrpcServerRule
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherLifeCycleServiceTests.java
{ "start": 3376, "end": 40669 }
class ____ extends ESTestCase { private WatcherService watcherService; private WatcherLifeCycleService lifeCycleService; @NotMultiProjectCapable(description = "Watcher is not available in serverless") private ProjectId projectId = ProjectId.DEFAULT; @Before public void prepareServices() { ClusterService clusterService = mock(ClusterService.class); Answer<Object> answer = invocationOnMock -> { AckedClusterStateUpdateTask updateTask = (AckedClusterStateUpdateTask) invocationOnMock.getArguments()[1]; updateTask.onAllNodesAcked(); return null; }; doAnswer(answer).when(clusterService).submitUnbatchedStateUpdateTask(anyString(), any(ClusterStateUpdateTask.class)); watcherService = mock(WatcherService.class); lifeCycleService = new WatcherLifeCycleService(clusterService, watcherService); } public void testNoRestartWithoutAllocationIdsConfigured() { IndexRoutingTable indexRoutingTable = IndexRoutingTable.builder(new Index("anything", "foo")).build(); ClusterState previousClusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTable).build()) .build(); IndexRoutingTable watchRoutingTable = IndexRoutingTable.builder(new Index(Watch.INDEX, "foo")).build(); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .putProjectMetadata( ProjectMetadata.builder(projectId) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())) .build() ) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(watchRoutingTable).build()) .build(); when(watcherService.validate(clusterState)).thenReturn(true); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, previousClusterState)); verifyNoMoreInteractions(watcherService); // Trying to start a second time, but that should have no effect. lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, previousClusterState)); verifyNoMoreInteractions(watcherService); } public void testStartWithStateNotRecoveredBlock() { DiscoveryNodes.Builder nodes = new DiscoveryNodes.Builder().add( DiscoveryNodeUtils.builder("id1").roles(new HashSet<>(DiscoveryNodeRole.roles())).build() ).masterNodeId("id1").localNodeId("id1"); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .blocks(ClusterBlocks.builder().addGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) .nodes(nodes) .build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); verifyNoMoreInteractions(watcherService); } public void testShutdown() { IndexRoutingTable watchRoutingTable = IndexRoutingTable.builder(new Index(Watch.INDEX, "foo")).build(); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(watchRoutingTable).build()) .putProjectMetadata( ProjectMetadata.builder(projectId) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())) .build() ) .build(); when(watcherService.validate(clusterState)).thenReturn(true); lifeCycleService.shutDown(); verify(watcherService, never()).stop(anyString(), any()); verify(watcherService, times(1)).shutDown(any()); reset(watcherService); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); verifyNoMoreInteractions(watcherService); } public void testManualStartStop() { Index index = new Index(Watch.INDEX, "uuid"); IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(index); indexRoutingTableBuilder.addShard( TestShardRouting.newShardRouting(new ShardId(index, 0), "node_1", true, ShardRoutingState.STARTED) ); IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(settings(IndexVersion.current()).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) // the internal index format, // required .numberOfShards(1) .numberOfReplicas(0); ProjectMetadata.Builder metadataBuilder = ProjectMetadata.builder(projectId) .put(indexMetadataBuilder) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())); if (randomBoolean()) { metadataBuilder.putCustom(WatcherMetadata.TYPE, new WatcherMetadata(false)); } ProjectMetadata metadata = metadataBuilder.build(); IndexRoutingTable indexRoutingTable = indexRoutingTableBuilder.build(); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTable).build()) .putProjectMetadata(metadata) .build(); when(watcherService.validate(clusterState)).thenReturn(true); // mark watcher manually as stopped ClusterState stoppedClusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(metadata).putCustom(WatcherMetadata.TYPE, new WatcherMetadata(true)).build()) .build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("foo", stoppedClusterState, clusterState)); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); verify(watcherService, times(1)).stop(eq("watcher manually marked to shutdown by cluster state update"), captor.capture()); assertEquals(WatcherState.STOPPING, lifeCycleService.getState().get()); captor.getValue().run(); assertEquals(WatcherState.STOPPED, lifeCycleService.getState().get()); // Starting via cluster state update, as the watcher metadata block is removed/set to true reset(watcherService); when(watcherService.validate(clusterState)).thenReturn(true); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, stoppedClusterState)); verify(watcherService, times(1)).start(eq(clusterState), any(), any()); // no change, keep going reset(watcherService); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); verifyNoMoreInteractions(watcherService); } @SuppressWarnings("unchecked") public void testExceptionOnStart() { /* * This tests that if watcher fails to start because of some exception (for example a timeout while refreshing indices) that it * will fail gracefully, and will start the next time there is a cluster change event if there is no exception that time. */ Index index = new Index(Watch.INDEX, "uuid"); IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(index); indexRoutingTableBuilder.addShard( TestShardRouting.newShardRouting(new ShardId(index, 0), "node_1", true, ShardRoutingState.STARTED) ); IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(settings(IndexVersion.current()).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) // the internal index format, // required .numberOfShards(1) .numberOfReplicas(0); ProjectMetadata.Builder metadataBuilder = ProjectMetadata.builder(projectId) .put(indexMetadataBuilder) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())); if (randomBoolean()) { metadataBuilder.putCustom(WatcherMetadata.TYPE, new WatcherMetadata(false)); } ProjectMetadata metadata = metadataBuilder.build(); IndexRoutingTable indexRoutingTable = indexRoutingTableBuilder.build(); ClusterState clusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTable).build()) .putProjectMetadata(metadata) .build(); // mark watcher manually as stopped ClusterState stoppedClusterState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(metadata).putCustom(WatcherMetadata.TYPE, new WatcherMetadata(true)).build()) .build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("foo", stoppedClusterState, clusterState)); assertThat(lifeCycleService.getState().get(), equalTo(WatcherState.STOPPING)); // Now attempt to start watcher with a simulated TimeoutException. Should be stopped when(watcherService.validate(clusterState)).thenReturn(true); AtomicBoolean exceptionHit = new AtomicBoolean(false); doAnswer(invocation -> { Consumer<Exception> exceptionConsumer = invocation.getArgument(2); exceptionConsumer.accept(new ElasticsearchTimeoutException(new TimeoutException("Artificial timeout"))); exceptionHit.set(true); return null; }).when(watcherService).start(any(), any(), any(Consumer.class)); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); assertTrue("Expected simulated timeout not hit", exceptionHit.get()); assertThat(lifeCycleService.getState().get(), equalTo(WatcherState.STOPPED)); // And now attempt to start watcher with no exception. It should start up. AtomicBoolean runnableCalled = new AtomicBoolean(false); doAnswer(invocation -> { Runnable runnable = invocation.getArgument(1); runnable.run(); runnableCalled.set(true); return null; }).when(watcherService).start(any(), any(Runnable.class), any()); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterState, clusterState)); assertTrue("Runnable not called", runnableCalled.get()); assertThat(lifeCycleService.getState().get(), equalTo(WatcherState.STARTED)); } public void testReloadWithIdenticalRoutingTable() { /* * This tests that the identical routing table causes reload only once. */ startWatcher(); ClusterChangedEvent[] events = masterChangeScenario(); assertThat(events[1].previousState(), equalTo(events[0].state())); assertFalse(events[1].routingTableChanged()); for (ClusterChangedEvent event : events) { when(watcherService.validate(event.state())).thenReturn(true); lifeCycleService.clusterChanged(event); } // reload should occur on the first event verify(watcherService).reload(eq(events[0].state()), anyString(), any()); // but it shouldn't on the second event unless routing table changes verify(watcherService, never()).reload(eq(events[1].state()), anyString(), any()); } public void testReloadWithIdenticalRoutingTableAfterException() { /* * This tests that even the identical routing table causes reload again if some exception (for example a timeout while loading * watches) interrupted the previous one. */ startWatcher(); ClusterChangedEvent[] events = masterChangeScenario(); assertThat(events[1].previousState(), equalTo(events[0].state())); assertFalse(events[1].routingTableChanged()); // simulate exception on the first event doAnswer(invocation -> { Consumer<Exception> exceptionConsumer = invocation.getArgument(2); exceptionConsumer.accept(new ElasticsearchTimeoutException(new TimeoutException("Artificial timeout"))); return null; }).when(watcherService).reload(eq(events[0].state()), anyString(), any()); for (ClusterChangedEvent event : events) { when(watcherService.validate(event.state())).thenReturn(true); lifeCycleService.clusterChanged(event); } // reload should occur on the first event but it fails verify(watcherService).reload(eq(events[0].state()), anyString(), any()); // reload should occur again on the second event because the previous one failed verify(watcherService).reload(eq(events[1].state()), anyString(), any()); } private ClusterChangedEvent[] masterChangeScenario() { DiscoveryNodes nodes = new DiscoveryNodes.Builder().localNodeId("node_1").add(newNode("node_1")).add(newNode("node_2")).build(); Index index = new Index(Watch.INDEX, "uuid"); IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(index); indexRoutingTableBuilder.addShard( TestShardRouting.newShardRouting(new ShardId(index, 0), "node_1", true, ShardRoutingState.STARTED) ); RoutingTable routingTable = RoutingTable.builder().add(indexRoutingTableBuilder.build()).build(); IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(settings(IndexVersion.current()).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) // the internal index format, // required .numberOfShards(1) .numberOfReplicas(0); ProjectMetadata metadata = ProjectMetadata.builder(projectId) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())) .put(indexMetadataBuilder) .build(); GlobalRoutingTable globalRoutingTable = GlobalRoutingTable.builder().put(metadata.id(), routingTable).build(); ClusterState emptyState = ClusterState.builder(new ClusterName("my-cluster")).nodes(nodes).putProjectMetadata(metadata).build(); ClusterState stateWithMasterNode1 = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes.withMasterNodeId("node_1")) .putProjectMetadata(metadata) .routingTable(globalRoutingTable) .build(); ClusterState stateWithMasterNode2 = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes.withMasterNodeId("node_2")) .putProjectMetadata(metadata) .routingTable(globalRoutingTable) .build(); return new ClusterChangedEvent[] { new ClusterChangedEvent("any", stateWithMasterNode1, emptyState), new ClusterChangedEvent("any", stateWithMasterNode2, stateWithMasterNode1) }; } public void testNoLocalShards() { Index watchIndex = new Index(Watch.INDEX, "foo"); ShardId shardId = new ShardId(watchIndex, 0); DiscoveryNodes nodes = new DiscoveryNodes.Builder().masterNodeId("node_1") .localNodeId("node_1") .add(newNode("node_1")) .add(newNode("node_2")) .build(); IndexMetadata indexMetadata = IndexMetadata.builder(Watch.INDEX) .settings(indexSettings(IndexVersion.current(), 1, 0).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) .build(); IndexRoutingTable watchRoutingTable = IndexRoutingTable.builder(watchIndex) .addShard( randomBoolean() ? TestShardRouting.newShardRouting(shardId, "node_1", true, STARTED) : TestShardRouting.newShardRouting(shardId, "node_1", "node_2", true, RELOCATING) ) .build(); ClusterState clusterStateWithLocalShards = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes) .putRoutingTable(projectId, RoutingTable.builder().add(watchRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadata, false)) .build(); // shard moved over to node 2 IndexRoutingTable watchRoutingTableNode2 = IndexRoutingTable.builder(watchIndex) .addShard( randomBoolean() ? TestShardRouting.newShardRouting(shardId, "node_2", true, STARTED) : TestShardRouting.newShardRouting(shardId, "node_2", "node_1", true, RELOCATING) ) .build(); ClusterState clusterStateWithoutLocalShards = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes) .putRoutingTable(projectId, RoutingTable.builder().add(watchRoutingTableNode2).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadata, false)) .build(); // set current allocation ids when(watcherService.validate(eq(clusterStateWithLocalShards))).thenReturn(true); when(watcherService.validate(eq(clusterStateWithoutLocalShards))).thenReturn(false); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterStateWithLocalShards, clusterStateWithoutLocalShards)); verify(watcherService, times(1)).reload(eq(clusterStateWithLocalShards), eq("new local watcher shard allocation ids"), any()); verify(watcherService, times(1)).validate(eq(clusterStateWithLocalShards)); verifyNoMoreInteractions(watcherService); // no more local shards, lets pause execution reset(watcherService); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterStateWithoutLocalShards, clusterStateWithLocalShards)); verify(watcherService, times(1)).pauseExecution(eq("no local watcher shards found")); verifyNoMoreInteractions(watcherService); // no further invocations should happen if the cluster state does not change in regard to local shards reset(watcherService); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterStateWithoutLocalShards, clusterStateWithoutLocalShards)); verifyNoMoreInteractions(watcherService); } public void testReplicaWasAddedOrRemoved() { Index watchIndex = new Index(Watch.INDEX, "foo"); ShardId shardId = new ShardId(watchIndex, 0); ShardId secondShardId = new ShardId(watchIndex, 1); DiscoveryNodes discoveryNodes = new DiscoveryNodes.Builder().masterNodeId("node_1") .localNodeId("node_1") .add(newNode("node_1")) .add(newNode("node_2")) .build(); ShardRouting firstShardOnSecondNode = TestShardRouting.newShardRouting(shardId, "node_2", true, STARTED); ShardRouting secondShardOnFirstNode = TestShardRouting.newShardRouting(secondShardId, "node_1", true, STARTED); IndexRoutingTable previousWatchRoutingTable = IndexRoutingTable.builder(watchIndex) .addShard(secondShardOnFirstNode) .addShard(firstShardOnSecondNode) .build(); IndexMetadata indexMetadata = IndexMetadata.builder(Watch.INDEX) .settings(indexSettings(IndexVersion.current(), 1, 0).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) .build(); ClusterState stateWithPrimaryShard = ClusterState.builder(new ClusterName("my-cluster")) .nodes(discoveryNodes) .putRoutingTable(projectId, RoutingTable.builder().add(previousWatchRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadata, false)) .build(); // add a replica in the local node boolean addShardOnLocalNode = randomBoolean(); final ShardRouting addedShardRouting; if (addShardOnLocalNode) { addedShardRouting = TestShardRouting.newShardRouting(shardId, "node_1", false, STARTED); } else { addedShardRouting = TestShardRouting.newShardRouting(secondShardId, "node_2", false, STARTED); } IndexRoutingTable currentWatchRoutingTable = IndexRoutingTable.builder(watchIndex) .addShard(secondShardOnFirstNode) .addShard(firstShardOnSecondNode) .addShard(addedShardRouting) .build(); ClusterState stateWithReplicaAdded = ClusterState.builder(new ClusterName("my-cluster")) .nodes(discoveryNodes) .putRoutingTable(projectId, RoutingTable.builder().add(currentWatchRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadata, false)) .build(); // randomize between addition or removal of a replica boolean replicaAdded = randomBoolean(); ClusterChangedEvent firstEvent; ClusterChangedEvent secondEvent; if (replicaAdded) { firstEvent = new ClusterChangedEvent("any", stateWithPrimaryShard, stateWithReplicaAdded); secondEvent = new ClusterChangedEvent("any", stateWithReplicaAdded, stateWithPrimaryShard); } else { firstEvent = new ClusterChangedEvent("any", stateWithReplicaAdded, stateWithPrimaryShard); secondEvent = new ClusterChangedEvent("any", stateWithPrimaryShard, stateWithReplicaAdded); } when(watcherService.validate(eq(firstEvent.state()))).thenReturn(true); lifeCycleService.clusterChanged(firstEvent); verify(watcherService).reload(eq(firstEvent.state()), anyString(), any()); reset(watcherService); when(watcherService.validate(eq(secondEvent.state()))).thenReturn(true); lifeCycleService.clusterChanged(secondEvent); verify(watcherService).reload(eq(secondEvent.state()), anyString(), any()); } // make sure that cluster state changes can be processed on nodes that do not hold data public void testNonDataNode() { Index index = new Index(Watch.INDEX, "foo"); ShardId shardId = new ShardId(index, 0); ShardRouting shardRouting = TestShardRouting.newShardRouting(shardId, "node2", true, STARTED); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index).addShard(shardRouting); DiscoveryNode node1 = DiscoveryNodeUtils.builder("node_1") .roles(new HashSet<>(asList(randomFrom(DiscoveryNodeRole.INGEST_ROLE, DiscoveryNodeRole.MASTER_ROLE)))) .build(); DiscoveryNode node2 = DiscoveryNodeUtils.builder("node_2").roles(new HashSet<>(asList(DiscoveryNodeRole.DATA_ROLE))).build(); DiscoveryNode node3 = DiscoveryNodeUtils.builder("node_3").roles(new HashSet<>(asList(DiscoveryNodeRole.DATA_ROLE))).build(); IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(indexSettings(IndexVersion.current(), 1, 0)); ClusterState previousState = ClusterState.builder(new ClusterName("my-cluster")) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadataBuilder)) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(node1).add(node2).add(node3)) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTable).build()) .build(); IndexMetadata.Builder newIndexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(indexSettings(IndexVersion.current(), 1, 1)); ShardRouting replicaShardRouting = TestShardRouting.newShardRouting(shardId, "node3", false, STARTED); IndexRoutingTable.Builder newRoutingTable = IndexRoutingTable.builder(index).addShard(shardRouting).addShard(replicaShardRouting); ClusterState currentState = ClusterState.builder(new ClusterName("my-cluster")) .putProjectMetadata(ProjectMetadata.builder(projectId).put(newIndexMetadataBuilder)) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(node1).add(node2).add(node3)) .putRoutingTable(projectId, RoutingTable.builder().add(newRoutingTable).build()) .build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", currentState, previousState)); verify(watcherService, times(0)).pauseExecution(any()); verify(watcherService, times(0)).reload(any(), any(), any()); } public void testThatMissingWatcherIndexMetadataOnlyResetsOnce() { Index watchIndex = new Index(Watch.INDEX, "foo"); ShardId shardId = new ShardId(watchIndex, 0); IndexRoutingTable watchRoutingTable = IndexRoutingTable.builder(watchIndex) .addShard(TestShardRouting.newShardRouting(shardId, "node_1", true, STARTED)) .build(); DiscoveryNodes nodes = new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1")).build(); IndexMetadata.Builder newIndexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(indexSettings(IndexVersion.current(), 1, 0).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)); ClusterState clusterStateWithWatcherIndex = ClusterState.builder(new ClusterName("my-cluster")) .nodes(nodes) .putRoutingTable(projectId, RoutingTable.builder().add(watchRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(newIndexMetadataBuilder)) .build(); ClusterState clusterStateWithoutWatcherIndex = ClusterState.builder(new ClusterName("my-cluster")).nodes(nodes).build(); when(watcherService.validate(eq(clusterStateWithWatcherIndex))).thenReturn(true); when(watcherService.validate(eq(clusterStateWithoutWatcherIndex))).thenReturn(false); // first add the shard allocation ids, by going from empty cs to CS with watcher index lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterStateWithWatcherIndex, clusterStateWithoutWatcherIndex)); verify(watcherService).reload(eq(clusterStateWithWatcherIndex), anyString(), any()); // now remove watches index, and ensure that pausing is only called once, no matter how often called (i.e. each CS update) lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterStateWithoutWatcherIndex, clusterStateWithWatcherIndex)); verify(watcherService, times(1)).pauseExecution(any()); reset(watcherService); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", clusterStateWithoutWatcherIndex, clusterStateWithWatcherIndex)); verifyNoMoreInteractions(watcherService); } public void testWatcherServiceDoesNotStartIfIndexTemplatesAreMissing() throws Exception { DiscoveryNodes nodes = new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1")).build(); ProjectMetadata.Builder metadataBuilder = ProjectMetadata.builder(projectId); boolean isHistoryTemplateAdded = randomBoolean(); if (isHistoryTemplateAdded) { metadataBuilder.put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())); } ClusterState state = ClusterState.builder(new ClusterName("my-cluster")).nodes(nodes).putProjectMetadata(metadataBuilder).build(); when(watcherService.validate(eq(state))).thenReturn(true); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", state, state)); verify(watcherService, times(0)).start(any(ClusterState.class), any(), any()); } public void testWatcherStopsWhenMasterNodeIsMissing() { startWatcher(); DiscoveryNodes nodes = new DiscoveryNodes.Builder().localNodeId("node_1").add(newNode("node_1")).build(); ClusterState state = ClusterState.builder(new ClusterName("my-cluster")).nodes(nodes).build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", state, state)); verify(watcherService, times(1)).pauseExecution(eq("no master node")); } public void testWatcherStopsOnClusterLevelBlock() { startWatcher(); DiscoveryNodes nodes = new DiscoveryNodes.Builder().localNodeId("node_1").masterNodeId("node_1").add(newNode("node_1")).build(); ClusterBlocks clusterBlocks = ClusterBlocks.builder().addGlobalBlock(NoMasterBlockService.NO_MASTER_BLOCK_WRITES).build(); ClusterState state = ClusterState.builder(new ClusterName("my-cluster")).nodes(nodes).blocks(clusterBlocks).build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("any", state, state)); verify(watcherService, times(1)).pauseExecution(eq("write level cluster block")); } public void testMasterOnlyNodeCanStart() { List<DiscoveryNodeRole> roles = Collections.singletonList(randomFrom(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.INGEST_ROLE)); ClusterState state = ClusterState.builder(new ClusterName("my-cluster")) .nodes( new DiscoveryNodes.Builder().masterNodeId("node_1") .localNodeId("node_1") .add(DiscoveryNodeUtils.builder("node_1").roles(new HashSet<>(roles)).build()) ) .build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("test", state, state)); assertThat(lifeCycleService.getState().get(), is(WatcherState.STARTED)); } public void testDataNodeWithoutDataCanStart() { ProjectMetadata metadata = ProjectMetadata.builder(projectId) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())) .build(); ClusterState state = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putProjectMetadata(metadata) .build(); lifeCycleService.clusterChanged(new ClusterChangedEvent("test", state, state)); assertThat(lifeCycleService.getState().get(), is(WatcherState.STARTED)); } // this emulates a node outage somewhere in the cluster that carried a watcher shard // the number of shards remains the same, but we need to ensure that watcher properly reloads // previously we only checked the local shard allocations, but we also need to check if shards in the cluster have changed public void testWatcherReloadsOnNodeOutageWithWatcherShard() { Index watchIndex = new Index(Watch.INDEX, "foo"); ShardId shardId = new ShardId(watchIndex, 0); String localNodeId = randomFrom("node_1", "node_2"); String outageNodeId = localNodeId.equals("node_1") ? "node_2" : "node_1"; DiscoveryNodes previousDiscoveryNodes = new DiscoveryNodes.Builder().masterNodeId(localNodeId) .localNodeId(localNodeId) .add(newNode(localNodeId)) .add(newNode(outageNodeId)) .build(); ShardRouting replicaShardRouting = TestShardRouting.newShardRouting(shardId, localNodeId, false, STARTED); ShardRouting primartShardRouting = TestShardRouting.newShardRouting(shardId, outageNodeId, true, STARTED); IndexRoutingTable previousWatchRoutingTable = IndexRoutingTable.builder(watchIndex) .addShard(replicaShardRouting) .addShard(primartShardRouting) .build(); IndexMetadata indexMetadata = IndexMetadata.builder(Watch.INDEX) .settings(indexSettings(IndexVersion.current(), 1, 0).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) .build(); ClusterState previousState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(previousDiscoveryNodes) .putRoutingTable(projectId, RoutingTable.builder().add(previousWatchRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadata, false)) .build(); ShardRouting nowPrimaryShardRouting = replicaShardRouting.moveActiveReplicaToPrimary(); IndexRoutingTable currentWatchRoutingTable = IndexRoutingTable.builder(watchIndex).addShard(nowPrimaryShardRouting).build(); DiscoveryNodes currentDiscoveryNodes = new DiscoveryNodes.Builder().masterNodeId(localNodeId) .localNodeId(localNodeId) .add(newNode(localNodeId)) .build(); ClusterState currentState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(currentDiscoveryNodes) .putRoutingTable(projectId, RoutingTable.builder().add(currentWatchRoutingTable).build()) .putProjectMetadata(ProjectMetadata.builder(projectId).put(indexMetadata, false)) .build(); // initialize the previous state, so all the allocation ids are loaded when(watcherService.validate(any())).thenReturn(true); lifeCycleService.clusterChanged(new ClusterChangedEvent("whatever", previousState, currentState)); reset(watcherService); when(watcherService.validate(any())).thenReturn(true); ClusterChangedEvent event = new ClusterChangedEvent("whatever", currentState, previousState); lifeCycleService.clusterChanged(event); verify(watcherService).reload(eq(event.state()), anyString(), any()); } private void startWatcher() { Index index = new Index(Watch.INDEX, "uuid"); IndexRoutingTable.Builder indexRoutingTableBuilder = IndexRoutingTable.builder(index); indexRoutingTableBuilder.addShard( TestShardRouting.newShardRouting(new ShardId(index, 0), "node_1", true, ShardRoutingState.STARTED) ); IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(Watch.INDEX) .settings(settings(IndexVersion.current()).put(IndexMetadata.INDEX_FORMAT_SETTING.getKey(), 6)) // the internal index format, // required .numberOfShards(1) .numberOfReplicas(0); ProjectMetadata metadata = ProjectMetadata.builder(projectId) .put(IndexTemplateMetadata.builder(HISTORY_TEMPLATE_NAME).patterns(randomIndexPatterns())) .put(indexMetadataBuilder) .build(); ClusterState state = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putRoutingTable(projectId, RoutingTable.builder().add(indexRoutingTableBuilder.build()).build()) .putProjectMetadata(metadata) .build(); ClusterState emptyState = ClusterState.builder(new ClusterName("my-cluster")) .nodes(new DiscoveryNodes.Builder().masterNodeId("node_1").localNodeId("node_1").add(newNode("node_1"))) .putProjectMetadata(metadata) .build(); when(watcherService.validate(state)).thenReturn(true); lifeCycleService.clusterChanged(new ClusterChangedEvent("foo", state, emptyState)); assertThat(lifeCycleService.getState().get(), is(WatcherState.STARTED)); verify(watcherService, times(1)).reload(eq(state), anyString(), any()); assertThat(lifeCycleService.shardRoutings(), hasSize(1)); // reset the mock, the user has to mock everything themselves again reset(watcherService); } private List<String> randomIndexPatterns() { return IntStream.range(0, between(1, 10)).mapToObj(n -> randomAlphaOfLengthBetween(1, 100)).collect(Collectors.toList()); } private static DiscoveryNode newNode(String nodeName) { return DiscoveryNodeUtils.builder(nodeName).build(); } }
WatcherLifeCycleServiceTests
java
spring-projects__spring-boot
system-test/spring-boot-image-system-tests/src/systemTest/java/org/springframework/boot/image/paketo/PaketoBuilderTests.java
{ "start": 19751, "end": 20101 }
class ____ {"); writer.println(); writer.println(" public static void main(String[] args) {"); writer.println(" SpringApplication.run(ExampleApplication.class, args);"); writer.println(" }"); writer.println(); writer.println("}"); writer.println(); writer.println("@Controller"); writer.println("
ExampleApplication
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_33.java
{ "start": 583, "end": 2401 }
class ____ extends TestCase { public void test_for_parameterize() throws Exception { final DbType dbType = JdbcConstants.MYSQL; String sql = "select * from t where id = 1 or id = 2"; String psql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE id = ?", psql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType); List<SQLStatement> stmtList = parser.parseStatementList(); StringBuilder out = new StringBuilder(); SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, JdbcConstants.MYSQL); List<Object> parameters = new ArrayList<Object>(); visitor.setParameterized(true); visitor.setParameterizedMergeInList(true); visitor.setParameters(parameters); visitor.setExportTables(true); /*visitor.setPrettyFormat(false);*/ SQLStatement stmt = stmtList.get(0); stmt.accept(visitor); // System.out.println(parameters); assertEquals(1, parameters.size()); //SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(psql, dbType); // List<SQLStatement> stmtList = parser.parseStatementList(); SQLStatement pstmt = SQLUtils.parseStatements(psql, dbType).get(0); StringBuilder buf = new StringBuilder(); SQLASTOutputVisitor visitor1 = SQLUtils.createOutputVisitor(buf, dbType); visitor1.addTableMapping("udata", "udata_0888"); visitor1.setInputParameters(visitor.getParameters()); pstmt.accept(visitor1); assertEquals("SELECT *\n" + "FROM t\n" + "WHERE id IN (1, 2)", buf.toString()); } }
MySqlParameterizedOutputVisitorTest_33
java
apache__flink
flink-core/src/test/java/org/apache/flink/configuration/ConfigurationUtilsTest.java
{ "start": 1342, "end": 10179 }
class ____ { @Test void testPropertiesToConfiguration() { final Properties properties = new Properties(); final int entries = 10; for (int i = 0; i < entries; i++) { properties.setProperty("key" + i, "value" + i); } final Configuration configuration = ConfigurationUtils.createConfiguration(properties); for (String key : properties.stringPropertyNames()) { assertThat(configuration.getString(key, "")).isEqualTo(properties.getProperty(key)); } assertThat(configuration.toMap()).hasSize(properties.size()); } @Test void testStandardYamlSupportLegacyPattern() { List<String> expectedList = Arrays.asList("a", "b", "c"); String legacyListPattern = "a;b;c"; Map<String, String> expectedMap = new HashMap<>(); expectedMap.put("k1", "v1"); expectedMap.put("k2", "v2"); String legacyMapPattern = "k1:v1,k2:v2"; Configuration configuration = new Configuration(); configuration.setString("listKey", legacyListPattern); configuration.setString("mapKey", legacyMapPattern); assertThat( configuration.get( ConfigOptions.key("listKey") .stringType() .asList() .noDefaultValue())) .isEqualTo(expectedList); assertThat(configuration.get(ConfigOptions.key("mapKey").mapType().noDefaultValue())) .isEqualTo(expectedMap); } @Test void testConvertConfigToWritableLinesAndFlattenYaml() { testConvertConfigToWritableLines(true); } @Test void testConvertConfigToWritableLinesAndNoFlattenYaml() { testConvertConfigToWritableLines(false); } private void testConvertConfigToWritableLines(boolean flattenYaml) { final Configuration configuration = new Configuration(); ConfigOption<List<String>> nestedListOption = ConfigOptions.key("nested.test-list-key").stringType().asList().noDefaultValue(); final String listValues = "value1;value2;value3"; final String yamlListValues = "[value1, value2, value3]"; configuration.set(nestedListOption, Arrays.asList(listValues.split(";"))); ConfigOption<Map<String, String>> nestedMapOption = ConfigOptions.key("nested.test-map-key").mapType().noDefaultValue(); final String mapValues = "key1:value1,key2:value2"; final String yamlMapValues = "{key1: value1, key2: value2}"; configuration.set( nestedMapOption, Arrays.stream(mapValues.split(",")) .collect(Collectors.toMap(e -> e.split(":")[0], e -> e.split(":")[1]))); ConfigOption<Duration> nestedDurationOption = ConfigOptions.key("nested.test-duration-key").durationType().noDefaultValue(); final Duration duration = Duration.ofMillis(3000); configuration.set(nestedDurationOption, duration); ConfigOption<String> nestedStringOption = ConfigOptions.key("nested.test-string-key").stringType().noDefaultValue(); final String strValues = "*"; final String yamlStrValues = "'*'"; configuration.set(nestedStringOption, strValues); ConfigOption<Integer> intOption = ConfigOptions.key("test-int-key").intType().noDefaultValue(); final int intValue = 1; configuration.set(intOption, intValue); List<String> actualData = ConfigurationUtils.convertConfigToWritableLines(configuration, flattenYaml); List<String> expected; if (flattenYaml) { expected = Arrays.asList( nestedListOption.key() + ": " + yamlListValues, nestedMapOption.key() + ": " + yamlMapValues, nestedDurationOption.key() + ": " + TimeUtils.formatWithHighestUnit(duration), nestedStringOption.key() + ": " + yamlStrValues, intOption.key() + ": " + intValue); } else { expected = Arrays.asList( "nested:", " test-list-key:", " - value1", " - value2", " - value3", " test-map-key:", " key1: value1", " key2: value2", " test-duration-key: 3 s", " test-string-key: '*'", "test-int-key: 1"); } assertThat(expected).containsExactlyInAnyOrderElementsOf(actualData); } @Test void testHideSensitiveValues() { final Map<String, String> keyValuePairs = new HashMap<>(); keyValuePairs.put("foobar", "barfoo"); final String secretKey1 = "secret.key"; keyValuePairs.put(secretKey1, "12345"); final String secretKey2 = "my.password"; keyValuePairs.put(secretKey2, "12345"); final Map<String, String> expectedKeyValuePairs = new HashMap<>(keyValuePairs); for (String secretKey : Arrays.asList(secretKey1, secretKey2)) { expectedKeyValuePairs.put(secretKey, GlobalConfiguration.HIDDEN_CONTENT); } final Map<String, String> hiddenSensitiveValues = ConfigurationUtils.hideSensitiveValues(keyValuePairs); assertThat(hiddenSensitiveValues).isEqualTo(expectedKeyValuePairs); } @Test void testGetPrefixedKeyValuePairs() { final String prefix = "test.prefix."; final Map<String, String> expectedKeyValuePairs = new HashMap<String, String>() { { put("k1", "v1"); put("k2", "v2"); } }; final Configuration configuration = new Configuration(); expectedKeyValuePairs.forEach((k, v) -> configuration.setString(prefix + k, v)); final Map<String, String> resultKeyValuePairs = ConfigurationUtils.getPrefixedKeyValuePairs(prefix, configuration); assertThat(resultKeyValuePairs).isEqualTo(expectedKeyValuePairs); } @Test void testConvertToString() { // String assertThat(ConfigurationUtils.convertToString("Simple String")).isEqualTo("Simple String"); // Duration assertThat(ConfigurationUtils.convertToString(Duration.ZERO)).isEqualTo("0 ms"); assertThat(ConfigurationUtils.convertToString(Duration.ofMillis(123L))).isEqualTo("123 ms"); assertThat(ConfigurationUtils.convertToString(Duration.ofMillis(1_234_000L))) .isEqualTo("1234 s"); assertThat(ConfigurationUtils.convertToString(Duration.ofHours(25L))).isEqualTo("25 h"); // List List<Object> listElements = new ArrayList<>(); listElements.add("Test;String"); listElements.add(Duration.ZERO); listElements.add(42); assertThat("[Test;String, 0 ms, 42]") .isEqualTo(ConfigurationUtils.convertToString(listElements)); // Map Map<Object, Object> mapElements = new HashMap<>(); mapElements.put("A:,B", "C:,D"); mapElements.put(10, 20); assertThat("{'A:,B': 'C:,D', 10: 20}") .isEqualTo(ConfigurationUtils.convertToString(mapElements)); } @Test void testRandomTempDirectorySelection() { final Configuration configuration = new Configuration(); final StringBuilder tempDirectories = new StringBuilder(); final int numberTempDirectories = 20; for (int i = 0; i < numberTempDirectories; i++) { tempDirectories.append(UUID.randomUUID()).append(','); } configuration.set(CoreOptions.TMP_DIRS, tempDirectories.toString()); final Set<File> allTempDirectories = Arrays.stream(ConfigurationUtils.parseTempDirectories(configuration)) .map(File::new) .collect(Collectors.toSet()); final Set<File> drawnTempDirectories = new HashSet<>(); final int numberDraws = 100; for (int i = 0; i < numberDraws; i++) { drawnTempDirectories.add(ConfigurationUtils.getRandomTempDirectory(configuration)); } assertThat(drawnTempDirectories).hasSizeGreaterThan(1); assertThat(drawnTempDirectories).isSubsetOf(allTempDirectories); } }
ConfigurationUtilsTest
java
spring-projects__spring-framework
spring-orm/src/main/java/org/springframework/orm/ObjectOptimisticLockingFailureException.java
{ "start": 5147, "end": 5637 }
class ____ the object for which the locking failed. * Will work for both Class objects and String names. */ public @Nullable String getPersistentClassName() { if (this.persistentClass instanceof Class<?> clazz) { return clazz.getName(); } return (this.persistentClass != null ? this.persistentClass.toString() : null); } /** * Return the identifier of the object for which the locking failed. */ public @Nullable Object getIdentifier() { return this.identifier; } }
of
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/SetFactoryCreationExpression.java
{ "start": 2119, "end": 6715 }
class ____ extends MultibindingFactoryCreationExpression { private final CompilerOptions compilerOptions; private final BindingGraph graph; private final MultiboundSetBinding binding; private final ShardImplementation shardImplementation; private String methodName; @AssistedInject SetFactoryCreationExpression( @Assisted MultiboundSetBinding binding, ComponentImplementation componentImplementation, ComponentRequestRepresentations componentRequestRepresentations, CompilerOptions compilerOptions, BindingGraph graph) { super(binding, componentImplementation, componentRequestRepresentations, compilerOptions); this.binding = checkNotNull(binding); this.shardImplementation = componentImplementation.shardImplementation(binding); this.compilerOptions = compilerOptions; this.graph = graph; } @Override public XCodeBlock creationExpression() { return XCodeBlock.of( "%N(%L)", methodName(), parameterNames(shardImplementation.constructorParameters())); } private String methodName() { if (methodName == null) { // Have to set methodName field before implementing the method in order to handle recursion. methodName = shardImplementation.getUniqueMethodName( KeyVariableNamer.name(binding.key()) + "Builder"); UniqueNameSet uniqueNameSet = new UniqueNameSet(); shardImplementation.constructorParameters().stream() .map(XParameterSpec::getName) // SUPPRESS_GET_NAME_CHECK .forEach(uniqueNameSet::claim); String builderName = uniqueNameSet.getUniqueName("builder"); int individualProviders = 0; int setProviders = 0; XCodeBlock.Builder builderMethodCalls = XCodeBlock.builder(); String methodNameSuffix = binding.bindingType().equals(BindingType.PROVISION) ? "Provider" : "Producer"; for (DependencyRequest dependency : binding.dependencies()) { String methodNamePrefix; XCodeBlock dependencyExpression = multibindingDependencyExpression(dependency); switch (graph.contributionBinding(dependency.key()).contributionType()) { case SET: individualProviders++; methodNamePrefix = "add"; break; case SET_VALUES: setProviders++; methodNamePrefix = "addCollection"; break; default: throw new AssertionError(dependency + " is not a set multibinding"); } builderMethodCalls.addStatement( "%N.%N%N(%L)", builderName, methodNamePrefix, methodNameSuffix, dependencyExpression); } XFunSpec methodSpec = methodBuilder(methodName) .addParameters(shardImplementation.constructorParameters()) // TODO(bcorso): remove once dagger.generatedClassExtendsComponent flag is removed. .addModifiers( !shardImplementation.isShardClassPrivate() ? ImmutableSet.of(PRIVATE) : ImmutableSet.of()) .returns(setFactoryType()) .addCode( XCodeBlock.builder() .addStatement( "%T %N = %T.builder(%L, %L)", setFactoryBuilderType(), builderName, setFactoryClassName(binding), individualProviders, setProviders) .add(builderMethodCalls.build()) .addStatement("return %N.build()", builderName) .build()) .build(); shardImplementation.addMethod(INITIALIZE_HELPER_METHOD, methodSpec); } return methodName; } private XTypeName setFactoryType() { return useRawType() ? setFactoryClassName(binding) : setFactoryClassName(binding).parametrizedBy(valueTypeName()); } private XTypeName setFactoryBuilderType() { return useRawType() ? setFactoryClassName(binding).nestedClass("Builder") : setFactoryClassName(binding) .nestedClass("Builder") .parametrizedBy(valueTypeName()); } private XTypeName valueTypeName() { SetType setType = SetType.from(binding.key()); return setType.elementsAreTypeOf(XTypeNames.PRODUCED) ? setType.unwrappedElementType(XTypeNames.PRODUCED).asTypeName() : setType.elementType().asTypeName(); } @AssistedFactory static
SetFactoryCreationExpression
java
quarkusio__quarkus
test-framework/junit5-component/src/main/java/io/quarkus/test/component/QuarkusComponentFacadeClassLoaderProvider.java
{ "start": 1390, "end": 3389 }
class ____ found: %s [CL=%s]", name, QuarkusComponentFacadeClassLoaderProvider.class.getClassLoader()); return null; } } for (Annotation a : inspectionClass.getAnnotations()) { if (a.annotationType().getName().equals("io.quarkus.test.component.QuarkusComponentTest")) { configuration = QuarkusComponentTestConfiguration.DEFAULT.update(inspectionClass); break; } } if (configuration == null) { for (Field field : inspectionClass.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) && field.getType().getName().equals("io.quarkus.test.component.QuarkusComponentTestExtension")) { QuarkusComponentTestExtension extension; try { field.setAccessible(true); extension = (QuarkusComponentTestExtension) field.get(null); buildShouldFail = extension.isBuildShouldFail(); configuration = extension.baseConfiguration.update(inspectionClass); break; } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException("Unable to read configuration from field: " + field, e); } } } } if (configuration != null) { try { LOG.debugf("Created QuarkusComponentTestClassLoader for %s", inspectionClass); return new QuarkusComponentTestClassLoader(parent, name, ComponentContainer.build(inspectionClass, configuration, buildShouldFail, tracedClasses)); } catch (Exception e) { throw new IllegalStateException("Unable to build container for %s".formatted(name), e); } } return null; } }
not
java
resilience4j__resilience4j
resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/TimerRegistry.java
{ "start": 1158, "end": 8085 }
interface ____ extends Registry<Timer, TimerConfig> { /** * Creates a TimerRegistry. * * @param meterRegistry the registry to bind Timer to * @return a TimerRegistry with a default Timer configuration. */ static TimerRegistry ofDefaults(MeterRegistry meterRegistry) { return of(TimerConfig.ofDefaults(), emptyMap(), emptyList(), emptyMap(), meterRegistry); } /** * Creates a TimerRegistry. * * @param defaultConfig the default config to use for new Timers * @param meterRegistry the registry to bind Timer to * @return a TimerRegistry with a custom Timer configuration. */ static TimerRegistry of(TimerConfig defaultConfig, MeterRegistry meterRegistry) { return of(defaultConfig, emptyMap(), emptyList(), emptyMap(), meterRegistry); } /** * Creates a TimerRegistry. * * @param defaultConfig the default config to use for new Timers * @param configs the additional configs to use for new Timers * @param meterRegistry the registry to bind Timer to * @return a TimerRegistry with a custom Timer configuration. */ static TimerRegistry of(TimerConfig defaultConfig, Map<String, TimerConfig> configs, MeterRegistry meterRegistry) { return of(defaultConfig, configs, emptyList(), emptyMap(), meterRegistry); } /** * Creates a TimerRegistry. * * @param configs the additional configs to use for new Timers * @param registryEventConsumers initialized consumers for timers * @param tags a map of tags for the registry * @param meterRegistry the registry to bind Timer to * @return a TimerRegistry with a Map of shared Timer configurations and a list of Timer * registry event consumers. */ static TimerRegistry of(Map<String, TimerConfig> configs, List<RegistryEventConsumer<Timer>> registryEventConsumers, Map<String, String> tags, MeterRegistry meterRegistry) { return new InMemoryTimerRegistry(configs, registryEventConsumers, tags, meterRegistry); } /** * Creates a TimerRegistry. * * @param defaultConfig the default config to use for new Timers * @param configs the additional configs to use for new Timers * @param registryEventConsumers initialized consumers for timers * @param tags a map of tags for the registry * @param meterRegistry the registry to bind Timer to * @return a TimerRegistry with a Map of shared Timer configurations and a list of Timer * registry event consumers. */ static TimerRegistry of(TimerConfig defaultConfig, Map<String, TimerConfig> configs, List<RegistryEventConsumer<Timer>> registryEventConsumers, Map<String, String> tags, MeterRegistry meterRegistry) { return new InMemoryTimerRegistry(defaultConfig, configs, registryEventConsumers, tags, meterRegistry); } /** * Returns all managed {@link Timer} instances. * * @return all managed {@link Timer} instances. */ Stream<Timer> getAllTimers(); /** * Returns a managed {@link Timer} or creates a new one with the default Timer * configuration. * * @param name the name of the Timer * @return The {@link Timer} */ Timer timer(String name); /** * Returns a managed {@link Timer} or creates a new one with the default Timer * configuration. * <p> * The {@code tags} passed will be appended to the tags already configured for the registry. * When tags (keys) of the two collide the tags passed with this method will override the tags * of the registry. * * @param name the name of the Timer * @param tags tags added to the Timer * @return The {@link Timer} */ Timer timer(String name, Map<String, String> tags); /** * Returns a managed {@link Timer} or creates a new one with a custom Timer * configuration. * * @param name the name of the Timer * @param config a custom Timer configuration * @return The {@link Timer} */ Timer timer(String name, TimerConfig config); /** * Returns a managed {@link Timer} or creates a new one with a custom Timer * configuration. * <p> * The {@code tags} passed will be appended to the tags already configured for the registry. * When tags (keys) of the two collide the tags passed with this method will override the tags * of the registry. * * @param name the name of the Timer * @param config a custom Timer configuration * @param tags tags added to the Timer * @return The {@link Timer} */ Timer timer(String name, TimerConfig config, Map<String, String> tags); /** * Returns a managed {@link TimerConfig} or creates a new one with a custom * TimerConfig configuration. * * @param name the name of the TimerConfig * @param configSupplier a supplier of a custom TimerConfig configuration * @return The {@link TimerConfig} */ Timer timer(String name, Supplier<TimerConfig> configSupplier); /** * Returns a managed {@link Timer} or creates a new one with a custom Timer * configuration. * <p> * The {@code tags} passed will be appended to the tags already configured for the registry. * When tags (keys) of the two collide the tags passed with this method will override the tags * of the registry. * * @param name the name of the Timer * @param configSupplier a supplier of a custom Timer configuration * @param tags tags added to the Timer * @return The {@link Timer} */ Timer timer(String name, Supplier<TimerConfig> configSupplier, Map<String, String> tags); /** * Returns a managed {@link Timer} or creates a new one. * The configuration must have been added upfront via {@link #addConfiguration(String, Object)}. * * @param name the name of the Timer * @param configName the name of the shared configuration * @return The {@link Timer} */ Timer timer(String name, String configName); /** * Returns a managed {@link Timer} or creates a new one. * The configuration must have been added upfront via {@link #addConfiguration(String, Object)}. * <p> * The {@code tags} passed will be appended to the tags already configured for the registry. * When tags (keys) of the two collide the tags passed with this method will override the tags * of the registry. * * @param name the name of the Timer * @param configName the name of the shared configuration * @param tags tags added to the Timer * @return The {@link Timer} */ Timer timer(String name, String configName, Map<String, String> tags); }
TimerRegistry
java
quarkusio__quarkus
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java
{ "start": 4886, "end": 5433 }
class ____ validationErrors.produce(new ValidationErrorBuildItem( new IllegalStateException(String.format( "The %s class %s declares an interceptor binding but it must be ignored per CDI rules", clazz.nestingType().toString(), clazz.name().toString())))); } // iterate over methods and verify those // note that since JDK 16, you can have static method inside inner non-static
level
java
apache__camel
components/camel-soap/src/test/java/org/apache/camel/converter/soap/name/TypeNameStrategyTest.java
{ "start": 1161, "end": 2394 }
class ____ { @Test public void testTypeNameStrategy() { TypeNameStrategy strategy = new TypeNameStrategy(); QName name = strategy.findQNameForSoapActionOrType("", GetCustomersByName.class); assertEquals("http://customerservice.example.com/", name.getNamespaceURI()); assertEquals("getCustomersByName", name.getLocalPart()); } @Test public void testNoAnnotation() { TypeNameStrategy strategy = new TypeNameStrategy(); try { strategy.findQNameForSoapActionOrType("", String.class); fail(); } catch (RuntimeException e) { // Expected here } } @Test public void testNoPackageInfo() { TypeNameStrategy strategy = new TypeNameStrategy(); QName name = strategy.findQNameForSoapActionOrType("", AnnotatedClassWithoutNamespace.class); assertEquals("test", name.getLocalPart()); assertEquals("##default", name.getNamespaceURI()); QName name2 = strategy.findQNameForSoapActionOrType("", AnnotatedClassWithNamespace.class); assertEquals("test", name2.getLocalPart()); assertEquals("http://mynamespace", name2.getNamespaceURI()); } }
TypeNameStrategyTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IterableAndIteratorTest.java
{ "start": 1574, "end": 2398 }
class ____ implements Iterator<MyNode>, Iterable<MyNode> { private MyNode head; public MyBadList() { head = null; } @Override public boolean hasNext() { return head != null; } @Override public MyNode next() { if (hasNext()) { MyNode ret = head; head = head.next; return ret; } return null; } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported"); } public void add(MyNode node) { if (!hasNext()) { head.next = node; } head = node; } @Override public Iterator<MyNode> iterator() { return this; } } /** Test List that extends the above bad implementation Diagnostic should bypass this */ public static
MyBadList
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/entity/EntityColumnFamily.java
{ "start": 1146, "end": 2164 }
enum ____ implements ColumnFamily<EntityTable> { /** * Info column family houses known columns, specifically ones included in * columnfamily filters. */ INFO("i"), /** * Configurations are in a separate column family for two reasons: a) the size * of the config values can be very large and b) we expect that config values * are often separately accessed from other metrics and info columns. */ CONFIGS("c"), /** * Metrics have a separate column family, because they have a separate TTL. */ METRICS("m"); /** * Byte representation of this column family. */ private final byte[] bytes; /** * @param value create a column family with this name. Must be lower case and * without spaces. */ EntityColumnFamily(String value) { // column families should be lower case and not contain any spaces. this.bytes = Bytes.toBytes(Separator.SPACE.encode(value)); } public byte[] getBytes() { return Bytes.copy(bytes); } }
EntityColumnFamily
java
apache__maven
compat/maven-embedder/src/main/java/org/apache/maven/cli/internal/extension/model/io/xpp3/CoreExtensionsXpp3Writer.java
{ "start": 1531, "end": 6865 }
class ____ { // --------------------------/ // - Class/Member Variables -/ // --------------------------/ /** * Field NAMESPACE. */ private static final String NAMESPACE = null; /** * Field fileComment. */ private String fileComment = null; // -----------/ // - Methods -/ // -----------/ /** * Method setFileComment. * * @param fileComment a fileComment object. */ public void setFileComment(String fileComment) { this.fileComment = fileComment; } // -- void setFileComment( String ) /** * Method write. * * @param writer a writer object. * @param coreExtensions a coreExtensions object. * @throws IOException IOException if any. */ public void write(Writer writer, CoreExtensions coreExtensions) throws IOException { XmlSerializer serializer = new MXSerializer(); serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " "); serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n"); serializer.setOutput(writer); serializer.startDocument(coreExtensions.getModelEncoding(), null); writeCoreExtensions(coreExtensions, "extensions", serializer); serializer.endDocument(); } // -- void write( Writer, CoreExtensions ) /** * Method write. * * @param stream a stream object. * @param coreExtensions a coreExtensions object. * @throws IOException IOException if any. */ public void write(OutputStream stream, CoreExtensions coreExtensions) throws IOException { XmlSerializer serializer = new MXSerializer(); serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-indentation", " "); serializer.setProperty("http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n"); serializer.setOutput(stream, coreExtensions.getModelEncoding()); serializer.startDocument(coreExtensions.getModelEncoding(), null); writeCoreExtensions(coreExtensions, "extensions", serializer); serializer.endDocument(); } // -- void write( OutputStream, CoreExtensions ) /** * Method writeCoreExtension. * * @param coreExtension a coreExtension object. * @param serializer a serializer object. * @param tagName a tagName object. * @throws IOException IOException if any. */ private void writeCoreExtension(CoreExtension coreExtension, String tagName, XmlSerializer serializer) throws IOException { serializer.startTag(NAMESPACE, tagName); if (coreExtension.getGroupId() != null) { serializer .startTag(NAMESPACE, "groupId") .text(coreExtension.getGroupId()) .endTag(NAMESPACE, "groupId"); } if (coreExtension.getArtifactId() != null) { serializer .startTag(NAMESPACE, "artifactId") .text(coreExtension.getArtifactId()) .endTag(NAMESPACE, "artifactId"); } if (coreExtension.getVersion() != null) { serializer .startTag(NAMESPACE, "version") .text(coreExtension.getVersion()) .endTag(NAMESPACE, "version"); } if ((coreExtension.getClassLoadingStrategy() != null) && !coreExtension.getClassLoadingStrategy().equals("self-first")) { serializer .startTag(NAMESPACE, "classLoadingStrategy") .text(coreExtension.getClassLoadingStrategy()) .endTag(NAMESPACE, "classLoadingStrategy"); } serializer.endTag(NAMESPACE, tagName); } // -- void writeCoreExtension( CoreExtension, String, XmlSerializer ) /** * Method writeCoreExtensions. * * @param coreExtensions a coreExtensions object. * @param serializer a serializer object. * @param tagName a tagName object. * @throws IOException IOException if any. */ private void writeCoreExtensions(CoreExtensions coreExtensions, String tagName, XmlSerializer serializer) throws IOException { if (this.fileComment != null) { serializer.comment(this.fileComment); } serializer.setPrefix("", "http://maven.apache.org/EXTENSIONS/1.1.0"); serializer.setPrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance"); serializer.startTag(NAMESPACE, tagName); serializer.attribute( "", "xsi:schemaLocation", "http://maven.apache.org/EXTENSIONS/1.1.0 https://maven.apache.org/xsd/core-extensions-1.1.0.xsd"); if ((coreExtensions.getExtensions() != null) && (coreExtensions.getExtensions().size() > 0)) { for (Iterator iter = coreExtensions.getExtensions().iterator(); iter.hasNext(); ) { CoreExtension o = (CoreExtension) iter.next(); writeCoreExtension(o, "extension", serializer); } } serializer.endTag(NAMESPACE, tagName); } // -- void writeCoreExtensions( CoreExtensions, String, XmlSerializer ) }
CoreExtensionsXpp3Writer