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__dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.java
{ "start": 1228, "end": 2265 }
class ____ implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { if (args.length != 1) { return "Unexpected argument length."; } Level level; switch (args[0]) { case "0": level = Level.ALL; break; case "1": level = Level.TRACE; break; case "2": level = Level.DEBUG; break; case "3": level = Level.INFO; break; case "4": level = Level.WARN; break; case "5": level = Level.ERROR; break; case "6": level = Level.OFF; break; default: level = Level.valueOf(args[0].toUpperCase(Locale.ROOT)); break; } LoggerFactory.setLevel(level); return "OK"; } }
SwitchLogLevel
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/retriever/RetrieverParser.java
{ "start": 761, "end": 1263 }
interface ____<RB extends RetrieverBuilder> { /** * Creates a new {@link RetrieverBuilder} from the retriever held by the * {@link XContentParser}. The state on the parser contained in this context * will be changed as a side effect of this method call. The * {@link RetrieverParserContext} tracks usage of retriever features and * queries when available. */ RB fromXContent(XContentParser parser, RetrieverParserContext context) throws IOException; }
RetrieverParser
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/exc/DefaultExceptionHandlerProvider.java
{ "start": 1830, "end": 3109 }
class ____<ReqT, RespT> extends ExceptionHandler<ReqT, RespT> { private final AuthExceptionHandlerProvider authExceptionHandlerProvider; public DefaultExceptionHandler(ServerCall.Listener<ReqT> listener, ServerCall<ReqT, RespT> call, Metadata metadata, AuthExceptionHandlerProvider authExceptionHandlerProvider) { super(listener, call, metadata); this.authExceptionHandlerProvider = authExceptionHandlerProvider; } @Override protected void handleException(Throwable exception, ServerCall<ReqT, RespT> call, Metadata metadata) { StatusException se = (StatusException) toStatusException(authExceptionHandlerProvider, exception); Metadata trailers = se.getTrailers() != null ? se.getTrailers() : metadata; try { call.close(se.getStatus(), trailers); } catch (IllegalStateException ise) { // Ignore the exception if the server is already closed // Since we don't have a specific exception type for this case, we need to check the message if (!"Already closed".equals(ise.getMessage())) { throw ise; } } } } }
DefaultExceptionHandler
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/fixed/ignoretrailing/BindySimpleIgnoreTrailingCharsTest.java
{ "start": 4523, "end": 8316 }
class ____ { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 3, length = 2) private String clientNr; // not annotated for this test private String firstName; @DataField(pos = 14, length = 5, align = "L") private String lastName; @DataField(pos = 19, length = 4) private String instrumentCode; @DataField(pos = 23, length = 10) private String instrumentNumber; @DataField(pos = 33, length = 3) private String orderType; @DataField(pos = 36, length = 5) private String instrumentType; @DataField(pos = 41, precision = 2, length = 12, paddingChar = '0') private BigDecimal amount; @DataField(pos = 53, length = 3) private String currency; @DataField(pos = 56, length = 10, pattern = "dd-MM-yyyy") private Date orderDate; @DataField(pos = 66, length = 10, align = "L", paddingChar = ' ') private String comment; public int getOrderNr() { return orderNr; } public void setOrderNr(int orderNr) { this.orderNr = orderNr; } public String getClientNr() { return clientNr; } public void setClientNr(String clientNr) { this.clientNr = clientNr; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getInstrumentCode() { return instrumentCode; } public void setInstrumentCode(String instrumentCode) { this.instrumentCode = instrumentCode; } public String getInstrumentNumber() { return instrumentNumber; } public void setInstrumentNumber(String instrumentNumber) { this.instrumentNumber = instrumentNumber; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getInstrumentType() { return instrumentType; } public void setInstrumentType(String instrumentType) { this.instrumentType = instrumentType; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @Override public String toString() { return "Model : " + Order.class.getName() + " : " + this.orderNr + ", " + this.orderType + ", " + String.valueOf(this.amount) + ", " + this.instrumentCode + ", " + this.instrumentNumber + ", " + this.instrumentType + ", " + this.currency + ", " + this.clientNr + ", " + this.firstName + ", " + this.lastName + ", " + String.valueOf(this.orderDate); } } }
Order
java
apache__camel
components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/processor/idempotent/MongoDbIdempotentRepository.java
{ "start": 1873, "end": 4843 }
class ____ extends ServiceSupport implements IdempotentRepository { @Metadata(description = "The MongoClient to use for connecting to the MongoDB server", required = true) private MongoClient mongoClient; @Metadata(description = "The Database name", required = true) private String dbName; @Metadata(description = "The collection name", required = true) private String collectionName; private MongoCollection<Document> collection; public MongoDbIdempotentRepository() { } public MongoDbIdempotentRepository(MongoClient mongoClient, String collectionName, String dbName) { this.mongoClient = mongoClient; this.collectionName = collectionName; this.dbName = dbName; } @ManagedOperation(description = "Adds the key to the store") @Override public boolean add(String key) { Document document = new Document(MONGO_ID, key); try { collection.insertOne(document); } catch (com.mongodb.MongoWriteException ex) { if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { return false; } throw ex; } return true; } @ManagedOperation(description = "Does the store contain the given key") @Override public boolean contains(String key) { Bson document = eq(MONGO_ID, key); long count = collection.countDocuments(document); return count > 0; } @ManagedOperation(description = "Remove the key from the store") @Override public boolean remove(String key) { Bson document = eq(MONGO_ID, key); DeleteResult res = collection.deleteOne(document); return res.getDeletedCount() > 0; } @Override public boolean confirm(String key) { return true; } @ManagedOperation(description = "Clear the store") @Override public void clear() { collection.deleteMany(new Document()); } @Override protected void doStart() throws Exception { ObjectHelper.notNull(mongoClient, "cli"); ObjectHelper.notNull(dbName, "dbName"); ObjectHelper.notNull(collectionName, "collectionName"); if (collection == null) { this.collection = mongoClient.getDatabase(dbName).getCollection(collectionName); } } @Override protected void doStop() throws Exception { // noop } public MongoClient getMongoClient() { return mongoClient; } public void setMongoClient(MongoClient mongoClient) { this.mongoClient = mongoClient; } public String getCollectionName() { return collectionName; } public void setCollectionName(String collectionName) { this.collectionName = collectionName; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } }
MongoDbIdempotentRepository
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/function/array/ArrayConcatTest.java
{ "start": 1576, "end": 8610 }
class ____ { @BeforeEach public void prepareData(SessionFactoryScope scope) { scope.inTransaction( em -> { em.persist( new EntityWithArrays( 1L, new String[]{} ) ); em.persist( new EntityWithArrays( 2L, new String[]{ "abc", null, "def" } ) ); em.persist( new EntityWithArrays( 3L, null ) ); } ); } @AfterEach public void cleanup(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testConcatAppend(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-concat-example[] List<Tuple> results = em.createQuery( "select e.id, array_concat(e.theArray, array('xyz')) from EntityWithArrays e order by e.id", Tuple.class ) .getResultList(); //end::hql-array-concat-example[] assertEquals( 3, results.size() ); assertEquals( 1L, results.get( 0 ).get( 0 ) ); assertArrayEquals( new String[]{ "xyz" }, results.get( 0 ).get( 1, String[].class ) ); assertEquals( 2L, results.get( 1 ).get( 0 ) ); assertArrayEquals( new String[]{ "abc", null, "def", "xyz" }, results.get( 1 ).get( 1, String[].class ) ); assertEquals( 3L, results.get( 2 ).get( 0 ) ); assertNull( results.get( 2 ).get( 1, String[].class ) ); } ); } @Test public void testConcatPrepend(SessionFactoryScope scope) { scope.inSession( em -> { List<Tuple> results = em.createQuery( "select e.id, array_concat(array('xyz'), e.theArray) from EntityWithArrays e order by e.id", Tuple.class ) .getResultList(); assertEquals( 3, results.size() ); assertEquals( 1L, results.get( 0 ).get( 0 ) ); assertArrayEquals( new String[]{ "xyz" }, results.get( 0 ).get( 1, String[].class ) ); assertEquals( 2L, results.get( 1 ).get( 0 ) ); assertArrayEquals( new String[]{ "xyz", "abc", null, "def" }, results.get( 1 ).get( 1, String[].class ) ); assertEquals( 3L, results.get( 2 ).get( 0 ) ); assertNull( results.get( 2 ).get( 1, String[].class ) ); } ); } @Test public void testConcatPipe(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-concat-pipe-example[] List<Tuple> results = em.createQuery( "select e.id, e.theArray || array('xyz') from EntityWithArrays e order by e.id", Tuple.class ) .getResultList(); //end::hql-array-concat-pipe-example[] assertEquals( 3, results.size() ); assertEquals( 1L, results.get( 0 ).get( 0 ) ); assertArrayEquals( new String[]{ "xyz" }, results.get( 0 ).get( 1, String[].class ) ); assertEquals( 2L, results.get( 1 ).get( 0 ) ); assertArrayEquals( new String[]{ "abc", null, "def", "xyz" }, results.get( 1 ).get( 1, String[].class ) ); assertEquals( 3L, results.get( 2 ).get( 0 ) ); assertNull( results.get( 2 ).get( 1, String[].class ) ); } ); } @Test public void testConcatPipeTwoArrayPaths(SessionFactoryScope scope) { scope.inSession( em -> { em.createQuery( "select e.id, e.theArray || e.theArray from EntityWithArrays e order by e.id" ).getResultList(); } ); } @Test public void testConcatPipeAppendLiteral(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-concat-pipe-element-example[] em.createQuery( "select e.id, e.theArray || 'last' from EntityWithArrays e order by e.id" ).getResultList(); //end::hql-array-concat-pipe-element-example[] } ); } @Test public void testConcatPipePrependLiteral(SessionFactoryScope scope) { scope.inSession( em -> { em.createQuery( "select e.id, 'first' || e.theArray from EntityWithArrays e order by e.id" ).getResultList(); } ); } @Test public void testConcatPipeAppendNull(SessionFactoryScope scope) { scope.inSession( em -> { em.createQuery( "select e.id, e.theArray || null from EntityWithArrays e order by e.id" ).getResultList(); } ); } @Test public void testConcatPipePrependNull(SessionFactoryScope scope) { scope.inSession( em -> { em.createQuery( "select e.id, null || e.theArray from EntityWithArrays e order by e.id" ).getResultList(); } ); } @Test public void testConcatPipeAppendParameter(SessionFactoryScope scope) { scope.inSession( em -> { em.createQuery( "select e.id, e.theArray || :p from EntityWithArrays e order by e.id" ) .setParameter( "p", null ) .getResultList(); em.createQuery( "select e.id, e.theArray || :p from EntityWithArrays e order by e.id" ) .setParameter( "p", "last" ) .getResultList(); em.createQuery( "select e.id, e.theArray || :p from EntityWithArrays e order by e.id" ) .setParameter( "p", new String[]{ "last" } ) .getResultList(); } ); } @Test public void testConcatPipePrependParameter(SessionFactoryScope scope) { scope.inSession( em -> { em.createQuery( "select e.id, :p || e.theArray from EntityWithArrays e order by e.id" ) .setParameter( "p", null ) .getResultList(); em.createQuery( "select e.id, :p || e.theArray from EntityWithArrays e order by e.id" ) .setParameter( "p", "first" ) .getResultList(); em.createQuery( "select e.id, :p || e.theArray from EntityWithArrays e order by e.id" ) .setParameter( "p", new String[]{ "first" } ) .getResultList(); } ); } @Test public void testNodeBuilderArray(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.arrayConcat( root.get( "theArray" ), cb.arrayLiteral( "xyz" ) ), cb.arrayConcat( root.get( "theArray" ), new String[]{ "xyz" } ), cb.arrayConcat( new String[]{ "xyz" }, root.get( "theArray" ) ) ); em.createQuery( cq ).getResultList(); // Should all fail to compile // cb.arrayConcat( root.<Integer[]>get( "theArray" ), cb.literal( new String[]{ "xyz" } ) ); // cb.arrayConcat( root.<Integer[]>get( "theArray" ), new String[]{ "xyz" } ); // cb.arrayConcat( new String[]{ "xyz" }, root.<Integer[]>get( "theArray" ) ); } ); } @Test public void testNodeBuilderCollection(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.collectionConcat( root.get( "theCollection" ), cb.collectionLiteral( "xyz" ) ), cb.collectionConcat( root.get( "theCollection" ), List.of( "xyz" ) ), cb.collectionConcat( List.of( "xyz" ), root.get( "theCollection" ) ) ); em.createQuery( cq ).getResultList(); // Should all fail to compile // cb.collectionConcat( root.<Collection<Integer>>get( "theCollection" ), cb.literal( List.of( "xyz" ) ) ); // cb.collectionConcat( root.<Collection<Integer>>get( "theCollection" ), List.of( "xyz" ) ); // cb.collectionConcat( List.of( "xyz" ), root.<Collection<Integer>>get( "theCollection" ) ); } ); } }
ArrayConcatTest
java
apache__camel
components/camel-vertx/camel-vertx-http/src/main/java/org/apache/camel/component/vertx/http/VertxHttpConstants.java
{ "start": 937, "end": 3307 }
class ____ { public static final String CONTENT_TYPE_JAVA_SERIALIZED_OBJECT = "application/x-java-serialized-object"; public static final String CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"; @Metadata(description = "The http method", javaType = "io.vertx.core.http.HttpMethod") public static final String HTTP_METHOD = Exchange.HTTP_METHOD; @Metadata(description = "The HTTP response code from the external server.", javaType = "Integer") public static final String HTTP_RESPONSE_CODE = Exchange.HTTP_RESPONSE_CODE; @Metadata(description = "The HTTP response text from the external server.", javaType = "String") public static final String HTTP_RESPONSE_TEXT = Exchange.HTTP_RESPONSE_TEXT; @Metadata(description = "The HTTP content type. Is set on both the IN and OUT message to provide\n" + "a content type, such as `text/html`.", javaType = "String") public static final String CONTENT_TYPE = Exchange.CONTENT_TYPE; @Metadata(description = "URI parameters. Will override existing URI parameters set directly on\n" + "the endpoint.", javaType = "String") public static final String HTTP_QUERY = Exchange.HTTP_QUERY; @Metadata(description = "URI to call. Will override the existing URI set directly on the endpoint.\n" + "This URI is the URI of the http server to call. Its not the same as the\n" + "Camel endpoint URI, where you can configure endpoint options such as\n" + "security etc. This header does not support that, its only the URI of the\n" + "http server.", javaType = "String") public static final String HTTP_URI = Exchange.HTTP_URI; @Metadata(description = "Request URI's path, the header will be used to build the request URI\n" + "with the HTTP_URI.", javaType = "String") public static final String HTTP_PATH = Exchange.HTTP_PATH; @Metadata(description = "The HTTP content encoding. Is set to provide a content encoding, such as `gzip`.", javaType = "String") public static final String CONTENT_ENCODING = Exchange.CONTENT_ENCODING; private VertxHttpConstants() { } }
VertxHttpConstants
java
quarkusio__quarkus
extensions/oidc-client-filter/deployment/src/test/java/io/quarkus/oidc/client/filter/OidcClientFilterRevokedAccessTokenDevModeTest.java
{ "start": 3371, "end": 3497 }
interface ____ extends MyClient { } @Priority(Priorities.AUTHENTICATION) public static
MyDefaultClientWithoutRefresh
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/inference/strategies/RowtimeTypeStrategyTest.java
{ "start": 1354, "end": 2693 }
class ____ extends TypeStrategiesTestBase { @Override protected Stream<TestSpec> testData() { return Stream.of( TestSpec.forStrategy("TIMESTAMP(3) *ROWTIME*", SpecificTypeStrategies.ROWTIME) .inputTypes(createRowtimeType(TimestampKind.ROWTIME, 3).notNull()) .expectDataType(createRowtimeType(TimestampKind.ROWTIME, 3).notNull()), TestSpec.forStrategy("TIMESTAMP_LTZ(3) *ROWTIME*", SpecificTypeStrategies.ROWTIME) .inputTypes(createRowtimeLtzType(TimestampKind.ROWTIME, 3).notNull()) .expectDataType(createRowtimeLtzType(TimestampKind.ROWTIME, 3).notNull()), TestSpec.forStrategy("BIGINT", SpecificTypeStrategies.ROWTIME) .inputTypes(DataTypes.BIGINT().notNull()) .expectDataType(DataTypes.TIMESTAMP(3).notNull())); } static DataType createRowtimeType(TimestampKind kind, int precision) { return TypeConversions.fromLogicalToDataType(new TimestampType(false, kind, precision)); } static DataType createRowtimeLtzType(TimestampKind kind, int precision) { return TypeConversions.fromLogicalToDataType( new LocalZonedTimestampType(false, kind, precision)); } }
RowtimeTypeStrategyTest
java
spring-projects__spring-boot
module/spring-boot-validation/src/test/java/org/springframework/boot/validation/autoconfigure/ValidationAutoConfigurationTests.java
{ "start": 17272, "end": 17713 }
class ____ implements BeanPostProcessor { private final Set<String> postProcessed = new HashSet<>(); @Override public Object postProcessAfterInitialization(Object bean, String name) { this.postProcessed.add(name); return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String name) { return bean; } } } @Configuration(proxyBeanMethods = false) static
TestBeanPostProcessor
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/impl/SpringSupervisingRouteControllerTest.java
{ "start": 1700, "end": 3472 }
class ____ extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/impl/SpringSupervisingRouteControllerTest.xml"); } @Test public void testSupervising() throws Exception { MockEndpoint mock = context.getEndpoint("mock:foo", MockEndpoint.class); mock.expectedMinimumMessageCount(3); MockEndpoint mock2 = context.getEndpoint("mock:cheese", MockEndpoint.class); mock2.expectedMessageCount(0); MockEndpoint mock3 = context.getEndpoint("mock:cake", MockEndpoint.class); mock3.expectedMessageCount(0); MockEndpoint mock4 = context.getEndpoint("mock:bar", MockEndpoint.class); mock4.expectedMessageCount(0); MockEndpoint.assertIsSatisfied(5, TimeUnit.SECONDS, mock, mock2, mock3, mock4); assertEquals("Started", context.getRouteController().getRouteStatus("foo").toString()); // cheese was not able to start assertEquals("Stopped", context.getRouteController().getRouteStatus("cheese").toString()); // cake was not able to start assertEquals("Stopped", context.getRouteController().getRouteStatus("cake").toString()); SupervisingRouteController src = context.getRouteController().adapt(SupervisingRouteController.class); Throwable e = src.getRestartException("cake"); assertNotNull(e); assertEquals("Cannot start", e.getMessage()); assertTrue(e instanceof IllegalArgumentException); // bar is no auto startup assertEquals("Stopped", context.getRouteController().getRouteStatus("bar").toString()); } public static
SpringSupervisingRouteControllerTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/analysis/PreBuiltTokenizers.java
{ "start": 802, "end": 1428 }
enum ____ { STANDARD(CachingStrategy.ONE) { @Override protected Tokenizer create(Version version) { return new StandardTokenizer(); } } ; protected abstract Tokenizer create(Version version); protected static TokenFilterFactory getMultiTermComponent(Version version) { return null; } private final CachingStrategy cachingStrategy; PreBuiltTokenizers(CachingStrategy cachingStrategy) { this.cachingStrategy = cachingStrategy; } public CachingStrategy getCachingStrategy() { return cachingStrategy; } }
PreBuiltTokenizers
java
apache__camel
components/camel-debezium/camel-debezium-common/camel-debezium-maven-plugin/src/main/java/org/apache/camel/maven/config/ConnectorConfigField.java
{ "start": 1047, "end": 6174 }
class ____ { private final ConfigDef.ConfigKey fieldDef; private final boolean isDeprecated; private final boolean isRequired; private final Object overrideDefaultValue; public ConnectorConfigField(final ConfigDef.ConfigKey configKey, final boolean isDeprecated, final boolean isRequired, final Object overrideDefaultValue) { ObjectHelper.notNull(configKey, "configKey"); ObjectHelper.notNull(isDeprecated, "isDeprecated"); ObjectHelper.notNull(isRequired, "isRequired"); this.fieldDef = configKey; this.isDeprecated = isDeprecated; this.isRequired = isRequired; this.overrideDefaultValue = overrideDefaultValue; } public String getRawName() { return fieldDef.name; } public String getFieldName() { return getCamelCase(fieldDef.name); } public String getFieldSetterMethodName() { return getSetterMethodName(fieldDef.name); } public String getFieldGetterMethodName() { return getGetterMethodName(fieldDef.name, fieldDef.type); } public Class<?> getRawType() { return getType(fieldDef.type); } public Object getDefaultValue() { if (overrideDefaultValue != null) { return overrideDefaultValue; } return fieldDef.defaultValue; } /** * @return the default value as a {@code String} between 2 double quotes. */ public String getDefaultValueAsStringLiteral() { Object defaultValue = getDefaultValue(); if (defaultValue == null) { return null; } if (fieldDef.type() == ConfigDef.Type.LIST || fieldDef.type() == ConfigDef.Type.CLASS && defaultValue instanceof Class) { defaultValue = ConfigDef.convertToString(defaultValue, fieldDef.type()); } return String.format("\"%s\"", defaultValue); } public String getDefaultValueAsString() { return getDefaultValueWrappedInString(fieldDef); } public boolean isInternal() { return fieldDef.name.startsWith(Field.INTERNAL_PREFIX); } public boolean isDeprecated() { return isDeprecated; } public boolean isRequired() { return isRequired; } public String getDescription() { if (fieldDef.documentation != null) { return removeNonAsciiChars(fieldDef.documentation); } return ""; } public boolean isTimeField() { // since we don't really have an info if the field is a time or not, we use a hack that if the field name ends with `ms` and of type // int or long. Not pretty but is the only feasible workaround here. return isMillSecondsInTheFieldName(fieldDef.name) && (fieldDef.type == ConfigDef.Type.INT || fieldDef.type == ConfigDef.Type.LONG); } private boolean isMillSecondsInTheFieldName(final String name) { final String[] parts = name.split("\\."); return parts.length > 0 && parts[parts.length - 1].equalsIgnoreCase("ms"); } private String getSetterMethodName(final String name) { return getCamelCase("set." + name); } private String getGetterMethodName(final String name, ConfigDef.Type type) { if (type == ConfigDef.Type.BOOLEAN) { return getCamelCase("is." + name); } else { return getCamelCase("get." + name); } } private String getCamelCase(final String name) { return CaseUtils.toCamelCase(name, false, '.', '_'); } private Class<?> getType(final ConfigDef.Type type) { switch (type) { case INT: return Integer.TYPE; case SHORT: return Short.TYPE; case DOUBLE: return Double.TYPE; case STRING: case PASSWORD: case CLASS: case LIST: return String.class; case BOOLEAN: return Boolean.TYPE; case LONG: return Long.TYPE; default: throw new IllegalArgumentException(String.format("Type '%s' is not supported", type.name())); } } private String getDefaultValueWrappedInString(final ConfigDef.ConfigKey field) { final Object defaultValue = getDefaultValue(); if (defaultValue == null) { return null; } if (fieldDef.type() == ConfigDef.Type.LIST || fieldDef.type() == ConfigDef.Type.CLASS && defaultValue instanceof Class) { return String.format("\"%s\"", ConfigDef.convertToString(defaultValue, fieldDef.type())); } else if (field.type() == ConfigDef.Type.STRING || field.type() == ConfigDef.Type.PASSWORD || field.type() == ConfigDef.Type.CLASS) { return String.format("\"%s\"", defaultValue); } return defaultValue.toString(); } private String removeNonAsciiChars(final String text) { return text.replaceAll("[^\\x00-\\x7F]", ""); } }
ConnectorConfigField
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java
{ "start": 488, "end": 1921 }
class ____ { @Id @GeneratedValue private Integer id; @Embedded @Audited private NotAuditedManyToOneComponent comp1; public NotAuditedManyToOneComponentTestEntity() { } public NotAuditedManyToOneComponentTestEntity(Integer id, NotAuditedManyToOneComponent comp1) { this.id = id; this.comp1 = comp1; } public NotAuditedManyToOneComponentTestEntity(NotAuditedManyToOneComponent comp1) { this.comp1 = comp1; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public NotAuditedManyToOneComponent getComp1() { return comp1; } public void setComp1(NotAuditedManyToOneComponent comp1) { this.comp1 = comp1; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } NotAuditedManyToOneComponentTestEntity that = (NotAuditedManyToOneComponentTestEntity) o; if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { return false; } if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (comp1 != null ? comp1.hashCode() : 0); return result; } public String toString() { return "NAMTOCTE(id = " + id + ", comp1 = " + comp1 + ")"; } }
NotAuditedManyToOneComponentTestEntity
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidInlineTagTest.java
{ "start": 5090, "end": 5411 }
interface ____ { /** Frobnicates a {@code foo}. */ void frobnicate(String foo); } """) .doTest(TestMode.TEXT_MATCH); } @Test public void parensRatherThanCurlies() { helper .addSourceLines( "Test.java", """
Test
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/delegation/FullCredentialsTokenBinding.java
{ "start": 1675, "end": 1840 }
class ____ to (a) support deployments * where there is not STS service and (b) validate the design of * S3A DT support to support different managers. */ public
exists
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/NestedTargetPropertyMappingHolder.java
{ "start": 38862, "end": 40066 }
class ____ { private final Map<PropertyEntry, Set<MappingReference>> groupedBySourceReferences; private final Set<MappingReference> nonNested; private final Set<MappingReference> notProcessedAppliesToAll; private final Set<MappingReference> sourceParameterMappings; private GroupedSourceReferences(Map<PropertyEntry, Set<MappingReference>> groupedBySourceReferences, Set<MappingReference> nonNested, Set<MappingReference> notProcessedAppliesToAll, Set<MappingReference> sourceParameterMappings) { this.groupedBySourceReferences = groupedBySourceReferences; this.nonNested = nonNested; this.notProcessedAppliesToAll = notProcessedAppliesToAll; this.sourceParameterMappings = sourceParameterMappings; } @Override public String toString() { return "GroupedSourceReferences{" + "groupedBySourceReferences=" + groupedBySourceReferences + ", nonNested=" + nonNested + ", notProcessedAppliesToAll=" + notProcessedAppliesToAll + ", sourceParameterMappings=" + sourceParameterMappings + '}'; } } }
GroupedSourceReferences
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/SqlServerDialectConfig.java
{ "start": 387, "end": 797 }
interface ____ { /** * The {@code compatibility_level} as defined in {@code sys.databases}. * * @see org.hibernate.cfg.DialectSpecificSettings#SQL_SERVER_COMPATIBILITY_LEVEL */ @WithConverter(TrimmedStringConverter.class) Optional<String> compatibilityLevel(); default boolean isAnyPropertySet() { return compatibilityLevel().isPresent(); } }
SqlServerDialectConfig
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTest.java
{ "start": 101681, "end": 102065 }
class ____ implements SourceFunction<Long> { private static final long serialVersionUID = 1L; @Override public void run(SourceContext<Long> ctx) {} @Override public void cancel() {} } /** * Mocked state backend factory which returns mocks for the operator and keyed state backends. */ public static final
MockSourceFunction
java
apache__camel
components/camel-aws/camel-aws2-ses/src/main/java/org/apache/camel/component/aws2/ses/client/Ses2ClientFactory.java
{ "start": 1263, "end": 1332 }
class ____ return the correct type of AWS SES client. */ public final
to
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
{ "start": 69339, "end": 71331 }
class ____ extends BaseFinalTransition { public AMContainerCrashedBeforeRunningTransition() { super(RMAppAttemptState.FAILED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { RMAppAttemptContainerFinishedEvent finishEvent = ((RMAppAttemptContainerFinishedEvent)event); // UnRegister from AMLivelinessMonitor appAttempt.rmContext.getAMLivelinessMonitor().unregister( appAttempt.getAppAttemptId()); // Setup diagnostic message and exit status appAttempt.setAMContainerCrashedDiagnosticsAndExitStatus(finishEvent); // Tell the app, scheduler super.transition(appAttempt, finishEvent); } } private void setAMContainerCrashedDiagnosticsAndExitStatus( RMAppAttemptContainerFinishedEvent finishEvent) { ContainerStatus status = finishEvent.getContainerStatus(); this.diagnostics.append(getAMContainerCrashedDiagnostics(finishEvent)); this.amContainerExitStatus = status.getExitStatus(); } private String getAMContainerCrashedDiagnostics( RMAppAttemptContainerFinishedEvent finishEvent) { ContainerStatus status = finishEvent.getContainerStatus(); StringBuilder diagnosticsBuilder = new StringBuilder(); diagnosticsBuilder.append("AM Container for ").append( finishEvent.getApplicationAttemptId()).append( " exited with ").append(" exitCode: ").append(status.getExitStatus()). append("\n"); diagnosticsBuilder.append("Failing this attempt.").append("Diagnostics: ") .append(status.getDiagnostics()); if (this.getTrackingUrl() != null) { diagnosticsBuilder.append("For more detailed output,").append( " check the application tracking page: ").append( this.getTrackingUrl()).append( " Then click on links to logs of each attempt.\n"); } return diagnosticsBuilder.toString(); } private static
AMContainerCrashedBeforeRunningTransition
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/DataSourceDisableExceptionTest.java
{ "start": 142, "end": 769 }
class ____ extends PoolTestCase { public void test_0() throws Exception { DataSourceDisableException ex = new DataSourceDisableException(); assertEquals(null, ex.getMessage()); } public void test_1() throws Exception { DataSourceDisableException ex = new DataSourceDisableException("XXX"); assertEquals("XXX", ex.getMessage()); } public void test_2() throws Exception { DataSourceDisableException ex = new DataSourceDisableException(new IllegalStateException()); assertTrue(ex.getCause() instanceof IllegalStateException); } }
DataSourceDisableExceptionTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertEqualByComparison_Test.java
{ "start": 1591, "end": 3792 }
class ____ extends BigDecimalsBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbers.assertEqualByComparison(someInfo(), null, ONE)) .withMessage(actualIsNull()); } @Test void should_pass_if_big_decimals_are_equal_by_comparison() { numbers.assertEqualByComparison(someInfo(), new BigDecimal("5.0"), new BigDecimal("5.00")); } @Test void should_fail_if_big_decimals_are_not_equal_by_comparison() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbers.assertEqualByComparison(info, TEN, ONE)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeEqual(TEN, ONE, info.representation())); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> numbersWithAbsValueComparisonStrategy.assertEqualByComparison(someInfo(), null, ONE)) .withMessage(actualIsNull()); } @Test void should_pass_if_big_decimals_are_equal_by_comparison_whatever_custom_comparison_strategy_is() { numbersWithAbsValueComparisonStrategy.assertEqualByComparison(someInfo(), new BigDecimal("5.0"), new BigDecimal("5")); } @Test void should_fail_if_big_decimals_are_not_equal_by_comparison_whatever_custom_comparison_strategy_is() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> numbersWithAbsValueComparisonStrategy.assertEqualByComparison(info, TEN, ONE)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeEqual(TEN, ONE, absValueComparisonStrategy, new StandardRepresentation())); } }
BigDecimals_assertEqualByComparison_Test
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/method/configuration/PrePostMethodSecurityConfigurationTests.java
{ "start": 71525, "end": 72406 }
class ____ { @RequireRole(role = "#role") boolean hasRole(String role) { return true; } @RequireRole(role = "'USER'") boolean hasUserRole() { return true; } @PreAuthorize("hasRole({role})") void placeholdersOnlyResolvedByMetaAnnotations() { } @HasClaim(claim = "message:read", roles = { "'ADMIN'" }) String readMessage() { return "message"; } @ResultStartsWith("dave") String startsWithDave(String value) { return value; } @ParameterContains("dave") List<String> parametersContainDave(List<String> list) { return list; } @ResultContains("dave") List<String> resultsContainDave(List<String> list) { return list; } @RestrictedAccess(entityClass = EntityClass.class) String getIdPath(String id) { return id; } } @Retention(RetentionPolicy.RUNTIME) @PreAuthorize("hasRole({idPath})") @
MetaAnnotationService
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/WindowPropertiesRules.java
{ "start": 3887, "end": 5400 }
interface ____ extends RelRule.Config { WindowPropertiesRuleConfig DEFAULT = ImmutableWindowPropertiesRuleConfig.builder() .build() .withOperandSupplier( b0 -> b0.operand(LogicalProject.class) .oneInput( b1 -> b1.operand(LogicalProject.class) .oneInput( b2 -> b2.operand( LogicalWindowAggregate .class) .noInputs()))) .withDescription("WindowPropertiesRule"); @Override default WindowPropertiesRule toRule() { return new WindowPropertiesRule(this); } } } public static
WindowPropertiesRuleConfig
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/collection/StringMap.java
{ "start": 836, "end": 4243 }
class ____ { private Integer sme1_id; private Integer sme2_id; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { StringMapEntity sme1 = new StringMapEntity(); StringMapEntity sme2 = new StringMapEntity(); // Revision 1 (sme1: initialy empty, sme2: initialy 1 mapping) scope.inTransaction( em -> { sme2.getStrings().put( "1", "a" ); em.persist( sme1 ); em.persist( sme2 ); } ); // Revision 2 (sme1: adding 2 mappings, sme2: no changes) scope.inTransaction( em -> { StringMapEntity sme1Ref = em.find( StringMapEntity.class, sme1.getId() ); sme1Ref.getStrings().put( "1", "a" ); sme1Ref.getStrings().put( "2", "b" ); } ); // Revision 3 (sme1: removing an existing mapping, sme2: replacing a value) scope.inTransaction( em -> { StringMapEntity sme1Ref = em.find( StringMapEntity.class, sme1.getId() ); StringMapEntity sme2Ref = em.find( StringMapEntity.class, sme2.getId() ); sme1Ref.getStrings().remove( "1" ); sme2Ref.getStrings().put( "1", "b" ); } ); // No revision (sme1: removing a non-existing mapping, sme2: replacing with the same value) scope.inTransaction( em -> { StringMapEntity sme1Ref = em.find( StringMapEntity.class, sme1.getId() ); StringMapEntity sme2Ref = em.find( StringMapEntity.class, sme2.getId() ); sme1Ref.getStrings().remove( "3" ); sme2Ref.getStrings().put( "1", "b" ); } ); sme1_id = sme1.getId(); sme2_id = sme2.getId(); } @Test public void testRevisionsCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( Arrays.asList( 1, 2, 3 ), auditReader.getRevisions( StringMapEntity.class, sme1_id ) ); assertEquals( Arrays.asList( 1, 3 ), auditReader.getRevisions( StringMapEntity.class, sme2_id ) ); } ); } @Test public void testHistoryOfSse1(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); StringMapEntity rev1 = auditReader.find( StringMapEntity.class, sme1_id, 1 ); StringMapEntity rev2 = auditReader.find( StringMapEntity.class, sme1_id, 2 ); StringMapEntity rev3 = auditReader.find( StringMapEntity.class, sme1_id, 3 ); StringMapEntity rev4 = auditReader.find( StringMapEntity.class, sme1_id, 4 ); assertEquals( Collections.EMPTY_MAP, rev1.getStrings() ); assertEquals( TestTools.makeMap( "1", "a", "2", "b" ), rev2.getStrings() ); assertEquals( TestTools.makeMap( "2", "b" ), rev3.getStrings() ); assertEquals( TestTools.makeMap( "2", "b" ), rev4.getStrings() ); } ); } @Test public void testHistoryOfSse2(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); StringMapEntity rev1 = auditReader.find( StringMapEntity.class, sme2_id, 1 ); StringMapEntity rev2 = auditReader.find( StringMapEntity.class, sme2_id, 2 ); StringMapEntity rev3 = auditReader.find( StringMapEntity.class, sme2_id, 3 ); StringMapEntity rev4 = auditReader.find( StringMapEntity.class, sme2_id, 4 ); assertEquals( TestTools.makeMap( "1", "a" ), rev1.getStrings() ); assertEquals( TestTools.makeMap( "1", "a" ), rev2.getStrings() ); assertEquals( TestTools.makeMap( "1", "b" ), rev3.getStrings() ); assertEquals( TestTools.makeMap( "1", "b" ), rev4.getStrings() ); } ); } }
StringMap
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/deser/asm/TestASM_Long_0.java
{ "start": 431, "end": 614 }
class ____ { private Long i = 12L; public Long getI() { return i; } public void setI(Long i) { this.i = i; } } }
V0
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_25.java
{ "start": 583, "end": 2333 }
class ____ extends TestCase { public void test_for_parameterize() throws Exception { final DbType dbType = JdbcConstants.MYSQL; String sql = "SELECT `xxx_reverse_order`.`id` from xxx_reverse_order_0446 XXX_REVERSE_ORDER limit 1;"; String psql = ParameterizedOutputVisitorUtils.parameterize(sql, dbType); assertEquals("SELECT `xxx_reverse_order`.`id`\n" + "FROM xxx_reverse_order XXX_REVERSE_ORDER\n" + "LIMIT ?;", psql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(psql, dbType); List<SQLStatement> stmtList = parser.parseStatementList(); StringBuilder out = new StringBuilder(); SQLASTOutputVisitor visitor = SQLUtils.createOutputVisitor(out, JdbcConstants.MYSQL); List<Object> parameters = new ArrayList<Object>(); visitor.setParameterized(true); visitor.setParameterizedMergeInList(true); visitor.setParameters(parameters); visitor.setExportTables(true); /*visitor.setPrettyFormat(false);*/ SQLStatement stmt = stmtList.get(0); stmt.accept(visitor); // System.out.println(parameters); assertEquals(0, parameters.size()); StringBuilder buf = new StringBuilder(); SQLASTOutputVisitor visitor1 = SQLUtils.createOutputVisitor(buf, dbType); visitor1.addTableMapping("xxx_reverse_order", "xxx_reverse_order_0446"); visitor1.setParameters(visitor.getParameters()); stmt.accept(visitor1); assertEquals("SELECT `xxx_reverse_order`.`id`\n" + "FROM xxx_reverse_order_0446 XXX_REVERSE_ORDER\n" + "LIMIT ?;", buf.toString()); } }
MySqlParameterizedOutputVisitorTest_25
java
google__guice
extensions/dagger-adapter/src/com/google/inject/daggeradapter/DaggerAdapter.java
{ "start": 12047, "end": 12537 }
class ____ are singletons deduplicatedModules.add(getFirst(instances, duplicates.iterator().next())); }); return deduplicatedModules.build(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("modules", declaredModules).toString(); } } private static Class<?> moduleClass(Object module) { return module instanceof Class ? (Class<?>) module : module.getClass(); } private static
instances
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java
{ "start": 2353, "end": 8998 }
class ____ { private static volatile @Nullable ReactiveAdapterRegistry sharedInstance; private static final boolean REACTIVE_STREAMS_PRESENT; private static final boolean REACTOR_PRESENT; private static final boolean RXJAVA_3_PRESENT; private static final boolean COROUTINES_REACTOR_PRESENT; private static final boolean MUTINY_PRESENT; static { ClassLoader classLoader = ReactiveAdapterRegistry.class.getClassLoader(); REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent("org.reactivestreams.Publisher", classLoader); REACTOR_PRESENT = ClassUtils.isPresent("reactor.core.publisher.Flux", classLoader); RXJAVA_3_PRESENT = ClassUtils.isPresent("io.reactivex.rxjava3.core.Flowable", classLoader); COROUTINES_REACTOR_PRESENT = ClassUtils.isPresent("kotlinx.coroutines.reactor.MonoKt", classLoader); MUTINY_PRESENT = ClassUtils.isPresent("io.smallrye.mutiny.Multi", classLoader); } private final List<ReactiveAdapter> adapters = new ArrayList<>(); /** * Create a registry and auto-register default adapters. * @see #getSharedInstance() */ public ReactiveAdapterRegistry() { // Defensive guard for the Reactive Streams API itself if (!REACTIVE_STREAMS_PRESENT) { return; } // Reactor if (REACTOR_PRESENT) { new ReactorRegistrar().registerAdapters(this); } // RxJava if (RXJAVA_3_PRESENT) { new RxJava3Registrar().registerAdapters(this); } // Kotlin Coroutines if (REACTOR_PRESENT && COROUTINES_REACTOR_PRESENT) { new CoroutinesRegistrar().registerAdapters(this); } // SmallRye Mutiny if (MUTINY_PRESENT) { new MutinyRegistrar().registerAdapters(this); } // Simple Flow.Publisher bridge if Reactor is not present if (!REACTOR_PRESENT) { new FlowAdaptersRegistrar().registerAdapters(this); } } /** * Register a reactive type along with functions to adapt to and from a * Reactive Streams {@link Publisher}. The function arguments assume that * their input is neither {@code null} nor {@link Optional}. * <p>This variant registers the new adapter after existing adapters. * It will be matched for the exact reactive type if no earlier adapter was * registered for the specific type, and it will be matched for assignability * in a second pass if no earlier adapter had an assignable type before. * @see #registerReactiveTypeOverride * @see #getAdapter */ public void registerReactiveType(ReactiveTypeDescriptor descriptor, Function<Object, Publisher<?>> toAdapter, Function<Publisher<?>, Object> fromAdapter) { this.adapters.add(buildAdapter(descriptor, toAdapter, fromAdapter)); } /** * Register a reactive type along with functions to adapt to and from a * Reactive Streams {@link Publisher}. The function arguments assume that * their input is neither {@code null} nor {@link Optional}. * <p>This variant registers the new adapter first, effectively overriding * any previously registered adapters for the same reactive type. This allows * for overriding existing adapters, in particular default adapters. * <p>Note that existing adapters for specific types will still match before * an assignability match with the new adapter. In order to override all * existing matches, a new reactive type adapter needs to be registered * for every specific type, not relying on subtype assignability matches. * @since 5.3.30 * @see #registerReactiveType * @see #getAdapter */ public void registerReactiveTypeOverride(ReactiveTypeDescriptor descriptor, Function<Object, Publisher<?>> toAdapter, Function<Publisher<?>, Object> fromAdapter) { this.adapters.add(0, buildAdapter(descriptor, toAdapter, fromAdapter)); } private ReactiveAdapter buildAdapter(ReactiveTypeDescriptor descriptor, Function<Object, Publisher<?>> toAdapter, Function<Publisher<?>, Object> fromAdapter) { return (REACTOR_PRESENT ? new ReactorAdapter(descriptor, toAdapter, fromAdapter) : new ReactiveAdapter(descriptor, toAdapter, fromAdapter)); } /** * Return whether the registry has any adapters. */ public boolean hasAdapters() { return !this.adapters.isEmpty(); } /** * Get the adapter for the given reactive type. * @return the corresponding adapter, or {@code null} if none available */ public @Nullable ReactiveAdapter getAdapter(Class<?> reactiveType) { return getAdapter(reactiveType, null); } /** * Get the adapter for the given reactive type. Or if a "source" object is * provided, its actual type is used instead. * @param reactiveType the reactive type * (may be {@code null} if a concrete source object is given) * @param source an instance of the reactive type * (i.e. to adapt from; may be {@code null} if the reactive type is specified) * @return the corresponding adapter, or {@code null} if none available */ public @Nullable ReactiveAdapter getAdapter(@Nullable Class<?> reactiveType, @Nullable Object source) { if (this.adapters.isEmpty()) { return null; } Object sourceToUse = (source instanceof Optional<?> optional ? optional.orElse(null) : source); Class<?> clazz = (sourceToUse != null ? sourceToUse.getClass() : reactiveType); if (clazz == null) { return null; } for (ReactiveAdapter adapter : this.adapters) { if (adapter.getReactiveType() == clazz) { return adapter; } } for (ReactiveAdapter adapter : this.adapters) { if (adapter.getReactiveType().isAssignableFrom(clazz)) { return adapter; } } return null; } /** * Return a shared default {@code ReactiveAdapterRegistry} instance, * lazily building it once needed. * <p><b>NOTE:</b> We highly recommend passing a long-lived, pre-configured * {@code ReactiveAdapterRegistry} instance for customization purposes. * This accessor is only meant as a fallback for code paths that want to * fall back on a default instance if one isn't provided. * @return the shared {@code ReactiveAdapterRegistry} instance * @since 5.0.2 */ public static ReactiveAdapterRegistry getSharedInstance() { ReactiveAdapterRegistry registry = sharedInstance; if (registry == null) { synchronized (ReactiveAdapterRegistry.class) { registry = sharedInstance; if (registry == null) { registry = new ReactiveAdapterRegistry(); sharedInstance = registry; } } } return registry; } /** * ReactiveAdapter variant that wraps adapted Publishers as {@link Flux} or * {@link Mono} depending on {@link ReactiveTypeDescriptor#isMultiValue()}. * This is important in places where only the stream and stream element type * information is available like encoders and decoders. */ private static
ReactiveAdapterRegistry
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/viewfs/InodeTree.java
{ "start": 2474, "end": 2595 }
class ____<T> { private static final Logger LOGGER = LoggerFactory.getLogger(InodeTree.class.getName());
InodeTree
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/message/codec/BinaryCodecFactory.java
{ "start": 1295, "end": 1895 }
class ____ implements HttpMessageEncoderFactory, HttpMessageDecoderFactory { private static final BinaryCodec INSTANCE = new BinaryCodec(); @Override public HttpMessageCodec createCodec(URL url, FrameworkModel frameworkModel, String mediaType) { return INSTANCE; } @Override public MediaType mediaType() { return MediaType.APPLICATION_OCTET_STREAM; } @Override public boolean supports(String mediaType) { return mediaType.startsWith(MediaType.APPLICATION_OCTET_STREAM.getName()) || mediaType.startsWith("image/"); } }
BinaryCodecFactory
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/localfs/TestLocalFSContractAppend.java
{ "start": 1043, "end": 1238 }
class ____ extends AbstractContractAppendTest { @Override protected AbstractFSContract createContract(Configuration conf) { return new LocalFSContract(conf); } }
TestLocalFSContractAppend
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/datetime/FormatCache.java
{ "start": 10112, "end": 10704 }
class ____ { private final Object[] keys; private int hashCode; /** * Constructs an instance of <code>MultipartKey</code> to hold the specified objects. * @param keys the set of objects that make up the key. Each key may be null. */ public MultipartKey(final Object... keys) { this.keys = keys; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { // Eliminate the usual boilerplate because // this inner static
MultipartKey
java
apache__camel
components/camel-knative/camel-knative-api/src/generated/java/org/apache/camel/component/knative/spi/KnativeEnvironmentConfigurer.java
{ "start": 730, "end": 2337 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.knative.spi.KnativeEnvironment target = (org.apache.camel.component.knative.spi.KnativeEnvironment) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "resources": target.setResources(property(camelContext, java.util.List.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "resources": return java.util.List.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.knative.spi.KnativeEnvironment target = (org.apache.camel.component.knative.spi.KnativeEnvironment) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "resources": return target.getResources(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "resources": return org.apache.camel.component.knative.spi.KnativeResource.class; default: return null; } } }
KnativeEnvironmentConfigurer
java
apache__kafka
metadata/src/main/java/org/apache/kafka/metadata/properties/MetaPropertiesEnsemble.java
{ "start": 5512, "end": 5612 }
class ____ copying a MetaPropertiesEnsemble object, possibly with changes. */ public static
for
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/operations/converters/table/SqlAlterTableAddDistributionConverter.java
{ "start": 1540, "end": 3037 }
class ____ extends AbstractAlterTableConverter<SqlAddDistribution> { @Override protected Operation convertToOperation( SqlAddDistribution sqlAddDistribution, ResolvedCatalogTable oldTable, ConvertContext context) { return buildAlterTableChangeOperation( sqlAddDistribution, List.of( TableChange.add( OperationConverterUtils.getDistributionFromSqlDistribution( sqlAddDistribution.getDistribution()))), oldTable.getUnresolvedSchema(), oldTable, context.getCatalogManager()); } protected TableDistribution getTableDistribution( SqlAlterTable alterTable, ResolvedCatalogTable oldTable) { Optional<TableDistribution> oldDistribution = oldTable.getDistribution(); if (oldDistribution.isPresent()) { throw new ValidationException( String.format( "%sThe base table has already defined the distribution `%s`. " + "You can modify it or drop it before adding a new one.", EX_MSG_PREFIX, oldDistribution.get())); } return OperationConverterUtils.getDistributionFromSqlDistribution( ((SqlAlterDistribution) alterTable).getDistribution()); } }
SqlAlterTableAddDistributionConverter
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_hasToString_format_Test.java
{ "start": 944, "end": 1577 }
class ____ extends AbstractAssertBaseTest { @Override protected ConcreteAssert invoke_api_method() { return assertions.hasToString("%s %s", "some", "description"); } @Override protected void verify_internal_effects() { verify(objects).assertHasToString(getInfo(assertions), getActual(assertions), "some description"); } @Test void nullStringArgumentsThrowAnException() { assertThatNullPointerException().isThrownBy(() -> assertions.hasToString(null, "foo", "bar")) .withMessage("The expectedStringTemplate must not be null"); } }
AbstractAssert_hasToString_format_Test
java
apache__flink
flink-table/flink-sql-gateway/src/main/java/org/apache/flink/table/gateway/rest/SqlGatewayRestEndpointFactory.java
{ "start": 1774, "end": 4181 }
class ____ implements SqlGatewayEndpointFactory { /** The identifier string for {@link SqlGatewayRestEndpointFactory}. */ public static final String IDENTIFIER = "rest"; @Override public SqlGatewayEndpoint createSqlGatewayEndpoint(Context context) { SqlGatewayEndpointFactoryUtils.EndpointFactoryHelper endpointFactoryHelper = SqlGatewayEndpointFactoryUtils.createEndpointFactoryHelper(this, context); // Check that ADDRESS must be set endpointFactoryHelper.validate(); Configuration config = rebuildRestEndpointOptions( context.getEndpointOptions(), context.getFlinkConfiguration().toMap()); try { return new SqlGatewayRestEndpoint(config, context.getSqlGatewayService()); } catch (Exception e) { throw new SqlGatewayException("Cannot start the rest endpoint.", e); } } public static Configuration rebuildRestEndpointOptions( Map<String, String> endpointConfigMap, Map<String, String> flinkConfigMap) { flinkConfigMap.put(RestOptions.ADDRESS.key(), endpointConfigMap.get(ADDRESS.key())); if (endpointConfigMap.containsKey(BIND_ADDRESS.key())) { flinkConfigMap.put( RestOptions.BIND_ADDRESS.key(), endpointConfigMap.get(BIND_ADDRESS.key())); } // we need to override RestOptions.PORT anyway, to use a different default value flinkConfigMap.put( RestOptions.PORT.key(), endpointConfigMap.getOrDefault(PORT.key(), PORT.defaultValue().toString())); if (endpointConfigMap.containsKey(BIND_PORT.key())) { flinkConfigMap.put(RestOptions.BIND_PORT.key(), endpointConfigMap.get(BIND_PORT.key())); } return Configuration.fromMap(flinkConfigMap); } @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Set<ConfigOption<?>> requiredOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(ADDRESS); return options; } @Override public Set<ConfigOption<?>> optionalOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(BIND_ADDRESS); options.add(PORT); options.add(BIND_PORT); return options; } }
SqlGatewayRestEndpointFactory
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/optional/OptionalDoubleMessageBodyWriterTest.java
{ "start": 793, "end": 3338 }
class ____ extends AbstractJerseyTest { @Override protected Application configure() { return DropwizardResourceConfig.forTesting() .register(new EmptyOptionalExceptionMapper()) .register(OptionalDoubleReturnResource.class); } @Test void presentOptionalsReturnTheirValue() { assertThat(target("optional-return") .queryParam("id", "1").request() .get(Double.class)) .isEqualTo(1); } @Test void presentOptionalsReturnTheirValueWithResponse() { assertThat(target("optional-return/response-wrapped") .queryParam("id", "1").request() .get(Double.class)) .isEqualTo(1); } @Test void absentOptionalsThrowANotFound() { Invocation.Builder request = target("optional-return").request(); assertThatExceptionOfType(WebApplicationException.class) .isThrownBy(() -> request.get(Double.class)) .satisfies(e -> assertThat(e.getResponse().getStatus()).isEqualTo(404)); } @Test void valueSetIgnoresDefault() { assertThat(target("optional-return/default").queryParam("id", "1").request().get(Double.class)) .isEqualTo(target("optional-return/double/default").queryParam("id", "1").request().get(Double.class)) .isEqualTo(1); } @Test void valueNotSetReturnsDefault() { assertThat(target("optional-return/default").request().get(Double.class)) .isEqualTo(target("optional-return/double/default").request().get(Double.class)) .isEqualTo(0); } @Test void valueEmptyReturns404() { assertThat(target("optional-return/default").queryParam("id", "").request().get()) .extracting(Response::getStatus) .isEqualTo(404); } @Test void valueInvalidReturns404() { Invocation.Builder request = target("optional-return/default").queryParam("id", "invalid") .request(); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> request.get(Double.class)); Invocation.Builder doubleRequest = target("optional-return/double/default").queryParam("id", "invalid") .request(); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> doubleRequest.get(Double.class)); } @Path("optional-return") @Produces(MediaType.TEXT_PLAIN) public static
OptionalDoubleMessageBodyWriterTest
java
spring-projects__spring-boot
buildSrc/src/test/java/org/springframework/boot/build/architecture/resources/noloads/ResourceUtilsWithoutLoading.java
{ "start": 814, "end": 1073 }
class ____ { void inspectResourceLocation() throws MalformedURLException { ResourceUtils.isUrl("gradle.properties"); ResourceUtils.isFileURL(new URL("gradle.properties")); "test".startsWith(ResourceUtils.FILE_URL_PREFIX); } }
ResourceUtilsWithoutLoading
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/join/Thing.java
{ "start": 171, "end": 1255 }
class ____ { private Employee salesperson; private String comments; /** * @return Returns the salesperson. */ public Employee getSalesperson() { return salesperson; } /** * @param salesperson The salesperson to set. */ public void setSalesperson(Employee salesperson) { this.salesperson = salesperson; } /** * @return Returns the comments. */ public String getComments() { return comments; } /** * @param comments The comments to set. */ public void setComments(String comments) { this.comments = comments; } Long id; String name; String nameUpper; /** * @return Returns the ID. */ public Long getId() { return id; } /** * @param id The ID to set. */ public void setId(Long id) { this.id = id; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } public String getNameUpper() { return nameUpper; } public void setNameUpper(String nameUpper) { this.nameUpper = nameUpper; } }
Thing
java
junit-team__junit5
junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/CsvFileSource.java
{ "start": 3881, "end": 8855 }
interface ____ { /** * The CSV classpath resources to use as the sources of arguments; must not * be empty unless {@link #files} is non-empty. */ String[] resources() default {}; /** * The CSV files to use as the sources of arguments; must not be empty * unless {@link #resources} is non-empty. */ String[] files() default {}; /** * The encoding to use when reading the CSV files; must be a valid charset. * * <p>Defaults to {@code "UTF-8"}. * * @see java.nio.charset.StandardCharsets */ String encoding() default "UTF-8"; /** * Configures whether the first CSV record should be treated as header names * for columns. * * <p>When set to {@code true}, the header names will be used in the * generated display name for each {@code @ParameterizedClass} or * {@code @ParameterizedTest} invocation. When using this feature, you must * ensure that the display name pattern for {@code @ParameterizedClass} or * {@code @ParameterizedTest} includes * {@value ParameterizedInvocationConstants#ARGUMENTS_PLACEHOLDER} instead of * {@value ParameterizedInvocationConstants#ARGUMENTS_WITH_NAMES_PLACEHOLDER} * as demonstrated in the example below. * * <p>Defaults to {@code false}. * * <h4>Example</h4> * <pre class="code"> * {@literal @}ParameterizedTest(name = "[{index}] {arguments}") * {@literal @}CsvFileSource(resources = "fruits.csv", useHeadersInDisplayName = true) * void test(String fruit, int rank) { * // ... * }</pre> * * @since 5.8.2 */ @API(status = STABLE, since = "5.10") boolean useHeadersInDisplayName() default false; /** * The quote character to use for <em>quoted strings</em>. * * <p>Defaults to a double quote ({@code "}). * * <p>You may change the quote character to anything that makes sense for * your use case. * * @since 5.8.2 */ @API(status = STABLE, since = "5.10") char quoteCharacter() default '"'; /** * The column delimiter character to use when reading the CSV files. * * <p>This is an alternative to {@link #delimiterString} and cannot be * used in conjunction with {@link #delimiterString}. * * <p>Defaults implicitly to {@code ','}, if neither delimiter attribute is * explicitly set. */ char delimiter() default '\0'; /** * The column delimiter string to use when reading the CSV files. * * <p>This is an alternative to {@link #delimiter} and cannot be used in * conjunction with {@link #delimiter}. * * <p>Defaults implicitly to {@code ","}, if neither delimiter attribute is * explicitly set. * * @since 5.6 */ String delimiterString() default ""; /** * The number of lines to skip when reading the CSV files. * * <p>Typically used to skip header lines. * * <p>Defaults to {@code 0}. * * @since 5.1 */ int numLinesToSkip() default 0; /** * The empty value to use when reading the CSV files. * * <p>This value replaces quoted empty strings read from the input. * * <p>Defaults to {@code ""}. * * @since 5.5 */ String emptyValue() default ""; /** * A list of strings that should be interpreted as {@code null} references. * * <p>For example, you may wish for certain values such as {@code "N/A"} or * {@code "NIL"} to be converted to {@code null} references. * * <p>Please note that <em>unquoted</em> empty values will always be converted * to {@code null} references regardless of the value of this {@code nullValues} * attribute; whereas, a <em>quoted</em> empty string will be treated as an * {@link #emptyValue}. * * <p>Defaults to {@code {}}. * * @since 5.6 */ String[] nullValues() default {}; /** * The maximum number of characters allowed per CSV column. * * <p>Must be a positive number or {@code -1} to allow an unlimited number * of characters. * * <p>Defaults to {@code 4096}. * * @since 5.7 */ @API(status = STABLE, since = "5.10") int maxCharsPerColumn() default 4096; /** * Controls whether leading and trailing whitespace characters of unquoted * CSV columns should be ignored. * * <p>Whitespace refers to characters with Unicode code points less than * or equal to {@code U+0020}, as defined by {@link String#trim()}. * * <p>Defaults to {@code true}. * * @since 5.8 */ @API(status = STABLE, since = "5.10") boolean ignoreLeadingAndTrailingWhitespace() default true; /** * The character used to denote comments when reading the CSV files. * * <p>Any line that begins with this character will be treated as a comment * and ignored during parsing. Note that there is one exception to this rule: * if the comment character appears within a quoted field, it loses its * special meaning. * * <p>The comment character must be the first character on the line without * any leading whitespace. * * <p>Defaults to {@code '#'}. * * @since 6.0.1 */ @API(status = EXPERIMENTAL, since = "6.0.1") char commentCharacter() default '#'; }
CsvFileSource
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/CamelEvent.java
{ "start": 5481, "end": 5663 }
interface ____ extends CamelContextEvent { @Override default Type getType() { return Type.RoutesStarting; } }
CamelContextRoutesStartingEvent
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java
{ "start": 69758, "end": 72153 }
class ____ implements SingleArcTransition<JobImpl, JobEvent> { @Override public void transition(JobImpl job, JobEvent event) { LOG.info("Timeout expired in FAIL_WAIT waiting for tasks to get killed." + " Going to fail job anyway"); job.failWaitTriggerScheduledFuture.cancel(false); job.eventHandler.handle(new CommitterJobAbortEvent(job.jobId, job.jobContext, org.apache.hadoop.mapreduce.JobStatus.State.FAILED)); } } // JobFinishedEvent triggers the move of the history file out of the staging // area. May need to create a new event type for this if JobFinished should // not be generated for KilledJobs, etc. private static JobFinishedEvent createJobFinishedEvent(JobImpl job) { job.mayBeConstructFinalFullCounters(); JobFinishedEvent jfe = new JobFinishedEvent( job.oldJobId, job.finishTime, job.succeededMapTaskCount, job.succeededReduceTaskCount, job.failedMapTaskCount, job.failedReduceTaskCount, job.killedMapTaskCount, job.killedReduceTaskCount, job.finalMapCounters, job.finalReduceCounters, job.fullCounters); return jfe; } private void mayBeConstructFinalFullCounters() { // Calculating full-counters. This should happen only once for the job. synchronized (this.fullCountersLock) { if (this.fullCounters != null) { // Already constructed. Just return. return; } this.constructFinalFullcounters(); } } @Private public void constructFinalFullcounters() { this.fullCounters = new Counters(); this.finalMapCounters = new Counters(); this.finalReduceCounters = new Counters(); this.fullCounters.incrAllCounters(jobCounters); for (Task t : this.tasks.values()) { Counters counters = t.getCounters(); switch (t.getType()) { case MAP: this.finalMapCounters.incrAllCounters(counters); break; case REDUCE: this.finalReduceCounters.incrAllCounters(counters); break; default: throw new IllegalStateException("Task type neither map nor reduce: " + t.getType()); } this.fullCounters.incrAllCounters(counters); } } // Task-start has been moved out of InitTransition, so this arc simply // hardcodes 0 for both map and reduce finished tasks. private static
JobFailWaitTimedOutTransition
java
resilience4j__resilience4j
resilience4j-micrometer/src/main/java/io/github/resilience4j/micrometer/tagged/ThreadPoolBulkheadMetricNames.java
{ "start": 107, "end": 4556 }
class ____ { private static final String DEFAULT_PREFIX = "resilience4j.bulkhead"; public static final String DEFAULT_BULKHEAD_QUEUE_DEPTH_METRIC_NAME = DEFAULT_PREFIX + ".queue.depth"; public static final String DEFAULT_BULKHEAD_QUEUE_CAPACITY_METRIC_NAME = DEFAULT_PREFIX + ".queue.capacity"; public static final String DEFAULT_THREAD_POOL_SIZE_METRIC_NAME = DEFAULT_PREFIX + ".thread.pool.size"; public static final String DEFAULT_MAX_THREAD_POOL_SIZE_METRIC_NAME = DEFAULT_PREFIX + ".max.thread.pool.size"; public static final String DEFAULT_CORE_THREAD_POOL_SIZE_METRIC_NAME = DEFAULT_PREFIX + ".core.thread.pool.size"; public static final String DEFAULT_BULKHEAD_ACTIVE_THREAD_COUNT_METRIC_NAME = DEFAULT_PREFIX + ".active.thread.count"; public static final String DEFAULT_BULKHEAD_AVAILABLE_THREAD_COUNT_METRIC_NAME = DEFAULT_PREFIX + ".available.thread.count"; private String queueDepthMetricName = DEFAULT_BULKHEAD_QUEUE_DEPTH_METRIC_NAME; private String threadPoolSizeMetricName = DEFAULT_THREAD_POOL_SIZE_METRIC_NAME; private String maxThreadPoolSizeMetricName = DEFAULT_MAX_THREAD_POOL_SIZE_METRIC_NAME; private String coreThreadPoolSizeMetricName = DEFAULT_CORE_THREAD_POOL_SIZE_METRIC_NAME; private String queueCapacityMetricName = DEFAULT_BULKHEAD_QUEUE_CAPACITY_METRIC_NAME; private String activeThreadCountMetricName = DEFAULT_BULKHEAD_ACTIVE_THREAD_COUNT_METRIC_NAME; private String availableThreadCountMetricName = DEFAULT_BULKHEAD_AVAILABLE_THREAD_COUNT_METRIC_NAME; protected ThreadPoolBulkheadMetricNames() { } /** * Returns a builder for creating custom metric names. Note that names have default values, * so only desired metrics can be renamed. * * @return The builder. */ public static Builder custom() { return new Builder(); } /** * Returns default metric names. * * @return The default {@link ThreadPoolBulkheadMetricNames} instance. */ public static ThreadPoolBulkheadMetricNames ofDefaults() { return new ThreadPoolBulkheadMetricNames(); } /** * Returns the metric name for queue depth, defaults to {@value * DEFAULT_BULKHEAD_QUEUE_DEPTH_METRIC_NAME}. * * @return The queue depth metric name. */ public String getQueueDepthMetricName() { return queueDepthMetricName; } /** * Returns the metric name for thread pool size, defaults to {@value * DEFAULT_THREAD_POOL_SIZE_METRIC_NAME}. * * @return The thread pool size metric name. */ public String getThreadPoolSizeMetricName() { return threadPoolSizeMetricName; } /** * Returns the metric name for max thread pool size, defaults to {@value * DEFAULT_MAX_THREAD_POOL_SIZE_METRIC_NAME}. * * @return The max thread pool size metric name. */ public String getMaxThreadPoolSizeMetricName() { return maxThreadPoolSizeMetricName; } /** * Returns the metric name for core thread pool size, defaults to {@value * DEFAULT_CORE_THREAD_POOL_SIZE_METRIC_NAME}. * * @return The core thread pool size metric name. */ public String getCoreThreadPoolSizeMetricName() { return coreThreadPoolSizeMetricName; } /** * Returns the metric name for queue capacity, defaults to {@value * DEFAULT_BULKHEAD_QUEUE_CAPACITY_METRIC_NAME}. * * @return The queue capacity metric name. */ public String getQueueCapacityMetricName() { return queueCapacityMetricName; } /** * Returns the metric name for bulkhead active count, defaults to {@value * DEFAULT_BULKHEAD_ACTIVE_THREAD_COUNT_METRIC_NAME}. * * @return The active thread count metric name. */ public String getActiveThreadCountMetricName() { return activeThreadCountMetricName; } /** * Returns the metric name for bulkhead available thread count, * defaults to {@value DEFAULT_BULKHEAD_AVAILABLE_THREAD_COUNT_METRIC_NAME}. * * @return The available thread count metric name. */ public String getAvailableThreadCountMetricName() { return availableThreadCountMetricName; } /** * Helps building custom instance of {@link ThreadPoolBulkheadMetricNames}. */ public static
ThreadPoolBulkheadMetricNames
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/CollectionUtilsTest.java
{ "start": 2129, "end": 8646 }
class ____ { @Test void testSort() { List<Integer> list = new ArrayList<Integer>(); list.add(100); list.add(10); list.add(20); List<Integer> expected = new ArrayList<Integer>(); expected.add(10); expected.add(20); expected.add(100); assertEquals(expected, CollectionUtils.sort(list)); } @Test void testSortNull() { assertNull(CollectionUtils.sort(null)); assertTrue(CollectionUtils.sort(new ArrayList<Integer>()).isEmpty()); } @Test void testSortSimpleName() { List<String> list = new ArrayList<String>(); list.add("aaa.z"); list.add("b"); list.add(null); list.add("zzz.a"); list.add("c"); list.add(null); List<String> sorted = CollectionUtils.sortSimpleName(list); assertNull(sorted.get(0)); assertNull(sorted.get(1)); } @Test void testSortSimpleNameNull() { assertNull(CollectionUtils.sortSimpleName(null)); assertTrue(CollectionUtils.sortSimpleName(new ArrayList<String>()).isEmpty()); } @Test void testFlip() { assertEquals(CollectionUtils.flip(null), null); Map<String, String> input1 = new HashMap<>(); input1.put("k1", null); input1.put("k2", "v2"); Map<String, String> output1 = new HashMap<>(); output1.put(null, "k1"); output1.put("v2", "k2"); assertEquals(CollectionUtils.flip(input1), output1); Map<String, String> input2 = new HashMap<>(); input2.put("k1", null); input2.put("k2", null); assertThrows(IllegalArgumentException.class, () -> CollectionUtils.flip(input2)); } @Test void testSplitAll() { assertNull(CollectionUtils.splitAll(null, null)); assertNull(CollectionUtils.splitAll(null, "-")); assertTrue(CollectionUtils.splitAll(new HashMap<String, List<String>>(), "-") .isEmpty()); Map<String, List<String>> input = new HashMap<String, List<String>>(); input.put("key1", Arrays.asList("1:a", "2:b", "3:c")); input.put("key2", Arrays.asList("1:a", "2:b")); input.put("key3", null); input.put("key4", new ArrayList<String>()); Map<String, Map<String, String>> expected = new HashMap<String, Map<String, String>>(); expected.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c")); expected.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b")); expected.put("key3", null); expected.put("key4", new HashMap<String, String>()); assertEquals(expected, CollectionUtils.splitAll(input, ":")); } @Test void testJoinAll() { assertNull(CollectionUtils.joinAll(null, null)); assertNull(CollectionUtils.joinAll(null, "-")); Map<String, List<String>> expected = new HashMap<String, List<String>>(); expected.put("key1", Arrays.asList("1:a", "2:b", "3:c")); expected.put("key2", Arrays.asList("1:a", "2:b")); expected.put("key3", null); expected.put("key4", new ArrayList<String>()); Map<String, Map<String, String>> input = new HashMap<String, Map<String, String>>(); input.put("key1", CollectionUtils.toStringMap("1", "a", "2", "b", "3", "c")); input.put("key2", CollectionUtils.toStringMap("1", "a", "2", "b")); input.put("key3", null); input.put("key4", new HashMap<String, String>()); Map<String, List<String>> output = CollectionUtils.joinAll(input, ":"); for (Map.Entry<String, List<String>> entry : output.entrySet()) { if (entry.getValue() == null) continue; Collections.sort(entry.getValue()); } assertEquals(expected, output); } @Test void testJoinList() { List<String> list = emptyList(); assertEquals("", CollectionUtils.join(list, "/")); list = Arrays.asList("x"); assertEquals("x", CollectionUtils.join(list, "-")); list = Arrays.asList("a", "b"); assertEquals("a/b", CollectionUtils.join(list, "/")); } @Test void testMapEquals() { assertTrue(CollectionUtils.mapEquals(null, null)); assertFalse(CollectionUtils.mapEquals(null, new HashMap<String, String>())); assertFalse(CollectionUtils.mapEquals(new HashMap<String, String>(), null)); assertTrue(CollectionUtils.mapEquals( CollectionUtils.toStringMap("1", "a", "2", "b"), CollectionUtils.toStringMap("1", "a", "2", "b"))); assertFalse(CollectionUtils.mapEquals( CollectionUtils.toStringMap("1", "a"), CollectionUtils.toStringMap("1", "a", "2", "b"))); } @Test void testStringMap1() { assertThat(toStringMap("key", "value"), equalTo(Collections.singletonMap("key", "value"))); } @Test void testStringMap2() { Assertions.assertThrows(IllegalArgumentException.class, () -> toStringMap("key", "value", "odd")); } @Test void testToMap1() { assertTrue(CollectionUtils.toMap().isEmpty()); Map<String, Integer> expected = new HashMap<String, Integer>(); expected.put("a", 1); expected.put("b", 2); expected.put("c", 3); assertEquals(expected, CollectionUtils.toMap("a", 1, "b", 2, "c", 3)); } @Test void testObjectToMap() throws Exception { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setSerialization("fastjson2"); assertFalse(CollectionUtils.objToMap(protocolConfig).isEmpty()); } @Test void testToMap2() { Assertions.assertThrows(IllegalArgumentException.class, () -> toMap("a", "b", "c")); } @Test void testIsEmpty() { assertThat(isEmpty(null), is(true)); assertThat(isEmpty(new HashSet()), is(true)); assertThat(isEmpty(emptyList()), is(true)); } @Test void testIsNotEmpty() { assertThat(isNotEmpty(singleton("a")), is(true)); } @Test void testOfSet() { Set<String> set = ofSet(); assertEquals(emptySet(), set); set = ofSet(((String[]) null)); assertEquals(emptySet(), set); set = ofSet("A", "B", "C"); Set<String> expectedSet = new LinkedHashSet<>(); expectedSet.add("A"); expectedSet.add("B"); expectedSet.add("C"); assertEquals(expectedSet, set); } }
CollectionUtilsTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicy.java
{ "start": 1539, "end": 1678 }
interface ____ used for choosing the desired number of targets * for placing block replicas. */ @InterfaceAudience.Private public abstract
is
java
grpc__grpc-java
api/src/testFixtures/java/io/grpc/testing/DeadlineSubject.java
{ "start": 1305, "end": 3366 }
class ____ extends ComparableSubject { public static final double NANOSECONDS_IN_A_SECOND = SECONDS.toNanos(1) * 1.0; private static final Subject.Factory<DeadlineSubject, Deadline> deadlineFactory = new Factory(); public static Subject.Factory<DeadlineSubject, Deadline> deadline() { return deadlineFactory; } private final Deadline actual; @SuppressWarnings("unchecked") private DeadlineSubject(FailureMetadata metadata, Deadline subject) { super(metadata, subject); this.actual = subject; } /** * Prepares for a check that the subject is deadline within the given tolerance of an * expected value that will be provided in the next call in the fluent chain. */ @CheckReturnValue public TolerantDeadlineComparison isWithin(final long delta, final TimeUnit timeUnit) { return new TolerantDeadlineComparison() { @Override public void of(Deadline expected) { Deadline actual = DeadlineSubject.this.actual; checkNotNull(actual, "actual value cannot be null. expected=%s", expected); // This is probably overkill, but easier than thinking about overflow. long actualNanos = actual.timeRemaining(NANOSECONDS); long expectedNanos = expected.timeRemaining(NANOSECONDS); long deltaNanos = timeUnit.toNanos(delta) ; if (Math.abs(actualNanos - expectedNanos) > deltaNanos) { failWithoutActual( fact("expected", expectedNanos / NANOSECONDS_IN_A_SECOND), fact("but was", actualNanos / NANOSECONDS_IN_A_SECOND), fact("outside tolerance in seconds", deltaNanos / NANOSECONDS_IN_A_SECOND)); } } }; } // TODO(carl-mastrangelo): Add a isNotWithin method once there is need for one. Currently there // is no such method since there is no code that uses it, and would lower our coverage numbers. /** * A partially specified proposition about an approximate relationship to a {@code deadline} * subject using a tolerance. */ public abstract static
DeadlineSubject
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/runtime/src/main/java/io/quarkus/restclient/runtime/QuarkusInvocationContextImpl.java
{ "start": 5955, "end": 6566 }
class ____ { @SuppressWarnings("rawtypes") private final Interceptor interceptor; private final Object interceptorInstance; public InterceptorInvocation(final Interceptor<?> interceptor, final Object interceptorInstance) { this.interceptor = interceptor; this.interceptorInstance = interceptorInstance; } @SuppressWarnings("unchecked") Object invoke(InvocationContext ctx) throws Exception { return interceptor.intercept(InterceptionType.AROUND_INVOKE, interceptorInstance, ctx); } } }
InterceptorInvocation
java
apache__kafka
connect/mirror/src/test/java/org/apache/kafka/connect/mirror/MirrorCheckpointConfigTest.java
{ "start": 2582, "end": 2986 }
class ____ been loaded and statically initialized by the JVM ConfigDef taskConfigDef = MirrorCheckpointTaskConfig.TASK_CONFIG_DEF; assertTrue( taskConfigDef.names().contains(MirrorCheckpointConfig.TASK_CONSUMER_GROUPS), MirrorCheckpointConfig.TASK_CONSUMER_GROUPS + " should be defined for task ConfigDef" ); // Ensure that the task config
has
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/DiffableUtils.java
{ "start": 33462, "end": 34116 }
class ____<K> extends NonDiffableValueSerializer<K, Set<String>> { private static final StringSetValueSerializer INSTANCE = new StringSetValueSerializer(); @SuppressWarnings("unchecked") public static <K> StringSetValueSerializer<K> getInstance() { return INSTANCE; } @Override public void write(Set<String> value, StreamOutput out) throws IOException { out.writeStringCollection(value); } @Override public Set<String> read(StreamInput in, K key) throws IOException { return Set.of(in.readStringArray()); } } }
StringSetValueSerializer
java
apache__camel
components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileOperationFailedException.java
{ "start": 967, "end": 2538 }
class ____ extends RuntimeCamelException { private static final long serialVersionUID = -64176625836814418L; private final int code; private final String reason; public GenericFileOperationFailedException(String message) { super(message); this.code = 0; this.reason = null; } public GenericFileOperationFailedException(String message, Throwable cause) { super(message, cause); this.code = 0; this.reason = null; } public GenericFileOperationFailedException(int code, String reason) { super("File operation failed" + (reason != null ? ": " + reason : "") + ". Code: " + code); this.code = code; this.reason = reason; } public GenericFileOperationFailedException(int code, String reason, Throwable cause) { super("File operation failed" + (reason != null ? ": " + reason : "") + ". Code: " + code, cause); this.code = code; this.reason = reason; } public GenericFileOperationFailedException(int code, String reason, String message) { this(code, reason + " " + message); } public GenericFileOperationFailedException(int code, String reason, String message, Throwable cause) { this(code, reason + " " + message, cause); } /** * Return the file failure code (if any) */ public int getCode() { return code; } /** * Return the file failure reason (if any) */ public String getReason() { return reason; } }
GenericFileOperationFailedException
java
apache__camel
components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/KclKinesis2Consumer.java
{ "start": 9396, "end": 12699 }
class ____ implements ShardRecordProcessor { private static final Logger LOG = LoggerFactory.getLogger(CamelKinesisRecordProcessor.class); private String shardId; private Kinesis2Endpoint endpoint; public CamelKinesisRecordProcessor(Kinesis2Endpoint endpoint) { this.endpoint = endpoint; } @Override public void initialize(InitializationInput initializationInput) { shardId = initializationInput.shardId(); LOG.debug("Initializing @ Sequence: {}", initializationInput.extendedSequenceNumber()); } @Override public void processRecords(ProcessRecordsInput processRecordsInput) { try { LOG.debug("Processing {} record(s)", processRecordsInput.records().size()); processRecordsInput.records() .forEach(r -> { try { processor.process(createExchange(r, shardId)); } catch (Exception e) { throw new RuntimeException(e); } }); } catch (Throwable t) { LOG.error("Caught throwable while processing records. Aborting."); } } @Override public void leaseLost(LeaseLostInput leaseLostInput) { LOG.debug("Lost lease, so terminating."); } @Override public void shardEnded(ShardEndedInput shardEndedInput) { try { LOG.debug("Reached shard end checkpointing."); shardEndedInput.checkpointer().checkpoint(); } catch (ShutdownException | InvalidStateException e) { LOG.error("Exception while checkpointing at shard end. Giving up.", e); } } @Override public void shutdownRequested(ShutdownRequestedInput shutdownRequestedInput) { try { LOG.debug("Scheduler is shutting down, checkpointing."); shutdownRequestedInput.checkpointer().checkpoint(); } catch (ShutdownException | InvalidStateException e) { LOG.error("Exception while checkpointing at requested shutdown. Giving up.", e); } } protected Exchange createExchange(KinesisClientRecord dataRecord, String shardId) { Exchange exchange = endpoint.createExchange(); exchange.getMessage().setBody(dataRecord.data()); exchange.getMessage().setHeader(Kinesis2Constants.APPROX_ARRIVAL_TIME, dataRecord.approximateArrivalTimestamp()); exchange.getMessage().setHeader(Kinesis2Constants.PARTITION_KEY, dataRecord.partitionKey()); exchange.getMessage().setHeader(Kinesis2Constants.SEQUENCE_NUMBER, dataRecord.sequenceNumber()); exchange.getMessage().setHeader(Kinesis2Constants.SHARD_ID, shardId); if (dataRecord.approximateArrivalTimestamp() != null) { long ts = dataRecord.approximateArrivalTimestamp().getEpochSecond() * 1000; exchange.getMessage().setHeader(Kinesis2Constants.MESSAGE_TIMESTAMP, ts); } return exchange; } }
CamelKinesisRecordProcessor
java
spring-projects__spring-boot
module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/observation/GraphQlObservationAutoConfigurationTests.java
{ "start": 3531, "end": 3785 }
class ____ { @Bean GraphQlObservationInstrumentation customInstrumentation(ObservationRegistry registry) { return new GraphQlObservationInstrumentation(registry); } } @Configuration(proxyBeanMethods = false) static
InstrumentationConfiguration
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/pipes/PipesReducer.java
{ "start": 1378, "end": 4457 }
class ____<K2 extends WritableComparable, V2 extends Writable, K3 extends WritableComparable, V3 extends Writable> implements Reducer<K2, V2, K3, V3> { private static final Logger LOG = LoggerFactory.getLogger(PipesReducer.class.getName()); private JobConf job; private Application<K2, V2, K3, V3> application = null; private DownwardProtocol<K2, V2> downlink = null; private boolean isOk = true; private boolean skipping = false; public void configure(JobConf job) { this.job = job; //disable the auto increment of the counter. For pipes, no of processed //records could be different(equal or less) than the no of records input. SkipBadRecords.setAutoIncrReducerProcCount(job, false); skipping = job.getBoolean(MRJobConfig.SKIP_RECORDS, false); } /** * Process all of the keys and values. Start up the application if we haven't * started it yet. */ public void reduce(K2 key, Iterator<V2> values, OutputCollector<K3, V3> output, Reporter reporter ) throws IOException { isOk = false; startApplication(output, reporter); downlink.reduceKey(key); while (values.hasNext()) { downlink.reduceValue(values.next()); } if(skipping) { //flush the streams on every record input if running in skip mode //so that we don't buffer other records surrounding a bad record. downlink.flush(); } isOk = true; } @SuppressWarnings("unchecked") private void startApplication(OutputCollector<K3, V3> output, Reporter reporter) throws IOException { if (application == null) { try { LOG.info("starting application"); application = new Application<K2, V2, K3, V3>( job, null, output, reporter, (Class<? extends K3>) job.getOutputKeyClass(), (Class<? extends V3>) job.getOutputValueClass()); downlink = application.getDownlink(); } catch (InterruptedException ie) { throw new RuntimeException("interrupted", ie); } int reduce=0; downlink.runReduce(reduce, Submitter.getIsJavaRecordWriter(job)); } } /** * Handle the end of the input by closing down the application. */ public void close() throws IOException { // if we haven't started the application, we have nothing to do if (isOk) { OutputCollector<K3, V3> nullCollector = new OutputCollector<K3, V3>() { public void collect(K3 key, V3 value) throws IOException { // NULL } }; startApplication(nullCollector, Reporter.NULL); } try { if (isOk) { application.getDownlink().endOfInput(); } else { // send the abort to the application and let it clean up application.getDownlink().abort(); } LOG.info("waiting for finish"); application.waitForFinish(); LOG.info("got done"); } catch (Throwable t) { application.abort(t); } finally { application.cleanup(); } } }
PipesReducer
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/server/TestServer.java
{ "start": 18990, "end": 19137 }
class ____ extends MyService { public MyService2() { super("s2", MyService2.class, null, true, false); } } public static
MyService2
java
elastic__elasticsearch
client/rest/src/main/java/org/elasticsearch/client/HttpAsyncResponseConsumerFactory.java
{ "start": 1412, "end": 2162 }
interface ____ { /** * Creates the default type of {@link HttpAsyncResponseConsumer}, based on heap buffering with a buffer limit of 100MB. */ HttpAsyncResponseConsumerFactory DEFAULT = new HeapBufferedResponseConsumerFactory(DEFAULT_BUFFER_LIMIT); /** * Creates the {@link HttpAsyncResponseConsumer}, called once per request attempt. */ HttpAsyncResponseConsumer<HttpResponse> createHttpAsyncResponseConsumer(); /** * Default factory used to create instances of {@link HttpAsyncResponseConsumer}. * Creates one instance of {@link HeapBufferedAsyncResponseConsumer} for each request attempt, with a configurable * buffer limit which defaults to 100MB. */
HttpAsyncResponseConsumerFactory
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/support/TransactionSupportTests.java
{ "start": 13558, "end": 15446 }
class ____ { private final AbstractPlatformTransactionManager tm = new TestTransactionManager(false, true); @Test void setTransactionSynchronizationNameToUnsupportedValues() { assertThatIllegalArgumentException().isThrownBy(() -> tm.setTransactionSynchronizationName(null)); assertThatIllegalArgumentException().isThrownBy(() -> tm.setTransactionSynchronizationName(" ")); assertThatIllegalArgumentException().isThrownBy(() -> tm.setTransactionSynchronizationName("bogus")); } /** * Verify that the internal 'constants' map is properly configured for all * SYNCHRONIZATION_ constants defined in {@link AbstractPlatformTransactionManager}. */ @Test void setTransactionSynchronizationNameToAllSupportedValues() { Set<Integer> uniqueValues = new HashSet<>(); streamSynchronizationConstants() .forEach(name -> { tm.setTransactionSynchronizationName(name); int transactionSynchronization = tm.getTransactionSynchronization(); int expected = AbstractPlatformTransactionManager.constants.get(name); assertThat(transactionSynchronization).isEqualTo(expected); uniqueValues.add(transactionSynchronization); }); assertThat(uniqueValues).containsExactlyInAnyOrderElementsOf(AbstractPlatformTransactionManager.constants.values()); } @Test void setTransactionSynchronization() { tm.setTransactionSynchronization(SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); assertThat(tm.getTransactionSynchronization()).isEqualTo(SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } private static Stream<String> streamSynchronizationConstants() { return Arrays.stream(AbstractPlatformTransactionManager.class.getFields()) .filter(ReflectionUtils::isPublicStaticFinal) .map(Field::getName) .filter(name -> name.startsWith("SYNCHRONIZATION_")); } } @Nested
AbstractPlatformTransactionManagerConfigurationTests
java
google__jimfs
jimfs/src/test/java/com/google/common/jimfs/AbstractPathMatcherTest.java
{ "start": 1280, "end": 1383 }
class ____ tests of {@link PathMatcher} implementations. * * @author Colin Decker */ public abstract
for
java
netty__netty
transport/src/main/java/io/netty/channel/PendingWriteQueue.java
{ "start": 1422, "end": 4720 }
class ____ { private static final InternalLogger logger = InternalLoggerFactory.getInstance(PendingWriteQueue.class); // Assuming a 64-bit JVM: // - 16 bytes object header // - 4 reference fields // - 1 long fields private static final int PENDING_WRITE_OVERHEAD = SystemPropertyUtil.getInt("io.netty.transport.pendingWriteSizeOverhead", 64); private final ChannelOutboundInvoker invoker; private final EventExecutor executor; private final PendingBytesTracker tracker; // head and tail pointers for the linked-list structure. If empty head and tail are null. private PendingWrite head; private PendingWrite tail; private int size; private long bytes; public PendingWriteQueue(ChannelHandlerContext ctx) { tracker = PendingBytesTracker.newTracker(ctx.channel()); this.invoker = ctx; this.executor = ctx.executor(); } public PendingWriteQueue(Channel channel) { tracker = PendingBytesTracker.newTracker(channel); this.invoker = channel; this.executor = channel.eventLoop(); } /** * Returns {@code true} if there are no pending write operations left in this queue. */ public boolean isEmpty() { assert executor.inEventLoop(); return head == null; } /** * Returns the number of pending write operations. */ public int size() { assert executor.inEventLoop(); return size; } /** * Returns the total number of bytes that are pending because of pending messages. This is only an estimate so * it should only be treated as a hint. */ public long bytes() { assert executor.inEventLoop(); return bytes; } private int size(Object msg) { // It is possible for writes to be triggered from removeAndFailAll(). To preserve ordering, // we should add them to the queue and let removeAndFailAll() fail them later. int messageSize = tracker.size(msg); if (messageSize < 0) { // Size may be unknown so just use 0 messageSize = 0; } return messageSize + PENDING_WRITE_OVERHEAD; } /** * Add the given {@code msg} and {@link ChannelPromise}. */ public void add(Object msg, ChannelPromise promise) { assert executor.inEventLoop(); ObjectUtil.checkNotNull(msg, "msg"); ObjectUtil.checkNotNull(promise, "promise"); // It is possible for writes to be triggered from removeAndFailAll(). To preserve ordering, // we should add them to the queue and let removeAndFailAll() fail them later. int messageSize = size(msg); PendingWrite write = PendingWrite.newInstance(msg, messageSize, promise); PendingWrite currentTail = tail; if (currentTail == null) { tail = head = write; } else { currentTail.next = write; tail = write; } size ++; bytes += messageSize; tracker.incrementPendingOutboundBytes(write.size); // Touch the message to make it easier to debug buffer leaks. // this save both checking against the ReferenceCounted interface // and makes better use of virtual calls vs
PendingWriteQueue
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/ApiVersionTests.java
{ "start": 1352, "end": 2668 }
class ____ { @Test void header() { String header = "API-Version"; Map<String, String> result = performRequest( configurer -> configurer.useRequestHeader(header), ApiVersionInserter.useHeader(header)); assertThat(result.get(header)).isEqualTo("1.2"); } @Test void queryParam() { String param = "api-version"; Map<String, String> result = performRequest( configurer -> configurer.useQueryParam(param), ApiVersionInserter.useQueryParam(param)); assertThat(result.get("query")).isEqualTo(param + "=1.2"); } @Test void pathSegment() { Map<String, String> result = performRequest( configurer -> configurer.usePathSegment(0), ApiVersionInserter.usePathSegment(0)); assertThat(result.get("path")).isEqualTo("/1.2/path"); } @SuppressWarnings("unchecked") private Map<String, String> performRequest( Consumer<ApiVersionConfigurer> versionConfigurer, ApiVersionInserter inserter) { WebTestClient client = WebTestClient.bindToController(new TestController()) .apiVersioning(versionConfigurer) .configureClient() .baseUrl("/path") .apiVersionInserter(inserter) .build(); return client.get() .apiVersion(1.2) .exchange() .returnResult(Map.class) .getResponseBody() .blockFirst(); } @RestController static
ApiVersionTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleForeignKeyDescriptor.java
{ "start": 3018, "end": 21943 }
class ____ implements ForeignKeyDescriptor, BasicValuedModelPart, FetchOptions { private final SimpleForeignKeyDescriptorSide keySide; private final SimpleForeignKeyDescriptorSide targetSide; private final boolean refersToPrimaryKey; private final boolean hasConstraint; private AssociationKey associationKey; public SimpleForeignKeyDescriptor( ManagedMappingType keyDeclaringType, BasicValuedModelPart keyModelPart, PropertyAccess keyPropertyAccess, SelectableMapping keySelectableMapping, BasicValuedModelPart targetModelPart, boolean insertable, boolean updateable, boolean refersToPrimaryKey, boolean hasConstraint) { this( BasicAttributeMapping.withSelectableMapping( keyDeclaringType, keyModelPart, keyPropertyAccess, insertable, updateable, keySelectableMapping ), targetModelPart, refersToPrimaryKey, hasConstraint, false ); } public SimpleForeignKeyDescriptor( BasicValuedModelPart keyModelPart, BasicValuedModelPart targetModelPart, boolean refersToPrimaryKey, boolean hasConstraint, boolean swapDirection) { assert targetModelPart != null; if ( swapDirection ) { keySide = new SimpleForeignKeyDescriptorSide( Nature.KEY, targetModelPart ); targetSide = new SimpleForeignKeyDescriptorSide( Nature.TARGET, keyModelPart ); } else { keySide = new SimpleForeignKeyDescriptorSide( Nature.KEY, keyModelPart ); targetSide = new SimpleForeignKeyDescriptorSide( Nature.TARGET, targetModelPart ); } this.refersToPrimaryKey = refersToPrimaryKey; this.hasConstraint = hasConstraint; } public SimpleForeignKeyDescriptor( ManagedMappingType keyDeclaringType, SelectableMapping keySelectableMapping, BasicValuedModelPart targetModelPart, boolean refersToPrimaryKey, boolean hasConstraint) { this( keyDeclaringType, keySelectableMapping, ( (PropertyBasedMapping) targetModelPart ).getPropertyAccess(), targetModelPart, refersToPrimaryKey, hasConstraint, false ); } /** * */ public SimpleForeignKeyDescriptor( ManagedMappingType keyDeclaringType, SelectableMapping keySelectableMapping, PropertyAccess valueAccess, BasicValuedModelPart targetModelPart, boolean refersToPrimaryKey, boolean hasConstraint, boolean swapDirection) { this( BasicAttributeMapping.withSelectableMapping( keyDeclaringType, targetModelPart, valueAccess, keySelectableMapping.isInsertable(), keySelectableMapping.isUpdateable(), keySelectableMapping ), targetModelPart, refersToPrimaryKey, hasConstraint, swapDirection ); } /* * Used by Hibernate Reactive */ @SuppressWarnings("unused") protected SimpleForeignKeyDescriptor(SimpleForeignKeyDescriptor original) { keySide = original.keySide; targetSide = original.targetSide; refersToPrimaryKey = original.refersToPrimaryKey; hasConstraint = original.hasConstraint; associationKey = original.associationKey; } @Override public String getKeyTable() { return keySide.getModelPart().getContainingTableExpression(); } @Override public String getTargetTable() { return targetSide.getModelPart().getContainingTableExpression(); } @Override public BasicValuedModelPart getKeyPart() { return keySide.getModelPart(); } @Override public BasicValuedModelPart getTargetPart() { return targetSide.getModelPart(); } @Override public boolean isKeyPart(ValuedModelPart modelPart) { return this == modelPart || keySide.getModelPart() == modelPart; } @Override public Side getKeySide() { return keySide; } @Override public Side getTargetSide() { return targetSide; } @Override public int compare(Object key1, Object key2) { //noinspection unchecked,rawtypes return ( (JavaType) keySide.getModelPart().getJavaType() ).getComparator().compare( key1, key2 ); } @Override public ForeignKeyDescriptor withKeySelectionMapping( ManagedMappingType declaringType, TableGroupProducer declaringTableGroupProducer, IntFunction<SelectableMapping> selectableMappingAccess, MappingModelCreationProcess creationProcess) { final var selectableMapping = selectableMappingAccess.apply( 0 ); return new SimpleForeignKeyDescriptor( declaringType, keySide.getModelPart(), ( (PropertyBasedMapping) keySide.getModelPart() ).getPropertyAccess(), selectableMapping, targetSide.getModelPart(), selectableMapping.isInsertable(), selectableMapping.isUpdateable(), refersToPrimaryKey, hasConstraint ); } @Override public ForeignKeyDescriptor withTargetPart(ValuedModelPart targetPart) { return new SimpleForeignKeyDescriptor( keySide.getModelPart(), targetPart.asBasicValuedModelPart(), refersToPrimaryKey, hasConstraint, false ); } @Override public DomainResult<?> createKeyDomainResult( NavigablePath navigablePath, TableGroup targetTableGroup, FetchParent fetchParent, DomainResultCreationState creationState) { assert isTargetTableGroup( targetTableGroup ); return createDomainResult( navigablePath.append( ForeignKeyDescriptor.PART_NAME ), targetTableGroup, keySide.getModelPart(), fetchParent, creationState ); } @Override public DomainResult<?> createKeyDomainResult( NavigablePath navigablePath, TableGroup targetTableGroup, Nature fromSide, FetchParent fetchParent, DomainResultCreationState creationState) { assert fromSide == Nature.TARGET ? targetTableGroup.getTableReference( navigablePath, associationKey.table(), false ) != null : isTargetTableGroup( targetTableGroup ); return createDomainResult( navigablePath.append( ForeignKeyDescriptor.PART_NAME ), targetTableGroup, keySide.getModelPart(), fetchParent, creationState ); } @Override public DomainResult<?> createTargetDomainResult( NavigablePath navigablePath, TableGroup targetTableGroup, FetchParent fetchParent, DomainResultCreationState creationState) { assert isTargetTableGroup( targetTableGroup ); return createDomainResult( navigablePath.append( ForeignKeyDescriptor.TARGET_PART_NAME ), targetTableGroup, targetSide.getModelPart(), fetchParent, creationState ); } @Override public <T> DomainResult<T> createDomainResult( NavigablePath navigablePath, TableGroup targetTableGroup, String resultVariable, DomainResultCreationState creationState) { assert isTargetTableGroup( targetTableGroup ); return createDomainResult( navigablePath.append( ForeignKeyDescriptor.PART_NAME ), targetTableGroup, keySide.getModelPart(), null, creationState ); } private boolean isTargetTableGroup(TableGroup tableGroup) { tableGroup = getUnderlyingTableGroup( tableGroup ); final var tableGroupProducer = tableGroup instanceof OneToManyTableGroup oneToManyTableGroup ? (TableGroupProducer) oneToManyTableGroup.getElementTableGroup().getModelPart() : (TableGroupProducer) tableGroup.getModelPart(); return tableGroupProducer.containsTableReference( targetSide.getModelPart().getContainingTableExpression() ); } private static TableGroup getUnderlyingTableGroup(TableGroup tableGroup) { if ( tableGroup.isVirtual() ) { tableGroup = getUnderlyingTableGroup( ( (VirtualTableGroup) tableGroup ).getUnderlyingTableGroup() ); } return tableGroup; } @Override public void applySqlSelections( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState) { throw new UnsupportedOperationException(); } @Override public void applySqlSelections( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState, BiConsumer<SqlSelection, JdbcMapping> selectionConsumer) { throw new UnsupportedOperationException(); } private <T> DomainResult<T> createDomainResult( NavigablePath navigablePath, TableGroup tableGroup, BasicValuedModelPart selectableMapping, FetchParent fetchParent, DomainResultCreationState creationState) { final var sqlAstCreationState = creationState.getSqlAstCreationState(); final var sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); final TableReference tableReference; try { tableReference = tableGroup.resolveTableReference( navigablePath, selectableMapping, selectableMapping.getContainingTableExpression() ); } catch (IllegalStateException tableNotFoundException) { throw new UnknownTableReferenceException( selectableMapping.getContainingTableExpression(), String.format( Locale.ROOT, "Unable to determine TableReference (`%s`) for `%s`", selectableMapping.getContainingTableExpression(), getNavigableRole().getFullPath() ) ); } final var javaType = selectableMapping.getJdbcMapping().getJdbcJavaType(); final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( sqlExpressionResolver.resolveSqlExpression( tableReference, selectableMapping ), javaType, fetchParent, sqlAstCreationState.getCreationContext().getTypeConfiguration() ); final var selectionType = sqlSelection.getExpressionType(); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), null, selectableMapping.getJdbcMapping(), navigablePath, // if the expression type is different that the expected type coerce the value selectionType != null && selectionType.getSingleJdbcMapping().getJdbcJavaType() != javaType, !sqlSelection.isVirtual() ); } @Override public Predicate generateJoinPredicate( TableReference targetSideReference, TableReference keySideReference, SqlAstCreationState creationState) { return new ComparisonPredicate( new ColumnReference( targetSideReference, targetSide.getModelPart() ), ComparisonOperator.EQUAL, new ColumnReference( keySideReference, keySide.getModelPart() ) ); } @Override public Predicate generateJoinPredicate( TableGroup targetSideTableGroup, TableGroup keySideTableGroup, SqlAstCreationState creationState) { final var lhsTableReference = targetSideTableGroup.resolveTableReference( targetSideTableGroup.getNavigablePath(), targetSide.getModelPart().getContainingTableExpression() ); final var rhsTableKeyReference = keySideTableGroup.resolveTableReference( null, keySide.getModelPart().getContainingTableExpression() ); return generateJoinPredicate( lhsTableReference, rhsTableKeyReference, creationState ); } @Override public boolean isSimpleJoinPredicate(Predicate predicate) { if ( !(predicate instanceof ComparisonPredicate comparisonPredicate) ) { return false; } if ( comparisonPredicate.getOperator() != ComparisonOperator.EQUAL ) { return false; } final var lhsExpr = comparisonPredicate.getLeftHandExpression(); final var rhsExpr = comparisonPredicate.getRightHandExpression(); if ( lhsExpr instanceof ColumnReference lhsColumnRef && rhsExpr instanceof ColumnReference rhsColumnRef ) { final String lhs = lhsColumnRef.getColumnExpression(); final String rhs = rhsColumnRef.getColumnExpression(); final String keyExpression = keySide.getModelPart().getSelectionExpression(); final String targetExpression = targetSide.getModelPart().getSelectionExpression(); return lhs.equals( keyExpression ) && rhs.equals( targetExpression ) || lhs.equals( targetExpression ) && rhs.equals( keyExpression ); } else { return false; } } @Override public MappingType getPartMappingType() { return targetSide.getModelPart().getMappedType(); } @Override public int forEachSelectable(int offset, SelectableConsumer consumer) { consumer.accept( offset, this ); return 1; } @Override public JavaType<?> getJavaType() { return targetSide.getModelPart().getJdbcMapping().getJavaTypeDescriptor(); } @Override public NavigableRole getNavigableRole() { return targetSide.getModelPart().getNavigableRole(); } @Override public EntityMappingType findContainingEntityMapping() { return targetSide.getModelPart().findContainingEntityMapping(); } @Override public Object disassemble(Object value, SharedSessionContractImplementor session) { return getJdbcMapping().convertToRelationalValue( value ); } @Override public void addToCacheKey(MutableCacheKeyBuilder cacheKey, Object value, SharedSessionContractImplementor session) { CacheHelper.addBasicValueToCacheKey( cacheKey, value, getJdbcMapping(), session ); } @Override public Object getAssociationKeyFromSide( Object targetObject, ForeignKeyDescriptor.Side side, SharedSessionContractImplementor session) { if ( targetObject == null ) { return null; } final var lazyInitializer = extractLazyInitializer( targetObject ); if ( lazyInitializer != null ) { if ( refersToPrimaryKey ) { return lazyInitializer.getInternalIdentifier(); } else { targetObject = lazyInitializer.getImplementation(); } } final var modelPart = side.getModelPart(); if ( modelPart.isEntityIdentifierMapping() ) { return ( (EntityIdentifierMapping) modelPart ).getIdentifierIfNotUnsaved( targetObject, session ); } if ( lazyInitializer == null && isPersistentAttributeInterceptable( targetObject ) ) { if ( asPersistentAttributeInterceptable( targetObject ).$$_hibernate_getInterceptor() instanceof EnhancementAsProxyLazinessInterceptor lazinessInterceptor && !lazinessInterceptor.isInitialized() ) { Hibernate.initialize( targetObject ); } } return ( (PropertyBasedMapping) modelPart ).getPropertyAccess().getGetter().get( targetObject ); } @Override public <X, Y> int forEachDisassembledJdbcValue( Object value, int offset, X x, Y y, JdbcValuesBiConsumer<X, Y> valuesConsumer, SharedSessionContractImplementor session) { valuesConsumer.consume( offset, x, y, value, getJdbcMapping() ); return getJdbcTypeCount(); } @Override public <X, Y> int breakDownJdbcValues( Object domainValue, int offset, X x, Y y, JdbcValueBiConsumer<X, Y> valueConsumer, SharedSessionContractImplementor session) { valueConsumer.consume( offset, x, y, disassemble( domainValue, session ), keySide.getModelPart() ); return getJdbcTypeCount(); } @Override public int visitKeySelectables(int offset, SelectableConsumer consumer) { consumer.accept( offset, keySide.getModelPart() ); return getJdbcTypeCount(); } @Override public int visitTargetSelectables(int offset, SelectableConsumer consumer) { consumer.accept( offset, targetSide.getModelPart() ); return getJdbcTypeCount(); } @Override public boolean hasConstraint() { return hasConstraint; } @Override public AssociationKey getAssociationKey() { if ( associationKey == null ) { final List<String> associationKeyColumns = Collections.singletonList( keySide.getModelPart().getSelectionExpression() ); associationKey = new AssociationKey( keySide.getModelPart().getContainingTableExpression(), associationKeyColumns ); } return associationKey; } @Override public JdbcMapping getJdbcMapping(int index) { if ( index != 0 ) { throw new IndexOutOfBoundsException( index ); } return targetSide.getModelPart().getJdbcMapping(); } @Override public JdbcMapping getSingleJdbcMapping() { return targetSide.getModelPart().getJdbcMapping(); } @Override public int forEachJdbcType(int offset, IndexedConsumer<JdbcMapping> action) { action.accept( offset, targetSide.getModelPart().getJdbcMapping() ); return getJdbcTypeCount(); } @Override public <X, Y> int forEachJdbcValue( Object value, int offset, X x, Y y, JdbcValuesBiConsumer<X, Y> valuesConsumer, SharedSessionContractImplementor session) { valuesConsumer.consume( offset, x, y, disassemble( value, session ), targetSide.getModelPart().getJdbcMapping() ); return getJdbcTypeCount(); } @Override public String getContainingTableExpression() { return keySide.getModelPart().getContainingTableExpression(); } @Override public String getSelectionExpression() { return keySide.getModelPart().getSelectionExpression(); } @Override public SelectableMapping getSelectable(int columnIndex) { return keySide.getModelPart(); } @Override public boolean isFormula() { return keySide.getModelPart().isFormula(); } @Override public boolean isNullable() { return keySide.getModelPart().isNullable(); } @Override public boolean isInsertable() { return keySide.getModelPart().isInsertable(); } @Override public boolean isUpdateable() { return keySide.getModelPart().isUpdateable(); } @Override public boolean isPartitioned() { return keySide.getModelPart().isPartitioned(); } @Override public @Nullable String getCustomReadExpression() { return keySide.getModelPart().getCustomReadExpression(); } @Override public @Nullable String getCustomWriteExpression() { return keySide.getModelPart().getCustomWriteExpression(); } @Override public @Nullable String getColumnDefinition() { return keySide.getModelPart().getColumnDefinition(); } @Override public @Nullable Long getLength() { return keySide.getModelPart().getLength(); } @Override public @Nullable Integer getArrayLength() { return keySide.getModelPart().getArrayLength(); } @Override public @Nullable Integer getPrecision() { return keySide.getModelPart().getPrecision(); } @Override public @Nullable Integer getScale() { return keySide.getModelPart().getScale(); } @Override public @Nullable Integer getTemporalPrecision() { return keySide.getModelPart().getTemporalPrecision(); } @Override public String getFetchableName() { return PART_NAME; } @Override public int getFetchableKey() { throw new UnsupportedOperationException(); } @Override public FetchOptions getMappedFetchOptions() { return this; } @Override public FetchStyle getStyle() { return FetchStyle.JOIN; } @Override public FetchTiming getTiming() { return FetchTiming.IMMEDIATE; } @Override public Fetch generateFetch( FetchParent fetchParent, NavigablePath fetchablePath, FetchTiming fetchTiming, boolean selected, String resultVariable, DomainResultCreationState creationState) { return null; } @Override public MappingType getMappedType() { return null; } @Override public JdbcMapping getJdbcMapping() { return keySide.getModelPart().getJdbcMapping(); } @Override public String toString() { return String.format( "SimpleForeignKeyDescriptor : %s.%s -> %s.%s", keySide.getModelPart().getContainingTableExpression(), keySide.getModelPart().getSelectionExpression(), targetSide.getModelPart().getContainingTableExpression(), targetSide.getModelPart().getSelectionExpression() ); } @Override public boolean isEmbedded() { return false; } }
SimpleForeignKeyDescriptor
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/filter/InFilter.java
{ "start": 662, "end": 991 }
class ____ extends FilterOperator<Object[]> { private InFilter(Object... filterParameter) { super(filterParameter); } public static InFilter in(Object... values) { return new InFilter(values); } @Override public <E> Filters<E> applyOn(Filters<E> filters) { return filters.in(filterParameter); } }
InFilter
java
apache__camel
components/camel-xslt/src/main/java/org/apache/camel/component/xslt/XsltMessageLogger.java
{ "start": 1240, "end": 1463 }
interface ____ { /** * Consumes a message generated by a XSLT transformation. * * @param message the message generated by the XSLT transformation. */ void accept(String message); }
XsltMessageLogger
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpPortMappingsTests.java
{ "start": 2815, "end": 3479 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .anyRequest().hasRole("USER")) .portMapper((mapper) -> mapper .http(9080).mapsTo(9443)) .requiresChannel((channel) -> channel .requestMatchers("/login", "/secured/**").requiresSecure() .anyRequest().requiresInsecure()); // @formatter:on return http.build(); } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin()); } } }
HttpInterceptUrlWithPortMapperConfig
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/AbstractTableUpdateBuilder.java
{ "start": 827, "end": 3409 }
class ____<O extends MutationOperation> extends AbstractRestrictedTableMutationBuilder<O, RestrictedTableMutation<O>> implements TableUpdateBuilder<O> { private final List<ColumnValueBinding> keyBindings = new ArrayList<>(); private final List<ColumnValueBinding> valueBindings = new ArrayList<>(); private List<ColumnValueBinding> lobValueBindings; private String sqlComment; public AbstractTableUpdateBuilder( MutationTarget<?> mutationTarget, TableMapping tableMapping, SessionFactoryImplementor sessionFactory) { super( MutationType.UPDATE, mutationTarget, tableMapping, sessionFactory ); this.sqlComment = "update for " + mutationTarget.getRolePath(); } public AbstractTableUpdateBuilder( MutationTarget<?> mutationTarget, MutatingTableReference tableReference, SessionFactoryImplementor sessionFactory) { super( MutationType.UPDATE, mutationTarget, tableReference, sessionFactory ); } public String getSqlComment() { return sqlComment; } public void setSqlComment(String sqlComment) { this.sqlComment = sqlComment; } /** * The bindings for each key restriction (WHERE clause). * * @see TableUpdate#getKeyBindings */ protected List<ColumnValueBinding> getKeyBindings() { return keyBindings; } /** * The (non-LOB) bindings for each column being updated (SET clause) * * @see TableUpdate#getValueBindings */ protected List<ColumnValueBinding> getValueBindings() { return valueBindings; } /** * @apiNote The distinction with {@link #getValueBindings} is to help * in cases e.g. where a dialect needs to order all LOB bindings after * all non-LOB bindings * * @see TableUpdate#getValueBindings */ protected List<ColumnValueBinding> getLobValueBindings() { return lobValueBindings; } @Override public void addValueColumn(String columnWriteFragment, SelectableMapping selectableMapping) { final ColumnValueBinding valueBinding = createValueBinding( columnWriteFragment, selectableMapping ); if ( selectableMapping.isLob() && getJdbcServices().getDialect().forceLobAsLastValue() ) { if ( lobValueBindings == null ) { lobValueBindings = new ArrayList<>(); } lobValueBindings.add( valueBinding ); } else { valueBindings.add( valueBinding ); } } @Override public void addValueColumn(ColumnValueBinding valueBinding) { valueBindings.add( valueBinding ); } @Override public void addKeyColumn(String columnWriteFragment, SelectableMapping selectableMapping) { addColumn( columnWriteFragment, selectableMapping, keyBindings ); } }
AbstractTableUpdateBuilder
java
quarkusio__quarkus
extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/timeseries/ReactiveTimeSeriesCommands.java
{ "start": 661, "end": 19035 }
interface ____<K> extends ReactiveRedisCommands { /** * Execute the command <a href="https://redis.io/commands/ts.create/">TS.CREATE</a>. * Summary: Create a new time series * Group: time series * * @param key the key name for the time series must not be {@code null} * @param args the creation arguments. * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsCreate(K key, CreateArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.create/">TS.CREATE</a>. * Summary: Create a new time series * Group: time series * * @param key the key name for the time series must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsCreate(K key); /** * Execute the command <a href="https://redis.io/commands/ts.add/">TS.ADD</a>. * Summary: Append a sample to a time series * Group: time series * * @param key the key name for the time series must not be {@code null} * @param timestamp the (long) UNIX sample timestamp in milliseconds or {@code -1} to set the timestamp according * to the server clock. * @param value the numeric data value of the sample. * @param args the creation arguments. * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsAdd(K key, long timestamp, double value, AddArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.add/">TS.ADD</a>. * Summary: Append a sample to a time series * Group: time series * * @param key the key name for the time series, must not be {@code null} * @param timestamp the (long) UNIX sample timestamp in milliseconds * @param value the numeric data value of the sample * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsAdd(K key, long timestamp, double value); /** * Execute the command <a href="https://redis.io/commands/ts.add/">TS.ADD</a>. * Summary: Append a sample to a time series * Group: time series * <p> * Unlike {@link #tsAdd(Object, long, double)}, set the timestamp according to the server clock. * * @param key the key name for the time series. must not be {@code null} * @param value the numeric data value of the sample, must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsAdd(K key, double value); /** * Execute the command <a href="https://redis.io/commands/ts.add/">TS.ADD</a>. * Summary: Append a sample to a time series * Group: time series * <p> * Unlike {@link #tsAdd(Object, long, double, AddArgs)}, set the timestamp according to the server clock. * * @param key the key name for the time series must not be {@code null} * @param value the numeric data value of the sample. * @param args the creation arguments. * @return A uni emitting {@code null} when the operation completes */ Uni<Void> tsAdd(K key, double value, AddArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.alter/">TS.ALTER</a>. * Summary: Update the retention, chunk size, duplicate policy, and labels of an existing time series * Group: time series * * @param key the key name for the time series, must not be {@code null} * @param args the alter parameters, must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsAlter(K key, AlterArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.createrule/">TS.CREATERULE</a>. * Summary: Create a compaction rule * Group: time series * * @param key the key name for the time series, must not be {@code null} * @param destKey the key name for destination (compacted) time series. It must be created before TS.CREATERULE * is called. Must not be {@code null}. * @param aggregation the aggregation function, must not be {@code null} * @param bucketDuration the duration of each bucket, must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsCreateRule(K key, K destKey, Aggregation aggregation, Duration bucketDuration); /** * Execute the command <a href="https://redis.io/commands/ts.createrule/">TS.CREATERULE</a>. * Summary: Create a compaction rule * Group: time series * * @param key the key name for the time series, must not be {@code null} * @param destKey the key name for destination (compacted) time series. It must be created before TS.CREATERULE * is called. Must not be {@code null}. * @param aggregation the aggregation function, must not be {@code null} * @param bucketDuration the duration of each bucket, must not be {@code null} * @param alignTimestamp when set, ensures that there is a bucket that starts exactly at alignTimestamp and aligns * all other buckets accordingly. It is expressed in milliseconds. The default value is 0 aligned * with the epoch. For example, if bucketDuration is 24 hours (24 * 3600 * 1000), setting * alignTimestamp to 6 hours after the epoch (6 * 3600 * 1000) ensures that each bucket’s * timeframe is [06:00 .. 06:00). * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsCreateRule(K key, K destKey, Aggregation aggregation, Duration bucketDuration, long alignTimestamp); /** * Execute the command <a href="https://redis.io/commands/ts.decrby/">TS.DECRBY</a>. * Summary: Decrease the value of the sample with the maximum existing timestamp, or create a new sample with a * value equal to the value of the sample with the maximum existing timestamp with a given decrement * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @param value the numeric data value of the sample, must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsDecrBy(K key, double value); /** * Execute the command <a href="https://redis.io/commands/ts.decrby/">TS.DECRBY</a>. * Summary: Decrease the value of the sample with the maximum existing timestamp, or create a new sample with a * value equal to the value of the sample with the maximum existing timestamp with a given decrement * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @param value the numeric data value of the sample, must not be {@code null} * @param args the extra command parameters * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsDecrBy(K key, double value, IncrementArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.del/">TS.DEL</a>. * Summary: Delete all samples between two timestamps for a given time series * Group: time series * <p> * The given timestamp interval is closed (inclusive), meaning that samples whose timestamp equals the fromTimestamp * or toTimestamp are also deleted. * * @param key the key name for the time series. must not be {@code null} * @param fromTimestamp the start timestamp for the range deletion. * @param toTimestamp the end timestamp for the range deletion. * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsDel(K key, long fromTimestamp, long toTimestamp); /** * Execute the command <a href="https://redis.io/commands/ts.deleterule/">TS.DELETERULE</a>. * Summary: Delete a compaction rule * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @param destKey the key name for destination (compacted) time series. Note that the command does not delete the * compacted series. Must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsDeleteRule(K key, K destKey); /** * Execute the command <a href="https://redis.io/commands/ts.get/">TS.GET</a>. * Summary: Get the last sample * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @return A uni emitting a {@code Sample}, i.e. a couple containing the timestamp and the value. **/ Uni<Sample> tsGet(K key); /** * Execute the command <a href="https://redis.io/commands/ts.get/">TS.GET</a>. * Summary: Get the last sample * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @param latest used when a time series is a compaction. With LATEST set to {@code true}, TS.MRANGE also reports * the compacted value of the latest possibly partial bucket, given that this bucket's start time * falls within [fromTimestamp, toTimestamp]. Without LATEST, TS.MRANGE does not report the latest * possibly partial bucket. When a time series is not a compaction, LATEST is ignored. * @return A uni emitting a {@code Sample}, i.e. a couple containing the timestamp and the value. **/ Uni<Sample> tsGet(K key, boolean latest); /** * Execute the command <a href="https://redis.io/commands/ts.incrby/">TS.INCRBY</a>. * Summary: Increase the value of the sample with the maximum existing timestamp, or create a new sample with a * value equal to the value of the sample with the maximum existing timestamp with a given increment. * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @param value the numeric data value of the sample, must not be {@code null} * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsIncrBy(K key, double value); /** * Execute the command <a href="https://redis.io/commands/ts.incrby/">TS.INCRBY</a>. * Summary: Increase the value of the sample with the maximum existing timestamp, or create a new sample with a * value equal to the value of the sample with the maximum existing timestamp with a given increment. * Group: time series * <p> * * @param key the key name for the time series. must not be {@code null} * @param value the numeric data value of the sample, must not be {@code null} * @param args the extra command parameters * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsIncrBy(K key, double value, IncrementArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.madd/">TS.MADD</a>. * Summary: Append new samples to one or more time series * Group: time series * * @param samples the set of samples to add to the time series. * @return A uni emitting {@code null} when the operation completes **/ Uni<Void> tsMAdd(SeriesSample<K>... samples); /** * Execute the command <a href="https://redis.io/commands/ts.mget/">TS.MGET</a>. * Summary: Get the last samples matching a specific filter * Group: time series * <p> * * @param args the extra command parameter, must not be {@code null} * @param filters the filters. Instanced are created using the static methods from {@link Filter}. Must not be * {@code null}, or contain a {@code null} value. * @return A uni emitting a Map of {@code String -> SampleGroup}, containing the matching sample grouped by key. * The key is the string representation of the time series key. **/ Uni<Map<String, SampleGroup>> tsMGet(MGetArgs args, Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.mget/">TS.MGET</a>. * Summary: Get the last samples matching a specific filter * Group: time series * <p> * * @param filters the filters. Instanced are created using the static methods from {@link Filter}. Must not be * {@code null}, or contain a {@code null} value. * @return A uni emitting a Map of {@code String -> SampleGroup}, containing the matching sample grouped by key. * The key is the string representation of the time series key. **/ Uni<Map<String, SampleGroup>> tsMGet(Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.mrange/">TS.MRANGE</a>. * Summary: Query a range across multiple time series by filters in forward direction * Group: time series * <p> * * @param range the range, must not be {@code null} * @param filters the filters. Instanced are created using the static methods from {@link Filter}. Must not be * {@code null}, or contain a {@code null} value. * @return A uni emitting a Map of {@code String -> SampleGroup}, containing the matching sample grouped by key. * The key is the string representation of the time series key. **/ Uni<Map<String, SampleGroup>> tsMRange(TimeSeriesRange range, Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.mrange/">TS.MRANGE</a>. * Summary: Query a range across multiple time series by filters in forward direction * Group: time series * <p> * * @param range the range, must not be {@code null} * @param args the extra command parameters * @param filters the filters. Instanced are created using the static methods from {@link Filter}. Must not be * {@code null}, or contain a {@code null} value. * @return A uni emitting a Map of {@code String -> SampleGroup}, containing the matching sample grouped by key. * The key is the string representation of the time series key. **/ Uni<Map<String, SampleGroup>> tsMRange(TimeSeriesRange range, MRangeArgs args, Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.mrevrange/">TS.MREVRANGE</a>. * Summary: Query a range across multiple time series by filters in reverse direction * Group: time series * <p> * * @param range the range, must not be {@code null} * @param filters the filters. Instanced are created using the static methods from {@link Filter}. Must not be * {@code null}, or contain a {@code null} value. * @return A uni emitting a Map of {@code String -> SampleGroup}, containing the matching sample grouped by key. * The key is the string representation of the time series key. **/ Uni<Map<String, SampleGroup>> tsMRevRange(TimeSeriesRange range, Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.mrevrange/">TS.MREVRANGE</a>. * Summary: Query a range across multiple time series by filters in reverse direction * Group: time series * <p> * * @param range the range, must not be {@code null} * @param args the extra command parameters * @param filters the filters. Instanced are created using the static methods from {@link Filter}. Must not be * {@code null}, or contain a {@code null} value. * @return A uni emitting a Map of {@code String -> SampleGroup}, containing the matching sample grouped by key. * The key is the string representation of the time series key. **/ Uni<Map<String, SampleGroup>> tsMRevRange(TimeSeriesRange range, MRangeArgs args, Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.queryindex/">TS.QUERYINDEX</a>. * Summary: Get all time series keys matching a filter list * Group: time series * * @param filters the filter, created from the {@link Filter} class. Must not be {@code null}, must not contain * {@code null} * @return A uni emitting the list of keys containing time series matching the filters **/ Uni<List<K>> tsQueryIndex(Filter... filters); /** * Execute the command <a href="https://redis.io/commands/ts.range/">TS.RANGE</a>. * Summary: Query a range in forward direction * Group: time series * <p> * * @param key the key name for the time series, must not be {@code null} * @param range the range, must not be {@code null} * @return A uni emitting the list of matching sample **/ Uni<List<Sample>> tsRange(K key, TimeSeriesRange range); /** * Execute the command <a href="https://redis.io/commands/ts.range/">TS.RANGE</a>. * Summary: Query a range in forward direction * Group: time series * <p> * * @param key the key name for the time series, must not be {@code null} * @param range the range, must not be {@code null} * @param args the extra command parameters * @return A uni emitting the list of matching sample **/ Uni<List<Sample>> tsRange(K key, TimeSeriesRange range, RangeArgs args); /** * Execute the command <a href="https://redis.io/commands/ts.revrange/">TS.REVRANGE</a>. * Summary: Query a range in reverse direction * Group: time series * <p> * * @param key the key name for the time series, must not be {@code null} * @param range the range, must not be {@code null} * @return A uni emitting the list of matching sample **/ Uni<List<Sample>> tsRevRange(K key, TimeSeriesRange range); /** * Execute the command <a href="https://redis.io/commands/ts.revrange/">TS.REVRANGE</a>. * Summary: Query a range in reverse direction * Group: time series * <p> * * @param key the key name for the time series, must not be {@code null} * @param range the range, must not be {@code null} * @param args the extra command parameters * @return A uni emitting the list of matching sample **/ Uni<List<Sample>> tsRevRange(K key, TimeSeriesRange range, RangeArgs args); }
ReactiveTimeSeriesCommands
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3983PluginResolutionFromProfileReposTest.java
{ "start": 2546, "end": 3095 }
class ____ within current JVM verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven.its.mng3983"); verifier.filterFile("settings.xml", "settings.xml"); verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); verifier.verifyArtifactPresent("org.apache.maven.its.mng3983", "p", "0.1", "jar"); } }
loader
java
apache__camel
components/camel-as2/camel-as2-component/src/generated/java/org/apache/camel/component/as2/converter/ContentTypeConverterLoader.java
{ "start": 889, "end": 2228 }
class ____ implements TypeConverterLoader, CamelContextAware { private CamelContext camelContext; public ContentTypeConverterLoader() { } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { registerConverters(registry); } private void registerConverters(TypeConverterRegistry registry) { addTypeConverter(registry, org.apache.hc.core5.http.ContentType.class, java.lang.String.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.as2.converter.ContentTypeConverter.toContentType((java.lang.String) value); if (false && answer == null) { answer = Void.class; } return answer; }); } private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) { registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method)); } }
ContentTypeConverterLoader
java
grpc__grpc-java
util/src/main/java/io/grpc/util/ForwardingLoadBalancer.java
{ "start": 872, "end": 1931 }
class ____ extends LoadBalancer { /** * Returns the underlying balancer. */ protected abstract LoadBalancer delegate(); @Override public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) { delegate().handleResolvedAddresses(resolvedAddresses); } @Override public void handleNameResolutionError(Status error) { delegate().handleNameResolutionError(error); } @Deprecated @Override public void handleSubchannelState( Subchannel subchannel, ConnectivityStateInfo stateInfo) { delegate().handleSubchannelState(subchannel, stateInfo); } @Override public void shutdown() { delegate().shutdown(); } @Override public boolean canHandleEmptyAddressListFromNameResolution() { return delegate().canHandleEmptyAddressListFromNameResolution(); } @Override public void requestConnection() { delegate().requestConnection(); } @Override public String toString() { return MoreObjects.toStringHelper(this).add("delegate", delegate()).toString(); } }
ForwardingLoadBalancer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/rank/context/RankFeaturePhaseRankShardContext.java
{ "start": 770, "end": 1004 }
class ____ to execute the RankFeature phase on each shard. * In this class, we can fetch the feature data for a given set of documents and pass them back to the coordinator * through the {@link RankShardResult}. */ public abstract
used
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/event/DrainDispatcher.java
{ "start": 960, "end": 1378 }
class ____ extends AsyncDispatcher { private volatile boolean drained = false; private final BlockingQueue<Event> queue; private final Object mutex; public DrainDispatcher() { this(new LinkedBlockingQueue<Event>()); } public DrainDispatcher(BlockingQueue<Event> eventQueue) { super(eventQueue); this.queue = eventQueue; this.mutex = this; // Disable system exit since this
DrainDispatcher
java
alibaba__druid
core/src/test/java/com/alibaba/druid/pool/MaxWaitTest.java
{ "start": 790, "end": 2326 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/sonar"); dataSource.setUsername("sonar"); dataSource.setPassword("sonar"); dataSource.setFilters("stat"); dataSource.setMaxWait(1000); dataSource.setInitialSize(3); dataSource.setMinIdle(3); dataSource.setMaxActive(3); } public void test_maxWait() throws Exception { final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 20; ++i) { Thread thread = new Thread() { public void run() { try { for (int i = 0; i < 10; ++i) { try { Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); stmt.execute("select sleep(" + (i % 5 + 1) + ")"); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } finally { latch.countDown(); } } }; thread.start(); } latch.await(); } }
MaxWaitTest
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestDecoder.java
{ "start": 14327, "end": 14559 }
class ____ extends DecoderException { private static final long serialVersionUID = 1336267941020800769L; } /** * Exception when a field content is too long */ public static final
TooManyFormFieldsException
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointStatsCounts.java
{ "start": 1044, "end": 6807 }
class ____ implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(CheckpointStatsCounts.class); private static final long serialVersionUID = -5229425063269482528L; /** Number of restored checkpoints. */ private long numRestoredCheckpoints; /** Number of total checkpoints (in progress, completed, failed). */ private long numTotalCheckpoints; /** Number of in progress checkpoints. */ private int numInProgressCheckpoints; /** Number of successfully completed checkpoints. */ private long numCompletedCheckpoints; /** Number of failed checkpoints. */ private long numFailedCheckpoints; /** Creates the initial zero checkpoint counts. */ CheckpointStatsCounts() { this(0, 0, 0, 0, 0); } /** * Creates the checkpoint counts with the given counts. * * @param numRestoredCheckpoints Number of restored checkpoints. * @param numTotalCheckpoints Number of total checkpoints (in progress, completed, failed). * @param numInProgressCheckpoints Number of in progress checkpoints. * @param numCompletedCheckpoints Number of successfully completed checkpoints. * @param numFailedCheckpoints Number of failed checkpoints. */ private CheckpointStatsCounts( long numRestoredCheckpoints, long numTotalCheckpoints, int numInProgressCheckpoints, long numCompletedCheckpoints, long numFailedCheckpoints) { checkArgument(numRestoredCheckpoints >= 0, "Negative number of restored checkpoints"); checkArgument(numTotalCheckpoints >= 0, "Negative total number of checkpoints"); checkArgument(numInProgressCheckpoints >= 0, "Negative number of in progress checkpoints"); checkArgument(numCompletedCheckpoints >= 0, "Negative number of completed checkpoints"); checkArgument(numFailedCheckpoints >= 0, "Negative number of failed checkpoints"); this.numRestoredCheckpoints = numRestoredCheckpoints; this.numTotalCheckpoints = numTotalCheckpoints; this.numInProgressCheckpoints = numInProgressCheckpoints; this.numCompletedCheckpoints = numCompletedCheckpoints; this.numFailedCheckpoints = numFailedCheckpoints; } /** * Returns the number of restored checkpoints. * * @return Number of restored checkpoints. */ public long getNumberOfRestoredCheckpoints() { return numRestoredCheckpoints; } /** * Returns the total number of checkpoints (in progress, completed, failed). * * @return Total number of checkpoints. */ public long getTotalNumberOfCheckpoints() { return numTotalCheckpoints; } /** * Returns the number of in progress checkpoints. * * @return Number of in progress checkpoints. */ public int getNumberOfInProgressCheckpoints() { return numInProgressCheckpoints; } /** * Returns the number of completed checkpoints. * * @return Number of completed checkpoints. */ public long getNumberOfCompletedCheckpoints() { return numCompletedCheckpoints; } /** * Returns the number of failed checkpoints. * * @return Number of failed checkpoints. */ public long getNumberOfFailedCheckpoints() { return numFailedCheckpoints; } /** Increments the number of restored checkpoints. */ void incrementRestoredCheckpoints() { numRestoredCheckpoints++; } /** Increments the number of total and in progress checkpoints. */ void incrementInProgressCheckpoints() { numInProgressCheckpoints++; numTotalCheckpoints++; } /** * Increments the number of successfully completed checkpoints. * * <p>It is expected that this follows a previous call to {@link * #incrementInProgressCheckpoints()}. */ void incrementCompletedCheckpoints() { if (canDecrementOfInProgressCheckpointsNumber()) { numInProgressCheckpoints--; } numCompletedCheckpoints++; } /** * Increments the number of failed checkpoints. * * <p>It is expected that this follows a previous call to {@link * #incrementInProgressCheckpoints()}. */ void incrementFailedCheckpoints() { if (canDecrementOfInProgressCheckpointsNumber()) { numInProgressCheckpoints--; } numFailedCheckpoints++; } /** * Increments the number of failed checkpoints without in progress checkpoint. For example, it * should be callback when triggering checkpoint failure before creating PendingCheckpoint. */ void incrementFailedCheckpointsWithoutInProgress() { numFailedCheckpoints++; numTotalCheckpoints++; } /** * Creates a snapshot of the current state. * * @return Snapshot of the current state. */ CheckpointStatsCounts createSnapshot() { return new CheckpointStatsCounts( numRestoredCheckpoints, numTotalCheckpoints, numInProgressCheckpoints, numCompletedCheckpoints, numFailedCheckpoints); } private boolean canDecrementOfInProgressCheckpointsNumber() { boolean decrementLeadsToNegativeNumber = numInProgressCheckpoints - 1 < 0; if (decrementLeadsToNegativeNumber) { String errorMessage = "Incremented the completed number of checkpoints " + "without incrementing the in progress checkpoints before."; LOG.warn(errorMessage); } return !decrementLeadsToNegativeNumber; } }
CheckpointStatsCounts
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestSchedConfCLI.java
{ "start": 3338, "end": 4191 }
class ____ extends JerseyTest { private SchedConfCLI cli; private static MockRM rm; private static String userName; private static final File CONF_FILE = new File(new File("target", "test-classes"), YarnConfiguration.CS_CONFIGURATION_FILE); private static final File OLD_CONF_FILE = new File(new File("target", "test-classes"), YarnConfiguration.CS_CONFIGURATION_FILE + ".tmp"); public TestSchedConfCLI() { } @Override protected Application configure() { ResourceConfig config = new ResourceConfig(); config.register(new JerseyBinder()); config.register(RMWebServices.class); config.register(GenericExceptionHandler.class); config.register(GenericExceptionHandler.class); config.register(new JettisonFeature()).register(JAXBContextResolver.class); return config; } private
TestSchedConfCLI
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/AbstractMapper.java
{ "start": 624, "end": 718 }
class ____ all entity mapper implementations. * * @author Chris Cranford */ public abstract
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/proxy/HibernateUnproxyTest.java
{ "start": 4684, "end": 5415 }
class ____ { @Id @GeneratedValue private Integer id; private String name; @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Child child; public Integer getId() { return id; } public void setChild(Child child) { this.child = child; child.setParent( this ); } public Child getChild() { return child; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Parent parent = (Parent) o; return Objects.equals( name, parent.name ); } @Override public int hashCode() { return Objects.hash( name ); } } @Entity(name = "Child") public static
Parent
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/TestVisibleTypeId.java
{ "start": 2835, "end": 3168 }
class ____ { public int a = 2; /* Type id property itself cannot be external, as it is conceptually * part of the bean for which info is written: */ @JsonTypeId public String getType() { return "SomeType"; } } // Invalid definition: multiple type ids static
ExternalIdBean2
java
google__guice
core/test/com/google/inject/errors/MissingConstructorErrorTest.java
{ "start": 1236, "end": 1321 }
class ____ { MissingAtInjectConstructor() {} } static
MissingAtInjectConstructor
java
apache__spark
examples/src/main/java/org/apache/spark/examples/sql/JavaSparkSQLCli.java
{ "start": 1000, "end": 1273 }
class ____ { public static void main(String[] args) { SparkSession spark = SparkSession .builder() .appName("Java Spark SQL Cli") .getOrCreate(); for (String a: args) { spark.sql(a).show(false); } spark.stop(); } }
JavaSparkSQLCli
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/repository/MetadataResolutionRequest.java
{ "start": 1058, "end": 5480 }
class ____ { private MavenArtifactMetadata mad; private String scope; // Needs to go away private Set<Artifact> artifactDependencies; private ArtifactRepository localRepository; private List<ArtifactRepository> remoteRepositories; // This is like a filter but overrides all transitive versions private Map managedVersionMap; /** result type - flat list; the default */ private boolean asList = true; /** result type - dirty tree */ private boolean asDirtyTree = false; /** result type - resolved tree */ private boolean asResolvedTree = false; /** result type - graph */ private boolean asGraph = false; public MetadataResolutionRequest() {} public MetadataResolutionRequest( MavenArtifactMetadata md, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories) { this.mad = md; this.localRepository = localRepository; this.remoteRepositories = remoteRepositories; } public MavenArtifactMetadata getArtifactMetadata() { return mad; } public MetadataResolutionRequest setArtifactMetadata(MavenArtifactMetadata md) { this.mad = md; return this; } public MetadataResolutionRequest setArtifactDependencies(Set<Artifact> artifactDependencies) { this.artifactDependencies = artifactDependencies; return this; } public Set<Artifact> getArtifactDependencies() { return artifactDependencies; } public ArtifactRepository getLocalRepository() { return localRepository; } public MetadataResolutionRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; return this; } /** * @deprecated instead use {@link #getRemoteRepositories()} */ @Deprecated public List<ArtifactRepository> getRemoteRepostories() { return remoteRepositories; } public List<ArtifactRepository> getRemoteRepositories() { return getRemoteRepostories(); } /** * @deprecated instead use {@link #setRemoteRepositories(List)} */ @Deprecated public MetadataResolutionRequest setRemoteRepostories(List<ArtifactRepository> remoteRepositories) { this.remoteRepositories = remoteRepositories; return this; } public MetadataResolutionRequest setRemoteRepositories(List<ArtifactRepository> remoteRepositories) { return setRemoteRepostories(remoteRepositories); } public Map getManagedVersionMap() { return managedVersionMap; } public MetadataResolutionRequest setManagedVersionMap(Map managedVersionMap) { this.managedVersionMap = managedVersionMap; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder() .append("REQUEST: ") .append("\n") .append("artifact: ") .append(mad) .append("\n") .append(artifactDependencies) .append("\n") .append("localRepository: ") .append(localRepository) .append("\n") .append("remoteRepositories: ") .append(remoteRepositories) .append("\n"); return sb.toString(); } public boolean isAsList() { return asList; } public MetadataResolutionRequest setAsList(boolean asList) { this.asList = asList; return this; } public boolean isAsDirtyTree() { return asDirtyTree; } public MetadataResolutionRequest setAsDirtyTree(boolean asDirtyTree) { this.asDirtyTree = asDirtyTree; return this; } public boolean isAsResolvedTree() { return asResolvedTree; } public MetadataResolutionRequest setAsResolvedTree(boolean asResolvedTree) { this.asResolvedTree = asResolvedTree; return this; } public boolean isAsGraph() { return asGraph; } public MetadataResolutionRequest setAsGraph(boolean asGraph) { this.asGraph = asGraph; return this; } public MetadataResolutionRequest setScope(String scope) { this.scope = scope; return this; } public String getScope() { return scope; } }
MetadataResolutionRequest
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/test/java/com/alibaba/nacos/plugin/auth/impl/configuration/AuthConfigsTest.java
{ "start": 973, "end": 2491 }
class ____ { private static final boolean TEST_AUTH_ENABLED = true; private static final boolean TEST_CACHING_ENABLED = false; private static final String TEST_SERVER_IDENTITY_KEY = "testKey"; private static final String TEST_SERVER_IDENTITY_VALUE = "testValue"; private AuthConfigs authConfigs; private MockEnvironment environment; @BeforeEach void setUp() throws Exception { environment = new MockEnvironment(); EnvUtil.setEnvironment(environment); environment.setProperty("nacos.core.auth.plugin.test.key", "test"); authConfigs = new AuthConfigs(); } @Test void testUpgradeFromEvent() { environment.setProperty("nacos.core.auth.enabled", String.valueOf(TEST_AUTH_ENABLED)); environment.setProperty("nacos.core.auth.caching.enabled", String.valueOf(TEST_CACHING_ENABLED)); environment.setProperty("nacos.core.auth.server.identity.key", TEST_SERVER_IDENTITY_KEY); environment.setProperty("nacos.core.auth.server.identity.value", TEST_SERVER_IDENTITY_VALUE); authConfigs.onEvent(ServerConfigChangeEvent.newEvent()); assertEquals(TEST_AUTH_ENABLED, authConfigs.isAuthEnabled()); assertEquals(TEST_CACHING_ENABLED, authConfigs.isCachingEnabled()); assertEquals(TEST_SERVER_IDENTITY_KEY, authConfigs.getServerIdentityKey()); assertEquals(TEST_SERVER_IDENTITY_VALUE, authConfigs.getServerIdentityValue()); } }
AuthConfigsTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2236/CarMapper.java
{ "start": 338, "end": 835 }
interface ____ { CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); @Mapping(target = "ownerA.name", source = "carDto.ownerNameA") @Mapping(target = "ownerA.city", source = "carDto.ownerCityA") @Mapping(target = "ownerB.name", source = "carDto.ownerNameB") @Mapping(target = "ownerB.city", source = "carDto.ownerCityB") @Mapping(target = "name", source = "carDto.name") @Mapping(target = "type", source = "type") Car vehicleToCar(Vehicle vehicle); }
CarMapper
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/PrintForeachAction.java
{ "start": 1106, "end": 2545 }
class ____<K, V> implements ForeachAction<K, V> { private final String label; private final PrintWriter printWriter; private final boolean closable; private final KeyValueMapper<? super K, ? super V, String> mapper; /** * Print customized output with given writer. The {@link OutputStream} can be {@link System#out} or the others. * * @param outputStream The output stream to write to. * @param mapper The mapper which can allow user to customize output will be printed. * @param label The given name will be printed. */ PrintForeachAction(final OutputStream outputStream, final KeyValueMapper<? super K, ? super V, String> mapper, final String label) { this.printWriter = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)); this.closable = outputStream != System.out && outputStream != System.err; this.mapper = mapper; this.label = label; } @Override public void apply(final K key, final V value) { final String data = String.format("[%s]: %s", label, mapper.apply(key, value)); printWriter.println(data); if (!closable) { printWriter.flush(); } } public void close() { if (closable) { printWriter.close(); } else { printWriter.flush(); } } }
PrintForeachAction
java
quarkusio__quarkus
test-framework/junit5-component/src/main/java/io/quarkus/test/component/MockBeanConfiguratorImpl.java
{ "start": 931, "end": 6905 }
class ____<T> implements MockBeanConfigurator<T> { final QuarkusComponentTestExtensionBuilder builder; final Class<?> beanClass; Set<Type> types; Set<Annotation> qualifiers; Class<? extends Annotation> scope; boolean alternative = false; Integer priority; String name; boolean defaultBean = false; Function<SyntheticCreationalContext<T>, T> create; Set<org.jboss.jandex.Type> jandexTypes; Set<AnnotationInstance> jandexQualifiers; public MockBeanConfiguratorImpl(QuarkusComponentTestExtensionBuilder builder, Class<?> beanClass) { this.builder = builder; this.beanClass = beanClass; this.types = new HierarchyDiscovery(beanClass).getTypeClosure(); if (beanClass.isAnnotationPresent(Singleton.class)) { this.scope = Singleton.class; } else if (beanClass.isAnnotationPresent(ApplicationScoped.class)) { this.scope = ApplicationScoped.class; } else if (beanClass.isAnnotationPresent(RequestScoped.class)) { this.scope = RequestScoped.class; } else { this.scope = Dependent.class; } this.qualifiers = new HashSet<>(); for (Annotation annotation : beanClass.getAnnotations()) { if (annotation.annotationType().isAnnotationPresent(Qualifier.class)) { this.qualifiers.add(annotation); } } if (this.qualifiers.isEmpty()) { this.qualifiers.add(Default.Literal.INSTANCE); } if (beanClass.isAnnotationPresent(Alternative.class)) { this.alternative = true; } Named named = beanClass.getAnnotation(Named.class); if (named != null) { String val = named.value(); if (!val.isBlank()) { this.name = val; } else { StringBuilder defaultName = new StringBuilder(); defaultName.append(beanClass.getSimpleName()); // URLMatcher becomes uRLMatcher defaultName.setCharAt(0, Character.toLowerCase(defaultName.charAt(0))); this.name = defaultName.toString(); } } Priority priority = beanClass.getAnnotation(Priority.class); if (priority != null) { this.priority = priority.value(); } if (beanClass.isAnnotationPresent(DefaultBean.class)) { this.defaultBean = true; } } @Override public MockBeanConfigurator<T> types(Class<?>... types) { this.types = Set.of(types); return this; } @Override public MockBeanConfigurator<T> types(Type types) { this.types = Set.of(types); return this; } @Override public MockBeanConfigurator<T> qualifiers(Annotation... qualifiers) { this.qualifiers = Set.of(qualifiers); return this; } @Override public MockBeanConfigurator<T> scope(Class<? extends Annotation> scope) { this.scope = scope; return this; } @Override public MockBeanConfigurator<T> name(String name) { this.name = name; return this; } @Override public MockBeanConfigurator<T> alternative(boolean alternative) { this.alternative = alternative; return this; } @Override public MockBeanConfigurator<T> priority(int priority) { this.priority = priority; return this; } @Override public MockBeanConfigurator<T> defaultBean(boolean defaultBean) { this.defaultBean = defaultBean; return this; } @Override public QuarkusComponentTestExtensionBuilder create(Function<SyntheticCreationalContext<T>, T> create) { this.create = create; return register(); } @Override public QuarkusComponentTestExtensionBuilder createMockitoMock() { this.create = c -> QuarkusComponentTestExtension.cast(Mockito.mock(beanClass)); return register(); } @Override public QuarkusComponentTestExtensionBuilder createMockitoMock(Consumer<T> mockInitializer) { this.create = c -> { T mock = QuarkusComponentTestExtension.cast(Mockito.mock(beanClass)); mockInitializer.accept(mock); return mock; }; return register(); } public QuarkusComponentTestExtensionBuilder register() { builder.registerMockBean(this); return builder; } boolean matches(BeanResolver beanResolver, org.jboss.jandex.Type requiredType, Set<AnnotationInstance> qualifiers) { return matchesType(requiredType, beanResolver) && hasQualifiers(qualifiers, beanResolver); } boolean matchesType(org.jboss.jandex.Type requiredType, BeanResolver beanResolver) { for (org.jboss.jandex.Type beanType : jandexTypes()) { if (beanResolver.matches(requiredType, beanType)) { return true; } } return false; } boolean hasQualifiers(Set<AnnotationInstance> requiredQualifiers, BeanResolver beanResolver) { for (AnnotationInstance qualifier : requiredQualifiers) { if (!beanResolver.hasQualifier(jandexQualifiers(), qualifier)) { return false; } } return true; } Set<org.jboss.jandex.Type> jandexTypes() { if (jandexTypes == null) { jandexTypes = new HashSet<>(); for (Type type : types) { jandexTypes.add(Types.jandexType(type)); } } return jandexTypes; } Set<AnnotationInstance> jandexQualifiers() { if (jandexQualifiers == null) { jandexQualifiers = new HashSet<>(); for (Annotation qualifier : qualifiers) { jandexQualifiers.add(Annotations.jandexAnnotation(qualifier)); } } return jandexQualifiers; } }
MockBeanConfiguratorImpl
java
spring-projects__spring-boot
module/spring-boot-data-commons/src/test/java/org/springframework/boot/data/metrics/TimedAnnotationsTests.java
{ "start": 993, "end": 2023 }
class ____ { @Test void getWhenNoneReturnsEmptySet() { Object bean = new None(); Method method = ReflectionUtils.findMethod(bean.getClass(), "handle"); assertThat(method).isNotNull(); Set<Timed> annotations = TimedAnnotations.get(method, bean.getClass()); assertThat(annotations).isEmpty(); } @Test void getWhenOnMethodReturnsMethodAnnotations() { Object bean = new OnMethod(); Method method = ReflectionUtils.findMethod(bean.getClass(), "handle"); assertThat(method).isNotNull(); Set<Timed> annotations = TimedAnnotations.get(method, bean.getClass()); assertThat(annotations).extracting(Timed::value).containsOnly("y", "z"); } @Test void getWhenNonOnMethodReturnsBeanAnnotations() { Object bean = new OnBean(); Method method = ReflectionUtils.findMethod(bean.getClass(), "handle"); assertThat(method).isNotNull(); Set<Timed> annotations = TimedAnnotations.get(method, bean.getClass()); assertThat(annotations).extracting(Timed::value).containsOnly("y", "z"); } static
TimedAnnotationsTests
java
qos-ch__slf4j
integration/src/test/java/org/slf4j/test_osgi/BundleTest.java
{ "start": 1296, "end": 2119 }
class ____ extends TestCase { FrameworkErrorListener fel = new FrameworkErrorListener(); CheckingBundleListener mbl = new CheckingBundleListener(); FelixHost felixHost = new FelixHost(fel, mbl); protected void setUp() throws Exception { super.setUp(); felixHost.doLaunch(); } protected void tearDown() throws Exception { super.tearDown(); felixHost.stop(); } public void testSmoke() { System.out.println("===========" + new File(".").getAbsolutePath()); mbl.dumpAll(); // check that the bundle was installed assertTrue(mbl.exists("iBundle")); if (fel.errorList.size() != 0) { fel.dumpAll(); } // check that no errors occured assertEquals(0, fel.errorList.size()); } }
BundleTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableAll.java
{ "start": 1420, "end": 3283 }
class ____<T> implements Observer<T>, Disposable { final Observer<? super Boolean> downstream; final Predicate<? super T> predicate; Disposable upstream; boolean done; AllObserver(Observer<? super Boolean> actual, Predicate<? super T> predicate) { this.downstream = actual; this.predicate = predicate; } @Override public void onSubscribe(Disposable d) { if (DisposableHelper.validate(this.upstream, d)) { this.upstream = d; downstream.onSubscribe(this); } } @Override public void onNext(T t) { if (done) { return; } boolean b; try { b = predicate.test(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); upstream.dispose(); onError(e); return; } if (!b) { done = true; upstream.dispose(); downstream.onNext(false); downstream.onComplete(); } } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } done = true; downstream.onError(t); } @Override public void onComplete() { if (done) { return; } done = true; downstream.onNext(true); downstream.onComplete(); } @Override public void dispose() { upstream.dispose(); } @Override public boolean isDisposed() { return upstream.isDisposed(); } } }
AllObserver
java
apache__flink
flink-table/flink-table-code-splitter/src/test/resources/declaration/expected/TestRewriteLocalVariableInForLoop1.java
{ "start": 7, "end": 221 }
class ____ { int sum; int i; public void myFun() { sum = 0; for ( i = 0; i < 100; i++) { sum += i; } System.out.println(sum); } }
TestRewriteLocalVariableInForLoop1
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/mapping/NestedEmbeddableTest.java
{ "start": 2454, "end": 3744 }
class ____ extends CcmObject implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "NAME", nullable = false) private String name; @Embedded @AssociationOverride( name = "values", joinTable = @JoinTable(name = "CATEGORY_TITLES", joinColumns = { @JoinColumn(name = "OBJECT_ID") } )) private LocalizedString title; @Embedded @AssociationOverride( name = "values", joinTable = @JoinTable(name = "CATEGORY_DESCRIPTIONS", joinColumns = { @JoinColumn(name = "OBJECT_ID") } )) private LocalizedString description; @OneToMany(mappedBy = "category", fetch = FetchType.LAZY) @OrderBy("objectOrder ASC") private List<Categorization> objects; public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalizedString getTitle() { return title; } public void setTitle(LocalizedString title) { this.title = title; } public LocalizedString getDescription() { return description; } public void setDescription(LocalizedString description) { this.description = description; } } @Entity @Table(name = "CCM_OBJECTS") @Inheritance(strategy = InheritanceType.JOINED) public static
Category
java
apache__flink
flink-test-utils-parent/flink-test-utils-junit/src/main/java/org/apache/flink/testutils/s3/S3TestCredentials.java
{ "start": 1037, "end": 4255 }
class ____ { @Nullable private static final String S3_TEST_BUCKET = System.getenv("IT_CASE_S3_BUCKET"); @Nullable private static final String S3_TEST_ACCESS_KEY = System.getenv("IT_CASE_S3_ACCESS_KEY"); @Nullable private static final String S3_TEST_SECRET_KEY = System.getenv("IT_CASE_S3_SECRET_KEY"); // ------------------------------------------------------------------------ /** * Checks whether S3 test credentials are available in the environment variables of this JVM. */ private static boolean credentialsAvailable() { return isNotEmpty(S3_TEST_BUCKET) && isNotEmpty(S3_TEST_ACCESS_KEY) && isNotEmpty(S3_TEST_SECRET_KEY); } /** Checks if a String is not null and not empty. */ private static boolean isNotEmpty(@Nullable String str) { return str != null && !str.isEmpty(); } /** * Checks whether credentials are available in the environment variables of this JVM. If not, * throws an {@link AssumptionViolatedException} which causes JUnit tests to be skipped. */ public static void assumeCredentialsAvailable() { Assume.assumeTrue( "No S3 credentials available in this test's environment", credentialsAvailable()); } /** * Gets the S3 Access Key. * * <p>This method throws an exception if the key is not available. Tests should use {@link * #assumeCredentialsAvailable()} to skip tests when credentials are not available. */ public static String getS3AccessKey() { if (S3_TEST_ACCESS_KEY != null) { return S3_TEST_ACCESS_KEY; } else { throw new IllegalStateException("S3 test access key not available"); } } /** * Gets the S3 Secret Key. * * <p>This method throws an exception if the key is not available. Tests should use {@link * #assumeCredentialsAvailable()} to skip tests when credentials are not available. */ public static String getS3SecretKey() { if (S3_TEST_SECRET_KEY != null) { return S3_TEST_SECRET_KEY; } else { throw new IllegalStateException("S3 test secret key not available"); } } /** * Gets the URI for the path under which all tests should put their data. * * <p>This method throws an exception if the bucket was not configured. Tests should use {@link * #assumeCredentialsAvailable()} to skip tests when credentials are not available. */ public static String getTestBucketUri() { return getTestBucketUriWithScheme("s3"); } /** * Gets the URI for the path under which all tests should put their data. * * <p>This method throws an exception if the bucket was not configured. Tests should use {@link * #assumeCredentialsAvailable()} to skip tests when credentials are not available. */ public static String getTestBucketUriWithScheme(String scheme) { if (S3_TEST_BUCKET != null) { return scheme + "://" + S3_TEST_BUCKET + "/temp/"; } else { throw new IllegalStateException("S3 test bucket not available"); } } }
S3TestCredentials
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/http/server/bind/type/ShoppingCartController.java
{ "start": 265, "end": 668 }
class ____ { // tag::method[] @Get("/typed") public HttpResponse<?> loadCart(ShoppingCart shoppingCart) { //<1> Map<String, Object> responseMap = new HashMap<>(); responseMap.put("sessionId", shoppingCart.getSessionId()); responseMap.put("total", shoppingCart.getTotal()); return HttpResponse.ok(responseMap); } // end::method[] }
ShoppingCartController
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/event/AnnotationDrivenEventListenerTests.java
{ "start": 31447, "end": 31776 }
class ____ extends AbstractIdentifiable implements AnnotatedSimpleService { @Autowired private EventCollector eventCollector; @Override public void handleIt(TestEvent event) { this.eventCollector.addEvent(this, event); } } @Component @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) static
AnnotatedProxyTestBean
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/SumAggFunction.java
{ "start": 3773, "end": 4003 }
class ____ extends SumAggFunction { @Override public DataType getResultType() { return DataTypes.INT(); } } /** Built-in Byte Sum aggregate function. */ public static
IntSumAggFunction
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethodTests.java
{ "start": 7092, "end": 7434 }
class ____ implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return true; } @Override public Object resolveArgument(MethodParameter parameter, Message<?> message) { throw new IllegalArgumentException("oops, can't read"); } } }
ExceptionRaisingArgumentResolver
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/watermark/InternalLongWatermarkDeclaration.java
{ "start": 1356, "end": 2803 }
class ____ extends AbstractInternalWatermarkDeclaration<Long> { public InternalLongWatermarkDeclaration(LongWatermarkDeclaration declaration) { this( declaration.getIdentifier(), declaration.getCombinationPolicy(), declaration.getDefaultHandlingStrategy(), (declaration instanceof Alignable) && ((Alignable) declaration).isAligned()); } public InternalLongWatermarkDeclaration( String identifier, WatermarkCombinationPolicy combinationPolicyForChannel, WatermarkHandlingStrategy defaultHandlingStrategyForFunction, boolean isAligned) { super( identifier, combinationPolicyForChannel, defaultHandlingStrategyForFunction, isAligned); } /** Creates a new {@code LongWatermark} with the specified value. */ @Override public LongWatermark newWatermark(Long val) { return new LongWatermark(val, this.getIdentifier()); } @Override public WatermarkCombiner createWatermarkCombiner( int numberOfInputChannels, Runnable gateResumer) { if (isAligned) { return new AlignedWatermarkCombiner(numberOfInputChannels, gateResumer); } else { return new LongWatermarkCombiner(getCombinationPolicy(), numberOfInputChannels); } } }
InternalLongWatermarkDeclaration
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManagerException.java
{ "start": 1030, "end": 1359 }
class ____ extends ResourceManagerException { public SlotManagerException(String message) { super(message); } public SlotManagerException(String message, Throwable cause) { super(message, cause); } public SlotManagerException(Throwable cause) { super(cause); } }
SlotManagerException
java
google__guava
android/guava/src/com/google/common/base/Enums.java
{ "start": 3655, "end": 3888 }
enum ____ in the specified enum. * * @since 16.0 */ public static <T extends Enum<T>> Converter<String, T> stringConverter(Class<T> enumClass) { return new StringConverter<>(enumClass); } private static final
constant