language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/util/JsonUtilsTest.java
{ "start": 1050, "end": 2567 }
class ____ { @Test void testQuoteCharSequenceAsString() { final StringBuilder output = new StringBuilder(); final StringBuilder builder = new StringBuilder(); builder.append("foobar"); JsonUtils.quoteAsString(builder, output); assertEquals("foobar", output.toString()); builder.setLength(0); output.setLength(0); builder.append("\"x\""); JsonUtils.quoteAsString(builder, output); assertEquals("\\\"x\\\"", output.toString()); } // For [JACKSON-853] @Test void testQuoteLongCharSequenceAsString() { final StringBuilder output = new StringBuilder(); final StringBuilder input = new StringBuilder(); final StringBuilder sb2 = new StringBuilder(); for (int i = 0; i < 1111; ++i) { input.append('"'); sb2.append("\\\""); } final String exp = sb2.toString(); JsonUtils.quoteAsString(input, output); assertEquals(2 * input.length(), output.length()); assertEquals(exp, output.toString()); } // [JACKSON-884] @Test void testCharSequenceWithCtrlChars() { final char[] input = new char[] {0, 1, 2, 3, 4}; final StringBuilder builder = new StringBuilder(); builder.append(input); final StringBuilder output = new StringBuilder(); JsonUtils.quoteAsString(builder, output); assertEquals("\\u0000\\u0001\\u0002\\u0003\\u0004", output.toString()); } }
JsonUtilsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/orphan/onetoone/OneToOneEagerOrphanRemovalTest.java
{ "start": 796, "end": 2482 }
class ____ { @Test public void testOneToOneEagerOrphanRemoval(EntityManagerFactoryScope scope) { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initialize the data scope.inTransaction( entityManager -> { final PaintColor color = new PaintColor( 1, "Red" ); final Engine engine = new Engine( 1, 275 ); final Car car = new Car( 1, engine, color ); entityManager.persist( engine ); entityManager.persist( color ); entityManager.persist( car ); } ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Test orphan removal for unidirectional relationship scope.inTransaction( entityManager -> { final Car car = entityManager.find( Car.class, 1 ); car.setEngine( null ); entityManager.merge( car ); } ); scope.inTransaction( entityManager -> { final Car car = entityManager.find( Car.class, 1 ); assertNull( car.getEngine() ); final Engine engine = entityManager.find( Engine.class, 1 ); assertNull( engine ); } ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Test orphan removal for bidirectional relationship scope.inTransaction( entityManager -> { final Car car = entityManager.find( Car.class, 1 ); car.setPaintColor( null ); entityManager.merge( car ); } ); scope.inTransaction( entityManager -> { final Car car = entityManager.find( Car.class, 1 ); assertNull( car.getPaintColor() ); final PaintColor color = entityManager.find( PaintColor.class, 1 ); assertNull( color ); } ); } @Entity(name = "Car") public static
OneToOneEagerOrphanRemovalTest
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/typesafe/TypeSafeLoopTest.java
{ "start": 2942, "end": 2997 }
class ____ { } @TemplateExtension static
Item
java
square__javapoet
src/test/java/com/squareup/javapoet/TypeNameTest.java
{ "start": 1043, "end": 1274 }
class ____ { private static final AnnotationSpec ANNOTATION_SPEC = AnnotationSpec.builder(ClassName.OBJECT).build(); protected <E extends Enum<E>> E generic(E[] values) { return values[0]; } protected static
TypeNameTest
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java
{ "start": 17300, "end": 17830 }
class ____ each row should be mapped to * @param conversionService the {@link ConversionService} for binding * JDBC values to bean properties, or {@code null} for none * @since 5.2.3 * @see #newInstance(Class) * @see #setConversionService */ public static <T> BeanPropertyRowMapper<T> newInstance( Class<T> mappedClass, @Nullable ConversionService conversionService) { BeanPropertyRowMapper<T> rowMapper = newInstance(mappedClass); rowMapper.setConversionService(conversionService); return rowMapper; } }
that
java
apache__flink
flink-test-utils-parent/flink-connector-test-utils/src/main/java/org/apache/flink/connector/testframe/container/ImageBuildException.java
{ "start": 933, "end": 1135 }
class ____ extends Exception { public ImageBuildException(String imageName, Throwable cause) { super(String.format("Failed to build image \"%s\"", imageName), cause); } }
ImageBuildException
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/interceptor/WithSpanInterceptorTest.java
{ "start": 11027, "end": 11160 }
class ____ { @WithSpan public void spanChild() { } } @ApplicationScoped public static
SpanChildBean
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 32141, "end": 32312 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return definesFunction( dialect, "xmlquery" ); } } public static
SupportsXmlquery
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java
{ "start": 5546, "end": 6129 }
interface ____ the AdvisedSupport's * {@link AdvisedSupport#setOpaque "opaque"} flag is on. Always adds the * {@link org.springframework.aop.SpringProxy} marker interface. * @param advised the proxy config * @return the complete set of interfaces to proxy * @see SpringProxy * @see Advised */ public static Class<?>[] completeProxiedInterfaces(AdvisedSupport advised) { return completeProxiedInterfaces(advised, false); } /** * Determine the complete set of interfaces to proxy for the given AOP configuration. * <p>This will always add the {@link Advised}
unless
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/NamedArgument.java
{ "start": 166, "end": 578 }
class ____ { private final String name; private volatile Object value; public NamedArgument(String name) { this.name = name; } public Object getValue() { return value; } public NamedArgument setValue(Object value) { this.value = value; return this; } public String getName() { return name; } public static final
NamedArgument
java
apache__dubbo
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java
{ "start": 1377, "end": 3373 }
class ____ { @Test void test() { ServerStatusChecker serverStatusChecker = new ServerStatusChecker(); Status status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.UNKNOWN); DubboProtocol dubboProtocol = Mockito.mock(DubboProtocol.class); ProtocolServer protocolServer = Mockito.mock(ProtocolServer.class); RemotingServer remotingServer = Mockito.mock(RemotingServer.class); List<ProtocolServer> servers = Arrays.asList(protocolServer); Mockito.when(dubboProtocol.getServers()).thenReturn(servers); Mockito.when(protocolServer.getRemotingServer()).thenReturn(remotingServer); Mockito.when(remotingServer.isBound()).thenReturn(true); Mockito.when(remotingServer.getLocalAddress()) .thenReturn(InetSocketAddress.createUnresolved("127.0.0.1", 9999)); Mockito.when(remotingServer.getChannels()).thenReturn(Arrays.asList(new MockChannel())); try (MockedStatic<DubboProtocol> mockDubboProtocol = Mockito.mockStatic(DubboProtocol.class)) { mockDubboProtocol.when(() -> DubboProtocol.getDubboProtocol()).thenReturn(dubboProtocol); status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.OK); // In JDK 17 : 127.0.0.1/<unresolved>:9999(clients:1) Assertions.assertTrue(status.getMessage().contains("127.0.0.1")); Assertions.assertTrue(status.getMessage().contains("9999(clients:1)")); Mockito.when(remotingServer.isBound()).thenReturn(false); status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.ERROR); // In JDK 17 : 127.0.0.1/<unresolved>:9999 Assertions.assertTrue(status.getMessage().contains("127.0.0.1")); Assertions.assertTrue(status.getMessage().contains("9999")); } } }
ServerStatusCheckerTest
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/stats/common/DataCountsTests.java
{ "start": 729, "end": 2155 }
class ____ extends AbstractBWCSerializationTestCase<DataCounts> { private boolean lenient; @Before public void chooseLenient() { lenient = randomBoolean(); } @Override protected boolean supportsUnknownFields() { return lenient; } @Override protected DataCounts mutateInstanceForVersion(DataCounts instance, TransportVersion version) { return instance; } @Override protected DataCounts doParseInstance(XContentParser parser) throws IOException { return lenient ? DataCounts.LENIENT_PARSER.apply(parser, null) : DataCounts.STRICT_PARSER.apply(parser, null); } @Override protected ToXContent.Params getToXContentParams() { return new ToXContent.MapParams(Collections.singletonMap(ToXContentParams.FOR_INTERNAL_STORAGE, "true")); } @Override protected Writeable.Reader<DataCounts> instanceReader() { return DataCounts::new; } @Override protected DataCounts createTestInstance() { return createRandom(); } @Override protected DataCounts mutateInstance(DataCounts instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } public static DataCounts createRandom() { return new DataCounts(randomAlphaOfLength(10), randomNonNegativeLong(), randomNonNegativeLong(), randomNonNegativeLong()); } }
DataCountsTests
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/InvocationInterceptorTests.java
{ "start": 16856, "end": 17190 }
class ____ extends ReportingInvocationInterceptor { BarInvocationInterceptor() { super("bar"); } @SuppressWarnings("deprecation") @Override public ExtensionContextScope getTestInstantiationExtensionContextScope(ExtensionContext rootContext) { return ExtensionContextScope.DEFAULT; } } static
BarInvocationInterceptor
java
google__guava
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
{ "start": 27177, "end": 27529 }
class ____ extends BaseClassThatFailsToThrow { @Override public void oneArg(@Nullable String s) {} } public void testSubclassThatOverridesBadSuperclassMethod() { shouldPass(new SubclassThatOverridesBadSuperclassMethod()); } @SuppressWarnings("unused") // for NullPointerTester private static
SubclassThatOverridesBadSuperclassMethod
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/policies/router/WeightedRandomRouterPolicy.java
{ "start": 1498, "end": 2735 }
class ____ extends AbstractRouterPolicy { @Override protected SubClusterId chooseSubCluster( String queue, Map<SubClusterId, SubClusterInfo> preSelectSubclusters) throws YarnException { // note: we cannot pre-compute the weights, as the set of activeSubCluster // changes dynamically (and this would unfairly spread the load to // sub-clusters adjacent to an inactive one), hence we need to count/scan // the list and based on weight pick the next sub-cluster. Map<SubClusterIdInfo, Float> weights = getPolicyInfo().getRouterPolicyWeights(); ArrayList<Float> weightList = new ArrayList<>(); ArrayList<SubClusterId> scIdList = new ArrayList<>(); for (Map.Entry<SubClusterIdInfo, Float> entry : weights.entrySet()) { SubClusterIdInfo key = entry.getKey(); if (key != null && preSelectSubclusters.containsKey(key.toId())) { weightList.add(entry.getValue()); scIdList.add(key.toId()); } } int pickedIndex = FederationPolicyUtils.getWeightedRandom(weightList); if (pickedIndex == -1) { throw new FederationPolicyException("No positive weight found on active subclusters"); } return scIdList.get(pickedIndex); } }
WeightedRandomRouterPolicy
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/util/ResettableRowBuffer.java
{ "start": 1277, "end": 1841 }
interface ____ extends Closeable { /** Re-initialize the buffer state. */ void reset(); /** Appends the specified row to the end of this buffer. */ void add(RowData row) throws IOException; /** Finally, complete add. */ void complete(); /** Get a new iterator starting from first row. */ ResettableIterator newIterator(); /** Get a new iterator starting from the `beginRow`-th row. `beginRow` is 0-indexed. */ ResettableIterator newIterator(int beginRow); /** Row iterator that can be reset. */
ResettableRowBuffer
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/constructor/EntityExtendingMapperSuperClassWithInstanceGetEntityManager.java
{ "start": 196, "end": 614 }
class ____ extends MapperSuperClassWithInstanceGetEntityManager { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private String otherName; public String getOtherName() { return otherName; } public void setOtherName(String otherName) { this.otherName = otherName; } }
EntityExtendingMapperSuperClassWithInstanceGetEntityManager
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DebeziumPostgresComponentBuilderFactory.java
{ "start": 75695, "end": 78778 }
interface ____ is called to determine how to lock * tables during schema snapshot. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: postgres * * @param snapshotLockingModeCustomName the value to set * @return the dsl builder */ default DebeziumPostgresComponentBuilder snapshotLockingModeCustomName(java.lang.String snapshotLockingModeCustomName) { doSetProperty("snapshotLockingModeCustomName", snapshotLockingModeCustomName); return this; } /** * The maximum number of millis to wait for table locks at the beginning * of a snapshot. If locks cannot be acquired in this time frame, the * snapshot will be aborted. Defaults to 10 seconds. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 10s * Group: postgres * * @param snapshotLockTimeoutMs the value to set * @return the dsl builder */ default DebeziumPostgresComponentBuilder snapshotLockTimeoutMs(long snapshotLockTimeoutMs) { doSetProperty("snapshotLockTimeoutMs", snapshotLockTimeoutMs); return this; } /** * The maximum number of threads used to perform the snapshot. Defaults * to 1. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 1 * Group: postgres * * @param snapshotMaxThreads the value to set * @return the dsl builder */ default DebeziumPostgresComponentBuilder snapshotMaxThreads(int snapshotMaxThreads) { doSetProperty("snapshotMaxThreads", snapshotMaxThreads); return this; } /** * The criteria for running a snapshot upon startup of the connector. * Select one of the following snapshot options: 'always': The connector * runs a snapshot every time that it starts. After the snapshot * completes, the connector begins to stream changes from the * transaction log.; 'initial' (default): If the connector does not * detect any offsets for the logical server name, it runs a snapshot * that captures the current full state of the configured tables. After * the snapshot completes, the connector begins to stream changes from * the transaction log. 'initial_only': The connector performs a * snapshot as it does for the 'initial' option, but after the connector * completes the snapshot, it stops, and does not stream changes from * the transaction log.; 'never': The connector does not run a snapshot. * Upon first startup, the connector immediately begins reading from the * beginning of the transaction log. 'exported': This option is * deprecated; use 'initial' instead.; 'custom': The connector loads a * custom
and
java
spring-projects__spring-framework
spring-core-test/src/main/java/org/springframework/aot/agent/InstrumentedBridgeMethods.java
{ "start": 1637, "end": 1802 }
class ____ only be used by the runtime-hints agent when instrumenting bytecode * and is not considered public API. */ @Deprecated(since = "6.0") public abstract
should
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/DialectOverride.java
{ "start": 10352, "end": 10651 }
interface ____ { SQLInsert[] value(); } /** * Specializes a {@link org.hibernate.annotations.SQLUpdate} * in a certain dialect. */ @Target({METHOD, FIELD, TYPE}) @Retention(RUNTIME) @Repeatable(SQLUpdates.class) @OverridesAnnotation(org.hibernate.annotations.SQLUpdate.class) @
SQLInserts
java
apache__camel
core/camel-cluster/src/main/java/org/apache/camel/impl/cluster/ClusteredRouteFilters.java
{ "start": 1283, "end": 2020 }
class ____ implements ClusteredRouteFilter { @Override public boolean test(CamelContext camelContext, String routeId, NamedNode route) { try { String autoStartup = ((RouteDefinition) route).getAutoStartup(); if (autoStartup == null) { // should auto startup by default return true; } Boolean isAutoStartup = CamelContextHelper.parseBoolean(camelContext, autoStartup); return isAutoStartup != null && isAutoStartup; } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } } } public static final
IsAutoStartup
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/UnsafeWildcardTest.java
{ "start": 13740, "end": 14139 }
class ____<T extends Number> {} public Test() { this(null, null); } public Test(WithBound<? super U> implicit) {} public Test(WithBound<Integer> xs, WithBound<? super Integer> contra) { // BUG: Diagnostic contains: Cast to wildcard type unsafe this(null); }
WithBound
java
google__dagger
javatests/dagger/functional/producers/cancellation/CancellationPolicyTest.java
{ "start": 1899, "end": 2008 }
interface ____ { @Named("a") ListenableFuture<String> a(); Child.Builder childBuilder();
Parent
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/bulk/BatchInfoList.java
{ "start": 1082, "end": 1770 }
class ____ BatchInfoList complex type. * <p/> * <p> * The following schema fragment specifies the expected content contained within this class. * <p/> * * <pre> * &lt;complexType name="BatchInfoList"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="batchInfo" type="{http://www.force.com/2009/06/asyncapi/dataload}BatchInfo" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BatchInfoList", propOrder = { "batchInfo" }) public
for
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/BaseSubscriber.java
{ "start": 1964, "end": 2150 }
class ____ in the * {@code reactor.core.publisher} package, as this subscriber is tied to a single * {@link org.reactivestreams.Publisher}. * * @author Simon Baslé */ public abstract
is
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/jdk8/LocalDateTest2.java
{ "start": 167, "end": 602 }
class ____ extends TestCase { public void test_for_issue() throws Exception { VO vo = JSON.parseObject("{\"date\":\"2016-05-06T20:24:28.484\"}", VO.class); Assert.assertEquals(2016, vo.date.getYear()); Assert.assertEquals(2016, vo.date.getYear()); Assert.assertEquals(5, vo.date.getMonthValue()); Assert.assertEquals(6, vo.date.getDayOfMonth()); } public static
LocalDateTest2
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/KeywordScriptFieldType.java
{ "start": 2423, "end": 10485 }
class ____ extends AbstractScriptFieldType.Builder<StringFieldScript.Factory> { Builder(String name) { super(name, StringFieldScript.CONTEXT); } @Override protected AbstractScriptFieldType<?> createFieldType( String name, StringFieldScript.Factory factory, Script script, Map<String, String> meta, OnScriptError onScriptError ) { return new KeywordScriptFieldType(name, factory, script, meta, onScriptError); } @Override protected StringFieldScript.Factory getParseFromSourceFactory() { return StringFieldScript.PARSE_FROM_SOURCE; } @Override protected StringFieldScript.Factory getCompositeLeafFactory( Function<SearchLookup, CompositeFieldScript.LeafFactory> parentScriptFactory ) { return StringFieldScript.leafAdapter(parentScriptFactory); } } public static RuntimeField sourceOnly(String name) { return new Builder(name).createRuntimeField(StringFieldScript.PARSE_FROM_SOURCE); } public KeywordScriptFieldType( String name, StringFieldScript.Factory scriptFactory, Script script, Map<String, String> meta, OnScriptError onScriptError ) { super( name, searchLookup -> scriptFactory.newFactory(name, script.getParams(), searchLookup, onScriptError), script, scriptFactory.isResultDeterministic(), meta, scriptFactory.isParsedFromSource() ); } @Override public String typeName() { return KeywordFieldMapper.CONTENT_TYPE; } @Override public Object valueForDisplay(Object value) { if (value == null) { return null; } // keywords are internally stored as utf8 bytes BytesRef binaryValue = (BytesRef) value; return binaryValue.utf8ToString(); } private FallbackSyntheticSourceBlockLoader.Reader<?> fallbackSyntheticSourceBlockLoaderReader() { return new FallbackSyntheticSourceBlockLoader.SingleValueReader<BytesRef>(null) { @Override public void convertValue(Object value, List<BytesRef> accumulator) { accumulator.add((BytesRef) value); } @Override public void parseNonNullValue(XContentParser parser, List<BytesRef> accumulator) throws IOException { assert parser.currentToken() == XContentParser.Token.VALUE_STRING : "Unexpected token " + parser.currentToken(); var utfBytes = parser.optimizedText().bytes(); accumulator.add(new BytesRef(utfBytes.bytes(), utfBytes.offset(), utfBytes.length())); } @Override public void writeToBlock(List<BytesRef> values, BlockLoader.Builder blockBuilder) { var bytesRefBuilder = (BlockLoader.BytesRefBuilder) blockBuilder; for (var value : values) { bytesRefBuilder.appendBytesRef(value); } } }; } @Override public BlockLoader blockLoader(BlockLoaderContext blContext) { var fallbackSyntheticSourceBlockLoader = fallbackSyntheticSourceBlockLoader( blContext, BlockLoader.BlockFactory::bytesRefs, this::fallbackSyntheticSourceBlockLoaderReader ); if (fallbackSyntheticSourceBlockLoader != null) { return fallbackSyntheticSourceBlockLoader; } else { return new KeywordScriptBlockDocValuesReader.KeywordScriptBlockLoader(leafFactory(blContext.lookup())); } } @Override public StringScriptFieldData.Builder fielddataBuilder(FieldDataContext fieldDataContext) { return new StringScriptFieldData.Builder(name(), leafFactory(fieldDataContext.lookupSupplier().get()), KeywordDocValuesField::new); } @Override public Query existsQuery(SearchExecutionContext context) { applyScriptContext(context); return new StringScriptFieldExistsQuery(script, leafFactory(context), name()); } @Override public Query fuzzyQuery( Object value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions, SearchExecutionContext context, @Nullable MultiTermQuery.RewriteMethod rewriteMethod ) { applyScriptContext(context); return StringScriptFieldFuzzyQuery.build( script, leafFactory(context), name(), BytesRefs.toString(Objects.requireNonNull(value)), fuzziness.asDistance(BytesRefs.toString(value)), prefixLength, transpositions ); } @Override public Query prefixQuery(String value, RewriteMethod method, boolean caseInsensitive, SearchExecutionContext context) { applyScriptContext(context); return new StringScriptFieldPrefixQuery(script, leafFactory(context), name(), value, caseInsensitive); } @Override public Query rangeQuery( Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, ZoneId timeZone, DateMathParser parser, SearchExecutionContext context ) { applyScriptContext(context); return new StringScriptFieldRangeQuery( script, leafFactory(context), name(), lowerTerm == null ? null : BytesRefs.toString(lowerTerm), upperTerm == null ? null : BytesRefs.toString(upperTerm), includeLower, includeUpper ); } @Override public Query regexpQuery( String value, int syntaxFlags, int matchFlags, int maxDeterminizedStates, RewriteMethod method, SearchExecutionContext context ) { applyScriptContext(context); if (matchFlags != 0) { throw new IllegalArgumentException("Match flags not yet implemented [" + matchFlags + "]"); } return new StringScriptFieldRegexpQuery( script, leafFactory(context), name(), value, syntaxFlags, matchFlags, maxDeterminizedStates ); } @Override public Query termQueryCaseInsensitive(Object value, SearchExecutionContext context) { applyScriptContext(context); return new StringScriptFieldTermQuery( script, leafFactory(context), name(), BytesRefs.toString(Objects.requireNonNull(value)), true ); } @Override public Query termQuery(Object value, SearchExecutionContext context) { applyScriptContext(context); return new StringScriptFieldTermQuery( script, leafFactory(context), name(), BytesRefs.toString(Objects.requireNonNull(value)), false ); } @Override public Query termsQuery(Collection<?> values, SearchExecutionContext context) { applyScriptContext(context); Set<String> terms = values.stream().map(v -> BytesRefs.toString(Objects.requireNonNull(v))).collect(toSet()); return new StringScriptFieldTermsQuery(script, leafFactory(context), name(), terms); } @Override public Query wildcardQuery(String value, RewriteMethod method, boolean caseInsensitive, SearchExecutionContext context) { applyScriptContext(context); return new StringScriptFieldWildcardQuery(script, leafFactory(context), name(), value, caseInsensitive); } @Override public Query normalizedWildcardQuery(String value, RewriteMethod method, SearchExecutionContext context) { applyScriptContext(context); return new StringScriptFieldWildcardQuery(script, leafFactory(context), name(), value, false); } }
Builder
java
netty__netty
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicheQuicCodec.java
{ "start": 14661, "end": 16164 }
class ____ implements QuicHeaderParser.QuicHeaderProcessor { private final ChannelHandlerContext ctx; QuicCodecHeaderProcessor(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void process(InetSocketAddress sender, InetSocketAddress recipient, ByteBuf buffer, QuicPacketType type, long version, ByteBuf scid, ByteBuf dcid, ByteBuf token) throws Exception { QuicheQuicChannel channel = quicPacketRead(ctx, sender, recipient, type, version, scid, dcid, token, senderSockaddrMemory, recipientSockaddrMemory, freeTask, localConnIdLength, config); if (channel != null) { // Add to queue first, we might be able to safe some flushes and consolidate them // in channelReadComplete(...) this way. if (channel.markInFireChannelReadCompleteQueue()) { needsFireChannelReadComplete.add(channel); } channel.recv(sender, recipient, buffer); for (ByteBuffer retiredSourceConnectionId : channel.retiredSourceConnectionId()) { removeMapping(channel, retiredSourceConnectionId); } for (ByteBuffer newSourceConnectionId : channel.newSourceConnectionIds()) { addMapping(channel, newSourceConnectionId); } } } } }
QuicCodecHeaderProcessor
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ReflectionSupport.java
{ "start": 1821, "end": 1920 }
class ____ { private ReflectionSupport() { /* no-op */ } /** * Try to load a
ReflectionSupport
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/internal/AbstractInvocationHandler.java
{ "start": 7335, "end": 10199 }
class ____ { private static final WeakHashMap<Class<?>, MethodTranslator> TRANSLATOR_MAP = new WeakHashMap<>(32); private static final Lock lock = new ReentrantLock(); private final Map<Method, Method> map; private MethodTranslator(Class<?> delegate, Class<?>... methodSources) { map = createMethodMap(delegate, methodSources); } public static MethodTranslator of(Class<?> delegate, Class<?>... methodSources) { lock.lock(); try { return TRANSLATOR_MAP.computeIfAbsent(delegate, key -> new MethodTranslator(key, methodSources)); } finally { lock.unlock(); } } private Map<Method, Method> createMethodMap(Class<?> delegate, Class<?>[] methodSources) { Map<Method, Method> map; List<Method> methods = new ArrayList<>(); for (Class<?> sourceClass : methodSources) { methods.addAll(getMethods(sourceClass)); } map = new HashMap<>(methods.size(), 1.0f); for (Method method : methods) { try { map.put(method, delegate.getMethod(method.getName(), method.getParameterTypes())); } catch (NoSuchMethodException ignore) { } } return map; } private Collection<? extends Method> getMethods(Class<?> sourceClass) { Set<Method> result = new HashSet<>(); Class<?> searchType = sourceClass; while (searchType != null && searchType != Object.class) { result.addAll(filterPublicMethods(Arrays.asList(sourceClass.getDeclaredMethods()))); if (sourceClass.isInterface()) { Class<?>[] interfaces = sourceClass.getInterfaces(); for (Class<?> interfaceClass : interfaces) { result.addAll(getMethods(interfaceClass)); } searchType = null; } else { searchType = searchType.getSuperclass(); } } return result; } private Collection<? extends Method> filterPublicMethods(List<Method> methods) { List<Method> result = new ArrayList<>(methods.size()); for (Method method : methods) { if (Modifier.isPublic(method.getModifiers())) { result.add(method); } } return result; } public Method get(Method key) { Method result = map.get(key); if (result != null) { return result; } throw new IllegalStateException("Cannot find source method " + key); } } }
MethodTranslator
java
quarkusio__quarkus
extensions/hibernate-search-orm-outbox-polling/runtime/src/main/java/io/quarkus/hibernate/search/orm/outboxpolling/runtime/HibernateSearchOutboxPollingConfigUtil.java
{ "start": 308, "end": 2180 }
class ____ { private HibernateSearchOutboxPollingConfigUtil() { } public static <T> void addCoordinationConfig(BiConsumer<String, Object> propertyCollector, String configPath, T value) { addCoordinationConfig(propertyCollector, null, configPath, value); } public static void addCoordinationConfig(BiConsumer<String, Object> propertyCollector, String configPath, Optional<?> value) { addCoordinationConfig(propertyCollector, null, configPath, value); } public static <T> void addCoordinationConfig(BiConsumer<String, Object> propertyCollector, String tenantId, String configPath, T value) { String key = HibernateOrmMapperOutboxPollingSettings.coordinationKey(tenantId, configPath); propertyCollector.accept(key, value); } public static void addCoordinationConfig(BiConsumer<String, Object> propertyCollector, String tenantId, String configPath, Optional<?> value) { addCoordinationConfig(propertyCollector, tenantId, configPath, value, Optional::isPresent, Optional::get); } public static void addCoordinationConfig(BiConsumer<String, Object> propertyCollector, String tenantId, String configPath, OptionalInt value) { addCoordinationConfig(propertyCollector, tenantId, configPath, value, OptionalInt::isPresent, OptionalInt::getAsInt); } public static <T> void addCoordinationConfig(BiConsumer<String, Object> propertyCollector, String tenantId, String configPath, T value, Function<T, Boolean> shouldBeAdded, Function<T, ?> getValue) { if (shouldBeAdded.apply(value)) { propertyCollector.accept(HibernateOrmMapperOutboxPollingSettings.coordinationKey(tenantId, configPath), getValue.apply(value)); } } }
HibernateSearchOutboxPollingConfigUtil
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithInitContainerResourceLimitsTest.java
{ "start": 644, "end": 3218 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("kubernetes-with-init-container-resource-limits") .setApplicationVersion("0.1-SNAPSHOT") .withConfigurationResource("kubernetes-with-init-container-resource-limits.properties") .setLogFileName("k8s.log") .setForcedDependencies(List.of(Dependency.of("io.quarkus", "quarkus-kubernetes", Version.getVersion()))); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml")); List<HasMetadata> kubernetesList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("kubernetes.yml")); assertThat(kubernetesList.get(0)).isInstanceOfSatisfying(Deployment.class, d -> { assertThat(d.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("kubernetes-with-init-container-resource-limits"); }); assertThat(d.getSpec()).satisfies(deploymentSpec -> { assertThat(deploymentSpec.getTemplate()).satisfies(t -> { assertThat(t.getSpec()).satisfies(podSpec -> { assertThat(podSpec.getInitContainers()).singleElement().satisfies(c -> { assertThat(c.getName()).isEqualTo("foo"); assertThat(c.getResources()).satisfies(r -> { assertThat(r.getRequests().get("cpu")).isEqualTo(new Quantity("250m")); assertThat(r.getRequests().get("memory")).isEqualTo(new Quantity("64Mi")); assertThat(r.getLimits().get("cpu")).isEqualTo(new Quantity("500m")); assertThat(r.getLimits().get("memory")).isEqualTo(new Quantity("128Mi")); }); assertThat(c.getImagePullPolicy()).isEqualTo("Always"); }); }); }); }); }); } }
KubernetesWithInitContainerResourceLimitsTest
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmProcessor.java
{ "start": 76768, "end": 84776 }
class ____ on model classes:\n\t- %s\nUse the `.packages` configuration property or package-level annotations instead.", String.join("\n\t- ", modelClassesWithPersistenceUnitAnnotations))); } assignedModelClasses.addAll(modelPerPersistenceUnit.values().stream() .map(JpaPersistenceUnitModel::allModelClassAndPackageNames).flatMap(Set::stream).toList()); Set<String> unaffectedModelClasses = jpaModel.getAllModelClassNames().stream() .filter(c -> !assignedModelClasses.contains(c)) .collect(Collectors.toCollection(TreeSet::new)); if (!unaffectedModelClasses.isEmpty()) { LOG.warnf("Could not find a suitable persistence unit for model classes:\n\t- %s", String.join("\n\t- ", unaffectedModelClasses)); } for (String modelPackageName : jpaModel.getAllModelPackageNames()) { // Package rules keys are "normalized" package names, so we want to normalize the package on lookup: Set<String> persistenceUnitNames = packageRules.get(normalizePackage(modelPackageName)); if (persistenceUnitNames == null) { continue; } for (String persistenceUnitName : persistenceUnitNames) { var model = modelPerPersistenceUnit.computeIfAbsent(persistenceUnitName, ignored -> new JpaPersistenceUnitModel()); model.allModelClassAndPackageNames().add(modelPackageName); } } return modelPerPersistenceUnit; } private static Set<String> getRelatedModelClassNames(IndexView index, Set<String> knownModelClassNames, ClassInfo modelClassInfo) { if (modelClassInfo == null) { return Collections.emptySet(); } Set<String> relatedModelClassNames = new HashSet<>(); // for now we only deal with entities and mapped super classes if (modelClassInfo.declaredAnnotation(ClassNames.JPA_ENTITY) == null && modelClassInfo.declaredAnnotation(ClassNames.MAPPED_SUPERCLASS) == null) { return Collections.emptySet(); } addRelatedModelClassNamesRecursively(index, knownModelClassNames, relatedModelClassNames, modelClassInfo); return relatedModelClassNames; } private static void addRelatedModelClassNamesRecursively(IndexView index, Set<String> knownModelClassNames, Set<String> relatedModelClassNames, ClassInfo modelClassInfo) { if (modelClassInfo == null || modelClassInfo.name().equals(DotNames.OBJECT)) { return; } String modelClassName = modelClassInfo.name().toString(); if (knownModelClassNames.contains(modelClassName)) { relatedModelClassNames.add(modelClassName); } addRelatedModelClassNamesRecursively(index, knownModelClassNames, relatedModelClassNames, index.getClassByName(modelClassInfo.superName())); for (DotName interfaceName : modelClassInfo.interfaceNames()) { addRelatedModelClassNamesRecursively(index, knownModelClassNames, relatedModelClassNames, index.getClassByName(interfaceName)); } } private static String normalizePackage(String pakkage) { if (pakkage.endsWith(".")) { return pakkage; } return pakkage + "."; } private static boolean hasPackagesInQuarkusConfig(HibernateOrmConfig hibernateOrmConfig) { for (HibernateOrmConfigPersistenceUnit persistenceUnitConfig : hibernateOrmConfig.persistenceUnits() .values()) { if (persistenceUnitConfig.packages().isPresent()) { return true; } } return false; } private static Collection<AnnotationInstance> getPackageLevelPersistenceUnitAnnotations(IndexView index) { Collection<AnnotationInstance> persistenceUnitAnnotations = index .getAnnotationsWithRepeatable(ClassNames.QUARKUS_PERSISTENCE_UNIT, index); Collection<AnnotationInstance> packageLevelPersistenceUnitAnnotations = new ArrayList<>(); for (AnnotationInstance persistenceUnitAnnotation : persistenceUnitAnnotations) { if (persistenceUnitAnnotation.target().kind() != Kind.CLASS) { continue; } if (!"package-info".equals(persistenceUnitAnnotation.target().asClass().simpleName())) { continue; } packageLevelPersistenceUnitAnnotations.add(persistenceUnitAnnotation); } return packageLevelPersistenceUnitAnnotations; } /** * Checks whether we should ignore {@code persistence.xml} files. * <p> * The main way to ignore {@code persistence.xml} files is to set the configuration property * {@code quarkus.hibernate-orm.persistence-xml.ignore}. * <p> * But there is also an undocumented feature: we allow setting the System property * "SKIP_PARSE_PERSISTENCE_XML" to ignore any {@code persistence.xml} resource. * * @return true if we're expected to ignore them */ private boolean shouldIgnorePersistenceXmlResources(HibernateOrmConfig config) { return config.persistenceXml().ignore() || Boolean.getBoolean("SKIP_PARSE_PERSISTENCE_XML"); } /** * Set up the scanner, as this scanning has already been done we need to just tell it about the classes we * have discovered. This scanner is bytecode serializable and is passed directly into the recorder * * @param jpaModel the previously discovered JPA model (domain objects, ...) * @return a new QuarkusScanner with all domainObjects registered */ public static QuarkusScanner buildQuarkusScanner(JpaModelBuildItem jpaModel) { QuarkusScanner scanner = new QuarkusScanner(); Set<PackageDescriptor> packageDescriptors = new HashSet<>(); for (String packageName : jpaModel.getAllModelPackageNames()) { QuarkusScanner.PackageDescriptorImpl desc = new QuarkusScanner.PackageDescriptorImpl(packageName); packageDescriptors.add(desc); } scanner.setPackageDescriptors(packageDescriptors); Set<ClassDescriptor> classDescriptors = new HashSet<>(); for (String className : jpaModel.getEntityClassNames()) { QuarkusScanner.ClassDescriptorImpl desc = new QuarkusScanner.ClassDescriptorImpl(className, ClassDescriptor.Categorization.MODEL); classDescriptors.add(desc); } scanner.setClassDescriptors(classDescriptors); return scanner; } private static MultiTenancyStrategy getMultiTenancyStrategy(Optional<String> multitenancyStrategy) { final MultiTenancyStrategy multiTenancyStrategy = MultiTenancyStrategy .valueOf(multitenancyStrategy.orElse(MultiTenancyStrategy.NONE.name()) .toUpperCase(Locale.ROOT)); return multiTenancyStrategy; } private PreGeneratedProxies generateProxies(Set<String> managedClassAndPackageNames, IndexView combinedIndex, TransformedClassesBuildItem transformedClassesBuildItem, BuildProducer<GeneratedClassBuildItem> generatedClassBuildItemBuildProducer, LiveReloadBuildItem liveReloadBuildItem, ExecutorService buildExecutor) throws ExecutionException, InterruptedException { ProxyCache proxyCache = liveReloadBuildItem.getContextObject(ProxyCache.class); if (proxyCache == null) { proxyCache = new ProxyCache(); liveReloadBuildItem.setContextObject(ProxyCache.class, proxyCache); } Set<String> changedClasses = Set.of(); if (liveReloadBuildItem.getChangeInformation() != null) { changedClasses = liveReloadBuildItem.getChangeInformation().getChangedClasses(); } else { //we don't have
level
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/filter/FiltersAggregator.java
{ "start": 2625, "end": 3033 }
class ____ extends BucketsAggregator { public static final ParseField FILTERS_FIELD = new ParseField("filters"); public static final ParseField OTHER_BUCKET_FIELD = new ParseField("other_bucket"); public static final ParseField OTHER_BUCKET_KEY_FIELD = new ParseField("other_bucket_key"); public static final ParseField KEYED_FIELD = new ParseField("keyed"); public static
FiltersAggregator
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java
{ "start": 2461, "end": 10402 }
class ____ implements Filter, ErrorPageRegistry, Ordered { private static final Log logger = LogFactory.getLog(ErrorPageFilter.class); // From RequestDispatcher but not referenced to remain compatible with Servlet 2.5 private static final String ERROR_EXCEPTION = "jakarta.servlet.error.exception"; private static final String ERROR_EXCEPTION_TYPE = "jakarta.servlet.error.exception_type"; private static final String ERROR_MESSAGE = "jakarta.servlet.error.message"; /** * The name of the servlet attribute containing request URI. */ public static final String ERROR_REQUEST_URI = "jakarta.servlet.error.request_uri"; private static final String ERROR_STATUS_CODE = "jakarta.servlet.error.status_code"; private static final Set<Class<?>> CLIENT_ABORT_EXCEPTIONS; static { Set<Class<?>> clientAbortExceptions = new HashSet<>(); addClassIfPresent(clientAbortExceptions, "org.apache.catalina.connector.ClientAbortException"); CLIENT_ABORT_EXCEPTIONS = Collections.unmodifiableSet(clientAbortExceptions); } private @Nullable String global; private final Map<Integer, String> statuses = new HashMap<>(); private final Map<@Nullable Class<?>, String> exceptions = new HashMap<>(); private final OncePerRequestFilter delegate = new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { ErrorPageFilter.this.doFilter(request, response, chain); } @Override protected boolean shouldNotFilterAsyncDispatch() { return false; } }; @Override public void init(FilterConfig filterConfig) throws ServletException { this.delegate.init(filterConfig); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.delegate.doFilter(request, response, chain); } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { ErrorWrapperResponse wrapped = new ErrorWrapperResponse(response); try { chain.doFilter(request, wrapped); if (wrapped.hasErrorToSend()) { handleErrorStatus(request, response, wrapped.getStatus(), wrapped.getMessage()); response.flushBuffer(); } else if (!request.isAsyncStarted() && !response.isCommitted()) { response.flushBuffer(); } } catch (Throwable ex) { Throwable exceptionToHandle = ex; if (ex instanceof ServletException servletException) { Throwable rootCause = servletException.getRootCause(); if (rootCause != null) { exceptionToHandle = rootCause; } } handleException(request, response, wrapped, exceptionToHandle); response.flushBuffer(); } } private void handleErrorStatus(HttpServletRequest request, HttpServletResponse response, int status, @Nullable String message) throws ServletException, IOException { if (response.isCommitted()) { handleCommittedResponse(request, null); return; } String errorPath = getErrorPath(this.statuses, status); if (errorPath == null) { response.sendError(status, message); return; } response.setStatus(status); setErrorAttributes(request, status, message); request.getRequestDispatcher(errorPath).forward(request, response); } private void handleException(HttpServletRequest request, HttpServletResponse response, ErrorWrapperResponse wrapped, Throwable ex) throws IOException, ServletException { Class<?> type = ex.getClass(); String errorPath = getErrorPath(type); if (errorPath == null) { rethrow(ex); return; } if (response.isCommitted()) { handleCommittedResponse(request, ex); return; } forwardToErrorPage(errorPath, request, wrapped, ex); } private void forwardToErrorPage(String path, HttpServletRequest request, HttpServletResponse response, Throwable ex) throws ServletException, IOException { if (logger.isErrorEnabled()) { String message = "Forwarding to error page from request " + getDescription(request) + " due to exception [" + ex.getMessage() + "]"; logger.error(message, ex); } setErrorAttributes(request, 500, ex.getMessage()); request.setAttribute(ERROR_EXCEPTION, ex); request.setAttribute(ERROR_EXCEPTION_TYPE, ex.getClass()); response.reset(); response.setStatus(500); request.getRequestDispatcher(path).forward(request, response); request.removeAttribute(ERROR_EXCEPTION); request.removeAttribute(ERROR_EXCEPTION_TYPE); } /** * Return the description for the given request. By default this method will return a * description based on the request {@code servletPath} and {@code pathInfo}. * @param request the source request * @return the description */ protected String getDescription(HttpServletRequest request) { String pathInfo = (request.getPathInfo() != null) ? request.getPathInfo() : ""; return "[" + request.getServletPath() + pathInfo + "]"; } private void handleCommittedResponse(HttpServletRequest request, @Nullable Throwable ex) { if (isClientAbortException(ex)) { return; } String message = "Cannot forward to error page for request " + getDescription(request) + " as the response has already been" + " committed. As a result, the response may have the wrong status" + " code. If your application is running on WebSphere Application" + " Server you may be able to resolve this problem by setting" + " com.ibm.ws.webcontainer.invokeFlushAfterService to false"; if (ex == null) { logger.error(message); } else { // User might see the error page without all the data here but throwing the // exception isn't going to help anyone (we'll log it to be on the safe side) logger.error(message, ex); } } private boolean isClientAbortException(@Nullable Throwable ex) { if (ex == null) { return false; } for (Class<?> candidate : CLIENT_ABORT_EXCEPTIONS) { if (candidate.isInstance(ex)) { return true; } } return isClientAbortException(ex.getCause()); } private @Nullable String getErrorPath(Map<Integer, String> map, Integer status) { if (map.containsKey(status)) { return map.get(status); } return this.global; } private @Nullable String getErrorPath(Class<?> type) { while (type != Object.class) { String path = this.exceptions.get(type); if (path != null) { return path; } type = type.getSuperclass(); } return this.global; } private void setErrorAttributes(HttpServletRequest request, int status, @Nullable String message) { request.setAttribute(ERROR_STATUS_CODE, status); request.setAttribute(ERROR_MESSAGE, message); request.setAttribute(ERROR_REQUEST_URI, request.getRequestURI()); } private void rethrow(Throwable ex) throws IOException, ServletException { if (ex instanceof RuntimeException runtimeException) { throw runtimeException; } if (ex instanceof Error error) { throw error; } if (ex instanceof IOException ioException) { throw ioException; } if (ex instanceof ServletException servletException) { throw servletException; } throw new IllegalStateException(ex); } @Override public void addErrorPages(ErrorPage... errorPages) { for (ErrorPage errorPage : errorPages) { if (errorPage.isGlobal()) { this.global = errorPage.getPath(); } else if (errorPage.getStatus() != null) { this.statuses.put(errorPage.getStatus().value(), errorPage.getPath()); } else { this.exceptions.put(errorPage.getException(), errorPage.getPath()); } } } @Override public void destroy() { } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 1; } private static void addClassIfPresent(Collection<Class<?>> collection, String className) { try { collection.add(ClassUtils.forName(className, null)); } catch (Throwable ex) { // Ignore } } private static
ErrorPageFilter
java
apache__camel
components/camel-joor/src/test/java/org/apache/camel/language/joor/JoorPredicateTest.java
{ "start": 1040, "end": 2031 }
class ____ extends CamelTestSupport { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .choice() .when().joor("((int) body) / 2 > 10") .to("mock:high") .otherwise() .to("mock:low"); } }; } @Test public void testPredicate() throws Exception { getMockEndpoint("mock:high").expectedBodiesReceived(44, 123); getMockEndpoint("mock:low").expectedBodiesReceived(1, 18, 6); template.sendBody("direct:start", 44); template.sendBody("direct:start", 1); template.sendBody("direct:start", 18); template.sendBody("direct:start", 123); template.sendBody("direct:start", 6); MockEndpoint.assertIsSatisfied(context); } }
JoorPredicateTest
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0479OverrideCentralRepoTest.java
{ "start": 1191, "end": 8721 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that using the same repo id allows to override "central". This test checks the effective model. * * @throws Exception in case of failure */ @Test public void testitModel() throws Exception { File testDir = extractResources("/mng-0479"); // Phase 1: Ensure the test plugin is downloaded before the test cuts off access to central File child1 = new File(testDir, "setup"); Verifier verifier = newVerifier(child1.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("org.apache.maven.its.plugins:maven-it-plugin-expression:2.1-SNAPSHOT:eval"); verifier.execute(); verifier.verifyErrorFreeLog(); // Phase 2: Now run the test File child2 = new File(testDir, "test"); verifier = newVerifier(child2.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("org.apache.maven.its.plugins:maven-it-plugin-expression:2.1-SNAPSHOT:eval"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("target/expression.properties"); Properties props = verifier.loadProperties("target/expression.properties"); int count = Integer.parseInt(props.getProperty("project.repositories", "0")); assertTrue(count > 0); for (int i = 0; i < count; i++) { String key = "project.repositories." + i; if ("central".equals(props.getProperty(key + ".id"))) { assertEquals("mng-0479", props.getProperty(key + ".name")); assertTrue(props.getProperty(key + ".url").endsWith("/target/mng-0479")); assertEquals("false", props.getProperty(key + ".releases.enabled")); assertEquals("ignore", props.getProperty(key + ".releases.checksumPolicy")); assertEquals("always", props.getProperty(key + ".releases.updatePolicy")); assertEquals("true", props.getProperty(key + ".snapshots.enabled")); assertEquals("fail", props.getProperty(key + ".snapshots.checksumPolicy")); assertEquals("never", props.getProperty(key + ".snapshots.updatePolicy")); } } count = Integer.parseInt(props.getProperty("project.pluginRepositories", "0")); for (int i = 0; i < count; i++) { String key = "project.pluginRepositories." + i; if ("central".equals(props.getProperty(key + ".id"))) { assertEquals("mng-0479", props.getProperty(key + ".name")); assertTrue(props.getProperty(key + ".url").endsWith("/target/mng-0479")); assertEquals("false", props.getProperty(key + ".releases.enabled")); assertEquals("ignore", props.getProperty(key + ".releases.checksumPolicy")); assertEquals("always", props.getProperty(key + ".releases.updatePolicy")); assertEquals("true", props.getProperty(key + ".snapshots.enabled")); assertEquals("fail", props.getProperty(key + ".snapshots.checksumPolicy")); assertEquals("never", props.getProperty(key + ".snapshots.updatePolicy")); } } } /** * Verify that using the same repo id allows to override "central". This test checks the actual repo access. * * @throws Exception in case of failure */ @Test public void testitResolution() throws Exception { File testDir = extractResources("/mng-0479"); Verifier verifier = newVerifier(new File(testDir, "test-1").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng0479"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyFilePresent("target/touch.txt"); verifier.verifyArtifactPresent("org.apache.maven.its.mng0479", "parent", "0.1-SNAPSHOT", "pom"); verifier.verifyArtifactPresent("org.apache.maven.its.mng0479", "a", "0.1-SNAPSHOT", "jar"); verifier.verifyArtifactPresent("org.apache.maven.its.mng0479", "a", "0.1-SNAPSHOT", "pom"); verifier.verifyArtifactPresent("org.apache.maven.its.mng0479", "a-parent", "0.1-SNAPSHOT", "pom"); verifier.verifyArtifactPresent("org.apache.maven.its.mng0479", "b", "0.1-SNAPSHOT", "jar"); verifier.verifyArtifactPresent("org.apache.maven.its.mng0479", "b", "0.1-SNAPSHOT", "pom"); verifier = newVerifier(new File(testDir, "test-2").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); try { verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); fail("Build should have failed to resolve parent POM"); } catch (VerificationException e) { // expected } verifier.verifyArtifactNotPresent("org.apache.maven.its.mng0479", "parent", "0.1", "pom"); verifier = newVerifier(new File(testDir, "test-3").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); try { verifier.addCliArgument("org.apache.maven.its.mng0479:maven-mng0479-plugin:0.1-SNAPSHOT:touch"); verifier.execute(); verifier.verifyErrorFreeLog(); fail("Build should have failed to resolve direct dependency"); } catch (VerificationException e) { // expected } verifier.verifyArtifactNotPresent("org.apache.maven.its.mng0479", "a", "0.1", "jar"); verifier.verifyArtifactNotPresent("org.apache.maven.its.mng0479", "a", "0.1", "pom"); verifier = newVerifier(new File(testDir, "test-4").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); try { verifier.addCliArgument("org.apache.maven.its.mng0479:maven-mng0479-plugin:0.1-SNAPSHOT:touch"); verifier.execute(); verifier.verifyErrorFreeLog(); fail("Build should have failed to resolve transitive dependency"); } catch (VerificationException e) { // expected } verifier.verifyArtifactNotPresent("org.apache.maven.its.mng0479", "b", "0.1", "jar"); verifier.verifyArtifactNotPresent("org.apache.maven.its.mng0479", "b", "0.1", "pom"); } }
MavenITmng0479OverrideCentralRepoTest
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/support/PageableUtils.java
{ "start": 916, "end": 1496 }
class ____ { private PageableUtils() { throw new IllegalStateException("Cannot instantiate a utility class!"); } /** * Convert a {@link Pageable}'s offset value from {@link Long} to {@link Integer} to support JPA spec methods. * * @param pageable * @return integer */ public static int getOffsetAsInteger(Pageable pageable) { if (pageable.getOffset() > Integer.MAX_VALUE) { throw new InvalidDataAccessApiUsageException("Page offset exceeds Integer.MAX_VALUE (" + Integer.MAX_VALUE + ")"); } return Math.toIntExact(pageable.getOffset()); } }
PageableUtils
java
spring-projects__spring-framework
spring-oxm/src/test/java/org/springframework/oxm/jaxb/Primitives.java
{ "start": 851, "end": 1791 }
class ____ { private static final QName NAME = new QName("https://springframework.org/oxm-test", "primitives"); // following methods are used to test support for primitives public JAXBElement<Boolean> primitiveBoolean() { return new JAXBElement<>(NAME, Boolean.class, true); } public JAXBElement<Byte> primitiveByte() { return new JAXBElement<>(NAME, Byte.class, (byte) 42); } public JAXBElement<Short> primitiveShort() { return new JAXBElement<>(NAME, Short.class, (short) 42); } public JAXBElement<Integer> primitiveInteger() { return new JAXBElement<>(NAME, Integer.class, 42); } public JAXBElement<Long> primitiveLong() { return new JAXBElement<>(NAME, Long.class, 42L); } public JAXBElement<Double> primitiveDouble() { return new JAXBElement<>(NAME, Double.class, 42D); } public JAXBElement<byte[]> primitiveByteArray() { return new JAXBElement<>(NAME, byte[].class, new byte[] {42}); } }
Primitives
java
ReactiveX__RxJava
src/jmh/java/io/reactivex/rxjava3/core/FlattenCrossMapPerf.java
{ "start": 1036, "end": 2233 }
class ____ { @Param({ "1", "10", "100", "1000", "10000", "100000", "1000000" }) public int times; Flowable<Integer> flowable; Observable<Integer> observable; @Setup public void setup() { Integer[] array = new Integer[times]; Arrays.fill(array, 777); Integer[] arrayInner = new Integer[1000000 / times]; Arrays.fill(arrayInner, 888); final Iterable<Integer> list = Arrays.asList(arrayInner); flowable = Flowable.fromArray(array).flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return list; } }); observable = Observable.fromArray(array).flatMapIterable(new Function<Integer, Iterable<Integer>>() { @Override public Iterable<Integer> apply(Integer v) { return list; } }); } @Benchmark public void flowable(Blackhole bh) { flowable.subscribe(new PerfConsumer(bh)); } @Benchmark public void observable(Blackhole bh) { observable.subscribe(new PerfConsumer(bh)); } }
FlattenCrossMapPerf
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingDefaultTest.java
{ "start": 4823, "end": 5275 }
class ____ { boolean f(int i) { switch (i) { case 42: return true; default: // fall out } return false; } } """) .doTest(TEXT_MATCH); } @Test public void interiorEmptyNoComment() { compilationHelper .addSourceLines( "Test.java", """
Test
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/nonexistentvariables/NonExistentVariablesTest.java
{ "start": 1142, "end": 1943 }
class ____ { protected static SqlSessionFactory sqlSessionFactory; @BeforeAll static void setUp() throws Exception { try (Reader reader = Resources .getResourceAsReader("org/apache/ibatis/submitted/nonexistentvariables/mybatis-config.xml")) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } BaseDataTest.runScript(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), "org/apache/ibatis/submitted/nonexistentvariables/CreateDB.sql"); } @Test void wrongParameter() { try (SqlSession sqlSession = sqlSessionFactory.openSession()) { Mapper mapper = sqlSession.getMapper(Mapper.class); Assertions.assertThrows(PersistenceException.class, () -> mapper.count(1, "John")); } } }
NonExistentVariablesTest
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/apptoflow/AppToFlowColumn.java
{ "start": 1495, "end": 3005 }
enum ____ implements Column<AppToFlowTable> { /** * The flow ID. */ FLOW_ID(AppToFlowColumnFamily.MAPPING, "flow_id"), /** * The flow run ID. */ FLOW_RUN_ID(AppToFlowColumnFamily.MAPPING, "flow_run_id"), /** * The user. */ USER_ID(AppToFlowColumnFamily.MAPPING, "user_id"); private final ColumnFamily<AppToFlowTable> columnFamily; private final String columnQualifier; private final byte[] columnQualifierBytes; private final ValueConverter valueConverter; AppToFlowColumn(ColumnFamily<AppToFlowTable> columnFamily, String columnQualifier) { this.columnFamily = columnFamily; this.columnQualifier = columnQualifier; // Future-proof by ensuring the right column prefix hygiene. this.columnQualifierBytes = Bytes.toBytes(Separator.SPACE.encode(columnQualifier)); this.valueConverter = GenericConverter.getInstance(); } /** * @return the column name value */ private String getColumnQualifier() { return columnQualifier; } @Override public byte[] getColumnQualifierBytes() { return columnQualifierBytes.clone(); } @Override public byte[] getColumnFamilyBytes() { return columnFamily.getBytes(); } @Override public ValueConverter getValueConverter() { return valueConverter; } @Override public Attribute[] getCombinedAttrsWithAggr(Attribute... attributes) { return attributes; } @Override public boolean supplementCellTimestamp() { return false; } }
AppToFlowColumn
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPath.java
{ "start": 422, "end": 802 }
interface ____ extends OrderingExpression, SequencePart { NavigablePath getNavigablePath(); DomainPath getLhs(); ModelPart getReferenceModelPart(); default PluralAttributeMapping getPluralAttribute() { return getLhs().getPluralAttribute(); } @Override default String toDescriptiveText() { return "domain path (" + getNavigablePath().getFullPath() + ")"; } }
DomainPath
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFlatMapSingle.java
{ "start": 1276, "end": 1920 }
class ____<T, R> extends AbstractObservableWithUpstream<T, R> { final Function<? super T, ? extends SingleSource<? extends R>> mapper; final boolean delayErrors; public ObservableFlatMapSingle(ObservableSource<T> source, Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean delayError) { super(source); this.mapper = mapper; this.delayErrors = delayError; } @Override protected void subscribeActual(Observer<? super R> observer) { source.subscribe(new FlatMapSingleObserver<>(observer, mapper, delayErrors)); } static final
ObservableFlatMapSingle
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/intercept/SpringParentChildInterceptStrategyTest.java
{ "start": 1073, "end": 1405 }
class ____ extends ParentChildInterceptStrategyTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/intercept/SpringParentChildInterceptStrategyTest.xml"); } }
SpringParentChildInterceptStrategyTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/bucket/terms/heuristic/JLHScoreTests.java
{ "start": 639, "end": 909 }
class ____ extends AbstractSignificanceHeuristicTestCase { @Override protected SignificanceHeuristic getHeuristic() { return new JLHScore(); } @Override public void testAssertions() { testAssertions(new JLHScore()); } }
JLHScoreTests
java
apache__camel
components/camel-aws/camel-aws2-sns/src/test/java/org/apache/camel/component/aws2/sns/integration/SnsTopicProducerBatchIT.java
{ "start": 1683, "end": 3562 }
class ____ extends Aws2SNSBase { @RegisterExtension public static SharedNameGenerator sharedNameGenerator = new TestEntityNameGenerator(); @Test public void sendInOnly() { Exchange exchange = template.send("direct:start", ExchangePattern.InOnly, new Processor() { public void process(Exchange exchange) { PublishBatchRequestEntry publishBatchRequestEntry1 = PublishBatchRequestEntry.builder() .id("message1") .message("This is message 1") .build(); PublishBatchRequestEntry publishBatchRequestEntry2 = PublishBatchRequestEntry.builder() .id("message2") .message("This is message 2") .build(); PublishBatchRequestEntry publishBatchRequestEntry3 = PublishBatchRequestEntry.builder() .id("message3") .message("This is message 3") .build(); List<PublishBatchRequestEntry> pubList = new ArrayList<>(); pubList.add(publishBatchRequestEntry1); pubList.add(publishBatchRequestEntry2); pubList.add(publishBatchRequestEntry3); exchange.getIn().setBody(pubList); } }); assertNotNull(exchange.getMessage().getBody(PublishBatchResponse.class)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .toF("aws2-sns://%s?subject=The+subject+message&autoCreateTopic=true&batchEnabled=true", sharedNameGenerator.getName()); } }; } }
SnsTopicProducerBatchIT
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/bundle/MapBundleOperatorTest.java
{ "start": 1508, "end": 3236 }
class ____ { @Test void testSimple() throws Exception { @SuppressWarnings("unchecked") TestMapBundleFunction func = new TestMapBundleFunction(); CountBundleTrigger<Tuple2<String, String>> trigger = new CountBundleTrigger<>(3); KeySelector<Tuple2<String, String>, String> keySelector = (KeySelector<Tuple2<String, String>, String>) value -> value.f0; OneInputStreamOperatorTestHarness<Tuple2<String, String>, String> op = new OneInputStreamOperatorTestHarness<>( new MapBundleOperator<>(func, trigger, keySelector)); op.open(); synchronized (op.getCheckpointLock()) { StreamRecord<Tuple2<String, String>> input = new StreamRecord<>(null); input.replace(new Tuple2<>("k1", "v1")); op.processElement(input); input.replace(new Tuple2<>("k1", "v2")); op.processElement(input); assertThat(func.getFinishCount()).isEqualTo(0); input.replace(new Tuple2<>("k2", "v3")); op.processElement(input); assertThat(func.getFinishCount()).isEqualTo(1); assertThat(Arrays.asList("k1=v1,v2", "k2=v3")).isEqualTo(func.getOutputs()); input.replace(new Tuple2<>("k3", "v4")); op.processElement(input); input.replace(new Tuple2<>("k4", "v5")); op.processElement(input); assertThat(func.getFinishCount()).isEqualTo(1); op.close(); assertThat(func.getFinishCount()).isEqualTo(2); assertThat(Arrays.asList("k3=v4", "k4=v5")).isEqualTo(func.getOutputs()); } } private static
MapBundleOperatorTest
java
quarkusio__quarkus
integration-tests/spring-web/src/test/java/io/quarkus/it/spring/web/openapi/OpenApiDefaultPathPMT.java
{ "start": 254, "end": 1736 }
class ____ { private static final String OPEN_API_PATH = "/q/openapi"; @RegisterExtension static QuarkusProdModeTest runner = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar .addClasses(OpenApiController.class) .addAsResource("test-roles.properties") .addAsResource("test-users.properties")) .setRun(true); @Test public void testOpenApiPathAccessResource() { RestAssured.given().header("Accept", "application/yaml") .when().get(OPEN_API_PATH) .then().header("Content-Type", "application/yaml;charset=UTF-8"); RestAssured.given().queryParam("format", "YAML") .when().get(OPEN_API_PATH) .then().header("Content-Type", "application/yaml;charset=UTF-8"); RestAssured.given().header("Accept", "application/json") .when().get(OPEN_API_PATH) .then().header("Content-Type", "application/json;charset=UTF-8"); RestAssured.given().queryParam("format", "JSON") .when().get(OPEN_API_PATH) .then() .header("Content-Type", "application/json;charset=UTF-8") .body("openapi", Matchers.startsWith("3.1")) .body("info.title", Matchers.equalTo("quarkus-integration-test-spring-web API")) .body("paths", Matchers.hasKey("/resource")); } }
OpenApiDefaultPathPMT
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ssl/BundleContentNotWatchableFailureAnalyzer.java
{ "start": 1009, "end": 1494 }
class ____ extends AbstractFailureAnalyzer<BundleContentNotWatchableException> { @Override protected FailureAnalysis analyze(Throwable rootFailure, BundleContentNotWatchableException cause) { return new FailureAnalysis(cause.getMessage(), "Update your application to correct the invalid configuration:\n" + "Either use a watchable resource, or disable bundle reloading by setting reload-on-update = false on the bundle.", cause); } }
BundleContentNotWatchableFailureAnalyzer
java
apache__kafka
tools/src/test/java/org/apache/kafka/tools/StreamsResetterTest.java
{ "start": 1856, "end": 13752 }
class ____ { private static final String TOPIC = "topic1"; private final StreamsResetter streamsResetter = new StreamsResetter(); private final MockConsumer<byte[], byte[]> consumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()); private final TopicPartition topicPartition = new TopicPartition(TOPIC, 0); private final Set<TopicPartition> inputTopicPartitions = Set.of(topicPartition); @BeforeEach public void beforeEach() { consumer.assign(List.of(topicPartition)); consumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 0L, new byte[] {}, new byte[] {})); consumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 1L, new byte[] {}, new byte[] {})); consumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 2L, new byte[] {}, new byte[] {})); consumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 3L, new byte[] {}, new byte[] {})); consumer.addRecord(new ConsumerRecord<>(TOPIC, 0, 4L, new byte[] {}, new byte[] {})); } @Test public void testResetToSpecificOffsetWhenBetweenBeginningAndEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); streamsResetter.resetOffsetsTo(consumer, inputTopicPartitions, 2L); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(3, records.count()); } @Test public void testResetOffsetToSpecificOffsetWhenAfterEndOffset() { final long beginningOffset = 5L; final long endOffset = 10L; final MockConsumer<byte[], byte[]> emptyConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()); emptyConsumer.assign(List.of(topicPartition)); final Map<TopicPartition, Long> beginningOffsetsMap = new HashMap<>(); beginningOffsetsMap.put(topicPartition, beginningOffset); emptyConsumer.updateBeginningOffsets(beginningOffsetsMap); final Map<TopicPartition, Long> endOffsetsMap = new HashMap<>(); endOffsetsMap.put(topicPartition, endOffset); emptyConsumer.updateEndOffsets(endOffsetsMap); // resetOffsetsTo only seeks the offset, but does not commit. streamsResetter.resetOffsetsTo(emptyConsumer, inputTopicPartitions, endOffset + 2L); final long position = emptyConsumer.position(topicPartition); assertEquals(endOffset, position); } @Test public void testResetToSpecificOffsetWhenBeforeBeginningOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 3L); consumer.updateBeginningOffsets(beginningOffsets); streamsResetter.resetOffsetsTo(consumer, inputTopicPartitions, 2L); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void testResetToSpecificOffsetWhenAfterEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 3L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); streamsResetter.resetOffsetsTo(consumer, inputTopicPartitions, 4L); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void testShiftOffsetByWhenBetweenBeginningAndEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); streamsResetter.shiftOffsetsBy(consumer, inputTopicPartitions, 3L); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void testShiftOffsetByWhenBeforeBeginningOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); streamsResetter.shiftOffsetsBy(consumer, inputTopicPartitions, -3L); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(5, records.count()); } @Test public void testShiftOffsetByWhenAfterEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 3L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); streamsResetter.shiftOffsetsBy(consumer, inputTopicPartitions, 5L); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void testResetUsingPlanWhenBetweenBeginningAndEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); final Map<TopicPartition, Long> topicPartitionsAndOffset = new HashMap<>(); topicPartitionsAndOffset.put(topicPartition, 3L); streamsResetter.resetOffsetsFromResetPlan(consumer, inputTopicPartitions, topicPartitionsAndOffset); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void testResetUsingPlanWhenBeforeBeginningOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 4L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 3L); consumer.updateBeginningOffsets(beginningOffsets); final Map<TopicPartition, Long> topicPartitionsAndOffset = new HashMap<>(); topicPartitionsAndOffset.put(topicPartition, 1L); streamsResetter.resetOffsetsFromResetPlan(consumer, inputTopicPartitions, topicPartitionsAndOffset); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void testResetUsingPlanWhenAfterEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 3L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); final Map<TopicPartition, Long> topicPartitionsAndOffset = new HashMap<>(); topicPartitionsAndOffset.put(topicPartition, 5L); streamsResetter.resetOffsetsFromResetPlan(consumer, inputTopicPartitions, topicPartitionsAndOffset); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void shouldSeekToEndOffset() { final Map<TopicPartition, Long> endOffsets = new HashMap<>(); endOffsets.put(topicPartition, 3L); consumer.updateEndOffsets(endOffsets); final Map<TopicPartition, Long> beginningOffsets = new HashMap<>(); beginningOffsets.put(topicPartition, 0L); consumer.updateBeginningOffsets(beginningOffsets); final Set<TopicPartition> intermediateTopicPartitions = new HashSet<>(); intermediateTopicPartitions.add(topicPartition); streamsResetter.maybeSeekToEnd("g1", consumer, intermediateTopicPartitions); final ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(500)); assertEquals(2, records.count()); } @Test public void shouldDeleteTopic() throws InterruptedException, ExecutionException { final Cluster cluster = createCluster(1); try (final MockAdminClient adminClient = new MockAdminClient(cluster.nodes(), cluster.nodeById(0))) { final TopicPartitionInfo topicPartitionInfo = new TopicPartitionInfo(0, cluster.nodeById(0), cluster.nodes(), List.of()); adminClient.addTopic(false, TOPIC, List.of(topicPartitionInfo), null); streamsResetter.doDelete(List.of(TOPIC), adminClient); assertEquals(Set.of(), adminClient.listTopics().names().get()); } } @Test public void shouldDetermineInternalTopicBasedOnTopicName1() { assertTrue(StreamsResetter.matchesInternalTopicFormat("appId-named-subscription-response-topic")); assertTrue(StreamsResetter.matchesInternalTopicFormat("appId-named-subscription-registration-topic")); assertTrue(StreamsResetter.matchesInternalTopicFormat("appId-KTABLE-FK-JOIN-SUBSCRIPTION-RESPONSE-12323232-topic")); assertTrue(StreamsResetter.matchesInternalTopicFormat("appId-KTABLE-FK-JOIN-SUBSCRIPTION-REGISTRATION-12323232-topic")); } @Test public void testResetToDatetimeWhenPartitionIsEmptyResetsToLatestOffset() { final long beginningAndEndOffset = 5L; // Empty partition implies beginning offset == end offset final MockConsumer<byte[], byte[]> emptyConsumer = new EmptyPartitionConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()); emptyConsumer.assign(List.of(topicPartition)); final Map<TopicPartition, Long> beginningOffsetsMap = new HashMap<>(); beginningOffsetsMap.put(topicPartition, beginningAndEndOffset); emptyConsumer.updateBeginningOffsets(beginningOffsetsMap); final Map<TopicPartition, Long> endOffsetsMap = new HashMap<>(); endOffsetsMap.put(topicPartition, beginningAndEndOffset); emptyConsumer.updateEndOffsets(endOffsetsMap); final long yesterdayTimestamp = Instant.now().minus(Duration.ofDays(1)).toEpochMilli(); // resetToDatetime only seeks the offset, but does not commit. streamsResetter.resetToDatetime(emptyConsumer, inputTopicPartitions, yesterdayTimestamp); final long position = emptyConsumer.position(topicPartition); assertEquals(beginningAndEndOffset, position); } private Cluster createCluster(final int numNodes) { final HashMap<Integer, Node> nodes = new HashMap<>(); for (int i = 0; i < numNodes; ++i) { nodes.put(i, new Node(i, "localhost", 8121 + i)); } return new Cluster("mockClusterId", nodes.values(), Set.of(), Set.of(), Set.of(), nodes.get(0)); } private static
StreamsResetterTest
java
quarkusio__quarkus
extensions/smallrye-fault-tolerance/deployment/src/test/java/io/quarkus/smallrye/faulttolerance/test/asynchronous/types/mutiny/resubscription/MutinyHelloService.java
{ "start": 372, "end": 651 }
class ____ { static final AtomicInteger COUNTER = new AtomicInteger(0); @AsynchronousNonBlocking @Retry public Uni<String> hello() { COUNTER.incrementAndGet(); return Uni.createFrom().failure(IllegalArgumentException::new); } }
MutinyHelloService
java
apache__flink
flink-core/src/test/java/org/apache/flink/testutils/runtime/NoFetchingInputTest.java
{ "start": 1325, "end": 2079 }
class ____ { /** * Try deserializing an object whose serialization result is an empty byte array, and don't * expect any exceptions. */ @Test void testDeserializeEmptyObject() { EmptyObjectSerializer emptyObjectSerializer = new EmptyObjectSerializer(); Output output = new ByteBufferOutput(1000); emptyObjectSerializer.write(null, output, new Object()); Input input = new NoFetchingInput(new ByteArrayInputStream(output.toBytes())); final Object deserialized = emptyObjectSerializer.read(null, input, Object.class); assertThat(deserialized).isExactlyInstanceOf(Object.class); } /** The serializer that serialize the empty object. */ public static
NoFetchingInputTest
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java
{ "start": 2309, "end": 14771 }
class ____ { // See RFC 7636: Appendix B. Example for the S256 code_challenge_method // https://tools.ietf.org/html/rfc7636#appendix-B private static final String S256_CODE_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; private static final String S256_CODE_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; private static final String AUTHORIZATION_CODE = "code"; private static final OAuth2TokenType AUTHORIZATION_CODE_TOKEN_TYPE = new OAuth2TokenType(OAuth2ParameterNames.CODE); private RegisteredClientRepository registeredClientRepository; private OAuth2AuthorizationService authorizationService; private PublicClientAuthenticationProvider authenticationProvider; @BeforeEach public void setUp() { this.registeredClientRepository = mock(RegisteredClientRepository.class); this.authorizationService = mock(OAuth2AuthorizationService.class); this.authenticationProvider = new PublicClientAuthenticationProvider(this.registeredClientRepository, this.authorizationService); } @Test public void constructorWhenRegisteredClientRepositoryNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PublicClientAuthenticationProvider(null, this.authorizationService)) .withMessage("registeredClientRepository cannot be null"); } @Test public void constructorWhenAuthorizationServiceNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new PublicClientAuthenticationProvider(this.registeredClientRepository, null)) .withMessage("authorizationService cannot be null"); } @Test public void supportsWhenTypeOAuth2ClientAuthenticationTokenThenReturnTrue() { assertThat(this.authenticationProvider.supports(OAuth2ClientAuthenticationToken.class)).isTrue(); } @Test public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId() + "-invalid", ClientAuthenticationMethod.NONE, null, null); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID); }); } @Test public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, null); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("authentication_method"); }); } @Test public void authenticateWhenInvalidCodeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) .willReturn(authorization); Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER); parameters.put(OAuth2ParameterNames.CODE, "invalid-code"); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, parameters); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CODE); }); } @Test public void authenticateWhenMissingCodeChallengeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) .willReturn(authorization); Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, parameters); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_CHALLENGE); }); } @Test public void authenticateWhenMissingCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) .willReturn(authorization); Map<String, Object> parameters = createAuthorizationCodeTokenParameters(); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, parameters); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER); }); } @Test public void authenticateWhenS256MethodAndInvalidCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) .willReturn(authorization); Map<String, Object> parameters = createPkceTokenParameters("invalid-code-verifier"); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, parameters); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER); }); } @Test public void authenticateWhenS256MethodAndValidCodeVerifierThenAuthenticated() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) .willReturn(authorization); Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, parameters); OAuth2ClientAuthenticationToken authenticationResult = (OAuth2ClientAuthenticationToken) this.authenticationProvider .authenticate(authentication); assertThat(authenticationResult.isAuthenticated()).isTrue(); assertThat(authenticationResult.getPrincipal().toString()).isEqualTo(registeredClient.getClientId()); assertThat(authenticationResult.getCredentials()).isNull(); assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient); } @Test public void authenticateWhenUnsupportedCodeChallengeMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) .willReturn(registeredClient); Map<String, Object> authorizationRequestAdditionalParameters = createPkceAuthorizationParametersS256(); // This should never happen: the Authorization endpoint should not allow it authorizationRequestAdditionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "unsupported-challenge-method"); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, authorizationRequestAdditionalParameters) .build(); given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) .willReturn(authorization); Map<String, Object> parameters = createPkceTokenParameters(S256_CODE_VERIFIER); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, parameters); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } private static Map<String, Object> createAuthorizationCodeTokenParameters() { Map<String, Object> parameters = new HashMap<>(); parameters.put(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); parameters.put(OAuth2ParameterNames.CODE, AUTHORIZATION_CODE); return parameters; } private static Map<String, Object> createPkceTokenParameters(String codeVerifier) { Map<String, Object> parameters = createAuthorizationCodeTokenParameters(); parameters.put(PkceParameterNames.CODE_VERIFIER, codeVerifier); return parameters; } private static Map<String, Object> createPkceAuthorizationParametersS256() { Map<String, Object> parameters = new HashMap<>(); parameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); parameters.put(PkceParameterNames.CODE_CHALLENGE, S256_CODE_CHALLENGE); return parameters; } }
PublicClientAuthenticationProviderTests
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/graph/JobGraphGeneratorTestBase.java
{ "start": 110237, "end": 110461 }
class ____<T> implements SinkFunction<T> { @Override public void invoke(T value, Context context) throws Exception {} } private static
TestingSinkFunctionNotSupportConcurrentExecutionAttempts
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/ExistingPropertyTest.java
{ "start": 2810, "end": 3115 }
class ____ extends Animal { public String furColor; private Cat() { super(null); } protected Cat(String name, String c) { super(name); furColor = c; } @Override public String getType() { return "kitty"; } } static
Cat
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/shuffle/NettyShuffleDescriptor.java
{ "start": 5040, "end": 5554 }
enum ____ implements PartitionConnectionInfo { INSTANCE; @Override public InetSocketAddress getAddress() { throw new UnsupportedOperationException( "Local execution does not support shuffle connection."); } @Override public int getConnectionIndex() { throw new UnsupportedOperationException( "Local execution does not support shuffle connection."); } } }
LocalExecutionPartitionConnectionInfo
java
quarkusio__quarkus
extensions/devui/deployment/src/test/java/io/quarkus/devui/testrunner/UnitET.java
{ "start": 122, "end": 410 }
class ____ { @Test public void unitStyleTest2() { Assertions.assertEquals("UNIT", UnitService.service()); } @Test public void unitStyleTest() { HelloResource res = new HelloResource(); Assertions.assertEquals("Hi", res.sayHello()); } }
UnitET
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestMRJobsWithHistoryService.java
{ "start": 2420, "end": 7282 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestMRJobsWithHistoryService.class); private static final EnumSet<RMAppState> TERMINAL_RM_APP_STATES = EnumSet.of(RMAppState.FINISHED, RMAppState.FAILED, RMAppState.KILLED); private static MiniMRYarnCluster mrCluster; private static Configuration conf = new Configuration(); private static FileSystem localFs; static { try { localFs = FileSystem.getLocal(conf); } catch (IOException io) { throw new RuntimeException("problem getting local fs", io); } } private static Path TEST_ROOT_DIR = localFs.makeQualified( new Path("target", TestMRJobs.class.getName() + "-tmpDir")); static Path APP_JAR = new Path(TEST_ROOT_DIR, "MRAppJar.jar"); @BeforeEach public void setup() throws InterruptedException, IOException { if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } if (mrCluster == null) { mrCluster = new MiniMRYarnCluster(getClass().getName()); mrCluster.init(new Configuration()); mrCluster.start(); } // Copy MRAppJar and make it private. TODO: FIXME. This is a hack to // workaround the absent public discache. localFs.copyFromLocalFile(new Path(MiniMRYarnCluster.APPJAR), APP_JAR); localFs.setPermission(APP_JAR, new FsPermission("700")); } @AfterEach public void tearDown() { if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } if (mrCluster != null) { mrCluster.stop(); } } @Test @Timeout(value = 90) public void testJobHistoryData() throws IOException, InterruptedException, AvroRemoteException, ClassNotFoundException { if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } SleepJob sleepJob = new SleepJob(); sleepJob.setConf(mrCluster.getConfig()); // Job with 3 maps and 2 reduces Job job = sleepJob.createJob(3, 2, 1000, 1, 500, 1); job.setJarByClass(SleepJob.class); job.addFileToClassPath(APP_JAR); // The AppMaster jar itself. job.waitForCompletion(true); Counters counterMR = job.getCounters(); JobId jobId = TypeConverter.toYarn(job.getJobID()); ApplicationId appID = jobId.getAppId(); int pollElapsed = 0; while (true) { Thread.sleep(1000); pollElapsed += 1000; if (TERMINAL_RM_APP_STATES.contains( mrCluster.getResourceManager().getRMContext().getRMApps().get(appID) .getState())) { break; } if (pollElapsed >= 60000) { LOG.warn("application did not reach terminal state within 60 seconds"); break; } } assertEquals(RMAppState.FINISHED, mrCluster.getResourceManager() .getRMContext().getRMApps().get(appID).getState()); Counters counterHS = job.getCounters(); //TODO the Assert below worked. need to check //Should we compare each field or convert to V2 counter and compare LOG.info("CounterHS " + counterHS); LOG.info("CounterMR " + counterMR); assertEquals(counterHS, counterMR); HSClientProtocol historyClient = instantiateHistoryProxy(); GetJobReportRequest gjReq = Records.newRecord(GetJobReportRequest.class); gjReq.setJobId(jobId); JobReport jobReport = historyClient.getJobReport(gjReq).getJobReport(); verifyJobReport(jobReport, jobId); } private void verifyJobReport(JobReport jobReport, JobId jobId) { List<AMInfo> amInfos = jobReport.getAMInfos(); assertEquals(1, amInfos.size()); AMInfo amInfo = amInfos.get(0); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(jobId.getAppId(), 1); ContainerId amContainerId = ContainerId.newContainerId(appAttemptId, 1); assertEquals(appAttemptId, amInfo.getAppAttemptId()); assertEquals(amContainerId, amInfo.getContainerId()); assertTrue(jobReport.getSubmitTime() > 0); assertTrue(jobReport.getStartTime() > 0 && jobReport.getStartTime() >= jobReport.getSubmitTime()); assertTrue(jobReport.getFinishTime() > 0 && jobReport.getFinishTime() >= jobReport.getStartTime()); } private HSClientProtocol instantiateHistoryProxy() { final String serviceAddr = mrCluster.getConfig().get(JHAdminConfig.MR_HISTORY_ADDRESS); final YarnRPC rpc = YarnRPC.create(conf); HSClientProtocol historyClient = (HSClientProtocol) rpc.getProxy(HSClientProtocol.class, NetUtils.createSocketAddr(serviceAddr), mrCluster.getConfig()); return historyClient; } }
TestMRJobsWithHistoryService
java
apache__camel
test-infra/camel-test-infra-openai-mock/src/main/java/org/apache/camel/test/infra/openai/mock/MockExpectation.java
{ "start": 1133, "end": 4048 }
class ____ { private final String expectedInput; private final ToolExecutionSequence toolSequence; private String expectedResponse; private String toolContentResponse; private BiFunction<HttpExchange, String, String> customResponseFunction; private Consumer<String> requestAssertion; public MockExpectation(String expectedInput) { this.expectedInput = expectedInput; this.toolSequence = new ToolExecutionSequence(); } // Getters public String getExpectedInput() { return expectedInput; } public String getExpectedResponse() { return expectedResponse; } public String getToolContentResponse() { return toolContentResponse; } public BiFunction<HttpExchange, String, String> getCustomResponseFunction() { return customResponseFunction; } public Consumer<String> getRequestAssertion() { return requestAssertion; } public ToolExecutionSequence getToolSequence() { return toolSequence; } // Setters public void setExpectedResponse(String expectedResponse) { this.expectedResponse = expectedResponse; } public void setCustomResponseFunction(BiFunction<HttpExchange, String, String> customResponseFunction) { this.customResponseFunction = customResponseFunction; } public void setRequestAssertion(Consumer<String> requestAssertion) { this.requestAssertion = requestAssertion; } public void setToolContentResponse(String toolContentResponse) { this.toolContentResponse = toolContentResponse; } // Tool sequence delegation methods public void addToolExecutionStep(ToolExecutionStep step) { toolSequence.addStep(step); } public ToolExecutionStep getCurrentToolStep() { return toolSequence.getCurrentStep(); } public void advanceToNextToolStep() { toolSequence.advanceToNextStep(); } public boolean hasMoreToolSteps() { return toolSequence.hasMoreSteps(); } public boolean isInToolSequence() { return toolSequence.isInProgress(); } public void resetToolSequence() { toolSequence.reset(); } // Response type determination public MockResponseType getResponseType() { if (customResponseFunction != null) { return MockResponseType.CUSTOM_FUNCTION; } if (!toolSequence.isEmpty() && toolSequence.hasCurrentStep()) { return MockResponseType.TOOL_CALLS; } return MockResponseType.SIMPLE_TEXT; } public boolean matches(String input) { return expectedInput.equals(input); } @Override public String toString() { return String.format("MockExpectation{input='%s', response='%s', toolSteps=%d}", expectedInput, expectedResponse, toolSequence.getTotalSteps()); } }
MockExpectation
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 66947, "end": 67180 }
class ____ { @Bean @ConfigurationPropertiesBinding static GenericConverter genericPersonConverter() { return new GenericPersonConverter(); } } @Configuration(proxyBeanMethods = false) static
GenericConverterConfiguration
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryWindowStore.java
{ "start": 23323, "end": 24781 }
class ____ extends InMemoryWindowStoreIteratorWrapper implements WindowStoreIterator<byte[]> { WrappedInMemoryWindowStoreIterator(final Bytes keyFrom, final Bytes keyTo, final Iterator<Map.Entry<Long, ConcurrentNavigableMap<Bytes, byte[]>>> segmentIterator, final ClosingCallback callback, final boolean retainDuplicates, final boolean forward) { super(keyFrom, keyTo, segmentIterator, callback, retainDuplicates, forward); } @Override public Long peekNextKey() { if (!hasNext()) { throw new NoSuchElementException(); } return super.currentTime; } @Override public KeyValue<Long, byte[]> next() { if (!hasNext()) { throw new NoSuchElementException(); } final KeyValue<Long, byte[]> result = new KeyValue<>(super.currentTime, super.next.value); super.next = null; return result; } public static WrappedInMemoryWindowStoreIterator emptyIterator() { return new WrappedInMemoryWindowStoreIterator(null, null, null, it -> { }, false, true); } } private static
WrappedInMemoryWindowStoreIterator
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableWindowBoundarySelector.java
{ "start": 2190, "end": 11354 }
class ____<T, B, V> extends AtomicInteger implements Observer<T>, Disposable, Runnable { private static final long serialVersionUID = 8646217640096099753L; final Observer<? super Observable<T>> downstream; final ObservableSource<B> open; final Function<? super B, ? extends ObservableSource<V>> closingIndicator; final int bufferSize; final CompositeDisposable resources; final WindowStartObserver<B> startObserver; final List<UnicastSubject<T>> windows; final SimplePlainQueue<Object> queue; final AtomicLong windowCount; final AtomicBoolean downstreamDisposed; final AtomicLong requested; long emitted; volatile boolean upstreamCanceled; volatile boolean upstreamDone; volatile boolean openDone; final AtomicThrowable error; Disposable upstream; WindowBoundaryMainObserver(Observer<? super Observable<T>> downstream, ObservableSource<B> open, Function<? super B, ? extends ObservableSource<V>> closingIndicator, int bufferSize) { this.downstream = downstream; this.queue = new MpscLinkedQueue<>(); this.open = open; this.closingIndicator = closingIndicator; this.bufferSize = bufferSize; this.resources = new CompositeDisposable(); this.windows = new ArrayList<>(); this.windowCount = new AtomicLong(1L); this.downstreamDisposed = new AtomicBoolean(); this.error = new AtomicThrowable(); this.startObserver = new WindowStartObserver<>(this); this.requested = new AtomicLong(); } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); open.subscribe(startObserver); } } @Override public void onNext(T t) { queue.offer(t); drain(); } @Override public void onError(Throwable t) { startObserver.dispose(); resources.dispose(); if (error.tryAddThrowableOrReport(t)) { upstreamDone = true; drain(); } } @Override public void onComplete() { startObserver.dispose(); resources.dispose(); upstreamDone = true; drain(); } @Override public void dispose() { if (downstreamDisposed.compareAndSet(false, true)) { if (windowCount.decrementAndGet() == 0) { upstream.dispose(); startObserver.dispose(); resources.dispose(); error.tryTerminateAndReport(); upstreamCanceled = true; drain(); } else { startObserver.dispose(); } } } @Override public boolean isDisposed() { return downstreamDisposed.get(); } @Override public void run() { if (windowCount.decrementAndGet() == 0) { upstream.dispose(); startObserver.dispose(); resources.dispose(); error.tryTerminateAndReport(); upstreamCanceled = true; drain(); } } void open(B startValue) { queue.offer(new WindowStartItem<>(startValue)); drain(); } void openError(Throwable t) { upstream.dispose(); resources.dispose(); if (error.tryAddThrowableOrReport(t)) { upstreamDone = true; drain(); } } void openComplete() { openDone = true; drain(); } void close(WindowEndObserverIntercept<T, V> what) { queue.offer(what); drain(); } void closeError(Throwable t) { upstream.dispose(); startObserver.dispose(); resources.dispose(); if (error.tryAddThrowableOrReport(t)) { upstreamDone = true; drain(); } } void drain() { if (getAndIncrement() != 0) { return; } int missed = 1; final Observer<? super Observable<T>> downstream = this.downstream; final SimplePlainQueue<Object> queue = this.queue; final List<UnicastSubject<T>> windows = this.windows; for (;;) { if (upstreamCanceled) { queue.clear(); windows.clear(); } else { boolean isDone = upstreamDone; Object o = queue.poll(); boolean isEmpty = o == null; if (isDone) { if (isEmpty || error.get() != null) { terminateDownstream(downstream); upstreamCanceled = true; continue; } } if (!isEmpty) { if (o instanceof WindowStartItem) { if (!downstreamDisposed.get()) { @SuppressWarnings("unchecked") B startItem = ((WindowStartItem<B>)o).item; ObservableSource<V> endSource; try { endSource = Objects.requireNonNull(closingIndicator.apply(startItem), "The closingIndicator returned a null ObservableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.dispose(); startObserver.dispose(); resources.dispose(); Exceptions.throwIfFatal(ex); error.tryAddThrowableOrReport(ex); upstreamDone = true; continue; } windowCount.getAndIncrement(); UnicastSubject<T> newWindow = UnicastSubject.create(bufferSize, this); WindowEndObserverIntercept<T, V> endObserver = new WindowEndObserverIntercept<>(this, newWindow); downstream.onNext(endObserver); if (endObserver.tryAbandon()) { newWindow.onComplete(); } else { windows.add(newWindow); resources.add(endObserver); endSource.subscribe(endObserver); } } } else if (o instanceof WindowEndObserverIntercept) { @SuppressWarnings("unchecked") UnicastSubject<T> w = ((WindowEndObserverIntercept<T, V>)o).window; windows.remove(w); resources.delete((Disposable)o); w.onComplete(); } else { @SuppressWarnings("unchecked") T item = (T)o; for (UnicastSubject<T> w : windows) { w.onNext(item); } } continue; } else if (openDone && windows.size() == 0) { upstream.dispose(); startObserver.dispose(); resources.dispose(); terminateDownstream(downstream); upstreamCanceled = true; continue; } } missed = addAndGet(-missed); if (missed == 0) { break; } } } void terminateDownstream(Observer<?> downstream) { Throwable ex = error.terminate(); if (ex == null) { for (UnicastSubject<T> w : windows) { w.onComplete(); } downstream.onComplete(); } else if (ex != ExceptionHelper.TERMINATED) { for (UnicastSubject<T> w : windows) { w.onError(ex); } downstream.onError(ex); } } static final
WindowBoundaryMainObserver
java
bumptech__glide
annotation/compiler/test/src/test/java/com/bumptech/glide/annotation/compiler/InvalidAppGlideModuleWithExcludesTest.java
{ "start": 3321, "end": 3423 }
class ____ extends AppGlideModule {}")); assertThat(compilation).failed(); } }
AppModuleWithExcludes
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/v2/adaptor/MapStateAdaptor.java
{ "start": 1334, "end": 7094 }
class ____<K, N, UK, UV> extends StateAdaptor< K, N, org.apache.flink.runtime.state.internal.InternalMapState<K, N, UK, UV>> implements InternalMapState<K, N, UK, UV> { public MapStateAdaptor( org.apache.flink.runtime.state.internal.InternalMapState<K, N, UK, UV> mapState) { super(mapState); } @Override public StateFuture<UV> asyncGet(UK key) { try { return StateFutureUtils.completedFuture(delegatedState.get(key)); } catch (Exception e) { throw new RuntimeException("Error while get value from raw MapState", e); } } @Override public UV get(UK key) { try { return delegatedState.get(key); } catch (Exception e) { throw new RuntimeException("Error while get value from raw MapState", e); } } @Override public StateFuture<Void> asyncPut(UK key, UV value) { try { delegatedState.put(key, value); } catch (Exception e) { throw new RuntimeException("Error while updating value to raw MapState", e); } return StateFutureUtils.completedVoidFuture(); } @Override public void put(UK key, UV value) { try { delegatedState.put(key, value); } catch (Exception e) { throw new RuntimeException("Error while updating value to raw MapState", e); } } @Override public StateFuture<Void> asyncPutAll(Map<UK, UV> map) { try { delegatedState.putAll(map); } catch (Exception e) { throw new RuntimeException("Error while updating values to raw MapState", e); } return StateFutureUtils.completedVoidFuture(); } @Override public void putAll(Map<UK, UV> map) { try { delegatedState.putAll(map); } catch (Exception e) { throw new RuntimeException("Error while updating values to raw MapState", e); } } @Override public StateFuture<Void> asyncRemove(UK key) { try { delegatedState.remove(key); } catch (Exception e) { throw new RuntimeException("Error while updating values to raw MapState", e); } return StateFutureUtils.completedVoidFuture(); } @Override public void remove(UK key) { try { delegatedState.remove(key); } catch (Exception e) { throw new RuntimeException("Error while updating values to raw MapState", e); } } @Override public StateFuture<Boolean> asyncContains(UK key) { try { return StateFutureUtils.completedFuture(delegatedState.contains(key)); } catch (Exception e) { throw new RuntimeException("Error while checking key from raw MapState", e); } } @Override public boolean contains(UK key) { try { return delegatedState.contains(key); } catch (Exception e) { throw new RuntimeException("Error while checking key from raw MapState", e); } } @Override public StateFuture<StateIterator<Map.Entry<UK, UV>>> asyncEntries() { try { return StateFutureUtils.completedFuture( new CompleteStateIterator<>(delegatedState.entries())); } catch (Exception e) { throw new RuntimeException("Error while get entries from raw MapState", e); } } @Override public Iterable<Map.Entry<UK, UV>> entries() { try { return delegatedState.entries(); } catch (Exception e) { throw new RuntimeException("Error while get entries from raw MapState", e); } } @Override public StateFuture<StateIterator<UK>> asyncKeys() { try { return StateFutureUtils.completedFuture( new CompleteStateIterator<>(delegatedState.keys())); } catch (Exception e) { throw new RuntimeException("Error while get keys from raw MapState", e); } } @Override public Iterable<UK> keys() { try { return delegatedState.keys(); } catch (Exception e) { throw new RuntimeException("Error while get keys from raw MapState", e); } } @Override public StateFuture<StateIterator<UV>> asyncValues() { try { return StateFutureUtils.completedFuture( new CompleteStateIterator<>(delegatedState.values())); } catch (Exception e) { throw new RuntimeException("Error while get values from raw MapState", e); } } @Override public Iterable<UV> values() { try { return delegatedState.values(); } catch (Exception e) { throw new RuntimeException("Error while get values from raw MapState", e); } } @Override public StateFuture<Boolean> asyncIsEmpty() { try { return StateFutureUtils.completedFuture(delegatedState.isEmpty()); } catch (Exception e) { throw new RuntimeException("Error while checking existence from raw MapState", e); } } @Override public boolean isEmpty() { try { return delegatedState.isEmpty(); } catch (Exception e) { throw new RuntimeException("Error while checking existence from raw MapState", e); } } @Override public Iterator<Map.Entry<UK, UV>> iterator() { try { return delegatedState.iterator(); } catch (Exception e) { throw new RuntimeException("Error while get entries from raw MapState", e); } } }
MapStateAdaptor
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/recording/BytecodeRecorderImpl.java
{ "start": 109191, "end": 109389 }
interface ____ { void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out); void prepare(MethodContext context); } /** *
SerializationStep
java
elastic__elasticsearch
modules/repository-s3/src/internalClusterTest/java/org/elasticsearch/repositories/s3/S3BlobStoreRepositoryMetricsTests.java
{ "start": 23115, "end": 24968 }
class ____ implements DelegatingHttpHandler { private final HttpHandler delegate; private final Queue<S3ErrorResponse> errorResponseQueue; S3MetricErroneousHttpHandler(HttpHandler delegate, Queue<S3ErrorResponse> errorResponseQueue) { this.delegate = delegate; this.errorResponseQueue = errorResponseQueue; } @Override public void handle(HttpExchange exchange) throws IOException { final S3ErrorResponse errorResponse = errorResponseQueue.poll(); if (errorResponse == null) { delegate.handle(exchange); } else if (errorResponse.status == INTERNAL_SERVER_ERROR) { // Simulate an retryable exception throw new IOException("ouch"); } else { try (exchange) { drainInputStream(exchange.getRequestBody()); errorResponse.writeResponse(exchange); } } } public HttpHandler getDelegate() { return delegate; } } record S3ErrorResponse(RestStatus status, String responseBody) { S3ErrorResponse(RestStatus status) { this(status, null); } @SuppressForbidden(reason = "this test uses a HttpServer to emulate an S3 endpoint") public void writeResponse(HttpExchange exchange) throws IOException { if (responseBody != null) { byte[] responseBytes = responseBody.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(status.getStatus(), responseBytes.length); exchange.getResponseBody().write(responseBytes); } else { exchange.sendResponseHeaders(status.getStatus(), -1); } } } }
S3MetricErroneousHttpHandler
java
grpc__grpc-java
binder/src/main/java/io/grpc/binder/SecurityPolicies.java
{ "start": 1620, "end": 21052 }
class ____ { private static final int MY_UID = Process.myUid(); private static final int SHA_256_BYTES_LENGTH = 32; private SecurityPolicies() {} @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8022") public static ServerSecurityPolicy serverInternalOnly() { return new ServerSecurityPolicy(); } /** * Creates a default {@link SecurityPolicy} that allows access only to callers with the same UID * as the current process. */ public static SecurityPolicy internalOnly() { return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { return uid == MY_UID ? Status.OK : Status.PERMISSION_DENIED.withDescription( "Rejected by (internal-only) security policy"); } }; } @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8022") public static SecurityPolicy permissionDenied(String description) { Status denied = Status.PERMISSION_DENIED.withDescription(description); return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { return denied; } }; } /** * Creates a {@link SecurityPolicy} which checks if the package signature matches {@code * requiredSignature}. * * @param packageName the package name of the allowed package. * @param requiredSignature the allowed signature of the allowed package. * @throws NullPointerException if any of the inputs are {@code null}. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8022") public static SecurityPolicy hasSignature( PackageManager packageManager, String packageName, Signature requiredSignature) { return oneOfSignatures(packageManager, packageName, ImmutableList.of(requiredSignature)); } /** * Creates {@link SecurityPolicy} which checks if the SHA-256 hash of the package signature * matches {@code requiredSignatureSha256Hash}. * * @param packageName the package name of the allowed package. * @param requiredSignatureSha256Hash the SHA-256 digest of the signature of the allowed package. * @throws NullPointerException if any of the inputs are {@code null}. * @throws IllegalArgumentException if {@code requiredSignatureSha256Hash} is not of length 32. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8022") public static SecurityPolicy hasSignatureSha256Hash( PackageManager packageManager, String packageName, byte[] requiredSignatureSha256Hash) { return oneOfSignatureSha256Hash( packageManager, packageName, ImmutableList.of(requiredSignatureSha256Hash)); } /** * Creates a {@link SecurityPolicy} which checks if the package signature matches any of {@code * requiredSignatures}. * * @param packageName the package name of the allowed package. * @param requiredSignatures the allowed signatures of the allowed package. * @throws NullPointerException if any of the inputs are {@code null}. * @throws IllegalArgumentException if {@code requiredSignatures} is empty. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/8022") public static SecurityPolicy oneOfSignatures( PackageManager packageManager, String packageName, Collection<Signature> requiredSignatures) { Preconditions.checkNotNull(packageManager, "packageManager"); Preconditions.checkNotNull(packageName, "packageName"); Preconditions.checkNotNull(requiredSignatures, "requiredSignatures"); Preconditions.checkArgument(!requiredSignatures.isEmpty(), "requiredSignatures"); ImmutableList<Signature> requiredSignaturesImmutable = ImmutableList.copyOf(requiredSignatures); for (Signature requiredSignature : requiredSignaturesImmutable) { Preconditions.checkNotNull(requiredSignature); } return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { return checkUidSignature(packageManager, uid, packageName, requiredSignaturesImmutable); } }; } /** * Creates {@link SecurityPolicy} which checks if the SHA-256 hash of the package signature * matches any of {@code requiredSignatureSha256Hashes}. * * @param packageName the package name of the allowed package. * @param requiredSignatureSha256Hashes the SHA-256 digests of the signatures of the allowed * package. * @throws NullPointerException if any of the inputs are {@code null}. * @throws IllegalArgumentException if {@code requiredSignatureSha256Hashes} is empty, or if any * of the {@code requiredSignatureSha256Hashes} are not of length 32. */ public static SecurityPolicy oneOfSignatureSha256Hash( PackageManager packageManager, String packageName, List<byte[]> requiredSignatureSha256Hashes) { Preconditions.checkNotNull(packageManager); Preconditions.checkNotNull(packageName); Preconditions.checkNotNull(requiredSignatureSha256Hashes); Preconditions.checkArgument(!requiredSignatureSha256Hashes.isEmpty()); ImmutableList.Builder<byte[]> immutableListBuilder = ImmutableList.builder(); for (byte[] requiredSignatureSha256Hash : requiredSignatureSha256Hashes) { Preconditions.checkNotNull(requiredSignatureSha256Hash); Preconditions.checkArgument(requiredSignatureSha256Hash.length == SHA_256_BYTES_LENGTH); immutableListBuilder.add( Arrays.copyOf(requiredSignatureSha256Hash, requiredSignatureSha256Hash.length)); } ImmutableList<byte[]> requiredSignaturesHashesImmutable = immutableListBuilder.build(); return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { return checkUidSha256Signature( packageManager, uid, packageName, requiredSignaturesHashesImmutable); } }; } /** * Creates {@link SecurityPolicy} which checks if the app is a device owner app. See {@link * DevicePolicyManager}. */ public static io.grpc.binder.SecurityPolicy isDeviceOwner(Context applicationContext) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) applicationContext.getSystemService(Context.DEVICE_POLICY_SERVICE); return anyPackageWithUidSatisfies( applicationContext, pkg -> devicePolicyManager.isDeviceOwnerApp(pkg), "Rejected by device owner policy. No packages found for UID.", "Rejected by device owner policy"); } /** * Creates {@link SecurityPolicy} which checks if the app is a profile owner app. See {@link * DevicePolicyManager}. */ public static SecurityPolicy isProfileOwner(Context applicationContext) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) applicationContext.getSystemService(Context.DEVICE_POLICY_SERVICE); return anyPackageWithUidSatisfies( applicationContext, pkg -> devicePolicyManager.isProfileOwnerApp(pkg), "Rejected by profile owner policy. No packages found for UID.", "Rejected by profile owner policy"); } /** * Creates {@link SecurityPolicy} which checks if the app is a profile owner app on an * organization-owned device. See {@link DevicePolicyManager}. */ public static SecurityPolicy isProfileOwnerOnOrganizationOwnedDevice(Context applicationContext) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) applicationContext.getSystemService(Context.DEVICE_POLICY_SERVICE); return anyPackageWithUidSatisfies( applicationContext, pkg -> VERSION.SDK_INT >= 30 && devicePolicyManager.isProfileOwnerApp(pkg) && devicePolicyManager.isOrganizationOwnedDeviceWithManagedProfile(), "Rejected by profile owner on organization-owned device policy. No packages found for UID.", "Rejected by profile owner on organization-owned device policy"); } private static Status checkUidSignature( PackageManager packageManager, int uid, String packageName, ImmutableList<Signature> requiredSignatures) { String[] packages = packageManager.getPackagesForUid(uid); if (packages == null) { return Status.UNAUTHENTICATED.withDescription("Rejected by signature check security policy"); } boolean packageNameMatched = false; for (String pkg : packages) { if (!packageName.equals(pkg)) { continue; } packageNameMatched = true; if (checkPackageSignature(packageManager, pkg, requiredSignatures::contains)) { return Status.OK; } } return Status.PERMISSION_DENIED.withDescription( "Rejected by signature check security policy. Package name matched: " + packageNameMatched); } private static Status checkUidSha256Signature( PackageManager packageManager, int uid, String packageName, ImmutableList<byte[]> requiredSignatureSha256Hashes) { String[] packages = packageManager.getPackagesForUid(uid); if (packages == null) { return Status.UNAUTHENTICATED.withDescription( "Rejected by (SHA-256 hash signature check) security policy"); } boolean packageNameMatched = false; for (String pkg : packages) { if (!packageName.equals(pkg)) { continue; } packageNameMatched = true; if (checkPackageSignature( packageManager, pkg, (signature) -> checkSignatureSha256HashesMatch(signature, requiredSignatureSha256Hashes))) { return Status.OK; } } return Status.PERMISSION_DENIED.withDescription( "Rejected by (SHA-256 hash signature check) security policy. Package name matched: " + packageNameMatched); } /** * Checks if the signature of {@code packageName} matches one of the given signatures. * * @param packageName the package to be checked * @param signatureCheckFunction {@link Predicate} that takes a signature and verifies if it * satisfies any signature constraints return {@code true} if {@code packageName} has a * signature that satisfies {@code signatureCheckFunction}. */ @SuppressWarnings("deprecation") // For PackageInfo.signatures @SuppressLint("PackageManagerGetSignatures") // We only allow 1 signature. private static boolean checkPackageSignature( PackageManager packageManager, String packageName, Predicate<Signature> signatureCheckFunction) { PackageInfo packageInfo; try { if (Build.VERSION.SDK_INT >= 28) { packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES); if (packageInfo.signingInfo == null) { return false; } Signature[] signatures = packageInfo.signingInfo.hasMultipleSigners() ? packageInfo.signingInfo.getApkContentsSigners() : packageInfo.signingInfo.getSigningCertificateHistory(); for (Signature signature : signatures) { if (signatureCheckFunction.apply(signature)) { return true; } } } else { packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); if (packageInfo.signatures == null || packageInfo.signatures.length != 1) { // Reject multiply-signed apks because of b/13678484 // (See PackageManagerGetSignatures suppression above). return false; } if (signatureCheckFunction.apply(packageInfo.signatures[0])) { return true; } } } catch (NameNotFoundException nnfe) { return false; } return false; } /** * Creates a {@link SecurityPolicy} that allows access if and only if *all* of the specified * {@code securityPolicies} allow access. * * @param securityPolicies the security policies that all must allow access. * @throws NullPointerException if any of the inputs are {@code null}. * @throws IllegalArgumentException if {@code securityPolicies} is empty. */ public static SecurityPolicy allOf(SecurityPolicy... securityPolicies) { Preconditions.checkNotNull(securityPolicies, "securityPolicies"); Preconditions.checkArgument(securityPolicies.length > 0, "securityPolicies must not be empty"); return allOfSecurityPolicy(securityPolicies); } private static SecurityPolicy allOfSecurityPolicy(SecurityPolicy... securityPolicies) { return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { for (SecurityPolicy policy : securityPolicies) { Status checkAuth = policy.checkAuthorization(uid); if (!checkAuth.isOk()) { return checkAuth; } } return Status.OK; } }; } /** * Creates a {@link SecurityPolicy} that allows access if *any* of the specified {@code * securityPolicies} allow access. * * <p>Policies will be checked in the order that they are passed. If a policy allows access, * subsequent policies will not be checked. * * <p>If all policies deny access, the {@link io.grpc.Status} returned by {@code * checkAuthorization} will included the concatenated descriptions of the failed policies and * attach any additional causes as suppressed throwables. The status code will be that of the * first failed policy. * * @param securityPolicies the security policies that will be checked. * @throws NullPointerException if any of the inputs are {@code null}. * @throws IllegalArgumentException if {@code securityPolicies} is empty. */ public static SecurityPolicy anyOf(SecurityPolicy... securityPolicies) { Preconditions.checkNotNull(securityPolicies, "securityPolicies"); Preconditions.checkArgument(securityPolicies.length > 0, "securityPolicies must not be empty"); return anyOfSecurityPolicy(securityPolicies); } private static SecurityPolicy anyOfSecurityPolicy(SecurityPolicy... securityPolicies) { return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { List<Status> failed = new ArrayList<>(); for (SecurityPolicy policy : securityPolicies) { Status checkAuth = policy.checkAuthorization(uid); if (checkAuth.isOk()) { return checkAuth; } failed.add(checkAuth); } Iterator<Status> iter = failed.iterator(); Status toReturn = iter.next(); while (iter.hasNext()) { Status append = iter.next(); toReturn = toReturn.augmentDescription(append.getDescription()); if (append.getCause() != null) { if (toReturn.getCause() != null) { toReturn.getCause().addSuppressed(append.getCause()); } else { toReturn = toReturn.withCause(append.getCause()); } } } return toReturn; } }; } /** * Creates a {@link SecurityPolicy} which checks if the caller has all of the given permissions * from {@code permissions}. * * <p>The gRPC framework assumes that a {@link SecurityPolicy}'s verdict for a given peer UID will * not change over the lifetime of any process with that UID. But Android runtime permissions can * be granted or revoked by the user at any time and so using the {@link #hasPermissions} {@link * SecurityPolicy} comes with certain special responsibilities. * * <p>In particular, callers must ensure that the *subjects* of the returned {@link * SecurityPolicy} hold all required {@code permissions} *before* making use of it. Android kills * an app's processes when it loses any permission but the same isn't true when a permission is * granted. And so without special care, a {@link #hasPermissions} denial could incorrectly * persist even if the subject is later granted all required {@code permissions}. * * <p>A server using {@link #hasPermissions} must, as part of its RPC API contract, require * clients to request and receive all {@code permissions} before making a call. This is in line * with official Android guidance to request and confirm receipt of runtime permissions before * using them. * * <p>A client, on the other hand, should only use {@link #hasPermissions} policies that require * install-time permissions which cannot change. * * @param permissions all permissions that the calling package needs to have * @throws NullPointerException if any of the inputs are {@code null} * @throws IllegalArgumentException if {@code permissions} is empty */ public static SecurityPolicy hasPermissions( PackageManager packageManager, ImmutableSet<String> permissions) { Preconditions.checkNotNull(packageManager, "packageManager"); Preconditions.checkNotNull(permissions, "permissions"); Preconditions.checkArgument(!permissions.isEmpty(), "permissions"); return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { return checkPermissions(uid, packageManager, permissions); } }; } private static Status checkPermissions( int uid, PackageManager packageManager, ImmutableSet<String> permissions) { String[] packages = packageManager.getPackagesForUid(uid); if (packages == null || packages.length == 0) { return Status.UNAUTHENTICATED.withDescription( "Rejected by permission check security policy. No packages found for uid"); } for (String pkg : packages) { for (String permission : permissions) { if (packageManager.checkPermission(permission, pkg) != PackageManager.PERMISSION_GRANTED) { return Status.PERMISSION_DENIED.withDescription( "Rejected by permission check security policy. " + pkg + " does not have permission " + permission); } } } return Status.OK; } private static SecurityPolicy anyPackageWithUidSatisfies( Context applicationContext, Predicate<String> condition, String errorMessageForNoPackages, String errorMessageForDenied) { return new SecurityPolicy() { @Override public Status checkAuthorization(int uid) { String[] packages = applicationContext.getPackageManager().getPackagesForUid(uid); if (packages == null || packages.length == 0) { return Status.UNAUTHENTICATED.withDescription(errorMessageForNoPackages); } for (String pkg : packages) { if (condition.apply(pkg)) { return Status.OK; } } return Status.PERMISSION_DENIED.withDescription(errorMessageForDenied); } }; } /** * Checks if the SHA-256 hash of the {@code signature} matches one of the {@code * expectedSignatureSha256Hashes}. */ private static boolean checkSignatureSha256HashesMatch( Signature signature, List<byte[]> expectedSignatureSha256Hashes) { byte[] signatureHash = getSha256Hash(signature); for (byte[] hash : expectedSignatureSha256Hashes) { if (Arrays.equals(hash, signatureHash)) { return true; } } return false; } /** Returns SHA-256 hash of the provided signature. */ private static byte[] getSha256Hash(Signature signature) { return Hashing.sha256().hashBytes(signature.toByteArray()).asBytes(); } }
SecurityPolicies
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/DefaultPollingEndpoint.java
{ "start": 957, "end": 1084 }
class ____ an endpoint which the default consumer mode is to use a {@link org.apache.camel.PollingConsumer} */ public abstract
for
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestProtosLegacy.java
{ "start": 142681, "end": 148662 }
class ____ extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_SlowPingRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_SlowPingRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto.class, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto.Builder.class); } // Construct using org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); shouldSlow_ = false; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_SlowPingRequestProto_descriptor; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto getDefaultInstanceForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto.getDefaultInstance(); } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto build() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto buildPartial() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto result = new org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.shouldSlow_ = shouldSlow_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto) { return mergeFrom((org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto other) { if (other == org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto.getDefaultInstance()) return this; if (other.hasShouldSlow()) { setShouldSlow(other.getShouldSlow()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasShouldSlow()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SlowPingRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required bool shouldSlow = 1; private boolean shouldSlow_ ; /** * <code>required bool shouldSlow = 1;</code> */ public boolean hasShouldSlow() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required bool shouldSlow = 1;</code> */ public boolean getShouldSlow() { return shouldSlow_; } /** * <code>required bool shouldSlow = 1;</code> */ public Builder setShouldSlow(boolean value) { bitField0_ |= 0x00000001; shouldSlow_ = value; onChanged(); return this; } /** * <code>required bool shouldSlow = 1;</code> */ public Builder clearShouldSlow() { bitField0_ = (bitField0_ & ~0x00000001); shouldSlow_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:hadoop.common.SlowPingRequestProto) } static { defaultInstance = new SlowPingRequestProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:hadoop.common.SlowPingRequestProto) } public
Builder
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/reflect/MethodDelegate.java
{ "start": 4793, "end": 5034 }
class ____ { private static final MethodDelegateKey KEY_FACTORY = (MethodDelegateKey)KeyFactory.create(MethodDelegateKey.class, KeyFactory.CLASS_BY_NAME); protected Object target; protected String eqMethod;
MethodDelegate
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java
{ "start": 1969, "end": 7074 }
class ____ { private final JmxOperationResponseMapper responseMapper = new TestJmxOperationResponseMapper(); private final List<ExposableJmxEndpoint> endpoints = new ArrayList<>(); @Mock @SuppressWarnings("NullAway.Init") private MBeanServer mBeanServer; @Spy @SuppressWarnings("NullAway.Init") private EndpointObjectNameFactory objectNameFactory = new TestEndpointObjectNameFactory(); private JmxEndpointExporter exporter; @BeforeEach void setup() { this.exporter = new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, this.endpoints); } @Test @SuppressWarnings("NullAway") // Test null check void createWhenMBeanServerIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, this.endpoints)) .withMessageContaining("'mBeanServer' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void createWhenObjectNameFactoryIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, this.endpoints)) .withMessageContaining("'objectNameFactory' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void createWhenResponseMapperIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, this.endpoints)) .withMessageContaining("'responseMapper' must not be null"); } @Test @SuppressWarnings("NullAway") // Test null check void createWhenEndpointsIsNullShouldThrowException() { assertThatIllegalArgumentException() .isThrownBy( () -> new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, this.responseMapper, null)) .withMessageContaining("'endpoints' must not be null"); } @Test void afterPropertiesSetShouldRegisterMBeans() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); then(this.mBeanServer).should() .registerMBean(assertArg((object) -> assertThat(object).isInstanceOf(EndpointMBean.class)), assertArg((objectName) -> assertThat(objectName.getKeyProperty("name")).isEqualTo("test"))); } @Test void registerShouldUseObjectNameFactory() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); then(this.objectNameFactory).should().getObjectName(any(ExposableJmxEndpoint.class)); } @Test void registerWhenObjectNameIsMalformedShouldThrowException() throws Exception { TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(new TestJmxOperation()); given(this.objectNameFactory.getObjectName(endpoint)).willThrow(MalformedObjectNameException.class); this.endpoints.add(endpoint); assertThatIllegalStateException().isThrownBy(this.exporter::afterPropertiesSet) .withMessageContaining("Invalid ObjectName for endpoint 'test'"); } @Test void registerWhenRegistrationFailsShouldThrowException() throws Exception { given(this.mBeanServer.registerMBean(any(), any(ObjectName.class))) .willThrow(new MBeanRegistrationException(new RuntimeException())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); assertThatExceptionOfType(MBeanExportException.class).isThrownBy(this.exporter::afterPropertiesSet) .withMessageContaining("Failed to register MBean for endpoint 'test"); } @Test void registerWhenEndpointHasNoOperationsShouldNotCreateMBean() { this.endpoints.add(new TestExposableJmxEndpoint()); this.exporter.afterPropertiesSet(); then(this.mBeanServer).shouldHaveNoInteractions(); } @Test void destroyShouldUnregisterMBeans() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); this.exporter.destroy(); then(this.mBeanServer).should() .unregisterMBean( assertArg((objectName) -> assertThat(objectName.getKeyProperty("name")).isEqualTo("test"))); } @Test void unregisterWhenInstanceNotFoundShouldContinue() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); willThrow(InstanceNotFoundException.class).given(this.mBeanServer).unregisterMBean(any(ObjectName.class)); this.exporter.destroy(); } @Test void unregisterWhenUnregisterThrowsExceptionShouldThrowException() throws Exception { this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); this.exporter.afterPropertiesSet(); willThrow(new MBeanRegistrationException(new RuntimeException())).given(this.mBeanServer) .unregisterMBean(any(ObjectName.class)); assertThatExceptionOfType(JmxException.class).isThrownBy(() -> this.exporter.destroy()) .withMessageContaining("Failed to unregister MBean with ObjectName 'boot"); } /** * Test {@link EndpointObjectNameFactory}. */ static
JmxEndpointExporterTests
java
google__error-prone
core/src/test/java/com/google/errorprone/SubContextTest.java
{ "start": 1118, "end": 1162 }
enum ____ { VALUE1, VALUE2; }
Enum1
java
elastic__elasticsearch
x-pack/plugin/inference/qa/test-service-plugin/src/main/java/org/elasticsearch/xpack/inference/mock/TestCompletionServiceExtension.java
{ "start": 6270, "end": 8990 }
class ____ { public static InferenceServiceConfiguration get() { return configuration.getOrCompute(); } private static final LazyInitializable<InferenceServiceConfiguration, RuntimeException> configuration = new LazyInitializable<>( () -> { var configurationMap = new HashMap<String, SettingsConfiguration>(); configurationMap.put( "model_id", new SettingsConfiguration.Builder(EnumSet.of(TaskType.COMPLETION)).setDescription("") .setLabel("Model ID") .setRequired(true) .setSensitive(true) .setType(SettingsConfigurationFieldType.STRING) .build() ); return new InferenceServiceConfiguration.Builder().setService(NAME) .setName(NAME) .setTaskTypes(SUPPORTED_TASK_TYPES) .setConfigurations(configurationMap) .build(); } ); } } public record TestServiceSettings(String modelId) implements ServiceSettings { public static final String NAME = "completion_test_service_settings"; public TestServiceSettings(StreamInput in) throws IOException { this(in.readString()); } public static TestServiceSettings fromMap(Map<String, Object> map) { var modelId = map.remove("model").toString(); if (modelId == null) { ValidationException validationException = new ValidationException(); validationException.addValidationError("missing model id"); throw validationException; } return new TestServiceSettings(modelId); } @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.current(); // fine for these tests but will not work for cluster upgrade tests } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(modelId()); } @Override public ToXContentObject getFilteredXContentObject() { return this; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject().field("model", modelId()).endObject(); } } }
Configuration
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/NoOpDeclareResourceRequirementServiceConnectionManager.java
{ "start": 1023, "end": 1478 }
enum ____ implements DeclareResourceRequirementServiceConnectionManager { INSTANCE; @Override public void connect(DeclareResourceRequirementsService declareResourceRequirementsService) {} @Override public void disconnect() {} @Override public void declareResourceRequirements(ResourceRequirements resourceRequirements) {} @Override public void close() {} }
NoOpDeclareResourceRequirementServiceConnectionManager
java
spring-projects__spring-boot
build-plugin/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunArguments.java
{ "start": 941, "end": 2008 }
class ____ { private static final String[] NO_ARGS = {}; private final Deque<String> args = new LinkedList<>(); RunArguments(@Nullable String arguments) { this(parseArgs(arguments)); } @SuppressWarnings("NullAway") // Maven can't handle nullable arrays RunArguments(@Nullable String[] args) { this((args != null) ? Arrays.asList(args) : null); } RunArguments(@Nullable Iterable<@Nullable String> args) { if (args != null) { for (String arg : args) { if (arg != null) { this.args.add(arg); } } } } Deque<String> getArgs() { return this.args; } String[] asArray() { return this.args.toArray(new String[0]); } static String[] parseArgs(@Nullable String arguments) { if (arguments == null || arguments.trim().isEmpty()) { return NO_ARGS; } try { arguments = arguments.replace('\n', ' ').replace('\t', ' '); return CommandLineUtils.translateCommandline(arguments); } catch (Exception ex) { throw new IllegalArgumentException("Failed to parse arguments [" + arguments + "]", ex); } } }
RunArguments
java
apache__flink
flink-core/src/main/java/org/apache/flink/configuration/EventOptions.java
{ "start": 4110, "end": 10754 }
class ____ use for the reporter named <name>."); @Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX) @Documentation.Section(value = Documentation.Sections.EVENT_REPORTERS, position = 5) public static final ConfigOption<String> REPORTER_CONFIG_PARAMETER = key("<parameter>") .stringType() .noDefaultValue() .withDescription( "Configures the parameter <parameter> for the reporter named <name>."); @Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX) @Documentation.Section(value = Documentation.Sections.EVENT_REPORTERS, position = 4) public static final ConfigOption<Map<String, String>> REPORTER_ADDITIONAL_VARIABLES = key("scope.variables.additional") .mapType() .defaultValue(Collections.emptyMap()) .withDescription( "The map of additional variables that should be included for the reporter named <name>."); @Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX) @Documentation.Section(value = Documentation.Sections.EVENT_REPORTERS, position = 2) public static final ConfigOption<String> REPORTER_SCOPE_DELIMITER = key("scope.delimiter") .stringType() .defaultValue(".") .withDescription( "The delimiter used to assemble the metric identifier for the reporter named <name>."); @Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX) @Documentation.Section(value = Documentation.Sections.EVENT_REPORTERS, position = 3) public static final ConfigOption<String> REPORTER_EXCLUDED_VARIABLES = key("scope.variables.excludes") .stringType() .defaultValue(".") .withDescription( "The set of variables that should be excluded for the reporter named <name>. Only applicable to tag-based reporters."); @Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX) @Documentation.Section(value = Documentation.Sections.EVENT_REPORTERS, position = 6) public static final ConfigOption<List<String>> REPORTER_INCLUDES = key("filter.includes") .stringType() .asList() .defaultValues("*:*:*") .withDescription( Description.builder() .text( "The events that should be included for the reporter named <name>." + " Filters are specified as a list, with each filter following this format:") .linebreak() .text("%s", code("<scope>[:<name>[,<name>]]")) .linebreak() .text( "An event matches a filter if the scope pattern and at least one of the name patterns match.") .linebreak() .list( text( "scope: Filters based on the logical scope.%s" + "Specified as a pattern where %s matches any sequence of characters and %s separates scope components.%s%s" + "For example:%s" + " \"%s\" matches any job-related events on the JobManager,%s" + " \"%s\" matches all job-related events and%s" + " \"%s\" matches all events below the job-level (i.e., task/operator events etc.).%s%s", linebreak(), code("*"), code("."), linebreak(), linebreak(), linebreak(), code("jobmanager.job"), linebreak(), code("*.job"), linebreak(), code("*.job.*"), linebreak(), linebreak()), text( "name: Filters based on the event name.%s" + "Specified as a comma-separated list of patterns where %s matches any sequence of characters.%s%s" + "For example, \"%s\" matches any event where the name contains %s.", linebreak(), code("*"), linebreak(), linebreak(), code("*Records*,*Bytes*"), code("\"Records\" or \"Bytes\""))) .build()); @Documentation.SuffixOption(NAMED_REPORTER_CONFIG_PREFIX) @Documentation.Section(value = Documentation.Sections.EVENT_REPORTERS, position = 7) public static final ConfigOption<List<String>> REPORTER_EXCLUDES = key("filter.excludes") .stringType() .asList() .defaultValues() .withDescription( Description.builder() .text( "The events that should be excluded for the reporter named <name>. The format is identical to %s", code(REPORTER_INCLUDES.key())) .linebreak() .build()); private EventOptions() {} }
to
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/messages/GenericMessageTester.java
{ "start": 7633, "end": 7846 }
class ____ implements Instantiator<Long> { @Override public Long instantiate(Random rnd) { return (long) rnd.nextInt(Integer.MAX_VALUE); } } public static
LongInstantiator
java
resilience4j__resilience4j
resilience4j-metrics/src/test/java/io/github/resilience4j/metrics/AbstractRetryMetricsTest.java
{ "start": 1221, "end": 5410 }
class ____ { private MetricRegistry metricRegistry; private HelloWorldService helloWorldService; @Before public void setUp() { metricRegistry = new MetricRegistry(); helloWorldService = mock(HelloWorldService.class); } protected abstract Retry givenMetricRegistry(String prefix, MetricRegistry metricRegistry); protected abstract Retry givenMetricRegistry(MetricRegistry metricRegistry); @Test public void shouldRegisterMetricsWithoutRetry() throws Throwable { Retry retry = givenMetricRegistry(metricRegistry); given(helloWorldService.returnHelloWorld()).willReturn("Hello world"); String value = retry.executeSupplier(helloWorldService::returnHelloWorld); assertThat(value).isEqualTo("Hello world"); then(helloWorldService).should(times(1)).returnHelloWorld(); assertThat(metricRegistry.getMetrics()).hasSize(4); assertThat(metricRegistry.getGauges() .get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITH_RETRY).getValue()) .isEqualTo(0L); assertThat(metricRegistry.getGauges() .get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY).getValue()) .isEqualTo(1L); assertThat( metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITH_RETRY) .getValue()).isEqualTo(0L); assertThat(metricRegistry.getGauges() .get("resilience4j.retry.testName." + FAILED_CALLS_WITHOUT_RETRY).getValue()) .isEqualTo(0L); } @Test public void shouldRegisterMetricsWithRetry() throws Throwable { Retry retry = givenMetricRegistry(metricRegistry); given(helloWorldService.returnHelloWorld()) .willThrow(new HelloWorldException()) .willReturn("Hello world") .willThrow(new HelloWorldException()) .willThrow(new HelloWorldException()) .willThrow(new HelloWorldException()); String value1 = retry.executeSupplier(helloWorldService::returnHelloWorld); Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld)); assertThat(value1).isEqualTo("Hello world"); then(helloWorldService).should(times(5)).returnHelloWorld(); assertThat(metricRegistry.getMetrics()).hasSize(4); assertThat(metricRegistry.getGauges() .get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITH_RETRY).getValue()) .isEqualTo(1L); assertThat(metricRegistry.getGauges() .get("resilience4j.retry.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY).getValue()) .isEqualTo(0L); assertThat( metricRegistry.getGauges().get("resilience4j.retry.testName." + FAILED_CALLS_WITH_RETRY) .getValue()).isEqualTo(1L); assertThat(metricRegistry.getGauges() .get("resilience4j.retry.testName." + FAILED_CALLS_WITHOUT_RETRY).getValue()) .isEqualTo(0L); } @Test public void shouldUseCustomPrefix() throws Throwable { Retry retry = givenMetricRegistry("testPrefix", metricRegistry); given(helloWorldService.returnHelloWorld()).willReturn("Hello world"); String value = retry.executeSupplier(helloWorldService::returnHelloWorld); assertThat(value).isEqualTo("Hello world"); then(helloWorldService).should(times(1)).returnHelloWorld(); assertThat(metricRegistry.getMetrics()).hasSize(4); assertThat( metricRegistry.getGauges().get("testPrefix.testName." + SUCCESSFUL_CALLS_WITH_RETRY) .getValue()).isEqualTo(0L); assertThat( metricRegistry.getGauges().get("testPrefix.testName." + SUCCESSFUL_CALLS_WITHOUT_RETRY) .getValue()).isEqualTo(1L); assertThat(metricRegistry.getGauges().get("testPrefix.testName." + FAILED_CALLS_WITH_RETRY) .getValue()).isEqualTo(0L); assertThat( metricRegistry.getGauges().get("testPrefix.testName." + FAILED_CALLS_WITHOUT_RETRY) .getValue()).isEqualTo(0L); } }
AbstractRetryMetricsTest
java
quarkusio__quarkus
integration-tests/grpc-mutual-auth/src/test/java/io/quarkus/grpc/examples/hello/HelloWorldMutualTlsServiceTestBase.java
{ "start": 311, "end": 1089 }
class ____ { Channel channel; @Test public void testHelloWorldServiceUsingBlockingStub() { GreeterGrpc.GreeterBlockingStub client = GreeterGrpc.newBlockingStub(channel); HelloReply reply = client .sayHello(HelloRequest.newBuilder().setName("neo-blocking").build()); assertThat(reply.getMessage()).isEqualTo("Hello neo-blocking"); } @Test public void testHelloWorldServiceUsingMutinyStub() { HelloReply reply = MutinyGreeterGrpc.newMutinyStub(channel) .sayHello(HelloRequest.newBuilder().setName("neo-blocking").build()) .await().atMost(Duration.ofSeconds(5)); assertThat(reply.getMessage()).isEqualTo("Hello neo-blocking"); } }
HelloWorldMutualTlsServiceTestBase
java
google__error-prone
core/src/test/java/com/google/errorprone/suppress/CustomSuppressionTest.java
{ "start": 1246, "end": 1358 }
class ____ { /** Custom suppression annotation for both checkers in this test. */ public @
CustomSuppressionTest
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Activemq6ComponentBuilderFactory.java
{ "start": 19458, "end": 20532 }
class ____ of the specified message listener. * Note: Only 1 concurrent consumer (which is the default of this * message listener container) is allowed for each subscription, except * for a shared subscription (which requires JMS 2.0). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param subscriptionName the value to set * @return the dsl builder */ default Activemq6ComponentBuilder subscriptionName(java.lang.String subscriptionName) { doSetProperty("subscriptionName", subscriptionName); return this; } /** * Set whether to make the subscription shared. The shared subscription * name to be used can be specified through the subscriptionName * property. Default is false. Set this to true to register a shared * subscription, typically in combination with a subscriptionName value * (unless your message listener
name
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Expressions.java
{ "start": 5015, "end": 5740 }
class ____ its value. * * <p>For example: * * <ul> * <li>{@code lit(12)} leads to {@code INT} * <li>{@code lit("abc")} leads to {@code CHAR(3)} * <li>{@code lit(new BigDecimal("123.45"))} leads to {@code DECIMAL(5, 2)} * </ul> * * <p>See {@link ValueDataTypeConverter} for a list of supported literal values. */ public static ApiExpression lit(Object v) { return new ApiExpression(valueLiteral(v)); } /** * Creates a literal (i.e. a constant value) of a given {@link DataType}. * * <p>The method {@link #lit(Object)} is preferred as it extracts the {@link DataType} * automatically. Use this method only when necessary. The
and
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/RangeHistogramAggregatorTests.java
{ "start": 1664, "end": 28987 }
class ____ extends AggregatorTestCase { public void testDoubles() throws Exception { RangeType rangeType = RangeType.DOUBLE; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1.0D, 5.0D, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3.1, 4.2, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4.2, 13.3, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 22.5, 29.3, true, true), // bucket 20, 25 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(7, histogram.getBuckets().size()); assertEquals(-5d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0d, histogram.getBuckets().get(1).getKey()); assertEquals(3, histogram.getBuckets().get(1).getDocCount()); assertEquals(5d, histogram.getBuckets().get(2).getKey()); assertEquals(2, histogram.getBuckets().get(2).getDocCount()); assertEquals(10d, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(15d, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(20d, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(25d, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); } } } public void testFloats() throws Exception { RangeType rangeType = RangeType.FLOAT; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1.0f, 5.0f, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3.1f, 4.2f, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4.2f, 13.3f, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 22.5f, 29.3f, true, true), // bucket 20, 25 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(7, histogram.getBuckets().size()); assertEquals(-5d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0d, histogram.getBuckets().get(1).getKey()); assertEquals(3, histogram.getBuckets().get(1).getDocCount()); assertEquals(5d, histogram.getBuckets().get(2).getKey()); assertEquals(2, histogram.getBuckets().get(2).getDocCount()); assertEquals(10d, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(15d, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(20d, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(25d, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); } } } public void testLongs() throws Exception { RangeType rangeType = RangeType.LONG; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1L, 5L, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3L, 4L, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4L, 13L, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 22L, 29L, true, true), // bucket 20, 25 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(7, histogram.getBuckets().size()); assertEquals(-5d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0d, histogram.getBuckets().get(1).getKey()); assertEquals(3, histogram.getBuckets().get(1).getDocCount()); assertEquals(5d, histogram.getBuckets().get(2).getKey()); assertEquals(2, histogram.getBuckets().get(2).getDocCount()); assertEquals(10d, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(15d, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(20d, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(25d, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); } } } public void testInts() throws Exception { RangeType rangeType = RangeType.INTEGER; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1, 5, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3, 4, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4, 13, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 22, 29, true, true), // bucket 20, 25 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(7, histogram.getBuckets().size()); assertEquals(-5d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0d, histogram.getBuckets().get(1).getKey()); assertEquals(3, histogram.getBuckets().get(1).getDocCount()); assertEquals(5d, histogram.getBuckets().get(2).getKey()); assertEquals(2, histogram.getBuckets().get(2).getDocCount()); assertEquals(10d, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(15d, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(20d, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(25d, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); } } } public void testMultipleRanges() throws Exception { RangeType rangeType = RangeType.LONG; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges( Set.of( new RangeFieldMapper.Range(rangeType, 1L, 5L, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3L, 4L, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4L, 13L, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 22L, 29L, true, true) // bucket 20, 25, 30 ) ); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(7, histogram.getBuckets().size()); assertEquals(-5d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0d, histogram.getBuckets().get(1).getKey()); assertEquals(1, histogram.getBuckets().get(1).getDocCount()); assertEquals(5d, histogram.getBuckets().get(2).getKey()); assertEquals(1, histogram.getBuckets().get(2).getDocCount()); assertEquals(10d, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(15d, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(20d, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(25d, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); } } } public void testMultipleRangesLotsOfOverlap() throws Exception { RangeType rangeType = RangeType.LONG; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges( Set.of( new RangeFieldMapper.Range(rangeType, 1L, 2L, true, true), // bucket 0 new RangeFieldMapper.Range(rangeType, 1L, 4L, true, true), // bucket 0 new RangeFieldMapper.Range(rangeType, 1L, 13L, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 1L, 5L, true, true) // bucket 0, 5 ) ); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(3, histogram.getBuckets().size()); assertEquals(0d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(5d, histogram.getBuckets().get(1).getKey()); assertEquals(1, histogram.getBuckets().get(1).getDocCount()); assertEquals(10d, histogram.getBuckets().get(2).getKey()); assertEquals(1, histogram.getBuckets().get(2).getDocCount()); } } } public void testLongsIrrationalInterval() throws Exception { RangeType rangeType = RangeType.LONG; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1L, 5L, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3L, 4L, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4L, 13L, true, true), // bucket 0, 5, 10 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(Math.PI); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(6, histogram.getBuckets().size()); assertEquals(-1 * Math.PI, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0 * Math.PI, histogram.getBuckets().get(1).getKey()); assertEquals(2, histogram.getBuckets().get(1).getDocCount()); assertEquals(1 * Math.PI, histogram.getBuckets().get(2).getKey()); assertEquals(3, histogram.getBuckets().get(2).getDocCount()); assertEquals(2 * Math.PI, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(3 * Math.PI, histogram.getBuckets().get(4).getKey()); assertEquals(1, histogram.getBuckets().get(4).getDocCount()); assertEquals(4 * Math.PI, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); } } } public void testMinDocCount() throws Exception { RangeType rangeType = RangeType.LONG; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, -14L, -11L, true, true), // bucket -15 new RangeFieldMapper.Range(rangeType, 0L, 9L, true, true), // bucket 0, 5 new RangeFieldMapper.Range(rangeType, 6L, 12L, true, true), // bucket 5, 10 new RangeFieldMapper.Range(rangeType, 13L, 14L, true, true), // bucket 10 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5).minDocCount(2); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(2, histogram.getBuckets().size()); assertEquals(5d, histogram.getBuckets().get(0).getKey()); assertEquals(2, histogram.getBuckets().get(0).getDocCount()); assertEquals(10d, histogram.getBuckets().get(1).getKey()); assertEquals(2, histogram.getBuckets().get(1).getDocCount()); } } } public void testOffset() throws Exception { RangeType rangeType = RangeType.DOUBLE; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1.0D, 5.0D, true, true), // bucket -1, 4 new RangeFieldMapper.Range(rangeType, -3.1, 4.2, true, true), // bucket -6 -1 4 new RangeFieldMapper.Range(rangeType, 4.2, 13.3, true, true), // bucket 4, 9 new RangeFieldMapper.Range(rangeType, 22.5, 29.3, true, true), // bucket 19, 24, 29 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5).offset(4); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(8, histogram.getBuckets().size()); assertEquals(-6d, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(-1d, histogram.getBuckets().get(1).getKey()); assertEquals(2, histogram.getBuckets().get(1).getDocCount()); assertEquals(4d, histogram.getBuckets().get(2).getKey()); assertEquals(3, histogram.getBuckets().get(2).getDocCount()); assertEquals(9d, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(14d, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(19d, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(24d, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); assertEquals(29d, histogram.getBuckets().get(7).getKey()); assertEquals(1, histogram.getBuckets().get(7).getDocCount()); } } } public void testOffsetGtInterval() throws Exception { RangeType rangeType = RangeType.DOUBLE; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { for (RangeFieldMapper.Range range : new RangeFieldMapper.Range[] { new RangeFieldMapper.Range(rangeType, 1.0D, 5.0D, true, true), // bucket 0 5 new RangeFieldMapper.Range(rangeType, -3.1, 4.2, true, true), // bucket -5, 0 new RangeFieldMapper.Range(rangeType, 4.2, 13.3, true, true), // bucket 0, 5, 10 new RangeFieldMapper.Range(rangeType, 22.5, 29.3, true, true), // bucket 20, 25 }) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges(Collections.singleton(range)); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); } // I'd like to randomize the offset here, like I did in the test for the numeric side, but there's no way I can think of to // construct the intervals such that they wouldn't "slosh" between buckets. final double offset = 20; final double interval = 5; final double expectedOffset = offset % interval; HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field") .interval(interval) .offset(offset); try (IndexReader reader = w.getReader()) { InternalHistogram histogram = searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); assertEquals(7, histogram.getBuckets().size()); assertEquals(-5d + expectedOffset, histogram.getBuckets().get(0).getKey()); assertEquals(1, histogram.getBuckets().get(0).getDocCount()); assertEquals(0d + expectedOffset, histogram.getBuckets().get(1).getKey()); assertEquals(3, histogram.getBuckets().get(1).getDocCount()); assertEquals(5d + expectedOffset, histogram.getBuckets().get(2).getKey()); assertEquals(2, histogram.getBuckets().get(2).getDocCount()); assertEquals(10d + expectedOffset, histogram.getBuckets().get(3).getKey()); assertEquals(1, histogram.getBuckets().get(3).getDocCount()); assertEquals(15d + expectedOffset, histogram.getBuckets().get(4).getKey()); assertEquals(0, histogram.getBuckets().get(4).getDocCount()); assertEquals(20d + expectedOffset, histogram.getBuckets().get(5).getKey()); assertEquals(1, histogram.getBuckets().get(5).getDocCount()); assertEquals(25d + expectedOffset, histogram.getBuckets().get(6).getKey()); assertEquals(1, histogram.getBuckets().get(6).getDocCount()); } } } public void testIpRangesUnsupported() throws Exception { RangeType rangeType = RangeType.IP; try (Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter(random(), dir)) { Document doc = new Document(); BytesRef encodedRange = rangeType.encodeRanges( Collections.singleton( new RangeFieldMapper.Range( rangeType, InetAddresses.forString("10.0.0.1"), InetAddresses.forString("10.0.0.10"), true, true ) ) ); doc.add(new BinaryDocValuesField("field", encodedRange)); w.addDocument(doc); HistogramAggregationBuilder aggBuilder = new HistogramAggregationBuilder("my_agg").field("field").interval(5); try (IndexReader reader = w.getReader()) { Exception e = expectThrows(IllegalArgumentException.class, () -> { searchAndReduce(reader, new AggTestConfig(aggBuilder, rangeField("field", rangeType))); }); assertThat(e.getMessage(), equalTo("Expected numeric range type but found non-numeric range [ip_range]")); } } } public void testAsSubAgg() throws IOException { AggregationBuilder request = new HistogramAggregationBuilder("outer").field("outer") .interval(5) .subAggregation( new HistogramAggregationBuilder("inner").field("inner") .interval(5) .subAggregation(new MinAggregationBuilder("min").field("n")) ); CheckedConsumer<RandomIndexWriter, IOException> buildIndex = iw -> { List<List<IndexableField>> docs = new ArrayList<>(); for (int n = 0; n < 10000; n++) { BytesRef outerRange = RangeType.LONG.encodeRanges( Set.of(new RangeFieldMapper.Range(RangeType.LONG, n % 100, n % 100 + 10, true, true)) ); BytesRef innerRange = RangeType.LONG.encodeRanges( Set.of(new RangeFieldMapper.Range(RangeType.LONG, n / 100, n / 100 + 10, true, true)) ); docs.add( List.of( new BinaryDocValuesField("outer", outerRange), new BinaryDocValuesField("inner", innerRange), new SortedNumericDocValuesField("n", n) ) ); } iw.addDocuments(docs); }; Consumer<InternalHistogram> verify = outer -> { assertThat(outer.getBuckets(), hasSize(22)); for (int outerIdx = 0; outerIdx < 22; outerIdx++) { InternalHistogram.Bucket outerBucket = outer.getBuckets().get(outerIdx); assertThat(outerBucket.getKey(), equalTo(5.0 * outerIdx)); InternalHistogram inner = outerBucket.getAggregations().get("inner"); assertThat(inner.getBuckets(), hasSize(22)); for (int innerIdx = 0; innerIdx < 22; innerIdx++) { InternalHistogram.Bucket innerBucket = inner.getBuckets().get(innerIdx); assertThat(innerBucket.getKey(), equalTo(5.0 * innerIdx)); Min min = innerBucket.getAggregations().get("min"); int minOuterIdxWithOverlappingRange = Math.max(0, outerIdx - 2); int minInnerIdxWithOverlappingRange = Math.max(0, innerIdx - 2); assertThat(min.value(), equalTo(minOuterIdxWithOverlappingRange * 5.0 + minInnerIdxWithOverlappingRange * 500.0)); } } }; testCase( buildIndex, verify, new AggTestConfig(request, rangeField("outer", RangeType.LONG), rangeField("inner", RangeType.LONG), longField("n")) ); } }
RangeHistogramAggregatorTests
java
quarkusio__quarkus
core/processor/src/main/java/io/quarkus/annotation/processor/documentation/config/model/ResolvedModel.java
{ "start": 843, "end": 1563 }
class ____ { /** * List of config roots: note that at this point they are not merged: you have one object per {@code @ConfigRoot} * annotation. */ private List<ConfigRoot> configRoots; @JsonCreator public ResolvedModel(List<ConfigRoot> configRoots) { this.configRoots = configRoots == null ? List.of() : Collections.unmodifiableList(configRoots); } public List<ConfigRoot> getConfigRoots() { return configRoots; } public void walk(ConfigItemVisitor visitor) { for (ConfigRoot configRoot : configRoots) { configRoot.walk(visitor); } } public boolean isEmpty() { return configRoots.isEmpty(); } }
ResolvedModel
java
elastic__elasticsearch
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java
{ "start": 6637, "end": 6958 }
class ____. Method argument types, method return types, and field types * must be specified with Painless type names (def, fully-qualified, or short) as described earlier. * * The following example is used to create a single whitelist text file: * * {@code * # primitive types * *
name
java
quarkusio__quarkus
integration-tests/oidc-client-reactive/src/main/java/io/quarkus/it/keycloak/FrontendResource.java
{ "start": 353, "end": 2234 }
class ____ { @Inject @RestClient ProtectedResourceServiceCustomFilter protectedResourceServiceCustomFilter; @Inject @RestClient ProtectedResourceServiceReactiveFilter protectedResourceServiceReactiveFilter; @Inject @RestClient ProtectedResourceServiceNamedFilter protectedResourceServiceNamedFilter; @Inject @RestClient ProtectedResourceServiceDisabledClient protectedResourceServiceDisabledClient; @Inject @RestClient MisconfiguredClientFilter misconfiguredClientFilter; @GET @Path("userNameCustomFilter") @Produces("text/plain") public Uni<String> userName() { return protectedResourceServiceCustomFilter.getUserName(); } @GET @Path("userNameReactive") @Produces("text/plain") public Uni<String> userNameReactive() { return protectedResourceServiceReactiveFilter.getUserName(); } @GET @Path("userNameNamedFilter") @Produces("text/plain") public Uni<String> userNameNamedFilter() { return protectedResourceServiceNamedFilter.getUserName(); } @GET @Path("userNameDisabledClient") @Produces("text/plain") public Uni<String> userNameDisabledClient() { return protectedResourceServiceDisabledClient.getUserName() .onFailure(WebApplicationException.class).recoverWithItem(t -> t.getMessage()); } @GET @Path("userNameMisconfiguredClientFilter") @Produces("text/plain") public Uni<String> userNameMisconfiguredClientFilter() { return misconfiguredClientFilter.getUserName().onFailure(Throwable.class) .recoverWithItem(new Function<Throwable, String>() { @Override public String apply(Throwable t) { return t.getMessage(); } }); } }
FrontendResource
java
spring-projects__spring-boot
module/spring-boot-zipkin/src/test/java/org/springframework/boot/zipkin/testcontainers/ZipkinContainerConnectionDetailsFactoryWithoutActuatorTests.java
{ "start": 1159, "end": 1415 }
class ____ { @Test void shouldRegisterHints() { RuntimeHints hints = ContainerConnectionDetailsFactoryHints.getRegisteredHints(getClass().getClassLoader()); assertThat(hints).isNotNull(); } }
ZipkinContainerConnectionDetailsFactoryWithoutActuatorTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/TaskExecutorFileMergingManager.java
{ "start": 2445, "end": 2549 }
class ____ * all {@link FileMergingSnapshotManager} objects for a task executor (manager). */ public
holds
java
apache__kafka
storage/src/main/java/org/apache/kafka/storage/internals/log/LogManager.java
{ "start": 1235, "end": 4194 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(LogManager.class); public static final String LOCK_FILE_NAME = ".lock"; public static final String RECOVERY_POINT_CHECKPOINT_FILE = "recovery-point-offset-checkpoint"; public static final String LOG_START_OFFSET_CHECKPOINT_FILE = "log-start-offset-checkpoint"; /** * Wait for all jobs to complete * @param jobs The jobs * @param callback This will be called to handle the exception caused by each Future#get * @return true if all pass. Otherwise, false */ public static boolean waitForAllToComplete(List<Future<?>> jobs, Consumer<Throwable> callback) { List<Future<?>> failed = new ArrayList<>(); for (Future<?> job : jobs) { try { job.get(); } catch (Exception e) { callback.accept(e); failed.add(job); } } return failed.isEmpty(); } /** * Returns true if the given log should not be on the current broker * according to the metadata image. * * @param brokerId The ID of the current broker. * @param newTopicsImage The new topics image after broker has been reloaded * @param log The log object to check * @return true if the log should not exist on the broker, false otherwise. */ public static boolean isStrayKraftReplica(int brokerId, TopicsImage newTopicsImage, UnifiedLog log) { if (log.topicId().isEmpty()) { // Missing topic ID could result from storage failure or unclean shutdown after topic creation but before flushing // data to the `partition.metadata` file. And before appending data to the log, the `partition.metadata` is always // flushed to disk. So if the topic ID is missing, it mostly means no data was appended, and we can treat this as // a stray log. LOG.info("The topicId does not exist in {}, treat it as a stray log.", log); return true; } Uuid topicId = log.topicId().get(); int partitionId = log.topicPartition().partition(); PartitionRegistration partition = newTopicsImage.getPartition(topicId, partitionId); if (partition == null) { LOG.info("Found stray log dir {}: the topicId {} does not exist in the metadata image.", log, topicId); return true; } else { List<Integer> replicas = Arrays.stream(partition.replicas).boxed().toList(); if (!replicas.contains(brokerId)) { LOG.info("Found stray log dir {}: the current replica assignment {} does not contain the local brokerId {}.", log, replicas.stream().map(String::valueOf).collect(Collectors.joining(", ", "[", "]")), brokerId); return true; } else { return false; } } } }
LogManager
java
apache__camel
components/camel-ai/camel-djl/src/main/java/org/apache/camel/component/djl/model/cv/ZooImageEnhancementPredictor.java
{ "start": 1212, "end": 1974 }
class ____ extends AbstractCvZooPredictor<Image> { public ZooImageEnhancementPredictor(DJLEndpoint endpoint) throws ModelNotFoundException, MalformedModelException, IOException { super(endpoint); Criteria.Builder<Image, Image> builder = Criteria.builder() .optApplication(Application.CV.IMAGE_ENHANCEMENT) .setTypes(Image.class, Image.class) .optArtifactId(endpoint.getArtifactId()); if (endpoint.isShowProgress()) { builder.optProgress(new ProgressBar()); } Criteria<Image, Image> criteria = builder.build(); this.model = ModelZoo.loadModel(criteria); } }
ZooImageEnhancementPredictor
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/array/BeanToArrayTest_long.java
{ "start": 233, "end": 2023 }
class ____ extends TestCase { public void test_long() throws Exception { Model model = JSON.parseObject("[-100,100]", Model.class, Feature.SupportArrayToBean); Assert.assertEquals(-100L, model.v1); Assert.assertEquals(100L, model.v2); } public void test_long_space() throws Exception { Model model = JSON.parseObject("[-100 ,100 ]", Model.class, Feature.SupportArrayToBean); Assert.assertEquals(-100L, model.v1); Assert.assertEquals(100L, model.v2); } public void test_long_error() throws Exception { Exception error = null; try { JSON.parseObject("[-", Model.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_long_error_2() throws Exception { Exception error = null; try { JSON.parseObject("[-1:", Model.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_long_error_max() throws Exception { Exception error = null; try { JSON.parseObject("[1,92233720368547758000}", Model.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public void test_long_error_min() throws Exception { Exception error = null; try { JSON.parseObject("[1,-92233720368547758000}", Model.class, Feature.SupportArrayToBean); } catch (JSONException ex) { error = ex; } Assert.assertNotNull(error); } public static
BeanToArrayTest_long
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlEventSchedule.java
{ "start": 858, "end": 2098 }
class ____ extends MySqlObjectImpl { private SQLExpr at; private SQLExpr every; private SQLExpr starts; private SQLExpr ends; @Override public void accept0(MySqlASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, at); acceptChild(visitor, every); acceptChild(visitor, starts); acceptChild(visitor, ends); } visitor.endVisit(this); } public SQLExpr getAt() { return at; } public void setAt(SQLExpr x) { if (x != null) { x.setParent(this); } this.at = x; } public SQLExpr getEvery() { return every; } public void setEvery(SQLExpr x) { if (x != null) { x.setParent(this); } this.every = x; } public SQLExpr getStarts() { return starts; } public void setStarts(SQLExpr x) { if (x != null) { x.setParent(this); } this.starts = x; } public SQLExpr getEnds() { return ends; } public void setEnds(SQLExpr x) { if (x != null) { x.setParent(this); } this.ends = x; } }
MySqlEventSchedule
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java
{ "start": 14555, "end": 14988 }
class ____ { public static void test() { Pattern pattern = Pattern.compile(".*"); } } """) .setArgs("-XepCompilingTestOnlyCode") .doTest(); } @Test public void withinList_noFinding() { compilationHelper .addSourceLines( "Test.java", """ import com.google.common.collect.ImmutableList; import java.util.regex.Pattern;
Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/src/test/java/org/apache/hadoop/yarn/server/timelineservice/storage/TestHBaseTimelineStorageDomain.java
{ "start": 2187, "end": 5495 }
class ____ { private static HBaseTestingUtility util; @BeforeAll public static void setupBeforeClass() throws Exception { util = new HBaseTestingUtility(); Configuration conf = util.getConfiguration(); conf.setInt("hfile.format.version", 3); try { util.startMiniCluster(); } catch (Exception e) { // TODO catch InaccessibleObjectException directly once Java 8 support is dropped if (e.getClass().getSimpleName().equals("InaccessibleObjectException")) { assumeTrue(false, "Could not start HBase because of HBASE-29234"); } else { throw e; } } DataGeneratorForTest.createSchema(util.getConfiguration()); } @Test public void testDomainIdTable() throws Exception { long l = System.currentTimeMillis(); HBaseTimelineWriterImpl hbi = null; Configuration c1 = util.getConfiguration(); String clusterId = "yarn-cluster"; TimelineCollectorContext context = new TimelineCollectorContext(clusterId, null, null, null, null, null); TimelineDomain domain2; try { hbi = new HBaseTimelineWriterImpl(); hbi.init(c1); // write empty domain domain2 = new TimelineDomain(); domain2.setCreatedTime(l); domain2.setDescription("domain-2"); domain2.setId("domain-2"); domain2.setModifiedTime(l); domain2.setOwner("owner1"); domain2.setReaders("user1,user2 group1,group2"); domain2.setWriters("writer1,writer2"); hbi.write(context, domain2); // flush everything to hbase hbi.flush(); } finally { if (hbi != null) { hbi.close(); } } Connection conn = ConnectionFactory.createConnection(c1); Table table1 = conn.getTable(BaseTableRW .getTableName(c1, DomainTableRW.TABLE_NAME_CONF_NAME, DomainTableRW.DEFAULT_TABLE_NAME)); byte[] startRow = new DomainRowKey(clusterId, domain2.getId()).getRowKey(); Get g = new Get(startRow); Result result = table1.get(g); assertNotNull(result); assertTrue(!result.isEmpty()); byte[] row = result.getRow(); DomainRowKey domainRowKey = DomainRowKey.parseRowKey(row); assertEquals(domain2.getId(), domainRowKey.getDomainId()); assertEquals(clusterId, domainRowKey.getClusterId()); Long cTime = (Long) ColumnRWHelper.readResult(result, DomainColumn.CREATED_TIME); String description = (String) ColumnRWHelper.readResult(result, DomainColumn.DESCRIPTION); Long mTime = (Long) ColumnRWHelper .readResult(result, DomainColumn.MODIFICATION_TIME); String owners = (String) ColumnRWHelper.readResult(result, DomainColumn.OWNER); String readers = (String) ColumnRWHelper.readResult(result, DomainColumn.READERS); String writers = (String) ColumnRWHelper.readResult(result, DomainColumn.WRITERS); assertEquals(l, cTime.longValue()); assertEquals(l, mTime.longValue()); assertEquals("domain-2", description); assertEquals("owner1", owners); assertEquals("user1,user2 group1,group2", readers); assertEquals("writer1,writer2", writers); } @AfterAll public static void tearDownAfterClass() throws Exception { if (util != null) { util.shutdownMiniCluster(); } } }
TestHBaseTimelineStorageDomain
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/locking/OptimisticLockingInstantTest.java
{ "start": 682, "end": 1342 }
class ____ { @AfterEach void tearDown(EntityManagerFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void test(EntityManagerFactoryScope factoryScope) { var _person = factoryScope.fromTransaction( entityManager -> { var person = new Person(); person.setName("John Doe"); entityManager.persist(person); return person; } ); factoryScope.inTransaction(entityManager -> { var person = entityManager.find(Person.class, _person.getId()); person.setName(person.getName().toUpperCase()); } ); } //tag::locking-optimistic-entity-mapping-example[] @Entity(name = "Person") public static
OptimisticLockingInstantTest
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/accesscontrol/wrapper/DlsFlsFeatureTrackingIndicesAccessControlWrapperTests.java
{ "start": 1465, "end": 4410 }
class ____ extends ESTestCase { public void testDlsFlsFeatureUsageTracking() { MockLicenseState licenseState = MockLicenseState.createMock(); Mockito.when(licenseState.isAllowed(DOCUMENT_LEVEL_SECURITY_FEATURE)).thenReturn(true); Mockito.when(licenseState.isAllowed(FIELD_LEVEL_SECURITY_FEATURE)).thenReturn(true); Settings settings = Settings.builder().put(XPackSettings.DLS_FLS_ENABLED.getKey(), true).build(); DlsFlsFeatureTrackingIndicesAccessControlWrapper wrapper = new DlsFlsFeatureTrackingIndicesAccessControlWrapper( settings, licenseState ); String flsIndexName = "fls-index"; String dlsIndexName = "dls-index"; String dlsFlsIndexName = "dls-fls-index"; String noDlsFlsIndexName = "no-dls-fls-restriction-index"; FieldPermissions fieldPermissions = new FieldPermissions( new FieldPermissionsDefinition(new String[] { "*" }, new String[] { "private" }) ); DocumentPermissions documentPermissions = DocumentPermissions.filteredBy(Set.of(new BytesArray(""" {"term":{"number":1}}"""))); IndicesAccessControl indicesAccessControl = wrapper.wrap( new IndicesAccessControl( true, Map.ofEntries( Map.entry(noDlsFlsIndexName, new IndexAccessControl(FieldPermissions.DEFAULT, DocumentPermissions.allowAll())), Map.entry(flsIndexName, new IndexAccessControl(fieldPermissions, DocumentPermissions.allowAll())), Map.entry(dlsIndexName, new IndexAccessControl(FieldPermissions.DEFAULT, documentPermissions)), Map.entry(dlsFlsIndexName, new IndexAccessControl(fieldPermissions, documentPermissions)) ) ) ); // Accessing index which does not have DLS nor FLS should not track usage indicesAccessControl.getIndexPermissions(randomFrom(noDlsFlsIndexName, randomAlphaOfLength(3))); verify(licenseState, never()).featureUsed(any()); // FLS should be tracked indicesAccessControl.getIndexPermissions(flsIndexName); verify(licenseState, times(1)).featureUsed(FIELD_LEVEL_SECURITY_FEATURE); verify(licenseState, times(0)).featureUsed(DOCUMENT_LEVEL_SECURITY_FEATURE); // DLS should be tracked indicesAccessControl.getIndexPermissions(dlsIndexName); verify(licenseState, times(1)).featureUsed(FIELD_LEVEL_SECURITY_FEATURE); verify(licenseState, times(1)).featureUsed(DOCUMENT_LEVEL_SECURITY_FEATURE); // Both DLS and FLS should be tracked indicesAccessControl.getIndexPermissions(dlsFlsIndexName); verify(licenseState, times(2)).featureUsed(FIELD_LEVEL_SECURITY_FEATURE); verify(licenseState, times(2)).featureUsed(DOCUMENT_LEVEL_SECURITY_FEATURE); } }
DlsFlsFeatureTrackingIndicesAccessControlWrapperTests
java
redisson__redisson
redisson/src/main/java/org/redisson/api/executor/TaskSuccessListener.java
{ "start": 764, "end": 1006 }
interface ____ extends TaskListener { /** * Invoked when task was succeeded * * @param taskId - id of task * @param result - result of task */ <T> void onSucceeded(String taskId, T result); }
TaskSuccessListener
java
spring-projects__spring-framework
spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/XhrTransportTests.java
{ "start": 1766, "end": 5060 }
class ____ { private final TestXhrTransport transport = new TestXhrTransport(); @Test void infoResponse() { transport.infoResponseToReturn = new ResponseEntity<>("body", HttpStatus.OK); assertThat(transport.executeInfoRequest(URI.create("https://example.com/info"), null)).isEqualTo("body"); } @Test // gh-35792 void infoResponseWithWebSocketHttpHeaders() { transport.infoResponseToReturn = new ResponseEntity<>("body", HttpStatus.OK); var headers = new WebSocketHttpHeaders(); headers.setSecWebSocketAccept("enigma"); headers.add("foo", "bar"); transport.executeInfoRequest(URI.create("https://example.com/info"), headers); assertThat(transport.actualInfoHeaders).isNotNull(); assertThat(transport.actualInfoHeaders.toSingleValueMap()).containsExactly( entry(WebSocketHttpHeaders.SEC_WEBSOCKET_ACCEPT, "enigma"), entry("foo", "bar") ); } @Test void infoResponseError() { transport.infoResponseToReturn = new ResponseEntity<>("body", HttpStatus.BAD_REQUEST); assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> transport.executeInfoRequest(URI.create("https://example.com/info"), null)); } @Test void sendMessage() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("foo", "bar"); requestHeaders.setContentType(MediaType.APPLICATION_JSON); transport.sendMessageResponseToReturn = new ResponseEntity<>(HttpStatus.NO_CONTENT); URI url = URI.create("https://example.com"); transport.executeSendRequest(url, requestHeaders, new TextMessage("payload")); assertThat(transport.actualSendRequestHeaders.size()).isEqualTo(2); assertThat(transport.actualSendRequestHeaders.getFirst("foo")).isEqualTo("bar"); assertThat(transport.actualSendRequestHeaders.getContentType()).isEqualTo(MediaType.APPLICATION_JSON); } @Test void sendMessageError() { transport.sendMessageResponseToReturn = new ResponseEntity<>(HttpStatus.BAD_REQUEST); URI url = URI.create("https://example.com"); assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> transport.executeSendRequest(url, new HttpHeaders(), new TextMessage("payload"))); } @Test void connect() { HttpHeaders handshakeHeaders = new HttpHeaders(); handshakeHeaders.setOrigin("foo"); TransportRequest request = mock(); given(request.getSockJsUrlInfo()).willReturn(new SockJsUrlInfo(URI.create("https://example.com"))); given(request.getHandshakeHeaders()).willReturn(handshakeHeaders); given(request.getHttpRequestHeaders()).willReturn(new HttpHeaders()); WebSocketHandler handler = mock(); transport.connectAsync(request, handler); ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); verify(request).getSockJsUrlInfo(); verify(request).addTimeoutTask(captor.capture()); verify(request).getTransportUrl(); verify(request).getHandshakeHeaders(); verify(request).getHttpRequestHeaders(); verifyNoMoreInteractions(request); assertThat(transport.actualHandshakeHeaders.size()).isOne(); assertThat(transport.actualHandshakeHeaders.getOrigin()).isEqualTo("foo"); assertThat(transport.actualSession.isDisconnected()).isFalse(); captor.getValue().run(); assertThat(transport.actualSession.isDisconnected()).isTrue(); } private static
XhrTransportTests