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
quarkusio__quarkus
extensions/scheduler/api/src/main/java/io/quarkus/scheduler/Scheduled.java
{ "start": 12874, "end": 13177 }
interface ____ { /** * * @param execution * @return {@code true} if the given execution should be skipped, {@code false} otherwise */ boolean test(ScheduledExecution execution); } /** * Execution is never skipped. */
SkipPredicate
java
apache__camel
components/camel-aws/camel-aws2-msk/src/main/java/org/apache/camel/component/aws2/msk/client/MSK2ClientFactory.java
{ "start": 1334, "end": 2218 }
class ____ { private MSK2ClientFactory() { } /** * Return the correct AWS Kafka client (based on remote vs local). * * @param configuration configuration * @return MqClient */ public static MSK2InternalClient getKafkaClient(MSK2Configuration configuration) { if (Boolean.TRUE.equals(configuration.isUseDefaultCredentialsProvider())) { return new MSK2ClientOptimizedImpl(configuration); } else if (Boolean.TRUE.equals(configuration.isUseProfileCredentialsProvider())) { return new MSK2ClientProfileOptimizedImpl(configuration); } else if (Boolean.TRUE.equals(configuration.isUseSessionCredentials())) { return new MSK2ClientSessionTokenImpl(configuration); } else { return new MSK2ClientStandardImpl(configuration); } } }
MSK2ClientFactory
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/math/Cosh.java
{ "start": 1021, "end": 2677 }
class ____ extends AbstractTrigonometricFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "Cosh", Cosh::new); @FunctionInfo( returnType = "double", description = "Returns the {wikipedia}/Hyperbolic_functions[hyperbolic cosine] of a number.", examples = @Example(file = "floats", tag = "cosh") ) public Cosh( Source source, @Param( name = "number", type = { "double", "integer", "long", "unsigned_long" }, description = "Numeric expression. If `null`, the function returns `null`." ) Expression angle ) { super(source, angle); } private Cosh(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected EvalOperator.ExpressionEvaluator.Factory doubleEvaluator(EvalOperator.ExpressionEvaluator.Factory field) { return new CoshEvaluator.Factory(source(), field); } @Override public Expression replaceChildren(List<Expression> newChildren) { return new Cosh(source(), newChildren.get(0)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, Cosh::new, field()); } @Evaluator(warnExceptions = ArithmeticException.class) static double process(double val) { double res = Math.cosh(val); if (Double.isNaN(res) || Double.isInfinite(res)) { throw new ArithmeticException("cosh overflow"); } return res; } }
Cosh
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InfiniteRecursionTest.java
{ "start": 1165, "end": 1732 }
class ____ { void f(int x) {} void f() { // BUG: Diagnostic contains: f(); } int g() { return 0; } int g(int x) { // BUG: Diagnostic contains: return g(x); } } """) .doTest(); } @Test public void positiveExplicitThis() { compilationHelper .addSourceLines( "p/Test.java", """ package p;
Test
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetomany/IndexColumnListTest.java
{ "start": 5631, "end": 6998 }
class ____ { @Id private Integer id; private String name; @ManyToOne private Parent parent; Child() { } Child(Integer id, String name) { this( id, name, null ); } Child(Integer id, String name, Parent parent) { this.id = id; this.name = name; this.parent = parent; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Child child = (Child) o; if ( id != null ? !id.equals( child.id ) : child.id != null ) { return false; } if ( name != null ? !name.equals( child.name ) : child.name != null ) { return false; } return parent != null ? parent.equals( child.parent ) : child.parent == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + ( name != null ? name.hashCode() : 0 ); result = 31 * result + ( parent != null ? parent.hashCode() : 0 ); return result; } } }
Child
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/sink/compactor/operator/CompactorOperatorStateHandlerFactory.java
{ "start": 1706, "end": 3794 }
class ____ extends AbstractStreamOperatorFactory<CommittableMessage<FileSinkCommittable>> implements OneInputStreamOperatorFactory< Either<CommittableMessage<FileSinkCommittable>, CompactorRequest>, CommittableMessage<FileSinkCommittable>> { private final SerializableSupplierWithException< SimpleVersionedSerializer<FileSinkCommittable>, IOException> committableSerializerSupplier; private final SerializableSupplierWithException<BucketWriter<?, String>, IOException> bucketWriterProvider; public CompactorOperatorStateHandlerFactory( SerializableSupplierWithException< SimpleVersionedSerializer<FileSinkCommittable>, IOException> committableSerializerSupplier, SerializableSupplierWithException<BucketWriter<?, String>, IOException> bucketWriterProvider) { this.committableSerializerSupplier = committableSerializerSupplier; this.bucketWriterProvider = bucketWriterProvider; } @Override public <T extends StreamOperator<CommittableMessage<FileSinkCommittable>>> T createStreamOperator( StreamOperatorParameters<CommittableMessage<FileSinkCommittable>> parameters) { try { final CompactorOperatorStateHandler handler = new CompactorOperatorStateHandler( parameters, committableSerializerSupplier.get(), bucketWriterProvider.get()); return (T) handler; } catch (Exception e) { throw new IllegalStateException( "Cannot create commit operator for " + parameters.getStreamConfig().getOperatorName(), e); } } @Override public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return CompactorOperator.class; } }
CompactorOperatorStateHandlerFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/proxy/BlobProxy.java
{ "start": 1063, "end": 1277 }
class ____ implements Blob, BlobImplementer { // In previous versions this used to be implemented by using a java.lang.reflect.Proxy to deal with // incompatibilities across various JDBC versions, hence the
BlobProxy
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AMetrics.java
{ "start": 1287, "end": 3128 }
class ____ extends AbstractS3ATestBase { @Test public void testMetricsRegister() throws IOException, InterruptedException { S3AFileSystem fs = getFileSystem(); Path dest = path("testMetricsRegister"); ContractTestUtils.touch(fs, dest); MutableCounterLong fileCreated = (MutableCounterLong) fs.getInstrumentation().getRegistry() .get(Statistic.FILES_CREATED.getSymbol()); assertEquals(1, fileCreated.value(), "Metrics system should report single file created event"); } @Test public void testStreamStatistics() throws IOException { S3AFileSystem fs = getFileSystem(); Path file = path("testStreamStatistics"); byte[] data = "abcdefghijklmnopqrstuvwxyz".getBytes(); ContractTestUtils.createFile(fs, file, false, data); InputStream inputStream = fs.open(file); try { while (inputStream.read(data) != -1) { LOG.debug("Read batch of data from input stream..."); } LOG.info("Final stream statistics: {}", ioStatisticsSourceToString(inputStream)); } finally { // this is not try-with-resources only to aid debugging inputStream.close(); } final String statName = Statistic.STREAM_READ_BYTES.getSymbol(); final S3AInstrumentation instrumentation = fs.getInstrumentation(); final long counterValue = instrumentation.getCounterValue(statName); final int expectedBytesRead = 26; Assertions.assertThat(counterValue) .describedAs("Counter %s from instrumentation %s", statName, instrumentation) .isEqualTo(expectedBytesRead); MutableCounterLong read = (MutableCounterLong) instrumentation.getRegistry() .get(statName); assertEquals(expectedBytesRead, read.value(), "Stream statistics were not merged"); } }
ITestS3AMetrics
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableMergeWithSingle.java
{ "start": 1342, "end": 1918 }
class ____<T> extends AbstractObservableWithUpstream<T, T> { final SingleSource<? extends T> other; public ObservableMergeWithSingle(Observable<T> source, SingleSource<? extends T> other) { super(source); this.other = other; } @Override protected void subscribeActual(Observer<? super T> observer) { MergeWithObserver<T> parent = new MergeWithObserver<>(observer); observer.onSubscribe(parent); source.subscribe(parent); other.subscribe(parent.otherObserver); } static final
ObservableMergeWithSingle
java
netty__netty
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/QuicConnectionCloseEvent.java
{ "start": 957, "end": 3039 }
class ____ implements QuicEvent { final boolean applicationClose; final int error; final byte[] reason; QuicConnectionCloseEvent(boolean applicationClose, int error, byte[] reason) { this.applicationClose = applicationClose; this.error = error; this.reason = reason; } /** * Return {@code true} if this was an application close, {@code false} otherwise. * * @return if this is an application close. */ public boolean isApplicationClose() { return applicationClose; } /** * Return the error that was provided for the close. * * @return the error. */ public int error() { return error; } /** * Returns {@code true} if a <a href="https://www.rfc-editor.org/rfc/rfc9001#section-4.8">TLS error</a> * is contained. * @return {@code true} if this is an {@code TLS error}, {@code false} otherwise. */ public boolean isTlsError() { return !applicationClose && error >= 0x0100; } /** * Returns the reason for the close, which may be empty if no reason was given as part of the close. * * @return the reason. */ public byte[] reason() { return reason.clone(); } @Override public String toString() { return "QuicConnectionCloseEvent{" + "applicationClose=" + applicationClose + ", error=" + error + ", reason=" + Arrays.toString(reason) + '}'; } /** * Extract the contained {@code TLS error} from the {@code QUIC error}. If the given {@code QUIC error} does not * contain a {@code TLS error} it will return {@code -1}. * * @param error the {@code QUIC error} * @return the {@code TLS error} or {@code -1} if there was no {@code TLS error} contained. */ public static int extractTlsError(int error) { int tlsError = error - 0x0100; if (tlsError < 0) { return -1; } return tlsError; } }
QuicConnectionCloseEvent
java
dropwizard__dropwizard
dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationMetadataTest.java
{ "start": 1755, "end": 1913 }
interface ____ { } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = DefaultExampleInterface.class) public
ExampleInterface
java
apache__camel
components/camel-debezium/camel-debezium-db2/src/generated/java/org/apache/camel/component/debezium/db2/configuration/Db2ConnectorEmbeddedDebeziumConfiguration.java
{ "start": 456, "end": 25042 }
class ____ extends EmbeddedDebeziumConfiguration { private static final String LABEL_NAME = "consumer,db2"; @UriParam(label = LABEL_NAME) private String messageKeyColumns; @UriParam(label = LABEL_NAME, defaultValue = "io.debezium.pipeline.txmetadata.DefaultTransactionMetadataFactory") private String transactionMetadataFactory = "io.debezium.pipeline.txmetadata.DefaultTransactionMetadataFactory"; @UriParam(label = LABEL_NAME, defaultValue = "0ms", javaType = "java.time.Duration") private long streamingDelayMs = 0; @UriParam(label = LABEL_NAME) private String customMetricTags; @UriParam(label = LABEL_NAME) private String openlineageIntegrationJobNamespace; @UriParam(label = LABEL_NAME, defaultValue = "10000") private int queryFetchSize = 10000; @UriParam(label = LABEL_NAME, defaultValue = "source") private String signalEnabledChannels = "source"; @UriParam(label = LABEL_NAME, defaultValue = "true") private boolean includeSchemaChanges = true; @UriParam(label = LABEL_NAME, defaultValue = "500ms", javaType = "java.time.Duration") private long pollIntervalMs = 500; @UriParam(label = LABEL_NAME, defaultValue = "0") private int guardrailCollectionsMax = 0; @UriParam(label = LABEL_NAME) private String signalDataCollection; @UriParam(label = LABEL_NAME) private String converters; @UriParam(label = LABEL_NAME, defaultValue = "__debezium-heartbeat") private String heartbeatTopicsPrefix = "__debezium-heartbeat"; @UriParam(label = LABEL_NAME) private int snapshotFetchSize; @UriParam(label = LABEL_NAME) private String openlineageIntegrationJobTags; @UriParam(label = LABEL_NAME, defaultValue = "10s", javaType = "java.time.Duration") private long snapshotLockTimeoutMs = 10000; @UriParam(label = LABEL_NAME, defaultValue = "ASNCDC") private String cdcChangeTablesSchema = "ASNCDC"; @UriParam(label = LABEL_NAME) private String databaseUser; @UriParam(label = LABEL_NAME) private String databaseDbname; @UriParam(label = LABEL_NAME) private String datatypePropagateSourceType; @UriParam(label = LABEL_NAME, defaultValue = "disabled") private String snapshotTablesOrderByRowCount = "disabled"; @UriParam(label = LABEL_NAME, defaultValue = "INSERT_INSERT") private String incrementalSnapshotWatermarkingStrategy = "INSERT_INSERT"; @UriParam(label = LABEL_NAME) private String snapshotSelectStatementOverrides; @UriParam(label = LABEL_NAME, defaultValue = "0ms", javaType = "java.time.Duration") private int heartbeatIntervalMs = 0; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean snapshotModeConfigurationBasedSnapshotOnSchemaError = false; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean schemaHistoryInternalSkipUnparseableDdl = false; @UriParam(label = LABEL_NAME) private String columnIncludeList; @UriParam(label = LABEL_NAME) private String columnPropagateSourceType; @UriParam(label = LABEL_NAME, defaultValue = "-1") private int errorsMaxRetries = -1; @UriParam(label = LABEL_NAME) private String tableExcludeList; @UriParam(label = LABEL_NAME) @Metadata(required = true) private String databasePassword; @UriParam(label = LABEL_NAME, defaultValue = "2048") private int maxBatchSize = 2048; @UriParam(label = LABEL_NAME, defaultValue = "t") private String skippedOperations = "t"; @UriParam(label = LABEL_NAME, defaultValue = "Debezium change data capture job") private String openlineageIntegrationJobDescription = "Debezium change data capture job"; @UriParam(label = LABEL_NAME, defaultValue = "io.debezium.schema.SchemaTopicNamingStrategy") private String topicNamingStrategy = "io.debezium.schema.SchemaTopicNamingStrategy"; @UriParam(label = LABEL_NAME, defaultValue = "initial") private String snapshotMode = "initial"; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean snapshotModeConfigurationBasedSnapshotData = false; @UriParam(label = LABEL_NAME, defaultValue = "true") private boolean extendedHeadersEnabled = true; @UriParam(label = LABEL_NAME, defaultValue = "8192") private int maxQueueSize = 8192; @UriParam(label = LABEL_NAME, defaultValue = "warn") private String guardrailCollectionsLimitAction = "warn"; @UriParam(label = LABEL_NAME, defaultValue = "1024") private int incrementalSnapshotChunkSize = 1024; @UriParam(label = LABEL_NAME) private String openlineageIntegrationJobOwners; @UriParam(label = LABEL_NAME, defaultValue = "./openlineage.yml") private String openlineageIntegrationConfigFilePath = "./openlineage.yml"; @UriParam(label = LABEL_NAME, defaultValue = "10s", javaType = "java.time.Duration") private long retriableRestartConnectorWaitMs = 10000; @UriParam(label = LABEL_NAME, defaultValue = "0ms", javaType = "java.time.Duration") private long snapshotDelayMs = 0; @UriParam(label = LABEL_NAME, defaultValue = "4s", javaType = "java.time.Duration") private long executorShutdownTimeoutMs = 4000; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean provideTransactionMetadata = false; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean schemaHistoryInternalStoreOnlyCapturedTablesDdl = false; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean schemaHistoryInternalStoreOnlyCapturedDatabasesDdl = false; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean snapshotModeConfigurationBasedSnapshotOnDataError = false; @UriParam(label = LABEL_NAME) private String schemaHistoryInternalFileFilename; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean tombstonesOnDelete = false; @UriParam(label = LABEL_NAME) @Metadata(required = true) private String topicPrefix; @UriParam(label = LABEL_NAME, defaultValue = "precise") private String decimalHandlingMode = "precise"; @UriParam(label = LABEL_NAME, defaultValue = "io.debezium.connector.db2.Db2SourceInfoStructMaker") private String sourceinfoStructMaker = "io.debezium.connector.db2.Db2SourceInfoStructMaker"; @UriParam(label = LABEL_NAME) private String openlineageIntegrationDatasetKafkaBootstrapServers; @UriParam(label = LABEL_NAME, defaultValue = "ASNCDC") private String cdcControlSchema = "ASNCDC"; @UriParam(label = LABEL_NAME, defaultValue = "true") private boolean tableIgnoreBuiltin = true; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean openlineageIntegrationEnabled = false; @UriParam(label = LABEL_NAME) private String snapshotIncludeCollectionList; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean snapshotModeConfigurationBasedStartStream = false; @UriParam(label = LABEL_NAME, defaultValue = "0") private long maxQueueSizeInBytes = 0; @UriParam(label = LABEL_NAME, defaultValue = "false") private boolean snapshotModeConfigurationBasedSnapshotSchema = false; @UriParam(label = LABEL_NAME, defaultValue = "adaptive") private String timePrecisionMode = "adaptive"; @UriParam(label = LABEL_NAME, defaultValue = "5s", javaType = "java.time.Duration") private long signalPollIntervalMs = 5000; @UriParam(label = LABEL_NAME) private String postProcessors; @UriParam(label = LABEL_NAME) private String notificationEnabledChannels; @UriParam(label = LABEL_NAME, defaultValue = "fail") private String eventProcessingFailureHandlingMode = "fail"; @UriParam(label = LABEL_NAME, defaultValue = "50000") private int databasePort = 50000; @UriParam(label = LABEL_NAME) private String notificationSinkTopicName; @UriParam(label = LABEL_NAME) private String snapshotModeCustomName; @UriParam(label = LABEL_NAME, defaultValue = "io.debezium.storage.kafka.history.KafkaSchemaHistory") private String schemaHistoryInternal = "io.debezium.storage.kafka.history.KafkaSchemaHistory"; @UriParam(label = LABEL_NAME) private String columnExcludeList; @UriParam(label = LABEL_NAME) private String databaseHostname; @UriParam(label = LABEL_NAME, defaultValue = "none") private String schemaNameAdjustmentMode = "none"; @UriParam(label = LABEL_NAME) private String tableIncludeList; @UriParam(label = LABEL_NAME, defaultValue = "1m", javaType = "java.time.Duration") private long connectionValidationTimeoutMs = 60000; @UriParam(label = LABEL_NAME, defaultValue = "LUW") private String db2Platform = "LUW"; /** * A semicolon-separated list of expressions that match fully-qualified * tables and column(s) to be used as message key. Each expression must * match the pattern '<fully-qualified table name>:<key columns>', where the * table names could be defined as (DB_NAME.TABLE_NAME) or * (SCHEMA_NAME.TABLE_NAME), depending on the specific connector, and the * key columns are a comma-separated list of columns representing the custom * key. For any table without an explicit key configuration the table's * primary key column(s) will be used as message key. Example: * dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id */ public void setMessageKeyColumns(String messageKeyColumns) { this.messageKeyColumns = messageKeyColumns; } public String getMessageKeyColumns() { return messageKeyColumns; } /** * Class to make transaction context & transaction struct/schemas */ public void setTransactionMetadataFactory(String transactionMetadataFactory) { this.transactionMetadataFactory = transactionMetadataFactory; } public String getTransactionMetadataFactory() { return transactionMetadataFactory; } /** * A delay period after the snapshot is completed and the streaming begins, * given in milliseconds. Defaults to 0 ms. */ public void setStreamingDelayMs(long streamingDelayMs) { this.streamingDelayMs = streamingDelayMs; } public long getStreamingDelayMs() { return streamingDelayMs; } /** * The custom metric tags will accept key-value pairs to customize the MBean * object name which should be appended the end of regular name, each key * would represent a tag for the MBean object name, and the corresponding * value would be the value of that tag the key is. For example: k1=v1,k2=v2 */ public void setCustomMetricTags(String customMetricTags) { this.customMetricTags = customMetricTags; } public String getCustomMetricTags() { return customMetricTags; } /** * The job's namespace emitted by Debezium */ public void setOpenlineageIntegrationJobNamespace( String openlineageIntegrationJobNamespace) { this.openlineageIntegrationJobNamespace = openlineageIntegrationJobNamespace; } public String getOpenlineageIntegrationJobNamespace() { return openlineageIntegrationJobNamespace; } /** * The maximum number of records that should be loaded into memory while * streaming. A value of '0' uses the default JDBC fetch size. The default * value is '10000'. */ public void setQueryFetchSize(int queryFetchSize) { this.queryFetchSize = queryFetchSize; } public int getQueryFetchSize() { return queryFetchSize; } /** * List of channels names that are enabled. Source channel is enabled by * default */ public void setSignalEnabledChannels(String signalEnabledChannels) { this.signalEnabledChannels = signalEnabledChannels; } public String getSignalEnabledChannels() { return signalEnabledChannels; } /** * Whether the connector should publish changes in the database schema to a * Kafka topic with the same name as the database server ID. Each schema * change will be recorded using a key that contains the database name and * whose value include logical description of the new schema and optionally * the DDL statement(s). The default is 'true'. This is independent of how * the connector internally records database schema history. */ public void setIncludeSchemaChanges(boolean includeSchemaChanges) { this.includeSchemaChanges = includeSchemaChanges; } public boolean isIncludeSchemaChanges() { return includeSchemaChanges; } /** * Time to wait for new change events to appear after receiving no events, * given in milliseconds. Defaults to 500 ms. */ public void setPollIntervalMs(long pollIntervalMs) { this.pollIntervalMs = pollIntervalMs; } public long getPollIntervalMs() { return pollIntervalMs; } /** * The maximum number of collections or tables that can be captured by the * connector. When this limit is exceeded, the action specified by * 'guardrail.collections.limit.action' will be taken. Set to 0 to disable * this guardrail. */ public void setGuardrailCollectionsMax(int guardrailCollectionsMax) { this.guardrailCollectionsMax = guardrailCollectionsMax; } public int getGuardrailCollectionsMax() { return guardrailCollectionsMax; } /** * The name of the data collection that is used to send signals/commands to * Debezium. Signaling is disabled when not set. */ public void setSignalDataCollection(String signalDataCollection) { this.signalDataCollection = signalDataCollection; } public String getSignalDataCollection() { return signalDataCollection; } /** * Optional list of custom converters that would be used instead of default * ones. The converters are defined using '<converter.prefix>.type' config * option and configured using options '<converter.prefix>.<option>' */ public void setConverters(String converters) { this.converters = converters; } public String getConverters() { return converters; } /** * The prefix that is used to name heartbeat topics.Defaults to * __debezium-heartbeat. */ public void setHeartbeatTopicsPrefix(String heartbeatTopicsPrefix) { this.heartbeatTopicsPrefix = heartbeatTopicsPrefix; } public String getHeartbeatTopicsPrefix() { return heartbeatTopicsPrefix; } /** * The maximum number of records that should be loaded into memory while * performing a snapshot. */ public void setSnapshotFetchSize(int snapshotFetchSize) { this.snapshotFetchSize = snapshotFetchSize; } public int getSnapshotFetchSize() { return snapshotFetchSize; } /** * The job's tags emitted by Debezium. A comma-separated list of key-value * pairs.For example: k1=v1,k2=v2 */ public void setOpenlineageIntegrationJobTags( String openlineageIntegrationJobTags) { this.openlineageIntegrationJobTags = openlineageIntegrationJobTags; } public String getOpenlineageIntegrationJobTags() { return openlineageIntegrationJobTags; } /** * The maximum number of millis to wait for table locks at the beginning of * a snapshot. If locks cannot be acquired in this time frame, the snapshot * will be aborted. Defaults to 10 seconds */ public void setSnapshotLockTimeoutMs(long snapshotLockTimeoutMs) { this.snapshotLockTimeoutMs = snapshotLockTimeoutMs; } public long getSnapshotLockTimeoutMs() { return snapshotLockTimeoutMs; } /** * The name of the schema where CDC change tables are located; defaults to * 'ASNCDC' */ public void setCdcChangeTablesSchema(String cdcChangeTablesSchema) { this.cdcChangeTablesSchema = cdcChangeTablesSchema; } public String getCdcChangeTablesSchema() { return cdcChangeTablesSchema; } /** * Name of the database user to be used when connecting to the database. */ public void setDatabaseUser(String databaseUser) { this.databaseUser = databaseUser; } public String getDatabaseUser() { return databaseUser; } /** * The name of the database from which the connector should capture changes */ public void setDatabaseDbname(String databaseDbname) { this.databaseDbname = databaseDbname; } public String getDatabaseDbname() { return databaseDbname; } /** * A comma-separated list of regular expressions matching the * database-specific data type names that adds the data type's original type * and original length as parameters to the corresponding field schemas in * the emitted change records. */ public void setDatatypePropagateSourceType( String datatypePropagateSourceType) { this.datatypePropagateSourceType = datatypePropagateSourceType; } public String getDatatypePropagateSourceType() { return datatypePropagateSourceType; } /** * Controls the order in which tables are processed in the initial snapshot. * A `descending` value will order the tables by row count descending. A * `ascending` value will order the tables by row count ascending. A value * of `disabled` (the default) will disable ordering by row count. */ public void setSnapshotTablesOrderByRowCount( String snapshotTablesOrderByRowCount) { this.snapshotTablesOrderByRowCount = snapshotTablesOrderByRowCount; } public String getSnapshotTablesOrderByRowCount() { return snapshotTablesOrderByRowCount; } /** * Specify the strategy used for watermarking during an incremental * snapshot: 'insert_insert' both open and close signal is written into * signal data collection (default); 'insert_delete' only open signal is * written on signal data collection, the close will delete the relative * open signal; */ public void setIncrementalSnapshotWatermarkingStrategy( String incrementalSnapshotWatermarkingStrategy) { this.incrementalSnapshotWatermarkingStrategy = incrementalSnapshotWatermarkingStrategy; } public String getIncrementalSnapshotWatermarkingStrategy() { return incrementalSnapshotWatermarkingStrategy; } /** * This property contains a comma-separated list of fully-qualified tables * (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the * specific connectors. Select statements for the individual tables are * specified in further configuration properties, one for each table, * identified by the id * 'snapshot.select.statement.overrides.[DB_NAME].[TABLE_NAME]' or * 'snapshot.select.statement.overrides.[SCHEMA_NAME].[TABLE_NAME]', * respectively. The value of those properties is the select statement to * use when retrieving data from the specific table during snapshotting. A * possible use case for large append-only tables is setting a specific * point where to start (resume) snapshotting, in case a previous * snapshotting was interrupted. */ public void setSnapshotSelectStatementOverrides( String snapshotSelectStatementOverrides) { this.snapshotSelectStatementOverrides = snapshotSelectStatementOverrides; } public String getSnapshotSelectStatementOverrides() { return snapshotSelectStatementOverrides; } /** * Length of an interval in milli-seconds in in which the connector * periodically sends heartbeat messages to a heartbeat topic. Use 0 to * disable heartbeat messages. Disabled by default. */ public void setHeartbeatIntervalMs(int heartbeatIntervalMs) { this.heartbeatIntervalMs = heartbeatIntervalMs; } public int getHeartbeatIntervalMs() { return heartbeatIntervalMs; } /** * When 'snapshot.mode' is set as configuration_based, this setting permits * to specify whenever the schema should be snapshotted or not in case of * error. */ public void setSnapshotModeConfigurationBasedSnapshotOnSchemaError( boolean snapshotModeConfigurationBasedSnapshotOnSchemaError) { this.snapshotModeConfigurationBasedSnapshotOnSchemaError = snapshotModeConfigurationBasedSnapshotOnSchemaError; } public boolean isSnapshotModeConfigurationBasedSnapshotOnSchemaError() { return snapshotModeConfigurationBasedSnapshotOnSchemaError; } /** * Controls the action Debezium will take when it meets a DDL statement in * binlog, that it cannot parse.By default the connector will stop operating * but by changing the setting it can ignore the statements which it cannot * parse. If skipping is enabled then Debezium can miss metadata changes. */ public void setSchemaHistoryInternalSkipUnparseableDdl( boolean schemaHistoryInternalSkipUnparseableDdl) { this.schemaHistoryInternalSkipUnparseableDdl = schemaHistoryInternalSkipUnparseableDdl; } public boolean isSchemaHistoryInternalSkipUnparseableDdl() { return schemaHistoryInternalSkipUnparseableDdl; } /** * Regular expressions matching columns to include in change events */ public void setColumnIncludeList(String columnIncludeList) { this.columnIncludeList = columnIncludeList; } public String getColumnIncludeList() { return columnIncludeList; } /** * A comma-separated list of regular expressions matching fully-qualified * names of columns that adds the columns original type and original length * as parameters to the corresponding field schemas in the emitted change * records. */ public void setColumnPropagateSourceType(String columnPropagateSourceType) { this.columnPropagateSourceType = columnPropagateSourceType; } public String getColumnPropagateSourceType() { return columnPropagateSourceType; } /** * The maximum number of retries on connection errors before failing (-1 = * no limit, 0 = disabled, > 0 = num of retries). */ public void setErrorsMaxRetries(int errorsMaxRetries) { this.errorsMaxRetries = errorsMaxRetries; } public int getErrorsMaxRetries() { return errorsMaxRetries; } /** * A comma-separated list of regular expressions that match the * fully-qualified names of tables to be excluded from monitoring */ public void setTableExcludeList(String tableExcludeList) { this.tableExcludeList = tableExcludeList; } public String getTableExcludeList() { return tableExcludeList; } /** * Password of the database user to be used when connecting to the database. */ public void setDatabasePassword(String databasePassword) { this.databasePassword = databasePassword; } public String getDatabasePassword() { return databasePassword; } /** * Maximum size of each batch of source records. Defaults to 2048. */ public void setMaxBatchSize(int maxBatchSize) { this.maxBatchSize = maxBatchSize; } public int getMaxBatchSize() { return maxBatchSize; } /** * The comma-separated list of operations to skip during streaming, defined * as: 'c' for inserts/create; 'u' for updates; 'd' for deletes, 't' for * truncates, and 'none' to indicate nothing skipped. By default, only * truncate operations will be skipped. */ public void setSkippedOperations(String skippedOperations) { this.skippedOperations = skippedOperations; } public String getSkippedOperations() { return skippedOperations; } /** * The job's description emitted by Debezium */ public void setOpenlineageIntegrationJobDescription( String openlineageIntegrationJobDescription) { this.openlineageIntegrationJobDescription = openlineageIntegrationJobDescription; } public String getOpenlineageIntegrationJobDescription() { return openlineageIntegrationJobDescription; } /** * The name of the TopicNamingStrategy
Db2ConnectorEmbeddedDebeziumConfiguration
java
apache__flink
flink-kubernetes/src/test/java/org/apache/flink/kubernetes/configuration/KubernetesDeploymentTargetTest.java
{ "start": 1188, "end": 3175 }
class ____ { @Test void testCorrectInstantiationFromConfiguration() { for (KubernetesDeploymentTarget t : KubernetesDeploymentTarget.values()) { testCorrectInstantiationFromConfigurationHelper(t); } } @Test public void testInvalidInstantiationFromConfiguration() { final Configuration configuration = getConfigurationWithTarget("invalid-target"); assertThatThrownBy(() -> KubernetesDeploymentTarget.fromConfig(configuration)) .isInstanceOf(IllegalArgumentException.class); } @Test public void testNullInstantiationFromConfiguration() { assertThatThrownBy(() -> KubernetesDeploymentTarget.fromConfig(new Configuration())) .isInstanceOf(IllegalArgumentException.class); } @Test void testThatAValidOptionIsValid() { assertThat( KubernetesDeploymentTarget.isValidKubernetesTarget( KubernetesDeploymentTarget.APPLICATION.getName())) .isTrue(); } @Test void testThatAnInvalidOptionIsInvalid() { assertThat(KubernetesDeploymentTarget.isValidKubernetesTarget("invalid-target")).isFalse(); } private void testCorrectInstantiationFromConfigurationHelper( final KubernetesDeploymentTarget expectedDeploymentTarget) { final Configuration configuration = getConfigurationWithTarget(expectedDeploymentTarget.getName().toUpperCase()); final KubernetesDeploymentTarget actualDeploymentTarget = KubernetesDeploymentTarget.fromConfig(configuration); assertThat(expectedDeploymentTarget).isSameAs(actualDeploymentTarget); } private Configuration getConfigurationWithTarget(final String target) { final Configuration configuration = new Configuration(); configuration.set(DeploymentOptions.TARGET, target); return configuration; } }
KubernetesDeploymentTargetTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/memory/SharedResources.java
{ "start": 4976, "end": 5193 }
interface ____<T extends AutoCloseable> { T resourceHandle(); long size(); } // ------------------------------------------------------------------------ private static final
ResourceAndSize
java
qos-ch__slf4j
slf4j-reload4j/src/test/java/org/slf4j/reload4j/InvocationTest.java
{ "start": 1812, "end": 6757 }
class ____ { ListAppender listAppender = new ListAppender(); org.apache.log4j.Logger root; @Before public void setUp() throws Exception { root = org.apache.log4j.Logger.getRootLogger(); root.addAppender(listAppender); } @After public void tearDown() throws Exception { root.getLoggerRepository().resetConfiguration(); } @Test public void test1() { Logger logger = LoggerFactory.getLogger("test1"); logger.debug("Hello world."); assertEquals(1, listAppender.list.size()); } @Test public void test2() { Integer i1 = Integer.valueOf(1); Integer i2 = Integer.valueOf(2); Integer i3 = Integer.valueOf(3); Exception e = new Exception("This is a test exception."); Logger logger = LoggerFactory.getLogger("test2"); logger.trace("Hello trace."); logger.debug("Hello world 1."); logger.debug("Hello world {}", i1); logger.debug("val={} val={}", i1, i2); logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); logger.debug("Hello world 2", e); logger.info("Hello world 2."); logger.warn("Hello world 3."); logger.warn("Hello world 3", e); logger.error("Hello world 4."); logger.error("Hello world {}", Integer.valueOf(3)); logger.error("Hello world 4.", e); assertEquals(11, listAppender.list.size()); } @Test public void testNull() { Logger logger = LoggerFactory.getLogger("testNull"); logger.trace(null); logger.debug(null); logger.info(null); logger.warn(null); logger.error(null); Exception e = new Exception("This is a test exception."); logger.debug(null, e); logger.info(null, e); logger.warn(null, e); logger.error(null, e); assertEquals(8, listAppender.list.size()); } // http://jira.qos.ch/browse/SLF4J-69 // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78 @Test public void testNullParameter_BUG78() { Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); String[] parameters = null; String msg = "hello {}"; logger.debug(msg, (Object[]) parameters); assertEquals(1, listAppender.list.size()); LoggingEvent e = (LoggingEvent) listAppender.list.get(0); assertEquals(msg, e.getMessage()); } @Test public void testMarker() { Logger logger = LoggerFactory.getLogger("testMarker"); Marker blue = MarkerFactory.getMarker("BLUE"); logger.trace(blue, "hello"); logger.debug(blue, "hello"); logger.info(blue, "hello"); logger.warn(blue, "hello"); logger.error(blue, "hello"); logger.debug(blue, "hello {}", "world"); logger.info(blue, "hello {}", "world"); logger.warn(blue, "hello {}", "world"); logger.error(blue, "hello {}", "world"); logger.debug(blue, "hello {} and {} ", "world", "universe"); logger.info(blue, "hello {} and {} ", "world", "universe"); logger.warn(blue, "hello {} and {} ", "world", "universe"); logger.error(blue, "hello {} and {} ", "world", "universe"); assertEquals(12, listAppender.list.size()); } @Test public void testMDC() { MDC.put("k", "v"); assertNotNull(MDC.get("k")); assertEquals("v", MDC.get("k")); MDC.remove("k"); assertNull(MDC.get("k")); MDC.put("k1", "v1"); assertEquals("v1", MDC.get("k1")); MDC.clear(); assertNull(MDC.get("k1")); try { MDC.put(null, "x"); fail("null keys are invalid"); } catch (IllegalArgumentException e) { } } @Test public void testMDCContextMapValues() { Map<String, String> map = new HashMap<>(); map.put("ka", "va"); map.put("kb", "vb"); MDC.put("k", "v"); assertEquals("v", MDC.get("k")); MDC.setContextMap(map); assertNull(MDC.get("k")); assertEquals("va", MDC.get("ka")); assertEquals("vb", MDC.get("kb")); } @Test public void testCallerInfo() { Logger logger = LoggerFactory.getLogger("testMarker"); listAppender.extractLocationInfo = true; logger.debug("hello"); LoggingEvent event = listAppender.list.get(0); assertEquals(this.getClass().getName(), event.getLocationInformation().getClassName()); } @Test public void testCallerInfoWithFluentAPI() { Logger logger = LoggerFactory.getLogger("testMarker"); listAppender.extractLocationInfo = true; logger.atDebug().log("hello"); LoggingEvent event = listAppender.list.get(0); assertEquals(this.getClass().getName(), event.getLocationInformation().getClassName()); } }
InvocationTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/InnerInnerTest.java
{ "start": 227, "end": 501 }
class ____{ private String name; private InnerInner ii; public String getName() { return name; } public void setName(String name) { this.name = name; } public InnerInner getIi() { return ii; } public void setIi(InnerInner ii) { this.ii = ii; }
Outter
java
apache__flink
flink-queryable-state/flink-queryable-state-runtime/src/test/java/org/apache/flink/queryablestate/network/MessageSerializerTest.java
{ "start": 1730, "end": 9366 }
class ____ { private final ByteBufAllocator alloc = UnpooledByteBufAllocator.DEFAULT; /** Tests request serialization. */ @Test void testRequestSerialization() throws Exception { long requestId = Integer.MAX_VALUE + 1337L; KvStateID kvStateId = new KvStateID(); byte[] serializedKeyAndNamespace = randomByteArray(1024); final KvStateInternalRequest request = new KvStateInternalRequest(kvStateId, serializedKeyAndNamespace); final MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); ByteBuf buf = MessageSerializer.serializeRequest(alloc, requestId, request); int frameLength = buf.readInt(); assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST); assertThat(MessageSerializer.getRequestId(buf)).isEqualTo(requestId); KvStateInternalRequest requestDeser = serializer.deserializeRequest(buf); assertThat(buf.readerIndex()).isEqualTo(frameLength + 4); assertThat(requestDeser.getKvStateId()).isEqualTo(kvStateId); assertThat(requestDeser.getSerializedKeyAndNamespace()) .isEqualTo(serializedKeyAndNamespace); } /** Tests request serialization with zero-length serialized key and namespace. */ @Test void testRequestSerializationWithZeroLengthKeyAndNamespace() throws Exception { long requestId = Integer.MAX_VALUE + 1337L; KvStateID kvStateId = new KvStateID(); byte[] serializedKeyAndNamespace = new byte[0]; final KvStateInternalRequest request = new KvStateInternalRequest(kvStateId, serializedKeyAndNamespace); final MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); ByteBuf buf = MessageSerializer.serializeRequest(alloc, requestId, request); int frameLength = buf.readInt(); assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST); assertThat(MessageSerializer.getRequestId(buf)).isEqualTo(requestId); KvStateInternalRequest requestDeser = serializer.deserializeRequest(buf); assertThat(buf.readerIndex()).isEqualTo(frameLength + 4); assertThat(requestDeser.getKvStateId()).isEqualTo(kvStateId); assertThat(requestDeser.getSerializedKeyAndNamespace()) .isEqualTo(serializedKeyAndNamespace); } /** * Tests that we don't try to be smart about <code>null</code> key and namespace. They should be * treated explicitly. */ @Test void testNullPointerExceptionOnNullSerializedKeyAndNamepsace() throws Exception { assertThatThrownBy(() -> new KvStateInternalRequest(new KvStateID(), null)) .isInstanceOf(NullPointerException.class); } /** Tests response serialization. */ @Test void testResponseSerialization() throws Exception { long requestId = Integer.MAX_VALUE + 72727278L; byte[] serializedResult = randomByteArray(1024); final KvStateResponse response = new KvStateResponse(serializedResult); final MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); ByteBuf buf = MessageSerializer.serializeResponse(alloc, requestId, response); int frameLength = buf.readInt(); assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_RESULT); assertThat(MessageSerializer.getRequestId(buf)).isEqualTo(requestId); KvStateResponse responseDeser = serializer.deserializeResponse(buf); assertThat(buf.readerIndex()).isEqualTo(frameLength + 4); assertThat(responseDeser.getContent()).isEqualTo(serializedResult); } /** Tests response serialization with zero-length serialized result. */ @Test void testResponseSerializationWithZeroLengthSerializedResult() throws Exception { byte[] serializedResult = new byte[0]; final KvStateResponse response = new KvStateResponse(serializedResult); final MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); ByteBuf buf = MessageSerializer.serializeResponse(alloc, 72727278L, response); int frameLength = buf.readInt(); assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_RESULT); assertThat(MessageSerializer.getRequestId(buf)).isEqualTo(72727278L); KvStateResponse responseDeser = serializer.deserializeResponse(buf); assertThat(buf.readerIndex()).isEqualTo(frameLength + 4); assertThat(responseDeser.getContent()).isEqualTo(serializedResult); } /** * Tests that we don't try to be smart about <code>null</code> results. They should be treated * explicitly. */ @Test void testNullPointerExceptionOnNullSerializedResult() throws Exception { assertThatThrownBy(() -> new KvStateResponse((byte[]) null)) .isInstanceOf(NullPointerException.class); } /** Tests request failure serialization. */ @Test void testKvStateRequestFailureSerialization() throws Exception { long requestId = Integer.MAX_VALUE + 1111222L; IllegalStateException cause = new IllegalStateException("Expected test"); ByteBuf buf = MessageSerializer.serializeRequestFailure(alloc, requestId, cause); int frameLength = buf.readInt(); assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.REQUEST_FAILURE); RequestFailure requestFailure = MessageSerializer.deserializeRequestFailure(buf); assertThat(buf.readerIndex()).isEqualTo(frameLength + 4); assertThat(requestFailure.getRequestId()).isEqualTo(requestId); assertThat(requestFailure.getCause()).isInstanceOf(cause.getClass()); assertThat(requestFailure.getCause().getMessage()).isEqualTo(cause.getMessage()); } /** Tests server failure serialization. */ @Test void testServerFailureSerialization() throws Exception { IllegalStateException cause = new IllegalStateException("Expected test"); ByteBuf buf = MessageSerializer.serializeServerFailure(alloc, cause); int frameLength = buf.readInt(); assertThat(MessageSerializer.deserializeHeader(buf)).isEqualTo(MessageType.SERVER_FAILURE); Throwable request = MessageSerializer.deserializeServerFailure(buf); assertThat(buf.readerIndex()).isEqualTo(frameLength + 4); assertThat(request).isInstanceOf(cause.getClass()); assertThat(request.getMessage()).isEqualTo(cause.getMessage()); } private byte[] randomByteArray(int capacity) { byte[] bytes = new byte[capacity]; ThreadLocalRandom.current().nextBytes(bytes); return bytes; } }
MessageSerializerTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/balancer/TestBalancerWithMultipleNameNodes.java
{ "start": 3134, "end": 23221 }
class ____ { final Configuration conf; final MiniDFSCluster cluster; final ClientProtocol[] clients; final short replication; final BalancerParameters parameters; Suite(MiniDFSCluster cluster, final int nNameNodes, final int nDataNodes, BalancerParameters parameters, Configuration conf) throws IOException { this.conf = conf; this.cluster = cluster; clients = new ClientProtocol[nNameNodes]; for(int i = 0; i < nNameNodes; i++) { clients[i] = cluster.getNameNode(i).getRpcServer(); } // hard coding replication factor to 1 so logical and raw HDFS size are // equal replication = 1; this.parameters = parameters; } Suite(MiniDFSCluster cluster, final int nNameNodes, final int nDataNodes, BalancerParameters parameters, Configuration conf, short replicationFactor) throws IOException { this.conf = conf; this.cluster = cluster; clients = new ClientProtocol[nNameNodes]; for(int i = 0; i < nNameNodes; i++) { clients[i] = cluster.getNameNode(i).getRpcServer(); } replication = replicationFactor; this.parameters = parameters; } } /* create a file with a length of <code>fileLen</code> */ private static void createFile(Suite s, int index, long len ) throws IOException, InterruptedException, TimeoutException { final FileSystem fs = s.cluster.getFileSystem(index); DFSTestUtil.createFile(fs, FILE_PATH, len, s.replication, RANDOM.nextLong()); DFSTestUtil.waitReplication(fs, FILE_PATH, s.replication); } /* fill up a cluster with <code>numNodes</code> datanodes * whose used space to be <code>size</code> */ private static ExtendedBlock[][] generateBlocks(Suite s, long size ) throws IOException, InterruptedException, TimeoutException { final ExtendedBlock[][] blocks = new ExtendedBlock[s.clients.length][]; for(int n = 0; n < s.clients.length; n++) { createFile(s, n, size); final List<LocatedBlock> locatedBlocks = s.clients[n].getBlockLocations(FILE_NAME, 0, size).getLocatedBlocks(); final int numOfBlocks = locatedBlocks.size(); blocks[n] = new ExtendedBlock[numOfBlocks]; for(int i = 0; i < numOfBlocks; i++) { final ExtendedBlock b = locatedBlocks.get(i).getBlock(); blocks[n][i] = new ExtendedBlock(b.getBlockPoolId(), b.getBlockId(), b.getNumBytes(), b.getGenerationStamp()); } } return blocks; } /* wait for one heartbeat */ static void wait(final Suite suite, long expectedUsedSpace, long expectedTotalSpace) throws IOException { LOG.info("WAIT expectedUsedSpace=" + expectedUsedSpace + ", expectedTotalSpace=" + expectedTotalSpace); suite.cluster.triggerHeartbeats(); for(int n = 0; n < suite.clients.length; n++) { int i = 0; for(boolean done = false; !done; ) { final long[] s = suite.clients[n].getStats(); done = s[0] == expectedTotalSpace && s[1] >= expectedUsedSpace; if (!done) { sleep(100L); if (++i % 100 == 0) { LOG.warn("WAIT i=" + i + ", s=[" + s[0] + ", " + s[1] + "]"); } } } } } static void runBalancer(Suite s, final long totalUsed, final long totalCapacity) throws Exception { double avg = totalUsed*100.0/totalCapacity; LOG.info("BALANCER 0: totalUsed=" + totalUsed + ", totalCapacity=" + totalCapacity + ", avg=" + avg); wait(s, totalUsed, totalCapacity); LOG.info("BALANCER 1"); // get storage reports for relevant blockpools so that we can compare // blockpool usages after balancer has run Map<Integer, DatanodeStorageReport[]> preBalancerPoolUsages = getStorageReports(s); // start rebalancing final Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(s.conf); final int r = Balancer.run(namenodes, s.parameters, s.conf); assertEquals(ExitStatus.SUCCESS.getExitCode(), r); LOG.info("BALANCER 2"); wait(s, totalUsed, totalCapacity); LOG.info("BALANCER 3"); int i = 0; for(boolean balanced = false; !balanced; i++) { final long[] used = new long[s.cluster.getDataNodes().size()]; final long[] cap = new long[used.length]; final long[][] bpUsed = new long[s.clients.length][s.cluster .getDataNodes().size()]; for(int n = 0; n < s.clients.length; n++) { final DatanodeInfo[] datanodes = s.clients[n].getDatanodeReport( DatanodeReportType.ALL); assertEquals(datanodes.length, used.length); for(int d = 0; d < datanodes.length; d++) { if (n == 0) { used[d] = datanodes[d].getDfsUsed(); cap[d] = datanodes[d].getCapacity(); if (i % 100 == 0) { LOG.warn("datanodes[" + d + "]: getDfsUsed()=" + datanodes[d].getDfsUsed() + ", getCapacity()=" + datanodes[d].getCapacity()); } } else { assertEquals(used[d], datanodes[d].getDfsUsed()); assertEquals(cap[d], datanodes[d].getCapacity()); } bpUsed[n][d] = datanodes[d].getBlockPoolUsed(); } } balanced = true; for(int d = 0; d < used.length; d++) { double p; if(s.parameters.getBalancingPolicy() == BalancingPolicy.Pool.INSTANCE) { for (int k = 0; k < s.parameters.getBlockPools().size(); k++) { avg = TestBalancer.sum(bpUsed[k])*100/totalCapacity; p = bpUsed[k][d] * 100.0 / cap[d]; balanced = p <= avg + s.parameters.getThreshold(); if (!balanced) { if (i % 100 == 0) { LOG.warn("datanodes " + d + " is not yet balanced: " + "block pool used=" + bpUsed[d][k] + ", cap=" + cap[d] + ", avg=" + avg); LOG.warn("sum(blockpoolUsed)=" + TestBalancer.sum(bpUsed[k]) + ", sum(cap)=" + TestBalancer.sum(cap)); } sleep(100); break; } } if (!balanced) { break; } } else { p = used[d] * 100.0 / cap[d]; balanced = p <= avg + s.parameters.getThreshold(); if (!balanced) { if (i % 100 == 0) { LOG.warn("datanodes " + d + " is not yet balanced: " + "used=" + used[d] + ", cap=" + cap[d] + ", avg=" + avg); LOG.warn("sum(used)=" + TestBalancer.sum(used) + ", sum(cap)=" + TestBalancer.sum(cap)); } sleep(100); break; } } } } LOG.info("BALANCER 6"); // cluster is balanced, verify that only selected blockpools were touched Map<Integer, DatanodeStorageReport[]> postBalancerPoolUsages = getStorageReports(s); assertEquals(preBalancerPoolUsages.size(), postBalancerPoolUsages.size()); for (Map.Entry<Integer, DatanodeStorageReport[]> entry : preBalancerPoolUsages.entrySet()) { compareTotalPoolUsage(entry.getValue(), postBalancerPoolUsages.get(entry.getKey())); } } /** * Compare the total blockpool usage on each datanode to ensure that nothing * was balanced. * * @param preReports storage reports from pre balancer run * @param postReports storage reports from post balancer run */ private static void compareTotalPoolUsage(DatanodeStorageReport[] preReports, DatanodeStorageReport[] postReports) { assertNotNull(preReports); assertNotNull(postReports); assertEquals(preReports.length, postReports.length); for (DatanodeStorageReport preReport : preReports) { String dnUuid = preReport.getDatanodeInfo().getDatanodeUuid(); for (DatanodeStorageReport postReport : postReports) { if (postReport.getDatanodeInfo().getDatanodeUuid().equals(dnUuid)) { assertEquals(getTotalPoolUsage(preReport), getTotalPoolUsage(postReport)); LOG.info("Comparision of datanode pool usage pre/post balancer run. " + "PrePoolUsage: " + getTotalPoolUsage(preReport) + ", PostPoolUsage: " + getTotalPoolUsage(postReport)); break; } } } } private static long getTotalPoolUsage(DatanodeStorageReport report) { long usage = 0L; for (StorageReport sr : report.getStorageReports()) { usage += sr.getBlockPoolUsed(); } return usage; } /** * Get the storage reports for all blockpools that were not specified by the * balancer blockpool parameters. If none were specified then the parameter * was not set and do not return any reports. * * @param s suite for the test * @return a map of storage reports where the key is the blockpool index * @throws IOException */ private static Map<Integer, DatanodeStorageReport[]> getStorageReports(Suite s) throws IOException { Map<Integer, DatanodeStorageReport[]> reports = new HashMap<Integer, DatanodeStorageReport[]>(); if (s.parameters.getBlockPools().size() == 0) { // the blockpools parameter was not set, so we don't need to track any // blockpools. return Collections.emptyMap(); } for (int i = 0; i < s.clients.length; i++) { if (s.parameters.getBlockPools().contains( s.cluster.getNamesystem(i) .getBlockPoolId())) { // we want to ensure that blockpools not specified by the balancer // parameters were left alone. Therefore, if the pool was specified, // skip it. Note: this code assumes the clients in the suite are ordered // the same way that they are indexed via cluster#getNamesystem(index). continue; } else { LOG.info("Tracking usage of blockpool id: " + s.cluster.getNamesystem(i).getBlockPoolId()); reports.put(i, s.clients[i].getDatanodeStorageReport(DatanodeReportType.LIVE)); } } LOG.info("Tracking " + reports.size() + " blockpool(s) for pre/post balancer usage."); return reports; } private static void sleep(long ms) { try { Thread.sleep(ms); } catch(InterruptedException e) { LOG.error("{}", e); } } private static Configuration createConf() { final Configuration conf = new HdfsConfiguration(); TestBalancer.initConf(conf); return conf; } /** * First start a cluster and fill the cluster up to a certain size. Then * redistribute blocks according the required distribution. Finally, balance * the cluster. * * @param nNameNodes Number of NameNodes * @param nNameNodesToBalance Number of NameNodes to run the balancer on * @param distributionPerNN The distribution for each NameNode. * @param capacities Capacities of the datanodes * @param racks Rack names * @param conf Configuration */ private void unevenDistribution(final int nNameNodes, final int nNameNodesToBalance, long distributionPerNN[], long capacities[], String[] racks, Configuration conf) throws Exception { LOG.info("UNEVEN 0"); final int nDataNodes = distributionPerNN.length; if (capacities.length != nDataNodes || racks.length != nDataNodes) { throw new IllegalArgumentException("Array length is not the same"); } if (nNameNodesToBalance > nNameNodes) { throw new IllegalArgumentException("Number of namenodes to balance is " + "greater than the number of namenodes."); } // calculate total space that need to be filled final long usedSpacePerNN = TestBalancer.sum(distributionPerNN); // fill the cluster final ExtendedBlock[][] blocks; { LOG.info("UNEVEN 1"); final MiniDFSCluster cluster = new MiniDFSCluster .Builder(new Configuration(conf)) .nnTopology(MiniDFSNNTopology.simpleFederatedTopology(nNameNodes)) .numDataNodes(nDataNodes) .racks(racks) .simulatedCapacities(capacities) .build(); LOG.info("UNEVEN 2"); try { cluster.waitActive(); DFSTestUtil.setFederatedConfiguration(cluster, conf); LOG.info("UNEVEN 3"); final Suite s = new Suite(cluster, nNameNodes, nDataNodes, null, conf); blocks = generateBlocks(s, usedSpacePerNN); LOG.info("UNEVEN 4"); } finally { cluster.shutdown(); } } conf.set(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, "0.0f"); // Adjust the capacity of each DN since it will redistribute blocks // nNameNodes times in the following operations. long[] newCapacities = new long[nDataNodes]; for (int i = 0; i < nDataNodes; i++) { newCapacities[i] = capacities[i] * nNameNodes; } { LOG.info("UNEVEN 10"); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .nnTopology(MiniDFSNNTopology.simpleFederatedTopology(nNameNodes)) .numDataNodes(nDataNodes) .racks(racks) .simulatedCapacities(newCapacities) .format(false) .build(); LOG.info("UNEVEN 11"); try { cluster.waitActive(); LOG.info("UNEVEN 12"); Set<String> blockpools = new HashSet<String>(); for (int i = 0; i < nNameNodesToBalance; i++) { blockpools.add(cluster.getNamesystem(i).getBlockPoolId()); } BalancerParameters.Builder b = new BalancerParameters.Builder(); b.setBlockpools(blockpools); BalancerParameters params = b.build(); final Suite s = new Suite(cluster, nNameNodes, nDataNodes, params, conf); for(int n = 0; n < nNameNodes; n++) { // redistribute blocks final Block[][] blocksDN = TestBalancer.distributeBlocks( blocks[n], s.replication, distributionPerNN); for(int d = 0; d < blocksDN.length; d++) cluster.injectBlocks(n, d, Arrays.asList(blocksDN[d])); LOG.info("UNEVEN 13: n=" + n); } final long totalCapacity = TestBalancer.sum(newCapacities); final long totalUsed = nNameNodes*usedSpacePerNN; LOG.info("UNEVEN 14"); runBalancer(s, totalUsed, totalCapacity); LOG.info("UNEVEN 15"); } finally { cluster.shutdown(); } LOG.info("UNEVEN 16"); } } /** * This test start a cluster, fill the DataNodes to be 30% full; * It then adds an empty node and start balancing. * * @param nNameNodes Number of NameNodes * @param racks Rack names * @param newRack the rack for the new DataNode * @param conf Configuration * @param nNameNodestoBalance noOfNameNodestoBalance * @param balancerParameters BalancerParameters */ private void runTest(final int nNameNodes, String[] racks, String[] newRack, Configuration conf, int nNameNodestoBalance, BalancerParameters balancerParameters) throws Exception { final int nDataNodes = racks.length; final long[] capacities = new long[nDataNodes]; Arrays.fill(capacities, CAPACITY); LOG.info("nNameNodes=" + nNameNodes + ", nDataNodes=" + nDataNodes); assertEquals(nDataNodes, racks.length); LOG.info("RUN_TEST -1: start a cluster with nNameNodes=" + nNameNodes + ", nDataNodes=" + nDataNodes); final MiniDFSCluster cluster = new MiniDFSCluster .Builder(new Configuration(conf)) .nnTopology(MiniDFSNNTopology.simpleFederatedTopology(nNameNodes)) .numDataNodes(nDataNodes) .racks(racks) .simulatedCapacities(capacities) .build(); LOG.info("RUN_TEST 0"); DFSTestUtil.setFederatedConfiguration(cluster, conf); try { cluster.waitActive(); LOG.info("RUN_TEST 1"); Suite s; Set<String> blockpools = new HashSet<>(); if(balancerParameters == null) { s = new Suite(cluster, nNameNodes, nDataNodes, BalancerParameters.DEFAULT, conf); } else { for (int i=0; i< nNameNodestoBalance; i++) { blockpools.add(cluster.getNamesystem(i).getBlockPoolId()); } BalancerParameters.Builder b = new BalancerParameters.Builder(); b.setBalancingPolicy(balancerParameters.getBalancingPolicy()); b.setBlockpools(blockpools); BalancerParameters params = b.build(); s = new Suite(cluster, nNameNodes, nDataNodes, params, conf, (short)2); } long totalCapacity = TestBalancer.sum(capacities); LOG.info("RUN_TEST 2: create files"); // fill up the cluster to be 30% full final long totalUsed = totalCapacity * 3 / 10; final long size = (totalUsed/nNameNodes)/s.replication; for(int n = 0; n < nNameNodes; n++) { createFile(s, n, size); } LOG.info("RUN_TEST 3: " + newRack.length + " new datanodes"); // start up an empty node with the same capacity and on the same rack final long[] newCapacity = new long[newRack.length]; Arrays.fill(newCapacity, CAPACITY); cluster.startDataNodes(conf, newCapacity.length, true, null, newRack, newCapacity); totalCapacity += TestBalancer.sum(newCapacity); LOG.info("RUN_TEST 4: run Balancer"); // run RUN_TEST and validate results runBalancer(s, totalUsed, totalCapacity); LOG.info("RUN_TEST 5"); } finally { cluster.shutdown(); } LOG.info("RUN_TEST 6: done"); } /** Test a cluster with even distribution, * then a new empty node is added to the cluster. */ @Test public void testTwoOneOne() throws Exception { final Configuration conf = createConf(); runTest(2, new String[]{RACK0}, new String[] {RACK0}, conf, 2, null); } /** Test unevenly distributed cluster */ @Test public void testUnevenDistribution() throws Exception { final Configuration conf = createConf(); unevenDistribution(2, 2, new long[] {30*CAPACITY/100, 5*CAPACITY/100}, new long[]{CAPACITY, CAPACITY}, new String[] {RACK0, RACK1}, conf); } @Test public void testBalancing1OutOf2Blockpools() throws Exception { final Configuration conf = createConf(); unevenDistribution(2, 1, new long[] { 30 * CAPACITY / 100, 5 * CAPACITY / 100 }, new long[] { CAPACITY, CAPACITY }, new String[] { RACK0, RACK1 }, conf); } @Test public void testBalancing2OutOf3Blockpools() throws Exception { final Configuration conf = createConf(); unevenDistribution(3, 2, new long[] { 30 * CAPACITY / 100, 5 * CAPACITY / 100, 10 * CAPACITY / 100 }, new long[] { CAPACITY, CAPACITY, CAPACITY }, new String[] { RACK0, RACK1, RACK2 }, conf); } /** Even distribution with 2 Namenodes, 4 Datanodes and 2 new Datanodes. */ @Test @Timeout(value = 600) public void testTwoFourTwo() throws Exception { final Configuration conf = createConf(); runTest(2, new String[]{RACK0, RACK0, RACK1, RACK1}, new String[]{RACK2, RACK2}, conf, 2, null); } @Test @Timeout(value = 600) public void testBalancingBlockpoolsWithBlockPoolPolicy() throws Exception { final Configuration conf = createConf(); BalancerParameters balancerParameters = new BalancerParameters.Builder() .setBalancingPolicy(BalancingPolicy.Pool.INSTANCE).build(); runTest(2, new String[]{RACK0, RACK0, RACK1, RACK1}, new String[]{RACK2, RACK2}, conf, 2, balancerParameters); } @Test @Timeout(value = 600) public void test1OutOf2BlockpoolsWithBlockPoolPolicy() throws Exception { final Configuration conf = createConf(); BalancerParameters balancerParameters = new BalancerParameters.Builder() .setBalancingPolicy(BalancingPolicy.Pool.INSTANCE).build(); runTest(2, new String[]{RACK0, RACK0, RACK1, RACK1}, new String[]{RACK2, RACK2}, conf, 1, balancerParameters); } }
Suite
java
google__guava
guava/src/com/google/common/collect/RegularImmutableSet.java
{ "start": 1210, "end": 3841 }
class ____<E> extends ImmutableSet.CachingAsList<E> { private static final Object[] EMPTY_ARRAY = new Object[0]; static final RegularImmutableSet<Object> EMPTY = new RegularImmutableSet<>(EMPTY_ARRAY, 0, EMPTY_ARRAY, 0); private final transient Object[] elements; private final transient int hashCode; // the same values as `elements` in hashed positions (plus nulls) @VisibleForTesting final transient @Nullable Object[] table; // 'and' with an int to get a valid table index. private final transient int mask; RegularImmutableSet(Object[] elements, int hashCode, @Nullable Object[] table, int mask) { this.elements = elements; this.hashCode = hashCode; this.table = table; this.mask = mask; } @Override public boolean contains(@Nullable Object target) { @Nullable Object[] table = this.table; if (target == null || table.length == 0) { return false; } for (int i = Hashing.smearedHash(target); ; i++) { i &= mask; Object candidate = table[i]; if (candidate == null) { return false; } else if (candidate.equals(target)) { return true; } } } @Override public int size() { return elements.length; } // We're careful to put only E instances into the array in the mainline. // (In the backport, we don't need this suppression, but we keep it to minimize diffs.) @SuppressWarnings("unchecked") @Override public UnmodifiableIterator<E> iterator() { return (UnmodifiableIterator<E>) Iterators.forArray(elements); } @Override public Spliterator<E> spliterator() { return Spliterators.spliterator(elements, SPLITERATOR_CHARACTERISTICS); } @Override Object[] internalArray() { return elements; } @Override int internalArrayStart() { return 0; } @Override int internalArrayEnd() { return elements.length; } @Override int copyIntoArray(@Nullable Object[] dst, int offset) { arraycopy(elements, 0, dst, offset, elements.length); return offset + elements.length; } @Override ImmutableList<E> createAsList() { return (table.length == 0) ? ImmutableList.of() : new RegularImmutableAsList<>(this, elements); } @Override boolean isPartialView() { return false; } @Override public int hashCode() { return hashCode; } @Override boolean isHashCodeFast() { return true; } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible @GwtIncompatible Object writeReplace() { return super.writeReplace(); } }
RegularImmutableSet
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/single/injvm/SingleRegistryCenterInjvmServiceImpl.java
{ "start": 950, "end": 1170 }
class ____ implements SingleRegistryCenterInjvmService { /** * {@inheritDoc} */ @Override public String hello(String name) { return "Hello " + name; } }
SingleRegistryCenterInjvmServiceImpl
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/timer/TimerTest.java
{ "start": 1075, "end": 2439 }
class ____ extends VertxTestBase { @Test public void testTimer() { timer(1); } @Test public void testPeriodic1() { periodic(new PeriodicArg(100, 100), (delay, handler) -> vertx.setPeriodic(delay.delay, handler)); } @Test public void testPeriodic2() { periodic(new PeriodicArg(100, 100), (delay, handler) -> vertx.setPeriodic(delay.delay, delay.delay, handler)); } @Test public void testPeriodicWithInitialDelay1() { periodic(new PeriodicArg(0, 100), (delay, handler) -> vertx.setPeriodic(delay.initialDelay, delay.delay, handler)); } @Test public void testPeriodicWithInitialDelay2() { periodic(new PeriodicArg(100, 200), (delay, handler) -> vertx.setPeriodic(delay.initialDelay, delay.delay, handler)); } /** * Test the timers fire with approximately the correct delay */ @Test public void testTimings() { final long start = System.currentTimeMillis(); final long delay = 2000; vertx.setTimer(delay, timerID -> { long dur = System.currentTimeMillis() - start; assertTrue(dur >= delay); long maxDelay = delay * 2; assertTrue("Timer accuracy: " + dur + " vs " + maxDelay, dur < maxDelay); // 100% margin of error (needed for CI) vertx.cancelTimer(timerID); testComplete(); }); await(); } @Test public void testInVerticle() {
TimerTest
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigMigratePersistServiceImpl.java
{ "start": 3452, "end": 20976 }
class ____ implements ConfigMigratePersistService { private static final String RESOURCE_CONFIG_INFO_ID = "config-info-id"; private static final String RESOURCE_CONFIG_HISTORY_GRAY_ID = "config-history-gray-id"; private final DatabaseOperate databaseOperate; private final IdGeneratorManager idGeneratorManager; private DataSourceService dataSourceService; private MapperManager mapperManager; private ConfigInfoPersistService configInfoPersistService; private ConfigInfoGrayPersistService configInfoGrayPersistService; /** * Instantiates a new Embedded config migrate persist service. * * @param databaseOperate the database operate * @param idGeneratorManager the id generator manager * @param configInfoPersistService the config info persist service * @param configInfoGrayPersistService the config info gray persist service */ public EmbeddedConfigMigratePersistServiceImpl(DatabaseOperate databaseOperate, IdGeneratorManager idGeneratorManager, @Qualifier("embeddedConfigInfoPersistServiceImpl") ConfigInfoPersistService configInfoPersistService, @Qualifier("embeddedConfigInfoGrayPersistServiceImpl") ConfigInfoGrayPersistService configInfoGrayPersistService) { this.databaseOperate = databaseOperate; this.idGeneratorManager = idGeneratorManager; this.dataSourceService = DynamicDataSource.getInstance().getDataSource(); idGeneratorManager.register(RESOURCE_CONFIG_INFO_ID, RESOURCE_CONFIG_HISTORY_GRAY_ID); Boolean isDataSourceLogEnable = EnvUtil.getProperty(CommonConstant.NACOS_PLUGIN_DATASOURCE_LOG, Boolean.class, false); this.mapperManager = MapperManager.instance(isDataSourceLogEnable); NotifyCenter.registerToSharePublisher(DerbyImportEvent.class); this.configInfoPersistService = configInfoPersistService; this.configInfoGrayPersistService = configInfoGrayPersistService; } @Override public <E> PaginationHelper<E> createPaginationHelper() { return new EmbeddedPaginationHelperImpl<>(databaseOperate); } @Override public Integer configInfoConflictCount(String srcUser) { ConfigMigrateMapper configInfoMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.SRC_USER, srcUser); MapperResult mapperResult = configInfoMigrateMapper.getConfigConflictCount(context); Integer result = databaseOperate.queryOne(mapperResult.getSql(), mapperResult.getParamList().toArray(), Integer.class); if (result == null) { throw new IllegalArgumentException("configInfoConflictCount error"); } return result; } @Override public Integer configInfoGrayConflictCount(String srcUser) { ConfigMigrateMapper configInfoMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.SRC_USER, srcUser); MapperResult mapperResult = configInfoMigrateMapper.getConfigGrayConflictCount(context); Integer result = databaseOperate.queryOne(mapperResult.getSql(), mapperResult.getParamList().toArray(), Integer.class); if (result == null) { throw new IllegalArgumentException("configInfoGrayConflictCount error"); } return result; } @Override public List<Long> getMigrateConfigInsertIdList(long startId, int pageSize) { ConfigMigrateMapper configInfoMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.ID, startId); context.setPageSize(pageSize); MapperResult mapperResult = configInfoMigrateMapper.findConfigIdNeedInsertMigrate(context); return databaseOperate.queryMany(mapperResult.getSql(), mapperResult.getParamList().toArray(), Long.class); } @Override public List<Long> getMigrateConfigGrayInsertIdList(long startId, int pageSize) { ConfigMigrateMapper configInfoMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.ID, startId); context.setPageSize(pageSize); MapperResult mapperResult = configInfoMigrateMapper.findConfigGrayIdNeedInsertMigrate(context); return databaseOperate.queryMany(mapperResult.getSql(), mapperResult.getParamList().toArray(), Long.class); } @Override public List<ConfigInfo> getMigrateConfigUpdateList(long startId, int pageSize, String srcTenant, String targetTenant, String srcUser) { ConfigMigrateMapper configMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.SRC_USER, srcUser); context.putWhereParameter(FieldConstant.ID, startId); context.putWhereParameter(FieldConstant.SRC_TENANT, srcTenant); context.putWhereParameter(FieldConstant.TARGET_TENANT, targetTenant); context.setPageSize(pageSize); MapperResult mapperResult = configMigrateMapper.findConfigNeedUpdateMigrate(context); return databaseOperate.queryMany(mapperResult.getSql(), mapperResult.getParamList().toArray(), CONFIG_INFO_ROW_MAPPER); } @Override public List<ConfigInfoGrayWrapper> getMigrateConfigGrayUpdateList(long startId, int pageSize, String srcTenant, String targetTenant, String srcUser) { ConfigMigrateMapper configMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.SRC_USER, srcUser); context.putWhereParameter(FieldConstant.ID, startId); context.putWhereParameter(FieldConstant.SRC_TENANT, srcTenant); context.putWhereParameter(FieldConstant.TARGET_TENANT, targetTenant); context.setPageSize(pageSize); MapperResult mapperResult = configMigrateMapper.findConfigGrayNeedUpdateMigrate(context); return databaseOperate.queryMany(mapperResult.getSql(), mapperResult.getParamList().toArray(), CONFIG_INFO_GRAY_WRAPPER_ROW_MAPPER); } @Override public void migrateConfigInsertByIds(List<Long> ids, String srcUser) { ConfigMigrateMapper configInfoMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); for (Long targetId : ids) { long configId = idGeneratorManager.nextId(RESOURCE_CONFIG_INFO_ID); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.TARGET_ID, targetId); context.putWhereParameter(FieldConstant.SRC_USER, srcUser); context.putWhereParameter(FieldConstant.ID, configId); MapperResult result = configInfoMigrateMapper.migrateConfigInsertByIds(context); EmbeddedStorageContextHolder.addSqlContext(result.getSql(), result.getParamList().toArray()); } databaseOperate.blockUpdate(); } @Override public void migrateConfigGrayInsertByIds(List<Long> ids, String srcUser) { ConfigMigrateMapper configInfoMigrateMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.MIGRATE_CONFIG); for (Long targetId : ids) { long configId = idGeneratorManager.nextId(RESOURCE_CONFIG_HISTORY_GRAY_ID); MapperContext context = new MapperContext(); context.putWhereParameter(FieldConstant.TARGET_ID, targetId); context.putWhereParameter(FieldConstant.ID, configId); context.putWhereParameter(FieldConstant.SRC_USER, srcUser); MapperResult result = configInfoMigrateMapper.migrateConfigGrayInsertByIds(context); EmbeddedStorageContextHolder.addSqlContext(result.getSql(), result.getParamList().toArray()); } databaseOperate.blockUpdate(); } @Override public void syncConfig(String dataId, String group, String tenant, String targetTenant, String srcUser) { ConfigInfoWrapper sourceConfigInfoWrapper = configInfoPersistService.findConfigInfo(dataId, group, tenant); ConfigInfoWrapper targetConfigInfoWrapper = configInfoPersistService.findConfigInfo(dataId, group, targetTenant); if (sourceConfigInfoWrapper == null) { configInfoPersistService.removeConfigInfo(dataId, group, targetTenant, null, srcUser); } else { if (targetConfigInfoWrapper == null) { sourceConfigInfoWrapper.setTenant(targetTenant); long configId = idGeneratorManager.nextId(RESOURCE_CONFIG_INFO_ID); configInfoPersistService.addConfigInfoAtomic(configId, null, srcUser, sourceConfigInfoWrapper, null); } else if (sourceConfigInfoWrapper.getLastModified() >= targetConfigInfoWrapper.getLastModified()) { sourceConfigInfoWrapper.setTenant(targetTenant); updateConfigInfoAtomic(sourceConfigInfoWrapper, null, srcUser, null, targetConfigInfoWrapper.getLastModified(), targetConfigInfoWrapper.getMd5()); } } } /** * Update config info atomic. * * @param configInfo the config info * @param srcIp the src ip * @param srcUser the src user * @param configAdvanceInfo the config advance info * @param lastModified the last modified */ public void updateConfigInfoAtomic(final ConfigInfo configInfo, final String srcIp, final String srcUser, Map<String, Object> configAdvanceInfo, long lastModified, final String targetMd5) { final String appNameTmp = StringUtils.defaultEmptyIfBlank(configInfo.getAppName()); final String tenantTmp = StringUtils.defaultEmptyIfBlank(configInfo.getTenant()); final String md5Tmp = MD5Utils.md5Hex(configInfo.getContent(), Constants.ENCODE); final String desc = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("desc"); final String use = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("use"); final String effect = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("effect"); final String type = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("type"); final String schema = configAdvanceInfo == null ? null : (String) configAdvanceInfo.get("schema"); final String encryptedDataKey = configInfo.getEncryptedDataKey() == null ? StringUtils.EMPTY : configInfo.getEncryptedDataKey(); ConfigInfoMapper configInfoMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO); final String sql = configInfoMapper.update( Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified@NOW()", "app_name", "c_desc", "c_use", "effect", "type", "c_schema", "encrypted_data_key"), Arrays.asList("data_id", "group_id", "tenant_id", "gmt_modified", "md5")); final Object[] args = new Object[] {configInfo.getContent(), md5Tmp, srcIp, srcUser, appNameTmp, desc, use, effect, type, schema, encryptedDataKey, configInfo.getDataId(), configInfo.getGroup(), tenantTmp, new Timestamp(lastModified), targetMd5}; EmbeddedStorageContextHolder.addSqlContext(sql, args); } @Override public void syncConfigGray(String dataId, String group, String tenant, String grayName, String targetTenant, String srcUser) { ConfigInfoGrayWrapper sourceConfigInfoGrayWrapper = configInfoGrayPersistService.findConfigInfo4Gray(dataId, group, tenant, grayName); ConfigInfoGrayWrapper targetConfigInfoGrayWrapper = configInfoGrayPersistService.findConfigInfo4Gray(dataId, group, targetTenant, grayName); if (sourceConfigInfoGrayWrapper == null) { removeConfigInfoGrayWithoutHistory(dataId, group, targetTenant, grayName, null, srcUser); } else { if (targetConfigInfoGrayWrapper == null) { sourceConfigInfoGrayWrapper.setTenant(targetTenant); long configGrayId = idGeneratorManager.nextId(RESOURCE_CONFIG_HISTORY_GRAY_ID); configInfoGrayPersistService.addConfigInfoGrayAtomic(configGrayId, sourceConfigInfoGrayWrapper, grayName, sourceConfigInfoGrayWrapper.getGrayRule(), null, srcUser); } else if (sourceConfigInfoGrayWrapper.getLastModified() >= targetConfigInfoGrayWrapper.getLastModified()) { sourceConfigInfoGrayWrapper.setTenant(targetTenant); updateConfigInfo4GrayWithoutHistory(sourceConfigInfoGrayWrapper, sourceConfigInfoGrayWrapper.getGrayName(), sourceConfigInfoGrayWrapper.getGrayRule(), null, srcUser, targetConfigInfoGrayWrapper.getLastModified(), targetConfigInfoGrayWrapper.getMd5()); } } } /** * Remove config info gray without history. * * @param dataId the data id * @param group the group * @param tenant the tenant * @param grayName the gray name * @param srcIp the src ip * @param srcUser the src user */ public void removeConfigInfoGrayWithoutHistory(final String dataId, final String group, final String tenant, final String grayName, final String srcIp, final String srcUser) { String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant; String grayNameTmp = StringUtils.isBlank(grayName) ? StringUtils.EMPTY : grayName; ConfigInfoGrayMapper configInfoGrayMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_GRAY); final String sql = configInfoGrayMapper.delete(Arrays.asList("data_id", "group_id", "tenant_id", "gray_name")); final Object[] args = new Object[] {dataId, group, tenantTmp, grayNameTmp}; EmbeddedStorageContextUtils.onDeleteConfigGrayInfo(tenantTmp, group, dataId, grayNameTmp, srcIp); EmbeddedStorageContextHolder.addSqlContext(sql, args); try { databaseOperate.update(EmbeddedStorageContextHolder.getCurrentSqlContext()); } finally { EmbeddedStorageContextHolder.cleanAllContext(); } } /** * Update config info 4 gray without history. * * @param configInfo the config info * @param grayName the gray name * @param grayRule the gray rule * @param srcIp the src ip * @param srcUser the src user */ public void updateConfigInfo4GrayWithoutHistory(ConfigInfo configInfo, String grayName, String grayRule, String srcIp, String srcUser, long lastModified, final String targetMd5) { String appNameTmp = StringUtils.defaultEmptyIfBlank(configInfo.getAppName()); String tenantTmp = StringUtils.defaultEmptyIfBlank(configInfo.getTenant()); String grayNameTmp = StringUtils.isBlank(grayName) ? StringUtils.EMPTY : grayName.trim(); String grayRuleTmp = StringUtils.isBlank(grayRule) ? StringUtils.EMPTY : grayRule.trim(); configInfo.setTenant(tenantTmp); try { String md5 = MD5Utils.md5Hex(configInfo.getContent(), Constants.ENCODE); ConfigInfoGrayMapper configInfoGrayMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(), TableConstant.CONFIG_INFO_GRAY); Timestamp time = new Timestamp(System.currentTimeMillis()); final String sql = configInfoGrayMapper.update( Arrays.asList("content", "md5", "src_ip", "src_user", "gmt_modified", "app_name", "gray_rule"), Arrays.asList("data_id", "group_id", "tenant_id", "gray_name", "gmt_modified", "md5")); final Object[] args = new Object[] {configInfo.getContent(), md5, srcIp, srcUser, time, appNameTmp, grayRuleTmp, configInfo.getDataId(), configInfo.getGroup(), tenantTmp, grayNameTmp, new Timestamp(lastModified), targetMd5}; EmbeddedStorageContextUtils.onModifyConfigGrayInfo(configInfo, grayNameTmp, grayRuleTmp, srcIp, time); EmbeddedStorageContextHolder.addSqlContext(sql, args); databaseOperate.blockUpdate(); } finally { EmbeddedStorageContextHolder.cleanAllContext(); } } }
EmbeddedConfigMigratePersistServiceImpl
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/seq/TestInnerClassReaderFor.java
{ "start": 390, "end": 670 }
class ____ { private String value; X(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
X
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/inheritance/User.java
{ "start": 338, "end": 604 }
class ____ extends Principal { private String level; public User() { } public User(String uid) { super( uid ); } @Column(name = "user_level") public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } }
User
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/webapp/AppPage.java
{ "start": 1369, "end": 2454 }
class ____ extends AHSView { @Override protected void preHead(Page.HTML<__> html) { commonPreHead(html); String appId = $(YarnWebParams.APPLICATION_ID); set( TITLE, appId.isEmpty() ? "Bad request: missing application ID" : join( "Application ", $(YarnWebParams.APPLICATION_ID))); set(DATATABLES_ID, "attempts ResourceRequests"); set(initID(DATATABLES, "attempts"), WebPageUtils.attemptsTableInit()); setTableStyles(html, "attempts", ".queue {width:6em}", ".ui {width:8em}"); setTableStyles(html, "ResourceRequests"); set(YarnWebParams.WEB_UI_TYPE, YarnWebParams.APP_HISTORY_WEB_UI); } @Override protected Class<? extends SubView> content() { return AppBlock.class; } protected String getAttemptsTableColumnDefs() { StringBuilder sb = new StringBuilder(); return sb.append("[\n").append("{'sType':'natural', 'aTargets': [0]") .append(", 'mRender': parseHadoopID }") .append("\n, {'sType':'numeric', 'aTargets': [1]") .append(", 'mRender': renderHadoopDate }]").toString(); } }
AppPage
java
apache__dubbo
dubbo-metrics/dubbo-metrics-default/src/test/java/org/apache/dubbo/metrics/metrics/model/sample/MetricSampleTest.java
{ "start": 1139, "end": 2165 }
class ____ { private static String name; private static String description; private static Map<String, String> tags; private static MetricSample.Type type; private static MetricsCategory category; private static String baseUnit; @BeforeAll public static void setup() { name = "test"; description = "test"; tags = new HashMap<>(); type = MetricSample.Type.GAUGE; category = MetricsCategory.REQUESTS; baseUnit = "byte"; } @Test void test() { MetricSample sample = new MetricSample(name, description, tags, type, category, baseUnit); Assertions.assertEquals(sample.getName(), name); Assertions.assertEquals(sample.getDescription(), description); Assertions.assertEquals(sample.getTags(), tags); Assertions.assertEquals(sample.getType(), type); Assertions.assertEquals(sample.getCategory(), category); Assertions.assertEquals(sample.getBaseUnit(), baseUnit); } }
MetricSampleTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java
{ "start": 43922, "end": 44504 }
class ____ { public static java.util.function.Function<String, String> identity() { return s -> s; } } """) .doTest(); } @Test public void negativeCases_returnParenthesizedLambda() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/MissingNullableReturnTest.java", """ package com.google.errorprone.bugpatterns.nullness; import javax.annotation.Nullable; public
MissingNullableReturnTest
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/operators/ObjectReuseITCase.java
{ "start": 1728, "end": 5751 }
class ____ extends MultipleProgramsTestBaseJUnit4 { private static final List<Tuple2<String, Integer>> REDUCE_DATA = Arrays.asList( new Tuple2<>("a", 1), new Tuple2<>("a", 2), new Tuple2<>("a", 3), new Tuple2<>("a", 4), new Tuple2<>("a", 50)); private static final List<Tuple2<String, Integer>> GROUP_REDUCE_DATA = Arrays.asList( new Tuple2<>("a", 1), new Tuple2<>("a", 2), new Tuple2<>("a", 3), new Tuple2<>("a", 4), new Tuple2<>("a", 5)); private final boolean objectReuse; public ObjectReuseITCase(boolean objectReuse) { super(TestExecutionMode.CLUSTER); this.objectReuse = objectReuse; } @Test public void testKeyedReduce() throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); if (objectReuse) { env.getConfig().enableObjectReuse(); } else { env.getConfig().disableObjectReuse(); } DataStreamSource<Tuple2<String, Integer>> input = env.fromData(REDUCE_DATA); DataStream<Tuple2<String, Integer>> result = input.keyBy(x -> x.f0) .reduce( new ReduceFunction<Tuple2<String, Integer>>() { @Override public Tuple2<String, Integer> reduce( Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) { value2.f1 += value1.f1; return value2; } }); Tuple2<String, Integer> res = result.executeAndCollect().next(); assertEquals(new Tuple2<>("a", 60), res); } @Test public void testGlobalReduce() throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setRuntimeMode(RuntimeExecutionMode.BATCH); if (objectReuse) { env.getConfig().enableObjectReuse(); } else { env.getConfig().disableObjectReuse(); } DataStreamSource<Tuple2<String, Integer>> input = env.fromData(REDUCE_DATA); DataStream<Tuple2<String, Integer>> result = input.windowAll(GlobalWindows.createWithEndOfStreamTrigger()) .reduce( new ReduceFunction<Tuple2<String, Integer>>() { @Override public Tuple2<String, Integer> reduce( Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) { if (value1.f1 % 3 == 0) { value1.f1 += value2.f1; return value1; } else { value2.f1 += value1.f1; return value2; } } }); Tuple2<String, Integer> res = result.executeAndCollect().next(); assertEquals(new Tuple2<>("a", 60), res); } @Parameterized.Parameters(name = "Execution mode = CLUSTER, Reuse = {0}") public static Collection<Object[]> executionModes() { return Arrays.asList( new Object[] { false, }, new Object[] {true}); } }
ObjectReuseITCase
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/logging/LoggingFilter.java
{ "start": 215, "end": 456 }
class ____ to Quarkus by the specified name. * The filter can then be configured for a handler (like the logging handler using {@code quarkus.log.console.filter}). */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @
known
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableTest2.java
{ "start": 911, "end": 2055 }
class ____ extends TestCase { public void test_alter_first() throws Exception { String sql = "ALTER TABLE `test`.`tb1` ADD COLUMN `f2` VARCHAR(45) NULL FIRST ;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE `test`.`tb1`\n\tADD COLUMN `f2` VARCHAR(45) NULL FIRST;", output); } public void test_alter_add_column() throws Exception { String sql = "ALTER TABLE `test`.`tb1` ADD COLUMN `f2` VARCHAR(45) NULL AFTER `fid` , ADD COLUMN `f3` VARCHAR(45) NULL FIRST `f2`"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE `test`.`tb1`" + "\n\tADD COLUMN `f2` VARCHAR(45) NULL AFTER `fid`," + "\n\tADD COLUMN `f3` VARCHAR(45) NULL FIRST `f2`", output); } }
MySqlAlterTableTest2
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_136.java
{ "start": 385, "end": 1307 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT `tinyint_test` / `tinyint_1bit_test` = `mediumint_test` = `decimal_test` / `double_test`\n" + "FROM `corona_one_db_one_tb`"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT `tinyint_test` / `tinyint_1bit_test` = `mediumint_test` = `decimal_test` / `double_test`\n" + "FROM `corona_one_db_one_tb`", stmt.toString()); assertEquals("SELECT `tinyint_test` / `tinyint_1bit_test` = `mediumint_test` = `decimal_test` / `double_test`\n" + "FROM `corona_one_db_one_tb`", ParameterizedOutputVisitorUtils.parameterize(sql, JdbcConstants.MYSQL)); } }
MySqlSelectTest_136
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/config/Blocked.java
{ "start": 914, "end": 3709 }
enum ____ { NONE, DELETE, RESET, REVERT; public static Reason fromString(String value) { return Reason.valueOf(value.toUpperCase(Locale.ROOT)); } @Override public String toString() { return name().toLowerCase(Locale.ROOT); } } public static final ParseField REASON = new ParseField("reason"); public static final ParseField TASK_ID = new ParseField("task_id"); public static final ConstructingObjectParser<Blocked, Void> LENIENT_PARSER = createParser(true); public static final ConstructingObjectParser<Blocked, Void> STRICT_PARSER = createParser(false); private static ConstructingObjectParser<Blocked, Void> createParser(boolean ignoreUnknownFields) { ConstructingObjectParser<Blocked, Void> parser = new ConstructingObjectParser<>( "blocked", ignoreUnknownFields, a -> new Blocked((Reason) a[0], (TaskId) a[1]) ); parser.declareString(ConstructingObjectParser.constructorArg(), Reason::fromString, REASON); parser.declareString(ConstructingObjectParser.optionalConstructorArg(), TaskId::new, TASK_ID); return parser; } private final Reason reason; @Nullable private final TaskId taskId; public Blocked(Reason reason, @Nullable TaskId taskId) { this.reason = Objects.requireNonNull(reason); this.taskId = taskId; } public Blocked(StreamInput in) throws IOException { this.reason = in.readEnum(Reason.class); this.taskId = in.readOptionalWriteable(TaskId::readFromStream); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeEnum(reason); out.writeOptionalWriteable(taskId); } public Reason getReason() { return reason; } @Nullable public TaskId getTaskId() { return taskId; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(REASON.getPreferredName(), reason); if (taskId != null) { builder.field(TASK_ID.getPreferredName(), taskId.toString()); } builder.endObject(); return builder; } @Override public int hashCode() { return Objects.hash(reason, taskId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Blocked that = (Blocked) o; return Objects.equals(reason, that.reason) && Objects.equals(taskId, that.taskId); } public static Blocked none() { return new Blocked(Reason.NONE, null); } }
Reason
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/factories/TestSupportsStagingTableFactory.java
{ "start": 3749, "end": 5697 }
class ____ implements DynamicTableSink, SupportsStaging { private final String dataDir; private final boolean sinkFail; private TestStagedTable stagedTable; public SupportsStagingTableSink(String dataDir, boolean sinkFail) { this(dataDir, sinkFail, null); } public SupportsStagingTableSink( String dataDir, boolean sinkFail, TestStagedTable stagedTable) { this.dataDir = dataDir; this.sinkFail = sinkFail; this.stagedTable = stagedTable; } @Override public ChangelogMode getChangelogMode(ChangelogMode requestedMode) { return ChangelogMode.insertOnly(); } @Override public SinkRuntimeProvider getSinkRuntimeProvider(Context context) { return new DataStreamSinkProvider() { @Override public DataStreamSink<?> consumeDataStream( ProviderContext providerContext, DataStream<RowData> dataStream) { return dataStream .addSink(new StagedSinkFunction(dataDir, sinkFail)) .setParallelism(1); } }; } @Override public DynamicTableSink copy() { return new SupportsStagingTableSink(dataDir, sinkFail, stagedTable); } @Override public String asSummaryString() { return "SupportsStagingTableSink"; } @Override public StagedTable applyStaging(StagingContext context) { JOB_STATUS_CHANGE_PROCESS.clear(); STAGING_PURPOSE_LIST.clear(); stagedTable = new TestStagedTable(dataDir); STAGING_PURPOSE_LIST.add(context.getStagingPurpose()); return stagedTable; } } /** The sink for delete existing data. */ private static
SupportsStagingTableSink
java
elastic__elasticsearch
modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/CopyBytesSocketChannel.java
{ "start": 2330, "end": 2462 }
class ____ us to create a one thread * local buffer with a defined size. */ @SuppressForbidden(reason = "Channel#write") public
allows
java
apache__camel
tests/camel-itest/src/test/java/org/apache/camel/itest/security/GreeterClientCxfMessageTest.java
{ "start": 1300, "end": 1365 }
class ____ extends GreeterClientTest { }
GreeterClientCxfMessageTest
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/engine/DecodePath.java
{ "start": 4280, "end": 4428 }
interface ____<ResourceType> { @NonNull Resource<ResourceType> onResourceDecoded(@NonNull Resource<ResourceType> resource); } }
DecodeCallback
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OidcBackChannelLogoutAuthentication.java
{ "start": 1446, "end": 2405 }
class ____ extends AbstractAuthenticationToken { @Serial private static final long serialVersionUID = 9095810699956350287L; private final OidcLogoutToken logoutToken; private final ClientRegistration clientRegistration; /** * Construct an {@link OidcBackChannelLogoutAuthentication} * @param logoutToken a deserialized, verified OIDC Logout Token */ OidcBackChannelLogoutAuthentication(OidcLogoutToken logoutToken, ClientRegistration clientRegistration) { super(Collections.emptyList()); this.logoutToken = logoutToken; this.clientRegistration = clientRegistration; setAuthenticated(true); } /** * {@inheritDoc} */ @Override public OidcLogoutToken getPrincipal() { return this.logoutToken; } /** * {@inheritDoc} */ @Override public OidcLogoutToken getCredentials() { return this.logoutToken; } ClientRegistration getClientRegistration() { return this.clientRegistration; } }
OidcBackChannelLogoutAuthentication
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/util/TestMessageHeaders.java
{ "start": 2933, "end": 6461 }
class ____< BREQ extends RequestBody, BRES extends ResponseBody, BM extends MessageParameters> { private Class<BREQ> requestClass; private Class<BRES> responseClass; private HttpResponseStatus responseStatusCode = HttpResponseStatus.OK; private String description = "Test description"; private BM messageParameters; private HttpMethodWrapper httpMethod = HttpMethodWrapper.GET; private String targetRestEndpointURL = "/test-endpoint"; private Builder(Class<BREQ> requestClass, Class<BRES> responseClass, BM messageParameters) { this.requestClass = requestClass; this.responseClass = responseClass; this.messageParameters = messageParameters; } public Builder<BREQ, BRES, BM> setResponseStatusCode( HttpResponseStatus responseStatusCode) { this.responseStatusCode = responseStatusCode; return this; } public Builder<BREQ, BRES, BM> setDescription(String description) { this.description = description; return this; } public Builder<BREQ, BRES, BM> setHttpMethod(HttpMethodWrapper httpMethod) { this.httpMethod = httpMethod; return this; } public Builder<BREQ, BRES, BM> setTargetRestEndpointURL(String targetRestEndpointURL) { this.targetRestEndpointURL = targetRestEndpointURL; return this; } public TestMessageHeaders<BREQ, BRES, BM> build() { return new TestMessageHeaders( requestClass, responseClass, responseStatusCode, description, messageParameters, httpMethod, targetRestEndpointURL); } } private final Class<REQ> requestClass; private final Class<RES> responseClass; private final HttpResponseStatus responseStatusCode; private final String description; private final M messageParameters; private final HttpMethodWrapper httpMethod; private final String targetRestEndpointURL; private TestMessageHeaders( Class<REQ> requestClass, Class<RES> responseClass, HttpResponseStatus responseStatusCode, String description, M messageParameters, HttpMethodWrapper httpMethod, String targetRestEndpointURL) { this.requestClass = requestClass; this.responseClass = responseClass; this.responseStatusCode = responseStatusCode; this.description = description; this.messageParameters = messageParameters; this.httpMethod = httpMethod; this.targetRestEndpointURL = targetRestEndpointURL; } @Override public Class<RES> getResponseClass() { return responseClass; } @Override public HttpResponseStatus getResponseStatusCode() { return responseStatusCode; } @Override public String getDescription() { return description; } @Override public Class<REQ> getRequestClass() { return requestClass; } @Override public M getUnresolvedMessageParameters() { return messageParameters; } @Override public HttpMethodWrapper getHttpMethod() { return httpMethod; } @Override public String getTargetRestEndpointURL() { return targetRestEndpointURL; } }
Builder
java
google__error-prone
annotations/src/main/java/com/google/errorprone/annotations/IncompatibleModifiers.java
{ "start": 1085, "end": 1427 }
interface ____ {} * </pre> * * <p>will be considered illegal when used as: * * <pre> * @MyAnnotation public void foo() {} * }</pre> * * @author benyu@google.com (Jige Yu) */ @Documented @Retention(RetentionPolicy.CLASS) // Element's source might not be available during analysis @Target(ElementType.ANNOTATION_TYPE) public @
MyAnnotation
java
quarkusio__quarkus
extensions/reactive-pg-client/deployment/src/test/java/io/quarkus/reactive/pg/client/PgPoolLoadBalanceTest.java
{ "start": 301, "end": 1273 }
class ____ { @RegisterExtension public static final QuarkusDevModeTest test = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClass(DevModeResource.class) .add(new StringAsset("quarkus.datasource.db-kind=postgresql\n" + "quarkus.datasource.reactive.url=vertx-reactive:postgresql://localhost:5342/load_balance_test," + "vertx-reactive:postgresql://localhost:5343/load_balance_test," + "vertx-reactive:postgresql://localhost:5344/load_balance_test"), "application.properties")); @Test public void testLoadBalance() { RestAssured .get("/dev/error") .then() .statusCode(200) .body(Matchers.anyOf(Matchers.endsWith(":5342"), Matchers.endsWith(":5343"), Matchers.endsWith(":5344"))); } }
PgPoolLoadBalanceTest
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/masterreplica/TopologyComparators.java
{ "start": 484, "end": 1446 }
class ____ implements Comparator<RedisNodeDescription> { private final Map<RedisNodeDescription, Long> latencies; public LatencyComparator(Map<RedisNodeDescription, Long> latencies) { this.latencies = latencies; } @Override public int compare(RedisNodeDescription o1, RedisNodeDescription o2) { Long latency1 = latencies.get(o1); Long latency2 = latencies.get(o2); if (latency1 != null && latency2 != null) { return latency1.compareTo(latency2); } if (latency1 != null) { return -1; } if (latency2 != null) { return 1; } return 0; } } /** * Sort action for topology. Defaults to sort by latency. Can be set via {@code io.lettuce.core.topology.sort} system * property. * * @since 4.5 */
LatencyComparator
java
apache__camel
components/camel-aws/camel-aws-secrets-manager/src/test/java/org/apache/camel/component/aws/secretsmanager/SecretsManagerProducerHealthCheckProfileCredsTest.java
{ "start": 1462, "end": 4044 }
class ____ extends CamelTestSupport { CamelContext context; @Override protected CamelContext createCamelContext() throws Exception { context = super.createCamelContext(); context.getPropertiesComponent().setLocation("ref:prop"); // install health check manually (yes a bit cumbersome) HealthCheckRegistry registry = new DefaultHealthCheckRegistry(); registry.setCamelContext(context); Object hc = registry.resolveById("context"); registry.register(hc); hc = registry.resolveById("routes"); registry.register(hc); hc = registry.resolveById("consumers"); registry.register(hc); HealthCheckRepository hcr = (HealthCheckRepository) registry.resolveById("producers"); hcr.setEnabled(true); registry.register(hcr); context.getCamelContextExtension().addContextPlugin(HealthCheckRegistry.class, registry); return context; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:listClusters") .to("aws-secrets-manager://test?operation=listSecrets&region=l&useDefaultCredentialsProvider=true"); } }; } @Test public void testConnectivity() { Collection<HealthCheck.Result> res = HealthCheckHelper.invokeLiveness(context); boolean up = res.stream().allMatch(r -> r.getState().equals(HealthCheck.State.UP)); Assertions.assertTrue(up, "liveness check"); // health-check readiness should be down await().atMost(20, TimeUnit.SECONDS).untilAsserted(() -> { Collection<HealthCheck.Result> res2 = HealthCheckHelper.invokeReadiness(context); boolean down = res2.stream().allMatch(r -> r.getState().equals(HealthCheck.State.DOWN)); boolean containsAwsSecretsManagerHealthCheck = res2.stream() .anyMatch(result -> result.getCheck().getId().startsWith("producer:aws-secrets-manager")); boolean hasRegionMessage = res2.stream() .anyMatch(r -> r.getMessage().stream().anyMatch(msg -> msg.contains("region"))); Assertions.assertTrue(down, "liveness check"); Assertions.assertTrue(containsAwsSecretsManagerHealthCheck, "aws-secrets-manager check"); Assertions.assertTrue(hasRegionMessage, "aws-secrets-manager check error message"); }); } }
SecretsManagerProducerHealthCheckProfileCredsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/cte/CteInsertWithPooledLoThreadLocalOptimizerTest.java
{ "start": 1256, "end": 1420 }
class ____ { @Test void test(SessionFactoryScope scope) { new CteInsertWithPooledLoOptimizerTest().test( scope ); } }
CteInsertWithPooledLoThreadLocalOptimizerTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java
{ "start": 40761, "end": 40977 }
class ____ to combine map-outputs. */ public Class<? extends Reducer> getCombinerClass() { return getClass("mapred.combiner.class", null, Reducer.class); } /** * Set the user-defined <i>combiner</i>
used
java
elastic__elasticsearch
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/planner/VerifierTests.java
{ "start": 861, "end": 5968 }
class ____ extends ESTestCase { private final SqlParser parser = new SqlParser(); private final IndexResolution indexResolution = IndexResolution.valid( new EsIndex("test", loadMapping("mapping-multi-field-with-nested.json")) ); private final Analyzer analyzer = analyzer(indexResolution); private final Planner planner = new Planner(); private PhysicalPlan verify(String sql) { return planner.plan(analyzer.analyze(parser.createStatement(sql), true), true); } private String error(String sql) { PlanningException e = expectThrows(PlanningException.class, () -> verify(sql)); String message = e.getMessage(); assertTrue(message.startsWith("Found ")); String pattern = "\nline "; int index = message.indexOf(pattern); return message.substring(index + pattern.length()); } private String innerLimitMsg(int line, int column) { return line + ":" + column + ": LIMIT or TOP cannot be used in a subquery if outer query contains GROUP BY, ORDER BY, PIVOT or WHERE"; } public void testSubselectWithOrderByOnTopOfOrderByAndLimit() { assertEquals(innerLimitMsg(1, 50), error("SELECT * FROM (SELECT * FROM test ORDER BY 1 ASC LIMIT 10) ORDER BY 2")); assertEquals(innerLimitMsg(1, 50), error("SELECT * FROM (SELECT * FROM (SELECT * FROM test LIMIT 10) ORDER BY 1) ORDER BY 2")); assertEquals( innerLimitMsg(1, 66), error("SELECT * FROM (SELECT * FROM (SELECT * FROM test ORDER BY 1 ASC) LIMIT 5) ORDER BY 1 DESC") ); assertEquals( innerLimitMsg(1, 142), error( "SELECT * FROM (" + "SELECT * FROM (" + "SELECT * FROM (" + "SELECT * FROM test ORDER BY int DESC" + ") ORDER BY int ASC NULLS LAST) " + "ORDER BY int DESC NULLS LAST LIMIT 12) " + "ORDER BY int DESC NULLS FIRST" ) ); assertEquals( innerLimitMsg(1, 50), error("SELECT * FROM (SELECT * FROM (SELECT * FROM test LIMIT 10) ORDER BY 1 LIMIT 20) ORDER BY 2") ); } public void testSubselectWithOrderByOnTopOfGroupByOrderByAndLimit() { assertEquals( innerLimitMsg(1, 86), error("SELECT * FROM (SELECT max(int) AS max, bool FROM test GROUP BY bool ORDER BY max ASC LIMIT 10) ORDER BY max DESC") ); assertEquals( innerLimitMsg(1, 102), error( "SELECT * FROM (" + "SELECT * FROM (" + "SELECT max(int) AS max, bool FROM test GROUP BY bool ORDER BY max ASC) " + "LIMIT 10) " + "ORDER BY max DESC" ) ); assertEquals( innerLimitMsg(1, 176), error( "SELECT * FROM (" + "SELECT * FROM (" + "SELECT * FROM (" + "SELECT max(int) AS max, bool FROM test GROUP BY bool ORDER BY max DESC" + ") ORDER BY max ASC NULLS LAST) " + "ORDER BY max DESC NULLS LAST LIMIT 12) " + "ORDER BY max DESC NULLS FIRST" ) ); } public void testInnerLimitWithWhere() { assertEquals(innerLimitMsg(1, 35), error("SELECT * FROM (SELECT * FROM test LIMIT 10) WHERE int = 1")); assertEquals(innerLimitMsg(1, 50), error("SELECT * FROM (SELECT * FROM (SELECT * FROM test LIMIT 10)) WHERE int = 1")); assertEquals(innerLimitMsg(1, 51), error("SELECT * FROM (SELECT * FROM (SELECT * FROM test) LIMIT 10) WHERE int = 1")); } public void testInnerLimitWithGroupBy() { assertEquals(innerLimitMsg(1, 37), error("SELECT int FROM (SELECT * FROM test LIMIT 10) GROUP BY int")); assertEquals(innerLimitMsg(1, 52), error("SELECT int FROM (SELECT * FROM (SELECT * FROM test LIMIT 10)) GROUP BY int")); assertEquals(innerLimitMsg(1, 53), error("SELECT int FROM (SELECT * FROM (SELECT * FROM test) LIMIT 10) GROUP BY int")); } public void testInnerLimitWithPivot() { assertEquals( innerLimitMsg(1, 52), error("SELECT * FROM (SELECT int, bool, keyword FROM test LIMIT 10) PIVOT (AVG(int) FOR bool IN (true, false))") ); } public void testTopWithOrderBySucceeds() { PhysicalPlan plan = verify("SELECT TOP 5 * FROM test ORDER BY int"); assertEquals(EsQueryExec.class, plan.getClass()); } public void testInnerTop() { assertEquals(innerLimitMsg(1, 23), error("SELECT * FROM (SELECT TOP 10 * FROM test) WHERE int = 1")); assertEquals(innerLimitMsg(1, 23), error("SELECT * FROM (SELECT TOP 10 * FROM test) ORDER BY int")); assertEquals( innerLimitMsg(1, 23), error("SELECT * FROM (SELECT TOP 10 int, bool, keyword FROM test) PIVOT (AVG(int) FOR bool IN (true, false))") ); } }
VerifierTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test6.java
{ "start": 263, "end": 599 }
class ____ extends TestCase { public void test_jsonpath_1() throws Exception { JSONObject aa= new JSONObject(); aa.put("app-a", "haj "); JSONPath.set(aa, "$.app\\-a\\.x", "123"); assertEquals("haj ", aa.getString("app-a")); assertEquals("123", aa.getString("app-a.x")); } }
JSONPath_set_test6
java
apache__camel
components/camel-telemetry/src/main/java/org/apache/camel/telemetry/decorators/FtpsSpanDecorator.java
{ "start": 858, "end": 1128 }
class ____ extends FileSpanDecorator { @Override public String getComponent() { return "ftps"; } @Override public String getComponentClassName() { return "org.apache.camel.component.file.remote.FtpsComponent"; } }
FtpsSpanDecorator
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/MultiBucketCollectorTests.java
{ "start": 12973, "end": 13370 }
class ____ extends LeafBucketCollector { private Scorable scorable; @Override public void setScorer(Scorable scorer) throws IOException { this.scorable = scorer; } @Override public void collect(int doc, long owningBucketOrd) throws IOException { scorable.score(); } } private static
ScoringLeafBucketCollector
java
eclipse-vertx__vert.x
vertx-core/src/main/generated/io/vertx/core/net/ServerSSLOptionsConverter.java
{ "start": 333, "end": 1268 }
class ____ { static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, ServerSSLOptions obj) { for (java.util.Map.Entry<String, Object> member : json) { switch (member.getKey()) { case "clientAuth": if (member.getValue() instanceof String) { obj.setClientAuth(io.vertx.core.http.ClientAuth.valueOf((String)member.getValue())); } break; case "sni": if (member.getValue() instanceof Boolean) { obj.setSni((Boolean)member.getValue()); } break; } } } static void toJson(ServerSSLOptions obj, JsonObject json) { toJson(obj, json.getMap()); } static void toJson(ServerSSLOptions obj, java.util.Map<String, Object> json) { if (obj.getClientAuth() != null) { json.put("clientAuth", obj.getClientAuth().name()); } json.put("sni", obj.isSni()); } }
ServerSSLOptionsConverter
java
apache__camel
components/camel-syslog/src/main/java/org/apache/camel/component/syslog/SyslogSeverity.java
{ "start": 854, "end": 965 }
enum ____ { EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG, }
SyslogSeverity
java
playframework__playframework
documentation/manual/working/javaGuide/main/dependencyinjection/code/javaguide/di/components/CompileTimeDependencyInjection.java
{ "start": 2457, "end": 2583 }
class ____ { SomeComponent(ConnectionPool pool) { // do nothing } } // #with-routing-dsl public
SomeComponent
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/sort/BucketedSortForLongsTests.java
{ "start": 615, "end": 1879 }
class ____ extends BucketedSortTestCase<BucketedSort.ForLongs> { @Override public BucketedSort.ForLongs build( SortOrder sortOrder, DocValueFormat format, int bucketSize, BucketedSort.ExtraData extra, double[] values ) { return new BucketedSort.ForLongs(bigArrays(), sortOrder, format, bucketSize, extra) { @Override public Leaf forLeaf(LeafReaderContext ctx) { return new Leaf(ctx) { int index = -1; @Override protected boolean advanceExact(int doc) { index = doc; return doc < values.length; } @Override protected long docValue() { return (long) values[index]; } }; } }; } @Override protected SortValue expectedSortValue(double v) { return SortValue.from((long) v); } @Override protected double randomValue() { // 2L^50 fits in the mantisa of a double which the test sort of needs. return randomLongBetween(-(1L << 50), (1L << 50)); } }
BucketedSortForLongsTests
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/CacheInvalidatorRegistryTests.java
{ "start": 1189, "end": 8170 }
class ____ extends ESTestCase { private CacheInvalidatorRegistry cacheInvalidatorRegistry; @Before public void setup() { cacheInvalidatorRegistry = new CacheInvalidatorRegistry(); } public void testRegistryWillNotAllowInvalidatorsWithDuplicatedName() { cacheInvalidatorRegistry.registerCacheInvalidator("service1", mock(CacheInvalidator.class)); final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> cacheInvalidatorRegistry.registerCacheInvalidator("service1", mock(CacheInvalidator.class)) ); assertThat(e.getMessage(), containsString("already has an entry with name: [service1]")); } public void testSecurityIndexStateChangeWillInvalidateAllRegisteredInvalidators() { final CacheInvalidator invalidator1 = mock(CacheInvalidator.class); when(invalidator1.shouldClearOnSecurityIndexStateChange()).thenReturn(true); cacheInvalidatorRegistry.registerCacheInvalidator("service1", invalidator1); final CacheInvalidator invalidator2 = mock(CacheInvalidator.class); when(invalidator2.shouldClearOnSecurityIndexStateChange()).thenReturn(true); cacheInvalidatorRegistry.registerCacheInvalidator("service2", invalidator2); final CacheInvalidator invalidator3 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("service3", invalidator3); final ProjectId projectId = randomProjectIdOrDefault(); final SecurityIndexManager indexManager = mock(SecurityIndexManager.class); final SecurityIndexManager.IndexState previousState = indexManager.new IndexState( projectId, SecurityIndexManager.ProjectStatus.CLUSTER_NOT_RECOVERED, null, false, false, false, false, false, null, false, null, null, null, null, null, null, null, Set.of() ); final SecurityIndexManager.IndexState currentState = indexManager.new IndexState( projectId, SecurityIndexManager.ProjectStatus.PROJECT_AVAILABLE, Instant.now(), true, true, true, true, true, null, false, null, new SystemIndexDescriptor.MappingsVersion(SecurityMainIndexMappingVersion.latest().id(), 0), null, ".security", ClusterHealthStatus.GREEN, IndexMetadata.State.OPEN, "my_uuid", Set.of() ); cacheInvalidatorRegistry.onSecurityIndexStateChange(Metadata.DEFAULT_PROJECT_ID, previousState, currentState); verify(invalidator1).invalidateAll(); verify(invalidator2).invalidateAll(); verify(invalidator3, never()).invalidateAll(); } public void testInvalidateByKeyCallsCorrectInvalidatorObject() { final CacheInvalidator invalidator1 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("service1", invalidator1); final CacheInvalidator invalidator2 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("service2", invalidator2); cacheInvalidatorRegistry.invalidateByKey("service2", List.of("k1", "k2")); verify(invalidator1, never()).invalidate(any()); verify(invalidator2).invalidate(List.of("k1", "k2")); // Trying to invalidate entries from a non-existing cache will throw error final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> cacheInvalidatorRegistry.invalidateByKey("non-exist", List.of("k1", "k2")) ); assertThat(e.getMessage(), containsString("No cache named [non-exist] is found")); } public void testInvalidateCache() { final CacheInvalidator invalidator1 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("service1", invalidator1); final CacheInvalidator invalidator2 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("service2", invalidator2); cacheInvalidatorRegistry.invalidateCache("service1"); verify(invalidator1).invalidateAll(); verify(invalidator2, never()).invalidateAll(); // Trying to invalidate entries from a non-existing cache will throw error final IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> cacheInvalidatorRegistry.invalidateCache("non-exist") ); assertThat(e.getMessage(), containsString("No cache named [non-exist] is found")); } public void testRegisterAlias() { final CacheInvalidator invalidator1 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("cache1", invalidator1); final CacheInvalidator invalidator2 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("cache2", invalidator2); final NullPointerException e1 = expectThrows( NullPointerException.class, () -> cacheInvalidatorRegistry.registerAlias(null, Set.of()) ); assertThat(e1.getMessage(), containsString("cache alias cannot be null")); final IllegalArgumentException e2 = expectThrows( IllegalArgumentException.class, () -> cacheInvalidatorRegistry.registerAlias("alias1", Set.of()) ); assertThat(e2.getMessage(), containsString("cache names cannot be empty for aliasing")); cacheInvalidatorRegistry.registerAlias("alias1", randomFrom(Set.of("cache1"), Set.of("cache1", "cache2"))); final IllegalArgumentException e3 = expectThrows( IllegalArgumentException.class, () -> cacheInvalidatorRegistry.registerAlias("alias1", Set.of("cache1")) ); assertThat(e3.getMessage(), containsString("cache alias already exists")); // validation should pass cacheInvalidatorRegistry.validate(); } public void testValidateWillThrowForClashingAliasAndCacheNames() { final CacheInvalidator invalidator1 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("cache1", invalidator1); cacheInvalidatorRegistry.registerAlias("cache1", Set.of("cache1")); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> cacheInvalidatorRegistry.validate()); assertThat(e.getMessage(), containsString("cache alias cannot clash with cache name")); } public void testValidateWillThrowForNotFoundCacheNames() { final CacheInvalidator invalidator1 = mock(CacheInvalidator.class); cacheInvalidatorRegistry.registerCacheInvalidator("cache1", invalidator1); cacheInvalidatorRegistry.registerAlias("alias1", Set.of("cache1", "cache2")); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> cacheInvalidatorRegistry.validate()); assertThat(e.getMessage(), containsString("cache names not found: [cache2]")); } }
CacheInvalidatorRegistryTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest_hierarchical_CONNECT_BY_ISCYCLE.java
{ "start": 967, "end": 2705 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "SELECT last_name \"Employee\", CONNECT_BY_ISCYCLE \"Cycle\",\n" + " LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') \"Path\"\n" + " FROM employees\n" + " WHERE level <= 3 AND department_id = 80\n" + " START WITH last_name = 'King'\n" + " CONNECT BY NOCYCLE PRIOR employee_id = manager_id AND LEVEL <= 4;"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("employees"))); assertEquals(4, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleSelectTest_hierarchical_CONNECT_BY_ISCYCLE
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FsImageValidation.java
{ "start": 3587, "end": 6307 }
class ____ { static final Logger LOG = LoggerFactory.getLogger(FsImageValidation.class); static final String FS_IMAGE = "FS_IMAGE"; /** * Use an environment variable "PRINT_ERROR" to enable/disable printing error messages. * The default is true */ static final boolean PRINT_ERROR; static { PRINT_ERROR = getEnvBoolean("PRINT_ERROR", true); } /** * @return the boolean value of an environment property. * If the environment property is not set or cannot be parsed as a boolean, * return the default value. */ static boolean getEnvBoolean(String property, boolean defaultValue) { final String env = System.getenv().get(property); final boolean setToNonDefault = ("" + !defaultValue).equalsIgnoreCase(env); // default | setToNonDefault | value // --------------------------------- // true | true | false // true | false | true // false | true | true // false | false | false final boolean value = defaultValue != setToNonDefault; LOG.info("ENV: {} = {} (\"{}\")", property, value, env); return value; } static String getEnv(String property) { final String value = System.getenv().get(property); LOG.info("ENV: {} = {}", property, value); return value; } static FsImageValidation newInstance(String... args) { final String f = Cli.parse(args); if (f == null) { throw new HadoopIllegalArgumentException( FS_IMAGE + " is not specified."); } return new FsImageValidation(new File(f)); } static void initConf(Configuration conf) { final int aDay = 24*3600_000; conf.setInt(DFS_NAMENODE_READ_LOCK_REPORTING_THRESHOLD_MS_KEY, aDay); conf.setInt(DFS_NAMENODE_WRITE_LOCK_REPORTING_THRESHOLD_MS_KEY, aDay); conf.setBoolean(DFS_NAMENODE_ENABLE_RETRY_CACHE_KEY, false); } /** Set (fake) HA so that edit logs will not be loaded. */ static void setHaConf(String nsId, Configuration conf) { conf.set(DFSConfigKeys.DFS_NAMESERVICES, nsId); final String haNNKey = DFS_HA_NAMENODES_KEY_PREFIX + "." + nsId; conf.set(haNNKey, "nn0,nn1"); final String rpcKey = DFS_NAMENODE_RPC_ADDRESS_KEY + "." + nsId + "."; conf.set(rpcKey + "nn0", "127.0.0.1:8080"); conf.set(rpcKey + "nn1", "127.0.0.1:8080"); } static void initLogLevels() { Util.setLogLevel(FSImage.class, Level.TRACE); Util.setLogLevel(FileJournalManager.class, Level.TRACE); Util.setLogLevel(GSet.class, Level.OFF); Util.setLogLevel(BlockManager.class, Level.OFF); Util.setLogLevel(DatanodeManager.class, Level.OFF); Util.setLogLevel(TopMetrics.class, Level.OFF); } static
FsImageValidation
java
spring-projects__spring-boot
module/spring-boot-webflux-test/src/test/java/org/springframework/boot/webflux/test/autoconfigure/WebFluxTypeExcludeFilterTests.java
{ "start": 7440, "end": 7515 }
class ____ extends SimpleModule { } @JacksonComponent static
ExampleModule
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/android/FragmentInjectionTest.java
{ "start": 6652, "end": 6986 }
class ____ extends MySuperPrefActivity {}") .doTest(); } @Test public void isValidFragmentImplementedOnAbstractSuperClass() { compilationHelper .addSourceLines( "MySuperPrefActivity.java", """ import android.preference.PreferenceActivity; abstract
MyPrefActivity
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/onexception/SpringOnExceptionContinueSubRouteTest.java
{ "start": 1076, "end": 1401 }
class ____ extends OnExceptionContinueSubRouteTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/onexception/OnExceptionContinueSubRouteTest.xml"); } }
SpringOnExceptionContinueSubRouteTest
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/IfSectionHelper.java
{ "start": 6815, "end": 7392 }
class ____ { final SectionBlock section; final Condition condition; public ConditionBlock(SectionBlock block, SectionInitContext context) { this.section = block; List<Object> params = parseParams(new ArrayList<>(block.parameters.values()), block); if (!params.isEmpty() && !SectionHelperFactory.MAIN_BLOCK_NAME.equals(block.label)) { params = params.subList(1, params.size()); } this.condition = createCondition(params, block, null, context); } }
ConditionBlock
java
google__dagger
java/dagger/example/atm/UserCommandsModule.java
{ "start": 828, "end": 1124 }
interface ____ { @Binds @IntoMap @StringKey("deposit") Command deposit(DepositCommand command); @Binds @IntoMap @StringKey("withdraw") Command withdraw(WithdrawCommand command); @Binds @IntoMap @StringKey("logout") Command logout(LogoutCommand command); }
UserCommandsModule
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/root/ProcessedRootSentinelMetadata.java
{ "start": 1384, "end": 2723 }
class ____ { /** Returns the aggregating element */ public abstract XTypeElement aggregatingElement(); /** Returns the processed root elements. */ abstract ImmutableSet<XTypeElement> rootElements(); static ImmutableSet<ProcessedRootSentinelMetadata> from(XProcessingEnv env) { return AggregatedElements.from( ClassNames.PROCESSED_ROOT_SENTINEL_PACKAGE, ClassNames.PROCESSED_ROOT_SENTINEL, env) .stream() .map(aggregatedElement -> create(aggregatedElement, env)) .collect(toImmutableSet()); } static ProcessedRootSentinelIr toIr(ProcessedRootSentinelMetadata metadata) { return new ProcessedRootSentinelIr( metadata.aggregatingElement().getClassName(), metadata.rootElements().stream() .map(XTypeElement::getClassName) .map(ClassName::canonicalName) .collect(Collectors.toList())); } private static ProcessedRootSentinelMetadata create(XTypeElement element, XProcessingEnv env) { XAnnotation annotationMirror = element.getAnnotation(ClassNames.PROCESSED_ROOT_SENTINEL); return new AutoValue_ProcessedRootSentinelMetadata( element, annotationMirror.getAsStringList("roots").stream() .map(env::requireTypeElement) .collect(toImmutableSet())); } }
ProcessedRootSentinelMetadata
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/type/DataType.java
{ "start": 38728, "end": 39531 }
class ____ { /** * The first transport version after the PR that introduced geotile/geohash/geohex, resp. * after 9.1. We didn't require transport versions at that point in time, as geotile/hash/hex require * using specific functions to even occur in query plans. */ public static final TransportVersion INDEX_SOURCE = TransportVersion.fromName("index_source"); public static final TransportVersion ESQL_DENSE_VECTOR_CREATED_VERSION = TransportVersion.fromName( "esql_dense_vector_created_version" ); public static final TransportVersion ESQL_AGGREGATE_METRIC_DOUBLE_CREATED_VERSION = TransportVersion.fromName( "esql_aggregate_metric_double_created_version" ); } }
DataTypesTransportVersions
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/KeysetScrollSpecification.java
{ "start": 4845, "end": 6777 }
class ____ implements QueryStrategy<JpqlQueryBuilder.Expression, JpqlQueryBuilder.Predicate> { private final Bindable<?> from; private final JpqlQueryBuilder.Entity entity; private final ParameterFactory factory; private final Metamodel metamodel; public JpqlStrategy(Metamodel metamodel, Bindable<?> from, JpqlQueryBuilder.Entity entity, ParameterFactory factory) { this.from = from; this.entity = entity; this.factory = factory; this.metamodel = metamodel; } @Override public JpqlQueryBuilder.Expression createExpression(String property) { PropertyPath path = PropertyPath.from(property, from.getBindableJavaType()); return JpqlUtils.toExpressionRecursively(metamodel, entity, from, path); } @Override public JpqlQueryBuilder.Predicate compare(Order order, JpqlQueryBuilder.Expression propertyExpression, @Nullable Object value) { JpqlQueryBuilder.WhereStep where = JpqlQueryBuilder.where(propertyExpression); if (value == null) { return order.isAscending() ? where.isNull() : where.isNotNull(); } QueryUtils.checkSortExpression(order); return order.isAscending() ? where.gt(factory.capture(order.getProperty(), value)) : where.lt(factory.capture(order.getProperty(), value)); } @Override public JpqlQueryBuilder.Predicate compare(String property, JpqlQueryBuilder.Expression propertyExpression, @Nullable Object value) { JpqlQueryBuilder.WhereStep where = JpqlQueryBuilder.where(propertyExpression); return value == null ? where.isNull() : where.eq(factory.capture(property, value)); } @Override public JpqlQueryBuilder.@Nullable Predicate and(List<JpqlQueryBuilder.Predicate> intermediate) { return JpqlQueryBuilder.and(intermediate); } @Override public JpqlQueryBuilder.@Nullable Predicate or(List<JpqlQueryBuilder.Predicate> intermediate) { return JpqlQueryBuilder.or(intermediate); } } public
JpqlStrategy
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/Conditional.java
{ "start": 2566, "end": 2773 }
interface ____ { /** * All {@link Condition} classes that must {@linkplain Condition#matches match} * in order for the component to be registered. */ Class<? extends Condition>[] value(); }
Conditional
java
elastic__elasticsearch
libs/grok/src/test/java/org/elasticsearch/grok/GrokTests.java
{ "start": 1783, "end": 46978 }
class ____ extends ESTestCase { public void testMatchWithoutCaptures() { testMatchWithoutCaptures(false); testMatchWithoutCaptures(true); } private void testMatchWithoutCaptures(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "value", logger::warn); assertThat(grok.captures("value"), equalTo(Map.of())); assertThat(grok.captures("prefix_value"), equalTo(Map.of())); assertThat(grok.captures("no_match"), nullValue()); } public void testCapturesBytes() { testCapturesBytes(false); testCapturesBytes(true); testCaptureBytesSuffix(true); testCaptureBytesSuffix(false); } private void testCaptureBytesSuffix(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{WORD:a} %{WORD:b} %{NUMBER:c:int}", logger::warn); byte[] utf8 = "x1 a1 b1 12 x2 a2 b2 13 ".getBytes(StandardCharsets.UTF_8); assertThat(captureBytes(grok, utf8, 0, 12), equalTo(Map.of("a", "a1", "b", "b1", "c", 12))); assertNull(captureBytes(grok, utf8, 0, 9)); assertThat(captureBytes(grok, utf8, 12, 12), equalTo(Map.of("a", "a2", "b", "b2", "c", 13))); assertNull(captureBytes(grok, utf8, 12, 9)); } private void testCapturesBytes(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{NUMBER:n:int}", logger::warn); byte[] utf8 = "10".getBytes(StandardCharsets.UTF_8); assertThat(captureBytes(grok, utf8, 0, utf8.length), equalTo(Map.of("n", 10))); assertThat(captureBytes(grok, utf8, 0, 1), equalTo(Map.of("n", 1))); utf8 = "10 11 12".getBytes(StandardCharsets.UTF_8); assertThat(captureBytes(grok, utf8, 0, 2), equalTo(Map.of("n", 10))); assertThat(captureBytes(grok, utf8, 3, 2), equalTo(Map.of("n", 11))); assertThat(captureBytes(grok, utf8, 6, 2), equalTo(Map.of("n", 12))); } private Map<String, Object> captureBytes(Grok grok, byte[] utf8, int offset, int length) { GrokCaptureExtracter.MapExtracter extracter = new GrokCaptureExtracter.MapExtracter( grok.captureConfig(), cfg -> cfg::objectExtracter ); if (grok.match(utf8, offset, length, extracter)) { return extracter.result(); } return null; } public void testCaptureRanges() { captureRanges(false); captureRanges(true); } private void captureRanges(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{WORD:a} %{WORD:b} %{NUMBER:c:int}", logger::warn); assertThat( grok.captureRanges("xx aaaaa bbb 1234 yyy"), equalTo( Map.of( "a", new GrokCaptureExtracter.Range("aaaaa", 3, 5), "b", new GrokCaptureExtracter.Range("bbb", 9, 3), "c", new GrokCaptureExtracter.Range("1234", 13, 4) ) ) ); } public void testCaptureRanges_noMatch() { captureRanges_noMatch(false); captureRanges_noMatch(true); } private void captureRanges_noMatch(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{WORD:a} %{WORD:b} %{NUMBER:c:int}", logger::warn); assertNull(grok.captureRanges("xx aaaaa bbb ccc yyy")); } public void testCaptureRanges_multipleNamedCapturesWithSameName() { captureRanges_multipleNamedCapturesWithSameName(false); captureRanges_multipleNamedCapturesWithSameName(true); } private void captureRanges_multipleNamedCapturesWithSameName(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{WORD:parts} %{WORD:parts}", logger::warn); assertThat( grok.captureRanges(" aa bbb c ddd e "), equalTo(Map.of("parts", List.of(new GrokCaptureExtracter.Range("aa", 2, 2), new GrokCaptureExtracter.Range("bbb", 5, 3)))) ); } public void testNoMatchingPatternInDictionary() { Exception e = expectThrows(IllegalArgumentException.class, () -> new Grok(PatternBank.EMPTY, "%{NOTFOUND}", logger::warn)); assertThat(e.getMessage(), equalTo("Unable to find pattern [NOTFOUND] in Grok's pattern dictionary")); } public void testSimpleSyslogLine() { final String logSource = "evita"; final String timestamp = "Mar 16 00:01:25"; final String message = "connect from camomile.cloud9.net[168.100.1.3]"; final String program = "postfix/smtpd"; testSimpleSyslogLine( false, tuple(Map.entry("facility", STRING), null), tuple(Map.entry("logsource", STRING), logSource), tuple(Map.entry("message", STRING), message), tuple(Map.entry("pid", STRING), "1713"), tuple(Map.entry("priority", STRING), null), tuple(Map.entry("program", STRING), program), tuple(Map.entry("timestamp", STRING), timestamp), tuple(Map.entry("timestamp8601", STRING), null), List.of() ); testSimpleSyslogLine( true, tuple(Map.entry("log.syslog.facility.code", INTEGER), null), tuple(Map.entry("host.hostname", STRING), logSource), tuple(Map.entry("message", STRING), message), tuple(Map.entry("process.pid", INTEGER), 1713), tuple(Map.entry("log.syslog.priority", INTEGER), null), tuple(Map.entry("process.name", STRING), program), tuple(Map.entry("timestamp", STRING), timestamp), null, List.of("timestamp") ); } private void testSimpleSyslogLine( boolean ecsCompatibility, Tuple<Map.Entry<String, GrokCaptureType>, Object> facility, Tuple<Map.Entry<String, GrokCaptureType>, Object> logSource, Tuple<Map.Entry<String, GrokCaptureType>, Object> message, Tuple<Map.Entry<String, GrokCaptureType>, Object> pid, Tuple<Map.Entry<String, GrokCaptureType>, Object> priority, Tuple<Map.Entry<String, GrokCaptureType>, Object> program, Tuple<Map.Entry<String, GrokCaptureType>, Object> timestamp, Tuple<Map.Entry<String, GrokCaptureType>, Object> timestamp8601, List<String> acceptedDuplicates ) { String line = "Mar 16 00:01:25 evita postfix/smtpd[1713]: connect from camomile.cloud9.net[168.100.1.3]"; Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{SYSLOGLINE}", logger::warn); Map<String, GrokCaptureType> captureTypes = new HashMap<>(); captureTypes.put(facility.v1().getKey(), facility.v1().getValue()); captureTypes.put(logSource.v1().getKey(), logSource.v1().getValue()); captureTypes.put(message.v1().getKey(), message.v1().getValue()); captureTypes.put(pid.v1().getKey(), pid.v1().getValue()); captureTypes.put(priority.v1().getKey(), priority.v1().getValue()); captureTypes.put(program.v1().getKey(), program.v1().getValue()); captureTypes.put(timestamp.v1().getKey(), timestamp.v1().getValue()); if (timestamp8601 != null) { captureTypes.put(timestamp8601.v1().getKey(), timestamp8601.v1().getValue()); } assertCaptureConfig(grok, captureTypes, acceptedDuplicates); Map<String, Object> matches = grok.captures(line); assertEquals(logSource.v2(), matches.get(logSource.v1().getKey())); assertEquals(timestamp.v2(), matches.get(timestamp.v1().getKey())); assertEquals(message.v2(), matches.get(message.v1().getKey())); assertEquals(program.v2(), matches.get(program.v1().getKey())); assertEquals(pid.v2(), matches.get(pid.v1().getKey())); String[] logsource = new String[1]; GrokCaptureExtracter logsourceExtracter = namedConfig(grok, logSource.v1().getKey()).nativeExtracter( new ThrowingNativeExtracterMap() { @Override public GrokCaptureExtracter forString(Function<Consumer<String>, GrokCaptureExtracter> buildExtracter) { return buildExtracter.apply(str -> logsource[0] = str); } } ); assertThat(specificCapture(grok, line, logsourceExtracter), is(true)); assertThat(logsource[0], equalTo(logSource.v2())); } public void testSyslog5424Line() { final String ts = "2009-06-30T18:30:00+02:00"; final String host = "paxton.local"; final String app = "grokdebug"; final String sd = "[id1 foo=\\\"bar\\\"][id2 baz=\\\"something\\\"]"; final String msg = "Hello, syslog."; final String ver = "1"; testSyslog5424Line( false, tuple(Map.entry("syslog5424_app", STRING), app), tuple(Map.entry("syslog5424_host", STRING), host), tuple(Map.entry("syslog5424_msg", STRING), msg), tuple(Map.entry("syslog5424_msgid", STRING), null), tuple(Map.entry("syslog5424_pri", STRING), "191"), tuple(Map.entry("syslog5424_proc", STRING), "4123"), tuple(Map.entry("syslog5424_sd", STRING), sd), tuple(Map.entry("syslog5424_ts", STRING), ts), tuple(Map.entry("syslog5424_ver", STRING), ver) ); testSyslog5424Line( true, tuple(Map.entry("process.name", STRING), app), tuple(Map.entry("host.hostname", STRING), host), tuple(Map.entry("message", STRING), msg), tuple(Map.entry("event.code", STRING), null), tuple(Map.entry("log.syslog.priority", INTEGER), 191), tuple(Map.entry("process.pid", INTEGER), 4123), tuple(Map.entry("system.syslog.structured_data", STRING), sd), tuple(Map.entry("timestamp", STRING), ts), tuple(Map.entry("system.syslog.version", STRING), ver) ); } private void testSyslog5424Line( boolean ecsCompatibility, Tuple<Map.Entry<String, GrokCaptureType>, Object> app, Tuple<Map.Entry<String, GrokCaptureType>, Object> host, Tuple<Map.Entry<String, GrokCaptureType>, Object> msg, Tuple<Map.Entry<String, GrokCaptureType>, Object> msgid, Tuple<Map.Entry<String, GrokCaptureType>, Object> pri, Tuple<Map.Entry<String, GrokCaptureType>, Object> proc, Tuple<Map.Entry<String, GrokCaptureType>, Object> sd, Tuple<Map.Entry<String, GrokCaptureType>, Object> ts, Tuple<Map.Entry<String, GrokCaptureType>, Object> ver ) { String line = "<191>1 2009-06-30T18:30:00+02:00 paxton.local grokdebug 4123 - [id1 foo=\\\"bar\\\"][id2 baz=\\\"something\\\"] " + "Hello, syslog."; Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{SYSLOG5424LINE}", logger::warn); assertCaptureConfig( grok, Map.ofEntries(app.v1(), host.v1(), msg.v1(), msgid.v1(), pri.v1(), proc.v1(), sd.v1(), ts.v1(), ver.v1()) ); Map<String, Object> matches = grok.captures(line); assertEquals(pri.v2(), matches.get(pri.v1().getKey())); assertEquals(ver.v2(), matches.get(ver.v1().getKey())); assertEquals(ts.v2(), matches.get(ts.v1().getKey())); assertEquals(host.v2(), matches.get(host.v1().getKey())); assertEquals(app.v2(), matches.get(app.v1().getKey())); assertEquals(proc.v2(), matches.get(proc.v1().getKey())); assertEquals(msgid.v2(), matches.get(msgid.v1().getKey())); assertEquals(sd.v2(), matches.get(sd.v1().getKey())); assertEquals(msg.v2(), matches.get(msg.v1().getKey())); } public void testDatePattern() { testDatePattern(false); testDatePattern(true); } private void testDatePattern(boolean ecsCompatibility) { String line = "fancy 12-12-12 12:12:12"; Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "(?<timestamp>%{DATE_EU} %{TIME})", logger::warn); assertCaptureConfig(grok, Map.of("timestamp", STRING)); Map<String, Object> matches = grok.captures(line); assertEquals("12-12-12 12:12:12", matches.get("timestamp")); } public void testNilCoercedValues() { testNilCoercedValues(false); testNilCoercedValues(true); } private void testNilCoercedValues(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "test (N/A|%{BASE10NUM:duration:float}ms)", logger::warn); assertCaptureConfig(grok, Map.of("duration", FLOAT)); Map<String, Object> matches = grok.captures("test 28.4ms"); assertEquals(28.4f, matches.get("duration")); matches = grok.captures("test N/A"); assertEquals(null, matches.get("duration")); } public void testNilWithNoCoercion() { testNilWithNoCoercion(false); testNilWithNoCoercion(true); } private void testNilWithNoCoercion(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "test (N/A|%{BASE10NUM:duration}ms)", logger::warn); assertCaptureConfig(grok, Map.of("duration", STRING)); Map<String, Object> matches = grok.captures("test 28.4ms"); assertEquals("28.4", matches.get("duration")); matches = grok.captures("test N/A"); assertEquals(null, matches.get("duration")); } public void testUnicodeSyslog() { testUnicodeSyslog(false); testUnicodeSyslog(true); } private void testUnicodeSyslog(boolean ecsCompatibility) { Grok grok = new Grok( GrokBuiltinPatterns.get(ecsCompatibility), "<%{POSINT:syslog_pri}>%{SPACE}%{SYSLOGTIMESTAMP:syslog_timestamp} " + "%{SYSLOGHOST:syslog_hostname} %{PROG:syslog_program}(:?)(?:\\[%{GREEDYDATA:syslog_pid}\\])?(:?) " + "%{GREEDYDATA:syslog_message}", logger::warn ); assertCaptureConfig( grok, Map.ofEntries( Map.entry("syslog_hostname", STRING), Map.entry("syslog_message", STRING), Map.entry("syslog_pid", STRING), Map.entry("syslog_pri", STRING), Map.entry("syslog_program", STRING), Map.entry("syslog_timestamp", STRING) ) ); Map<String, Object> matches = grok.captures( "<22>Jan 4 07:50:46 mailmaster postfix/policy-spf[9454]: : " + "SPF permerror (Junk encountered in record 'v=spf1 mx a:mail.domain.no ip4:192.168.0.4 �all'): Envelope-from: " + "email@domain.no" ); assertThat(matches.get("syslog_pri"), equalTo("22")); assertThat(matches.get("syslog_program"), equalTo("postfix/policy-spf")); assertThat(matches.get("tags"), nullValue()); } public void testNamedFieldsWithWholeTextMatch() { testNamedFieldsWithWholeTextMatch(false); testNamedFieldsWithWholeTextMatch(true); } private void testNamedFieldsWithWholeTextMatch(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{DATE_EU:stimestamp}", logger::warn); assertCaptureConfig(grok, Map.of("stimestamp", STRING)); Map<String, Object> matches = grok.captures("11/01/01"); assertThat(matches.get("stimestamp"), equalTo("11/01/01")); } public void testWithOniguramaNamedCaptures() { testWithOniguramaNamedCaptures(false); testWithOniguramaNamedCaptures(true); } private void testWithOniguramaNamedCaptures(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "(?<foo>\\w+)", logger::warn); assertCaptureConfig(grok, Map.of("foo", STRING)); Map<String, Object> matches = grok.captures("hello world"); assertThat(matches.get("foo"), equalTo("hello")); } public void testISO8601() { testISO8601(false); testISO8601(true); } private void testISO8601(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "^%{TIMESTAMP_ISO8601}$", logger::warn); assertCaptureConfig(grok, Map.of()); List<String> timeMessages = Arrays.asList( "2001-01-01T00:00:00", "1974-03-02T04:09:09", "2010-05-03T08:18:18+00:00", "2004-07-04T12:27:27-00:00", "2001-09-05T16:36:36+0000", "2001-11-06T20:45:45-0000", "2001-12-07T23:54:54Z", "2001-01-01T00:00:00.123456", "1974-03-02T04:09:09.123456", "2010-05-03T08:18:18.123456+00:00", "2004-07-04T12:27:27.123456-00:00", "2001-09-05T16:36:36.123456+0000", "2001-11-06T20:45:45.123456-0000", "2001-12-07T23:54:54.123456Z", "2001-12-07T23:54:60.123456Z" // '60' second is a leap second. ); for (String msg : timeMessages) { assertThat(grok.match(msg), is(true)); } } public void testNotISO8601() { testNotISO8601(false, List.of("2001-01-01T0:00:00")); // legacy patterns do not permit single-digit hours testNotISO8601(true, List.of()); } private void testNotISO8601(boolean ecsCompatibility, List<String> additionalCases) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "^%{TIMESTAMP_ISO8601}$", logger::warn); assertCaptureConfig(grok, Map.of()); List<String> timeMessages = Arrays.asList( "2001-13-01T00:00:00", // invalid month "2001-00-01T00:00:00", // invalid month "2001-01-00T00:00:00", // invalid day "2001-01-32T00:00:00", // invalid day "2001-01-aT00:00:00", // invalid day "2001-01-1aT00:00:00", // invalid day "2001-01-01Ta0:00:00", // invalid hour "2001-01-01T25:00:00", // invalid hour "2001-01-01T01:60:00", // invalid minute "2001-01-01T00:aa:00", // invalid minute "2001-01-01T00:00:aa", // invalid second "2001-01-01T00:00:-1", // invalid second "2001-01-01T00:00:61", // invalid second "2001-01-01T00:00:00A", // invalid timezone "2001-01-01T00:00:00+", // invalid timezone "2001-01-01T00:00:00+25", // invalid timezone "2001-01-01T00:00:00+2500", // invalid timezone "2001-01-01T00:00:00+25:00", // invalid timezone "2001-01-01T00:00:00-25", // invalid timezone "2001-01-01T00:00:00-2500", // invalid timezone "2001-01-01T00:00:00-00:61" // invalid timezone ); List<String> timesToTest = new ArrayList<>(timeMessages); timesToTest.addAll(additionalCases); for (String msg : timesToTest) { assertThat(grok.match(msg), is(false)); } } public void testNoNamedCaptures() { var bank = new PatternBank(Map.of("NAME", "Tal", "EXCITED_NAME", "!!!%{NAME:name}!!!", "TEST", "hello world")); String text = "wowza !!!Tal!!! - Tal"; String pattern = "%{EXCITED_NAME} - %{NAME}"; Grok g = new Grok(bank, pattern, false, logger::warn); assertCaptureConfig(g, Map.of("EXCITED_NAME_0", STRING, "NAME_21", STRING, "NAME_22", STRING)); assertEquals("(?<EXCITED_NAME_0>!!!(?<NAME_21>Tal)!!!) - (?<NAME_22>Tal)", g.toRegex(bank, pattern)); assertEquals(true, g.match(text)); Object actual = g.captures(text); Map<String, Object> expected = new HashMap<>(); expected.put("EXCITED_NAME_0", "!!!Tal!!!"); expected.put("NAME_21", "Tal"); expected.put("NAME_22", "Tal"); assertEquals(expected, actual); } public void testBooleanCaptures() { testBooleanCaptures(false); testBooleanCaptures(true); } private void testBooleanCaptures(boolean ecsCompatibility) { String pattern = "%{WORD:name}=%{WORD:status:boolean}"; Grok g = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), pattern, logger::warn); assertCaptureConfig(g, Map.of("name", STRING, "status", BOOLEAN)); String text = "active=true"; Map<String, Object> expected = new HashMap<>(); expected.put("name", "active"); expected.put("status", true); Map<String, Object> actual = g.captures(text); assertEquals(expected, actual); boolean[] status = new boolean[1]; GrokCaptureExtracter statusExtracter = namedConfig(g, "status").nativeExtracter(new ThrowingNativeExtracterMap() { @Override public GrokCaptureExtracter forBoolean(Function<Consumer<Boolean>, GrokCaptureExtracter> buildExtracter) { return buildExtracter.apply(b -> status[0] = b); } }); assertThat(specificCapture(g, text, statusExtracter), is(true)); assertThat(status[0], equalTo(true)); } public void testNumericCaptures() { Map<String, String> bank = new HashMap<>(); bank.put("BASE10NUM", "(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+)))"); bank.put("NUMBER", "(?:%{BASE10NUM})"); String pattern = "%{NUMBER:bytes:float} %{NUMBER:id:long} %{NUMBER:rating:double}"; Grok g = new Grok(new PatternBank(bank), pattern, logger::warn); assertCaptureConfig(g, Map.of("bytes", FLOAT, "id", LONG, "rating", DOUBLE)); String text = "12009.34 20000000000 4820.092"; Map<String, Object> expected = new HashMap<>(); expected.put("bytes", 12009.34f); expected.put("id", 20000000000L); expected.put("rating", 4820.092); Map<String, Object> actual = g.captures(text); assertEquals(expected, actual); float[] bytes = new float[1]; GrokCaptureExtracter bytesExtracter = namedConfig(g, "bytes").nativeExtracter(new ThrowingNativeExtracterMap() { @Override public GrokCaptureExtracter forFloat(Function<FloatConsumer, GrokCaptureExtracter> buildExtracter) { return buildExtracter.apply(f -> bytes[0] = f); } }); assertThat(specificCapture(g, text, bytesExtracter), is(true)); assertThat(bytes[0], equalTo(12009.34f)); long[] id = new long[1]; GrokCaptureExtracter idExtracter = namedConfig(g, "id").nativeExtracter(new ThrowingNativeExtracterMap() { @Override public GrokCaptureExtracter forLong(Function<LongConsumer, GrokCaptureExtracter> buildExtracter) { return buildExtracter.apply(l -> id[0] = l); } }); assertThat(specificCapture(g, text, idExtracter), is(true)); assertThat(id[0], equalTo(20000000000L)); double[] rating = new double[1]; GrokCaptureExtracter ratingExtracter = namedConfig(g, "rating").nativeExtracter(new ThrowingNativeExtracterMap() { public GrokCaptureExtracter forDouble(java.util.function.Function<DoubleConsumer, GrokCaptureExtracter> buildExtracter) { return buildExtracter.apply(d -> rating[0] = d); } }); assertThat(specificCapture(g, text, ratingExtracter), is(true)); assertThat(rating[0], equalTo(4820.092)); } public void testNumericCapturesCoercion() { Map<String, String> bank = new HashMap<>(); bank.put("BASE10NUM", "(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+)))"); bank.put("NUMBER", "(?:%{BASE10NUM})"); String pattern = "%{NUMBER:bytes:float} %{NUMBER:status} %{NUMBER}"; Grok g = new Grok(new PatternBank(bank), pattern, logger::warn); assertCaptureConfig(g, Map.of("bytes", FLOAT, "status", STRING)); String text = "12009.34 200 9032"; Map<String, Object> expected = new HashMap<>(); expected.put("bytes", 12009.34f); expected.put("status", "200"); Map<String, Object> actual = g.captures(text); assertEquals(expected, actual); } public void testGarbageTypeNameBecomesString() { Map<String, String> bank = new HashMap<>(); bank.put("BASE10NUM", "(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+)))"); bank.put("NUMBER", "(?:%{BASE10NUM})"); String pattern = "%{NUMBER:f:not_a_valid_type}"; Grok g = new Grok(new PatternBank(bank), pattern, logger::warn); assertCaptureConfig(g, Map.of("f", STRING)); assertThat(g.captures("12009.34"), equalTo(Map.of("f", "12009.34"))); } public void testApacheLog() { final String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.12785 " + "YaBrowser/13.12.1599.12785 Safari/537.36"; final String clientIp = "31.184.238.164"; final String timestamp = "24/Jul/2014:05:35:37 +0530"; final String verb = "GET"; final String request = "/logs/access.log"; final String httpVersion = "1.0"; final String referrer = "http://8rursodiol.enjin.com"; testApacheLog( false, tuple(Map.entry("agent", STRING), "\"" + agent + "\""), tuple(Map.entry("auth", STRING), "-"), tuple(Map.entry("bytes", STRING), "69849"), tuple(Map.entry("clientip", STRING), clientIp), tuple(Map.entry("httpversion", STRING), httpVersion), tuple(Map.entry("ident", STRING), "-"), tuple(Map.entry("rawrequest", STRING), null), tuple(Map.entry("referrer", STRING), "\"" + referrer + "\""), tuple(Map.entry("request", STRING), request), tuple(Map.entry("timestamp", STRING), timestamp), tuple(Map.entry("verb", STRING), verb), List.of(tuple(Map.entry("response", STRING), "200")) ); testApacheLog( true, tuple(Map.entry("user_agent.original", STRING), agent), tuple(Map.entry("user.name", STRING), null), tuple(Map.entry("http.response.body.bytes", LONG), 69849L), tuple(Map.entry("source.address", STRING), clientIp), tuple(Map.entry("http.version", STRING), httpVersion), tuple(Map.entry("apache.access.user.identity", STRING), null), tuple(Map.entry("http.response.status_code", INTEGER), 200), tuple(Map.entry("http.request.referrer", STRING), referrer), tuple(Map.entry("url.original", STRING), request), tuple(Map.entry("timestamp", STRING), timestamp), tuple(Map.entry("http.request.method", STRING), verb), List.of() ); } public void testApacheLog( boolean ecsCompatibility, Tuple<Map.Entry<String, GrokCaptureType>, Object> agent, Tuple<Map.Entry<String, GrokCaptureType>, Object> auth, Tuple<Map.Entry<String, GrokCaptureType>, Object> bytes, Tuple<Map.Entry<String, GrokCaptureType>, Object> clientIp, Tuple<Map.Entry<String, GrokCaptureType>, Object> httpVersion, Tuple<Map.Entry<String, GrokCaptureType>, Object> ident, Tuple<Map.Entry<String, GrokCaptureType>, Object> rawRequest, Tuple<Map.Entry<String, GrokCaptureType>, Object> referrer, Tuple<Map.Entry<String, GrokCaptureType>, Object> request, Tuple<Map.Entry<String, GrokCaptureType>, Object> timestamp, Tuple<Map.Entry<String, GrokCaptureType>, Object> verb, List<Tuple<Map.Entry<String, GrokCaptureType>, Object>> additionalFields ) { String logLine = """ 31.184.238.164 - - [24/Jul/2014:05:35:37 +0530] "GET /logs/access.log HTTP/1.0" 200 69849 "http://8rursodiol.enjin.com" \ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.12785 YaBrowser/13.12.1599.12785 \ Safari/537.36" "www.dlwindianrailways.com\""""; Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{COMBINEDAPACHELOG}", logger::warn); Map<String, GrokCaptureType> captureTypes = new HashMap<>(); captureTypes.put(agent.v1().getKey(), agent.v1().getValue()); captureTypes.put(auth.v1().getKey(), auth.v1().getValue()); captureTypes.put(bytes.v1().getKey(), bytes.v1().getValue()); captureTypes.put(clientIp.v1().getKey(), clientIp.v1().getValue()); captureTypes.put(httpVersion.v1().getKey(), httpVersion.v1().getValue()); captureTypes.put(ident.v1().getKey(), ident.v1().getValue()); captureTypes.put(rawRequest.v1().getKey(), rawRequest.v1().getValue()); captureTypes.put(referrer.v1().getKey(), referrer.v1().getValue()); captureTypes.put(request.v1().getKey(), request.v1().getValue()); captureTypes.put(timestamp.v1().getKey(), timestamp.v1().getValue()); captureTypes.put(verb.v1().getKey(), verb.v1().getValue()); for (var additionalField : additionalFields) { captureTypes.put(additionalField.v1().getKey(), additionalField.v1().getValue()); } assertCaptureConfig(grok, captureTypes); Map<String, Object> matches = grok.captures(logLine); assertEquals(clientIp.v2(), matches.get(clientIp.v1().getKey())); assertEquals(ident.v2(), matches.get(ident.v1().getKey())); assertEquals(auth.v2(), matches.get(auth.v1().getKey())); assertEquals(timestamp.v2(), matches.get(timestamp.v1().getKey())); assertEquals(verb.v2(), matches.get(verb.v1().getKey())); assertEquals(request.v2(), matches.get(request.v1().getKey())); assertEquals(httpVersion.v2(), matches.get(httpVersion.v1().getKey())); assertEquals(bytes.v2(), matches.get(bytes.v1().getKey())); assertEquals(referrer.v2(), matches.get(referrer.v1().getKey())); assertEquals(null, matches.get("port")); assertEquals(agent.v2(), matches.get(agent.v1().getKey())); assertEquals(rawRequest.v2(), matches.get(rawRequest.v1().getKey())); for (var additionalField : additionalFields) { assertEquals(additionalField.v2(), matches.get(additionalField.v1().getKey())); } } public void testComplete() { Map<String, String> bank = new HashMap<>(); bank.put("MONTHDAY", "(?:(?:0[1-9])|(?:[12][0-9])|(?:3[01])|[1-9])"); bank.put( "MONTH", "\\b(?:Jan(?:uary|uar)?|Feb(?:ruary|ruar)?|M(?:a|ä)?r(?:ch|z)?|Apr(?:il)?|Ma(?:y|i)?|Jun(?:e|i)" + "?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|O(?:c|k)?t(?:ober)?|Nov(?:ember)?|De(?:c|z)(?:ember)?)\\b" ); bank.put("MINUTE", "(?:[0-5][0-9])"); bank.put("YEAR", "(?>\\d\\d){1,2}"); bank.put("HOUR", "(?:2[0123]|[01]?[0-9])"); bank.put("SECOND", "(?:(?:[0-5]?[0-9]|60)(?:[:.,][0-9]+)?)"); bank.put("TIME", "(?!<[0-9])%{HOUR}:%{MINUTE}(?::%{SECOND})(?![0-9])"); bank.put("INT", "(?:[+-]?(?:[0-9]+))"); bank.put("HTTPDATE", "%{MONTHDAY}/%{MONTH}/%{YEAR}:%{TIME} %{INT}"); bank.put("WORD", "\\b\\w+\\b"); bank.put("BASE10NUM", "(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+)))"); bank.put("NUMBER", "(?:%{BASE10NUM})"); bank.put( "IPV6", "((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]" + "\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4})" + "{1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:)" + "{4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\" + "d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]" + "\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4})" + "{1,5})" + "|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))" + "|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)" + "(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}" + ":((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?" ); bank.put( "IPV4", "(?<![0-9])(?:(?:[0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])[.](?:[0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])[.]" + "(?:[0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])[.](?:[0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(?![0-9])" ); bank.put("IP", "(?:%{IPV6}|%{IPV4})"); bank.put("HOSTNAME", "\\b(?:[0-9A-Za-z][0-9A-Za-z-]{0,62})(?:\\.(?:[0-9A-Za-z][0-9A-Za-z-]{0,62}))*(\\.?|\\b)"); bank.put("IPORHOST", "(?:%{IP}|%{HOSTNAME})"); bank.put("USER", "[a-zA-Z0-9._-]+"); bank.put("DATA", ".*?"); bank.put("QS", "(?>(?<!\\\\)(?>\"(?>\\\\.|[^\\\\\"]+)+\"|\"\"|(?>'(?>\\\\.|[^\\\\']+)+')|''|(?>`(?>\\\\.|[^\\\\`]+)+`)|``))"); String text = """ 83.149.9.216 - - [19/Jul/2015:08:13:42 +0000] "GET /presentations/logstash-monitorama-2013/images/kibana-dashboard3.png \ HTTP/1.1" 200 171717 "http://semicomplete.com/presentations/logstash-monitorama-2013/" "Mozilla/5.0 (Macintosh; Intel Mac \ OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.77 Safari/537.36\""""; String pattern = """ %{IPORHOST:clientip} %{USER:ident} %{USER:auth} \\[%{HTTPDATE:timestamp}\\] "%{WORD:verb} %{DATA:request} \ HTTP/%{NUMBER:httpversion}" %{NUMBER:response:int} (?:-|%{NUMBER:bytes:int}) %{QS:referrer} %{QS:agent}"""; Grok grok = new Grok(new PatternBank(bank), pattern, logger::warn); assertCaptureConfig( grok, Map.ofEntries( Map.entry("agent", STRING), Map.entry("auth", STRING), Map.entry("bytes", INTEGER), Map.entry("clientip", STRING), Map.entry("httpversion", STRING), Map.entry("ident", STRING), Map.entry("referrer", STRING), Map.entry("request", STRING), Map.entry("response", INTEGER), Map.entry("timestamp", STRING), Map.entry("verb", STRING) ) ); Map<String, Object> expected = new HashMap<>(); expected.put("clientip", "83.149.9.216"); expected.put("ident", "-"); expected.put("auth", "-"); expected.put("timestamp", "19/Jul/2015:08:13:42 +0000"); expected.put("verb", "GET"); expected.put("request", "/presentations/logstash-monitorama-2013/images/kibana-dashboard3.png"); expected.put("httpversion", "1.1"); expected.put("response", 200); expected.put("bytes", 171717); expected.put("referrer", "\"http://semicomplete.com/presentations/logstash-monitorama-2013/\""); expected.put( "agent", "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/32.0.1700.77 Safari/537.36\"" ); Map<String, Object> actual = grok.captures(text); assertEquals(expected, actual); } public void testNoMatch() { Map<String, String> bank = new HashMap<>(); bank.put("MONTHDAY", "(?:(?:0[1-9])|(?:[12][0-9])|(?:3[01])|[1-9])"); Grok grok = new Grok(new PatternBank(bank), "%{MONTHDAY:greatday}", logger::warn); assertThat(grok.captures("nomatch"), nullValue()); } public void testMultipleNamedCapturesWithSameName() { Map<String, String> bank = new HashMap<>(); bank.put("SINGLEDIGIT", "[0-9]"); Grok grok = new Grok(new PatternBank(bank), "%{SINGLEDIGIT:num}%{SINGLEDIGIT:num}", logger::warn); assertCaptureConfig(grok, Map.of("num", STRING)); assertThat(grok.captures("12"), equalTo(Map.of("num", List.of("1", "2")))); grok = new Grok(new PatternBank(bank), "%{SINGLEDIGIT:num:int}(%{SINGLEDIGIT:num:int})?", logger::warn); assertCaptureConfig(grok, Map.of("num", INTEGER)); assertEquals(grok.captures("1"), Map.of("num", 1)); assertEquals(grok.captures("1a"), Map.of("num", 1)); assertEquals(grok.captures("a1"), Map.of("num", 1)); assertEquals(grok.captures("12"), Map.of("num", List.of(1, 2))); assertEquals(grok.captures("123"), Map.of("num", List.of(1, 2))); } public void testExponentialExpressions() { testExponentialExpressions(false); testExponentialExpressions(true); } private void testExponentialExpressions(boolean ecsCompatibility) { AtomicBoolean run = new AtomicBoolean(true); // to avoid a lingering thread when test has completed // keeping track of the matcher watchdog and whether it has executed at all (hunting a rare test failure) AtomicBoolean hasExecuted = new AtomicBoolean(false); String grokPattern = "Bonsuche mit folgender Anfrage: Belegart->\\[%{WORD:param2},(?<param5>(\\s*%{NOTSPACE})*)\\] " + "Zustand->ABGESCHLOSSEN Kassennummer->%{WORD:param9} Bonnummer->%{WORD:param10} Datum->%{DATESTAMP_OTHER:param11}"; String logLine = "Bonsuche mit folgender Anfrage: Belegart->[EINGESCHRAENKTER_VERKAUF, VERKAUF, NACHERFASSUNG] " + "Zustand->ABGESCHLOSSEN Kassennummer->2 Bonnummer->6362 Datum->Mon Jan 08 00:00:00 UTC 2018"; BiConsumer<Long, Runnable> scheduler = (delay, command) -> { hasExecuted.set(true); Thread t = new Thread(() -> { try { Thread.sleep(delay); } catch (InterruptedException e) { throw new AssertionError(e); } if (run.get()) { command.run(); } }); t.start(); }; Grok grok = new Grok( GrokBuiltinPatterns.get(ecsCompatibility), grokPattern, MatcherWatchdog.newInstance(10, 200, System::currentTimeMillis, scheduler), logger::warn ); // hunting a rare test failure -- sometimes we get a failure in the expectThrows below, and the most // logical reason for it to be hit is that the matcher watchdog just never even started up. Thread t = new Thread(() -> { try { Thread.sleep(100); // half of max execution, 10x the interval, should be plenty } catch (InterruptedException e) { throw new AssertionError(e); } assertTrue("The MatchWatchdog scheduler should have run by now", hasExecuted.get()); }); t.setName("Quis custodiet ipsos custodes?"); t.start(); Exception e = expectThrows(RuntimeException.class, () -> grok.captures(logLine)); run.set(false); assertThat(e.getMessage(), equalTo("grok pattern matching was interrupted after [200] ms")); } public void testAtInFieldName() { assertGrokedField("@metadata"); } public void assertNonAsciiLetterInFieldName() { assertGrokedField("metädata"); } public void assertSquareBracketInFieldName() { assertGrokedField("metadat[a]"); assertGrokedField("metad[a]ta"); assertGrokedField("[m]etadata"); } public void testUnderscoreInFieldName() { assertGrokedField("meta_data"); } public void testDotInFieldName() { assertGrokedField("meta.data"); } public void testMinusInFieldName() { assertGrokedField("meta-data"); } public void testAlphanumericFieldName() { assertGrokedField(randomAlphaOfLengthBetween(1, 5)); assertGrokedField(randomAlphaOfLengthBetween(1, 5) + randomIntBetween(0, 100)); assertGrokedField(randomIntBetween(0, 100) + randomAlphaOfLengthBetween(1, 5)); assertGrokedField(String.valueOf(randomIntBetween(0, 100))); } public void testUnsupportedBracketsInFieldName() { testUnsupportedBracketsInFieldName(false); testUnsupportedBracketsInFieldName(true); } private void testUnsupportedBracketsInFieldName(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{WORD:unsuppo(r)ted}", logger::warn); Map<String, Object> matches = grok.captures("line"); assertNull(matches); } public void testJavaClassPatternWithUnderscore() { testJavaClassPatternWithUnderscore(false); testJavaClassPatternWithUnderscore(true); } private void testJavaClassPatternWithUnderscore(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{JAVACLASS}", logger::warn); assertThat(grok.match("Test_Class.class"), is(true)); } public void testJavaFilePatternWithSpaces() { testJavaFilePatternWithSpaces(false); testJavaFilePatternWithSpaces(true); } private void testJavaFilePatternWithSpaces(boolean ecsCompatibility) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{JAVAFILE}", logger::warn); assertThat(grok.match("Test Class.java"), is(true)); } public void testLogCallBack() { testLogCallBack(false); testLogCallBack(true); } private void testLogCallBack(boolean ecsCompatibility) { AtomicReference<String> message = new AtomicReference<>(); Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), ".*\\[.*%{SPACE}*\\].*", message::set); grok.match("[foo]"); // this message comes from Joni, so updates to Joni may change the expectation assertThat(message.get(), containsString("regular expression has redundant nested repeat operator")); } public void testCombinedPatterns() { String matchKey = "_ingest._grok_match_index"; String combined; combined = Grok.combinePatterns(List.of(""), null); assertThat(combined, equalTo("")); combined = Grok.combinePatterns(List.of(""), matchKey); assertThat(combined, equalTo("")); combined = Grok.combinePatterns(List.of("foo"), null); assertThat(combined, equalTo("foo")); combined = Grok.combinePatterns(List.of("foo"), matchKey); assertThat(combined, equalTo("foo")); combined = Grok.combinePatterns(List.of("foo", "bar"), null); assertThat(combined, equalTo("(?:foo)|(?:bar)")); combined = Grok.combinePatterns(List.of("foo", "bar")); assertThat(combined, equalTo("(?:foo)|(?:bar)")); combined = Grok.combinePatterns(List.of("foo", "bar"), matchKey); assertThat(combined, equalTo("(?<_ingest._grok_match_index.0>foo)|(?<_ingest._grok_match_index.1>bar)")); } private void assertGrokedField(String fieldName) { String line = "foo"; // test both with and without ECS compatibility for (boolean ecsCompatibility : new boolean[] { false, true }) { Grok grok = new Grok(GrokBuiltinPatterns.get(ecsCompatibility), "%{WORD:" + fieldName + "}", logger::warn); Map<String, Object> matches = grok.captures(line); assertEquals(line, matches.get(fieldName)); } } private void assertCaptureConfig(Grok grok, Map<String, GrokCaptureType> nameToType) { assertCaptureConfig(grok, nameToType, List.of()); } private void assertCaptureConfig(Grok grok, Map<String, GrokCaptureType> nameToType, List<String> acceptedDuplicates) { Map<String, GrokCaptureType> fromGrok = new TreeMap<>(); for (GrokCaptureConfig config : grok.captureConfig()) { Object old = fromGrok.put(config.name(), config.type()); if (acceptedDuplicates.contains(config.name()) == false) { assertThat("duplicates not allowed", old, nullValue()); } } assertThat(fromGrok, equalTo(new TreeMap<>(nameToType))); } private GrokCaptureConfig namedConfig(Grok grok, String name) { return grok.captureConfig().stream().filter(i -> i.name().equals(name)).findFirst().get(); } private boolean specificCapture(Grok grok, String str, GrokCaptureExtracter extracter) { byte[] utf8 = str.getBytes(StandardCharsets.UTF_8); return grok.match(utf8, 0, utf8.length, extracter); } private abstract
GrokTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/binder/TypeBinder.java
{ "start": 1870, "end": 2104 }
interface ____<A extends Annotation> { /** * Perform some custom configuration of the model relating to the given annotated * {@linkplain PersistentClass entity class}. * * @param annotation an annotation of the entity
TypeBinder
java
quarkusio__quarkus
extensions/panache/panache-common/deployment/src/main/java/io/quarkus/panache/common/deployment/PanacheCompanionEnhancer.java
{ "start": 200, "end": 714 }
class ____ implements BiFunction<String, ClassVisitor, ClassVisitor> { protected final IndexView indexView; protected final List<PanacheMethodCustomizer> methodCustomizers; public PanacheCompanionEnhancer(IndexView index, List<PanacheMethodCustomizer> methodCustomizers) { this.indexView = index; this.methodCustomizers = methodCustomizers; } @Override public abstract ClassVisitor apply(String className, ClassVisitor outputClassVisitor); }
PanacheCompanionEnhancer
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/function/FailableTest.java
{ "start": 73634, "end": 74213 }
interface ____ properly defined to throw any exception using String and IOExceptions as * generic test types. */ @Test void testThrows_FailableBiPredicate_String_IOException() { assertThrows(IOException.class, () -> new FailableBiPredicate<String, String, IOException>() { @Override public boolean test(final String object1, final String object2) throws IOException { throw new IOException("test"); } }.test(StringUtils.EMPTY, StringUtils.EMPTY)); } /** * Tests that our failable
is
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/OracleUnnestFunction.java
{ "start": 679, "end": 1647 }
class ____ extends UnnestFunction { public OracleUnnestFunction() { super( "column_value", "i" ); } @Override protected void renderUnnest( SqlAppender sqlAppender, Expression array, BasicPluralType<?, ?> pluralType, @Nullable SqlTypedMapping sqlTypedMapping, AnonymousTupleTableGroupProducer tupleType, String tableIdentifierVariable, SqlAstTranslator<?> walker) { final ModelPart ordinalitySubPart = tupleType.findSubPart( CollectionPart.Nature.INDEX.getName(), null ); final boolean withOrdinality = ordinalitySubPart != null; if ( withOrdinality ) { sqlAppender.appendSql( "lateral (select t.*, rownum " ); sqlAppender.appendSql( ordinalitySubPart.asBasicValuedModelPart().getSelectionExpression() ); sqlAppender.appendSql( " from " ); } sqlAppender.appendSql( "table(" ); array.accept( walker ); sqlAppender.appendSql( ")" ); if ( withOrdinality ) { sqlAppender.appendSql( " t)" ); } } }
OracleUnnestFunction
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvSumTests.java
{ "start": 1091, "end": 4303 }
class ____ extends AbstractMultivalueFunctionTestCase { public MvSumTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { List<TestCaseSupplier> cases = new ArrayList<>(); doubles(cases, "mv_sum", "MvSum", (size, values) -> equalTo(values.sum())); // TODO turn these on once we are summing without overflow // ints(cases, "mv_sum", "MvSum", (size, values) -> equalTo(values.sum())); // longs(cases, "mv_sum", "MvSum", (size, values) -> equalTo(values.sum())); // unsignedLongAsBigInteger(cases, "mv_sum", "MvSum", (size, values) -> equalTo(values.sum())); cases.add(arithmeticExceptionCase(DataType.INTEGER, () -> { List<Object> data = randomList(1, 10, () -> randomIntBetween(0, Integer.MAX_VALUE)); data.add(Integer.MAX_VALUE); return data; })); cases.add(arithmeticExceptionCase(DataType.INTEGER, () -> { List<Object> data = randomList(1, 10, () -> randomIntBetween(Integer.MIN_VALUE, 0)); data.add(Integer.MIN_VALUE); return data; })); cases.add(arithmeticExceptionCase(DataType.LONG, () -> { List<Object> data = randomList(1, 10, () -> randomLongBetween(0L, Long.MAX_VALUE)); data.add(Long.MAX_VALUE); return data; })); cases.add(arithmeticExceptionCase(DataType.LONG, () -> { List<Object> data = randomList(1, 10, () -> randomLongBetween(Long.MIN_VALUE, 0L)); data.add(Long.MIN_VALUE); return data; })); cases.add(arithmeticExceptionCase(DataType.UNSIGNED_LONG, () -> { List<Object> data = randomList(1, 10, ESTestCase::randomLong); data.add(asLongUnsigned(UNSIGNED_LONG_MAX)); return data; })); return parameterSuppliersFromTypedDataWithDefaultChecks(false, cases); } private static TestCaseSupplier arithmeticExceptionCase(DataType dataType, Supplier<Object> dataSupplier) { String typeNameOverflow = dataType.typeName().toLowerCase(Locale.ROOT) + " overflow"; return new TestCaseSupplier( "<" + typeNameOverflow + ">", List.of(dataType), () -> new TestCaseSupplier.TestCase( List.of(new TestCaseSupplier.TypedData(dataSupplier.get(), dataType, "field")), "MvSum[field=Attribute[channel=0]]", dataType, is(nullValue()) ).withWarning("Line 1:1: evaluation of [source] failed, treating result as null. Only first 20 failures recorded.") .withWarning("Line 1:1: java.lang.ArithmeticException: " + typeNameOverflow) ); } @Override protected Expression build(Source source, Expression field) { return new MvSum(source, field); } @Override protected Expression serializeDeserializeExpression(Expression expression) { // TODO: This function doesn't serialize the Source, and must be fixed. return expression; } }
MvSumTests
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestKDiag.java
{ "start": 1630, "end": 6927 }
class ____ extends Assertions { private static final Logger LOG = LoggerFactory.getLogger(TestKDiag.class); public static final String KEYLEN = "128"; public static final String HDFS_SITE_XML = "org/apache/hadoop/security/secure-hdfs-site.xml"; @BeforeAll public static void nameThread() { Thread.currentThread().setName("JUnit"); } private static MiniKdc kdc; private static File workDir; private static File keytab; private static Properties securityProperties; private static Configuration conf; @BeforeAll public static void startMiniKdc() throws Exception { workDir = GenericTestUtils.getTestDir(TestKDiag.class.getSimpleName()); securityProperties = MiniKdc.createConf(); kdc = new MiniKdc(securityProperties, workDir); kdc.start(); keytab = createKeytab("foo"); conf = new Configuration(); conf.set(HADOOP_SECURITY_AUTHENTICATION, "KERBEROS"); } @AfterAll public static synchronized void stopMiniKdc() { if (kdc != null) { kdc.stop(); kdc = null; } } @BeforeEach public void reset() { UserGroupInformation.reset(); } private static File createKeytab(String...principals) throws Exception { File keytab = new File(workDir, "keytab"); kdc.createPrincipal(keytab, principals); return keytab; } /** * Exec KDiag and expect a failure of a given category * @param category category * @param args args list * @throws Exception any unexpected exception */ void kdiagFailure(String category, String ...args) throws Exception { try { int ex = exec(conf, args); LOG.error("Expected an exception in category {}, return code {}", category, ex); } catch (KerberosDiagsFailure e) { if (!e.getCategory().equals(category)) { LOG.error("Expected an exception in category {}, got {}", category, e, e); throw e; } } } void kdiag(String... args) throws Exception { KDiag.exec(conf, args); } @Test public void testBasicLoginFailure() throws Throwable { kdiagFailure(CAT_LOGIN, ARG_KEYLEN, KEYLEN); } @Test public void testBasicLoginSkipped() throws Throwable { kdiagFailure(CAT_LOGIN, ARG_KEYLEN, KEYLEN, ARG_NOLOGIN); } /** * This fails as the default cluster config is checked along with * the CLI * @throws Throwable */ @Test public void testSecure() throws Throwable { kdiagFailure(CAT_CONFIG, ARG_KEYLEN, KEYLEN, ARG_SECURE); } @Test public void testNoKeytab() throws Throwable { kdiagFailure(CAT_KERBEROS, ARG_KEYLEN, KEYLEN, ARG_KEYTAB, "target/nofile"); } @Test public void testKeytabNoPrincipal() throws Throwable { kdiagFailure(CAT_KERBEROS, ARG_KEYLEN, KEYLEN, ARG_KEYTAB, keytab.getAbsolutePath()); } @Test public void testConfIsSecure() throws Throwable { assertFalse(SecurityUtil.getAuthenticationMethod(conf) .equals(UserGroupInformation.AuthenticationMethod.SIMPLE)); } @Test public void testKeytabAndPrincipal() throws Throwable { kdiag(ARG_KEYLEN, KEYLEN, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, "foo@EXAMPLE.COM"); } @Test public void testKerberosName() throws Throwable { kdiagFailure(ARG_KEYLEN, KEYLEN, ARG_VERIFYSHORTNAME, ARG_PRINCIPAL, "foo/foo/foo@BAR.COM"); } @Test public void testShortName() throws Throwable { kdiag(ARG_KEYLEN, KEYLEN, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, ARG_VERIFYSHORTNAME, ARG_PRINCIPAL, "foo@EXAMPLE.COM"); } @Test public void testFileOutput() throws Throwable { File f = new File("target/kdiag.txt"); kdiag(ARG_KEYLEN, KEYLEN, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, "foo@EXAMPLE.COM", ARG_OUTPUT, f.getAbsolutePath()); LOG.info("Output of {}", f); dump(f); } @Test public void testLoadResource() throws Throwable { kdiag(ARG_KEYLEN, KEYLEN, ARG_RESOURCE, HDFS_SITE_XML, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, "foo@EXAMPLE.COM"); } @Test public void testLoadInvalidResource() throws Throwable { kdiagFailure(CAT_CONFIG, ARG_KEYLEN, KEYLEN, ARG_RESOURCE, "no-such-resource.xml", ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, "foo@EXAMPLE.COM"); } @Test public void testRequireJAAS() throws Throwable { kdiagFailure(CAT_JAAS, ARG_KEYLEN, KEYLEN, ARG_JAAS, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, "foo@EXAMPLE.COM"); } /* commented out as once JVM gets configured, it stays configured @Test(expected = IOException.class) public void testKeytabUnknownPrincipal() throws Throwable { kdiag(ARG_KEYLEN, KEYLEN, ARG_KEYTAB, keytab.getAbsolutePath(), ARG_PRINCIPAL, "bob@EXAMPLE.COM"); } */ /** * Dump any file to standard out. * @param file file to dump * @throws IOException IO problems */ private void dump(File file) throws IOException { try (FileInputStream in = new FileInputStream(file)) { for (String line : IOUtils.readLines(in, StandardCharsets.UTF_8)) { LOG.info(line); } } } }
TestKDiag
java
elastic__elasticsearch
test/fixtures/azure-fixture/src/main/java/fixture/azure/MockAzureBlobStore.java
{ "start": 11042, "end": 11156 }
class ____ { /** * Minimal set of states, we don't support breaking/broken */
Lease
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/order/OrderUtil.java
{ "start": 2068, "end": 2531 }
class ____ avoid lambda overhead during the startup public static final Comparator<Object> COMPARATOR_ZERO = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { int order1 = getOrder(o1); int order2 = getOrder(o2); return Integer.compare(order1, order2); } }; /** * The comparator of elements implementing {@link Ordered}. */ // Keep as an anonymous
to
java
quarkusio__quarkus
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoCollection.java
{ "start": 20408, "end": 21006 }
class ____ decode each document into * @param <D> the target document type of the iterable. * @return the stream of changes */ <D> Multi<ChangeStreamDocument<D>> watch(ClientSession clientSession, List<? extends Bson> pipeline, Class<D> clazz); /** * Creates a change stream for this collection. * * @param options the stream options * @return the stream of changes */ Multi<ChangeStreamDocument<Document>> watch(ChangeStreamOptions options); /** * Creates a change stream for this collection. * * @param clazz the
to
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/lookup/LookupConditionOnProducersTest.java
{ "start": 1201, "end": 2041 }
class ____ { // -> suppressed because service.alpha.enabled=false @LookupIfProperty(name = "service.alpha.enabled", stringValue = "true") @Produces public Service alpha() { return new Service() { @Override public String ping() { return "alpha"; } }; } // -> NOT suppressed because the property is not specified and lookUpIfMissing=true @LookupUnlessProperty(name = "service.bravo.enabled", stringValue = "false", lookupIfMissing = true) @Produces public Service bravo() { return new Service() { @Override public String ping() { return "bravo"; } }; } } }
ServiceProducer
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/pagecache/ManyMessageTransfer.java
{ "start": 1116, "end": 3349 }
class ____ extends AbstractReferenceCounted implements FileRegion { private final ByteBuffer byteBufferHeader; private final GetMessageResult getMessageResult; /** * Bytes which were transferred already. */ private long transferred; public ManyMessageTransfer(ByteBuffer byteBufferHeader, GetMessageResult getMessageResult) { this.byteBufferHeader = byteBufferHeader; this.getMessageResult = getMessageResult; } @Override public long position() { int pos = byteBufferHeader.position(); List<ByteBuffer> messageBufferList = this.getMessageResult.getMessageBufferList(); for (ByteBuffer bb : messageBufferList) { pos += bb.position(); } return pos; } @Override public long transfered() { return transferred; } @Override public long transferred() { return transferred; } @Override public long count() { return byteBufferHeader.limit() + this.getMessageResult.getBufferTotalSize(); } @Override public long transferTo(WritableByteChannel target, long position) throws IOException { if (this.byteBufferHeader.hasRemaining()) { transferred += target.write(this.byteBufferHeader); return transferred; } else { List<ByteBuffer> messageBufferList = this.getMessageResult.getMessageBufferList(); for (ByteBuffer bb : messageBufferList) { if (bb.hasRemaining()) { transferred += target.write(bb); return transferred; } } } return 0; } @Override public FileRegion retain() { super.retain(); return this; } @Override public FileRegion retain(int increment) { super.retain(increment); return this; } @Override public FileRegion touch() { return this; } @Override public FileRegion touch(Object hint) { return this; } public void close() { this.deallocate(); } @Override protected void deallocate() { this.getMessageResult.release(); } }
ManyMessageTransfer
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/object/RdbmsOperation.java
{ "start": 2473, "end": 16757 }
class ____ to execute SQL. */ private JdbcTemplate jdbcTemplate = new JdbcTemplate(); private int resultSetType = ResultSet.TYPE_FORWARD_ONLY; private boolean updatableResults = false; private boolean returnGeneratedKeys = false; private String @Nullable [] generatedKeysColumnNames; private @Nullable String sql; private final List<SqlParameter> declaredParameters = new ArrayList<>(); /** * Has this operation been compiled? Compilation means at * least checking that a DataSource and sql have been provided, * but subclasses may also implement their own custom validation. */ private volatile boolean compiled; /** * An alternative to the more commonly used {@link #setDataSource} when you want to * use the same {@link JdbcTemplate} in multiple {@code RdbmsOperations}. This is * appropriate if the {@code JdbcTemplate} has special configuration such as a * {@link org.springframework.jdbc.support.SQLExceptionTranslator} to be reused. */ public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } /** * Return the {@link JdbcTemplate} used by this operation object. */ public JdbcTemplate getJdbcTemplate() { return this.jdbcTemplate; } /** * Set the JDBC {@link DataSource} to obtain connections from. * @see org.springframework.jdbc.core.JdbcTemplate#setDataSource */ public void setDataSource(DataSource dataSource) { this.jdbcTemplate.setDataSource(dataSource); } /** * Set the fetch size for this RDBMS operation. This is important for processing * large result sets: Setting this higher than the default value will increase * processing speed at the cost of memory consumption; setting this lower can * avoid transferring row data that will never be read by the application. * <p>Default is -1, indicating to use the driver's default. * @see org.springframework.jdbc.core.JdbcTemplate#setFetchSize */ public void setFetchSize(int fetchSize) { this.jdbcTemplate.setFetchSize(fetchSize); } /** * Set the maximum number of rows for this RDBMS operation. This is important * for processing subsets of large result sets, in order to avoid reading and * holding the entire result set in the database or in the JDBC driver. * <p>Default is -1, indicating to use the driver's default. * @see org.springframework.jdbc.core.JdbcTemplate#setMaxRows */ public void setMaxRows(int maxRows) { this.jdbcTemplate.setMaxRows(maxRows); } /** * Set the query timeout for statements that this RDBMS operation executes. * <p>Default is -1, indicating to use the JDBC driver's default. * <p>Note: Any timeout specified here will be overridden by the remaining * transaction timeout when executing within a transaction that has a * timeout specified at the transaction level. */ public void setQueryTimeout(int queryTimeout) { this.jdbcTemplate.setQueryTimeout(queryTimeout); } /** * Set whether to use statements that return a specific type of ResultSet. * @param resultSetType the ResultSet type * @see java.sql.ResultSet#TYPE_FORWARD_ONLY * @see java.sql.ResultSet#TYPE_SCROLL_INSENSITIVE * @see java.sql.ResultSet#TYPE_SCROLL_SENSITIVE * @see java.sql.Connection#prepareStatement(String, int, int) */ public void setResultSetType(int resultSetType) { this.resultSetType = resultSetType; } /** * Return whether statements will return a specific type of ResultSet. */ public int getResultSetType() { return this.resultSetType; } /** * Set whether to use statements that are capable of returning * updatable ResultSets. * @see java.sql.Connection#prepareStatement(String, int, int) */ public void setUpdatableResults(boolean updatableResults) { if (isCompiled()) { throw new InvalidDataAccessApiUsageException( "The updatableResults flag must be set before the operation is compiled"); } this.updatableResults = updatableResults; } /** * Return whether statements will return updatable ResultSets. */ public boolean isUpdatableResults() { return this.updatableResults; } /** * Set whether prepared statements should be capable of returning * auto-generated keys. * @see java.sql.Connection#prepareStatement(String, int) */ public void setReturnGeneratedKeys(boolean returnGeneratedKeys) { if (isCompiled()) { throw new InvalidDataAccessApiUsageException( "The returnGeneratedKeys flag must be set before the operation is compiled"); } this.returnGeneratedKeys = returnGeneratedKeys; } /** * Return whether statements should be capable of returning * auto-generated keys. */ public boolean isReturnGeneratedKeys() { return this.returnGeneratedKeys; } /** * Set the column names of the auto-generated keys. * @see java.sql.Connection#prepareStatement(String, String[]) */ public void setGeneratedKeysColumnNames(String @Nullable ... names) { if (isCompiled()) { throw new InvalidDataAccessApiUsageException( "The column names for the generated keys must be set before the operation is compiled"); } this.generatedKeysColumnNames = names; } /** * Return the column names of the auto generated keys. */ public String @Nullable [] getGeneratedKeysColumnNames() { return this.generatedKeysColumnNames; } /** * Set the SQL executed by this operation. */ public void setSql(@Nullable String sql) { this.sql = sql; } /** * Subclasses can override this to supply dynamic SQL if they wish, but SQL is * normally set by calling the {@link #setSql} method or in a subclass constructor. */ public @Nullable String getSql() { return this.sql; } /** * Resolve the configured SQL for actual use. * @return the SQL (never {@code null}) * @since 5.0 */ protected String resolveSql() { String sql = getSql(); Assert.state(sql != null, "No SQL set"); return sql; } /** * Add anonymous parameters, specifying only their SQL types * as defined in the {@code java.sql.Types} class. * <p>Parameter ordering is significant. This method is an alternative * to the {@link #declareParameter} method, which should normally be preferred. * @param types array of SQL types as defined in the * {@code java.sql.Types} class * @throws InvalidDataAccessApiUsageException if the operation is already compiled */ public void setTypes(int @Nullable [] types) throws InvalidDataAccessApiUsageException { if (isCompiled()) { throw new InvalidDataAccessApiUsageException("Cannot add parameters once query is compiled"); } if (types != null) { for (int type : types) { declareParameter(new SqlParameter(type)); } } } /** * Declare a parameter for this operation. * <p>The order in which this method is called is significant when using * positional parameters. It is not significant when using named parameters * with named SqlParameter objects here; it remains significant when using * named parameters in combination with unnamed SqlParameter objects here. * @param param the SqlParameter to add. This will specify SQL type and (optionally) * the parameter's name. Note that you typically use the {@link SqlParameter} class * itself here, not any of its subclasses. * @throws InvalidDataAccessApiUsageException if the operation is already compiled, * and hence cannot be configured further */ public void declareParameter(SqlParameter param) throws InvalidDataAccessApiUsageException { if (isCompiled()) { throw new InvalidDataAccessApiUsageException("Cannot add parameters once the query is compiled"); } this.declaredParameters.add(param); } /** * Add one or more declared parameters. Used for configuring this operation * when used in a bean factory. Each parameter will specify SQL type and (optionally) * the parameter's name. * @param parameters an array containing the declared {@link SqlParameter} objects * @see #declaredParameters */ public void setParameters(SqlParameter... parameters) { if (isCompiled()) { throw new InvalidDataAccessApiUsageException("Cannot add parameters once the query is compiled"); } for (int i = 0; i < parameters.length; i++) { if (parameters[i] != null) { this.declaredParameters.add(parameters[i]); } else { throw new InvalidDataAccessApiUsageException("Cannot add parameter at index " + i + " from " + Arrays.asList(parameters) + " since it is 'null'"); } } } /** * Return a list of the declared {@link SqlParameter} objects. */ protected List<SqlParameter> getDeclaredParameters() { return this.declaredParameters; } /** * Ensures compilation if used in a bean factory. */ @Override public void afterPropertiesSet() { compile(); } /** * Compile this query. * Ignores subsequent attempts to compile. * @throws InvalidDataAccessApiUsageException if the object hasn't * been correctly initialized, for example if no DataSource has been provided */ public final void compile() throws InvalidDataAccessApiUsageException { if (!isCompiled()) { if (getSql() == null) { throw new InvalidDataAccessApiUsageException("Property 'sql' is required"); } try { this.jdbcTemplate.afterPropertiesSet(); } catch (IllegalArgumentException ex) { throw new InvalidDataAccessApiUsageException(ex.getMessage()); } compileInternal(); this.compiled = true; if (logger.isDebugEnabled()) { logger.debug("RdbmsOperation with SQL [" + getSql() + "] compiled"); } } } /** * Is this operation "compiled"? Compilation, as in JDO, * means that the operation is fully configured, and ready to use. * The exact meaning of compilation will vary between subclasses. * @return whether this operation is compiled and ready to use */ public boolean isCompiled() { return this.compiled; } /** * Check whether this operation has been compiled already; * lazily compile it if not already compiled. * <p>Automatically called by {@code validateParameters}. * @see #validateParameters */ protected void checkCompiled() { if (!isCompiled()) { logger.debug("SQL operation not compiled before execution - invoking compile"); compile(); } } /** * Validate the parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} * or {@code update()} method. * @param parameters the parameters supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateParameters(Object @Nullable [] parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } declaredInParameters++; } } validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters); } /** * Validate the named parameters passed to an execute method based on declared parameters. * Subclasses should invoke this method before every {@code executeQuery()} or * {@code update()} method. * @param parameters parameter Map supplied (may be {@code null}) * @throws InvalidDataAccessApiUsageException if the parameters are invalid */ protected void validateNamedParameters(@Nullable Map<String, ?> parameters) throws InvalidDataAccessApiUsageException { checkCompiled(); Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object> emptyMap()); int declaredInParameters = 0; for (SqlParameter param : this.declaredParameters) { if (param.isInputValueProvided()) { if (!supportsLobParameters() && (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) { throw new InvalidDataAccessApiUsageException( "BLOB or CLOB parameters are not allowed for this kind of operation"); } if (param.getName() != null && !paramsToUse.containsKey(param.getName())) { throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName() + "' was not among the parameters supplied: " + paramsToUse.keySet()); } declaredInParameters++; } } validateParameterCount(paramsToUse.size(), declaredInParameters); } /** * Validate the given parameter count against the given declared parameters. * @param suppliedParamCount the number of actual parameters given * @param declaredInParamCount the number of input parameters declared */ private void validateParameterCount(int suppliedParamCount, int declaredInParamCount) { if (suppliedParamCount < declaredInParamCount) { throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " + declaredInParamCount + " in parameters were declared in class [" + getClass().getName() + "]"); } if (suppliedParamCount > this.declaredParameters.size() && !allowsUnusedParameters()) { throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " + declaredInParamCount + " parameters were declared in class [" + getClass().getName() + "]"); } } /** * Subclasses must implement this template method to perform their own compilation. * Invoked after this base class's compilation is complete. * <p>Subclasses can assume that SQL and a DataSource have been supplied. * @throws InvalidDataAccessApiUsageException if the subclass hasn't been * properly configured */ protected abstract void compileInternal() throws InvalidDataAccessApiUsageException; /** * Return whether BLOB/CLOB parameters are supported for this kind of operation. * <p>The default is {@code true}. */ protected boolean supportsLobParameters() { return true; } /** * Return whether this operation accepts additional parameters that are * given but not actually used. Applies in particular to parameter Maps. * <p>The default is {@code false}. * @see StoredProcedure */ protected boolean allowsUnusedParameters() { return false; } }
used
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/query/StateQueryRequest.java
{ "start": 6072, "end": 6782 }
class ____ { private final String name; private InStore(final String name) { this.name = name; } /** * Specifies the query to run on the specified store. */ public <R> StateQueryRequest<R> withQuery(final Query<R> query) { return new StateQueryRequest<>( name, // name is already specified PositionBound.unbounded(), // default: unbounded Optional.empty(), // default: all partitions query, // the query is specified false, // default: no execution info false // default: don't require active ); } } }
InStore
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/convert/multiple/StringToNavigableSetConverter.java
{ "start": 1001, "end": 1096 }
class ____ convert {@link String} to {@link SortedSet}-based value * * @since 2.7.6 */ public
to
java
google__guava
android/guava/src/com/google/common/collect/ImmutableCollection.java
{ "start": 17644, "end": 18239 }
class ____ this method in order to covariantly return its own * type. * * @param elements the elements to add * @return this {@code Builder} instance * @throws NullPointerException if {@code elements} is null or contains a null element */ @CanIgnoreReturnValue public Builder<E> addAll(Iterable<? extends E> elements) { for (E element : elements) { add(element); } return this; } /** * Adds each element of {@code elements} to the {@code ImmutableCollection} being built. * * <p>Note that each builder
overrides
java
apache__flink
flink-end-to-end-tests/flink-end-to-end-tests-table-api/src/main/java/org/apache/flink/table/test/async/AsyncScalarFunctionExample.java
{ "start": 1791, "end": 6826 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(AsyncScalarFunctionExample.class); /** * Sets up and executes the Flink processing pipeline. * * @return TableResult from the execution */ public TableResult execute() throws Exception { LOG.info("Starting AsyncScalarFunctionExample"); // Set up Table Environment EnvironmentSettings settings = EnvironmentSettings.inStreamingMode(); TableEnvironment tableEnv = TableEnvironment.create(settings); // Register source table createSourceTable(tableEnv); // Register sink table createSinkTable(tableEnv); // Register the lookup function registerLookupFunction(tableEnv); // Create and execute the transformation using Table API TableResult result = processProducts(tableEnv); LOG.info("Executing Flink job"); return result; } /** Creates the source table using datagen connector. */ protected void createSourceTable(TableEnvironment tableEnv) { final Schema schema = Schema.newBuilder() .column("product_id", DataTypes.STRING()) .column("price", DataTypes.DECIMAL(10, 2)) .column("quantity", DataTypes.INT()) .column("ts", DataTypes.TIMESTAMP(3)) .watermark("ts", "ts - INTERVAL '5' SECOND") .build(); // Create a temporary mock products table tableEnv.createTemporaryTable( "products", TableDescriptor.forConnector("datagen") .schema(schema) .option("number-of-rows", "10") .option("fields.product_id.kind", "sequence") .option("fields.product_id.start", "1") .option("fields.product_id.end", "10") .option("fields.price.min", "10.00") .option("fields.price.max", "100.00") .option("fields.quantity.min", "1") .option("fields.quantity.max", "10") .build()); LOG.info("Source table 'products' created"); } /** Creates the sink table using blackhole connector. */ protected void createSinkTable(TableEnvironment tableEnv) { tableEnv.createTemporaryTable( "enriched_products", TableDescriptor.forConnector("blackhole") .schema( Schema.newBuilder() .column("product_id", DataTypes.STRING()) .column("price", DataTypes.DECIMAL(10, 2)) .column("quantity", DataTypes.INT()) .column("timestamp", DataTypes.TIMESTAMP(3)) .column("name", DataTypes.STRING()) .build()) .build()); LOG.info("Sink table 'enriched_products' created"); } /** Registers the async lookup function. */ protected void registerLookupFunction(TableEnvironment tableEnv) { tableEnv.createTemporaryFunction("lookup_name", new MockAsyncLookupFunction("name")); LOG.info("Registered async lookup function"); } /** * Processes products data using Table API with async lookups. - Performs async lookups - * Enriches the data with product details - Inserts into the sink table * * @return TableResult from the execution */ protected TableResult processProducts(TableEnvironment tableEnv) { Table products = tableEnv.from("products"); Table enrichedProducts = products.select( $("product_id"), $("price"), $("quantity"), $("ts").as("timestamp"), call("lookup_name", $("product_id")).as("name")); // Execute the query - will fail with NoClassDefFoundError for StringSubstitutor TableResult result = enrichedProducts.executeInsert("enriched_products"); LOG.info("Product enrichment transformation created"); return result; } /** Application entry point. */ public static void main(String[] args) throws Exception { AsyncScalarFunctionExample example = new AsyncScalarFunctionExample(); try { TableResult result = example.execute(); LOG.info("Job completed successfully"); result.await(); } catch (Throwable t) { // Log the exception chain to find the root cause LOG.error("Job failed with exception", t); } } /** Mock implementation of an AsyncScalarFunction that simulates async lookups. */ public static
AsyncScalarFunctionExample
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conditional/propertyname/targetpropertyname/ConditionalMethodInUsesMapperWithTargetPropertyName.java
{ "start": 1068, "end": 1382 }
class ____ { @Condition public boolean isNotBlank(String value, @TargetPropertyName String propName) { if ( propName.equalsIgnoreCase( "lastName" ) ) { return false; } return value != null && !value.trim().isEmpty(); } } }
PresenceUtils
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/diversification/ResultDiversificationContext.java
{ "start": 674, "end": 1810 }
class ____ { private final String field; private final int size; private final VectorData queryVector; private Map<Integer, VectorData> fieldVectors = null; protected ResultDiversificationContext(String field, int size, @Nullable VectorData queryVector) { this.field = field; this.size = size; this.queryVector = queryVector; } public String getField() { return field; } public int getSize() { return size; } /** * Sets the field vectors for this context. * Note that the key should be the `RankDoc` rank in the total result set * @param fieldVectors the vectors to set */ public void setFieldVectors(Map<Integer, VectorData> fieldVectors) { this.fieldVectors = fieldVectors; } public VectorData getQueryVector() { return queryVector; } public VectorData getFieldVector(int rank) { return fieldVectors.getOrDefault(rank, null); } public Set<Map.Entry<Integer, VectorData>> getFieldVectorsEntrySet() { return fieldVectors.entrySet(); } }
ResultDiversificationContext
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/logs/OtelLoggingFileTest.java
{ "start": 1637, "end": 4746 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClasses(JBossLoggingBean.class) .addClasses(InMemoryLogRecordExporter.class, InMemoryLogRecordExporterProvider.class) .addAsResource(new StringAsset(InMemoryLogRecordExporterProvider.class.getCanonicalName()), "META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider") .add(new StringAsset( "quarkus.otel.logs.enabled=true\n" + "quarkus.log.file.enabled=true\n" + // enable log file "quarkus.otel.traces.enabled=false\n"), "application.properties")); @Inject InMemoryLogRecordExporter logRecordExporter; @Inject JBossLoggingBean jBossLoggingBean; @BeforeEach void setup() { logRecordExporter.reset(); } @Test public void testLoggingData() { final String message = "Logging message to test the different logging attributes"; assertEquals("hello", jBossLoggingBean.hello(message)); List<LogRecordData> finishedLogRecordItems = logRecordExporter.getFinishedLogRecordItemsAtLeast(1); LogRecordData last = finishedLogRecordItems.get(finishedLogRecordItems.size() - 1); OpenTelemetryAssertions.assertThat(last) .hasSeverity(Severity.INFO) .hasSeverityText("INFO") .hasBody(message) .hasAttributesSatisfying( attributes -> OpenTelemetryAssertions.assertThat(attributes) .containsEntry(CODE_FUNCTION_NAME.getKey(), "io.quarkus.opentelemetry.deployment.logs.OtelLoggingFileTest$JBossLoggingBean.hello") .containsEntry(THREAD_NAME.getKey(), Thread.currentThread().getName()) .containsEntry(THREAD_ID.getKey(), Thread.currentThread().getId()) .containsEntry("log.logger.namespace", "org.jboss.logging.Logger") .containsEntry(LOG_FILE_PATH, "target" + File.separator + "quarkus.log") .containsKey(CODE_LINE_NUMBER.getKey()) .doesNotContainKey(EXCEPTION_TYPE) .doesNotContainKey(EXCEPTION_MESSAGE) .doesNotContainKey(EXCEPTION_STACKTRACE) // attributes do not duplicate tracing data .doesNotContainKey("spanId") .doesNotContainKey("traceId") .doesNotContainKey("sampled")); } @ApplicationScoped public static
OtelLoggingFileTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/IndexVersionTests.java
{ "start": 2278, "end": 2698 }
class ____ { public static final IndexVersion V_0_00_01 = new IndexVersion(199, Version.LATEST); public static final IndexVersion V_0_000_002 = new IndexVersion(2, Version.LATEST); public static final IndexVersion V_0_000_003 = new IndexVersion(3, Version.LATEST); public static final IndexVersion V_0_000_004 = new IndexVersion(4, Version.LATEST); } public static
CorrectFakeVersion
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
{ "start": 59223, "end": 60027 }
class ____ implements Validator { final int maxSize; private ListSize(final int maxSize) { this.maxSize = maxSize; } public static ListSize atMostOfSize(final int maxSize) { return new ListSize(maxSize); } @Override public void ensureValid(final String name, final Object value) { @SuppressWarnings("unchecked") List<String> values = (List<String>) value; if (values.size() > maxSize) { throw new ConfigException(name, value, "exceeds maximum list size of [" + maxSize + "]."); } } @Override public String toString() { return "List containing maximum of " + maxSize + " elements"; } } public static
ListSize
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/ScriptAppenderSelector.java
{ "start": 2125, "end": 6960 }
class ____ implements org.apache.logging.log4j.core.util.Builder<Appender> { @PluginElement("AppenderSet") @Required private AppenderSet appenderSet; @PluginConfiguration @Required private Configuration configuration; @PluginBuilderAttribute @Required private String name; @PluginElement("Script") @Required private AbstractScript script; @Override public Appender build() { if (name == null) { LOGGER.error("Name missing."); return null; } if (script == null) { LOGGER.error("Script missing for ScriptAppenderSelector appender {}", name); return null; } if (appenderSet == null) { LOGGER.error("AppenderSet missing for ScriptAppenderSelector appender {}", name); return null; } if (configuration == null) { LOGGER.error("Configuration missing for ScriptAppenderSelector appender {}", name); return null; } final ScriptManager scriptManager = configuration.getScriptManager(); if (scriptManager == null) { LOGGER.error("Script support is not enabled"); return null; } if (!scriptManager.addScript(script)) { return null; } final Bindings bindings = scriptManager.createBindings(script); LOGGER.debug( "ScriptAppenderSelector '{}' executing {} '{}': {}", name, script.getLanguage(), script.getId(), script.getScriptText()); final Object object = scriptManager.execute(script.getId(), bindings); final String actualAppenderName = Objects.toString(object, null); LOGGER.debug("ScriptAppenderSelector '{}' selected '{}'", name, actualAppenderName); return appenderSet.createAppender(actualAppenderName, name); } public AppenderSet getAppenderSet() { return appenderSet; } public Configuration getConfiguration() { return configuration; } public String getName() { return name; } public AbstractScript getScript() { return script; } /** * @since 2.26.0 */ public Builder setAppenderNodeSet(final AppenderSet appenderSet) { this.appenderSet = appenderSet; return this; } /** * @since 2.26.0 */ public Builder setConfiguration(final Configuration configuration) { this.configuration = configuration; return this; } /** * @since 2.26.0 */ public Builder setName(final String name) { this.name = name; return this; } /** * @since 2.26.0 */ public Builder setScript(final AbstractScript script) { this.script = script; return this; } /** * @deprecated since 2.26.0 use {@link #setAppenderNodeSet(AppenderSet)}. */ @Deprecated public Builder withAppenderNodeSet(final AppenderSet appenderSet) { this.appenderSet = appenderSet; return this; } /** * @deprecated since 2.26.0 use {@link #setConfiguration(Configuration)}. */ @Deprecated public Builder withConfiguration(final Configuration configuration) { this.configuration = configuration; return this; } /** * @deprecated since 2.26.0 use {@link #setName(String)}. */ @Deprecated public Builder withName(final String name) { this.name = name; return this; } /** * @deprecated since 2.26.0 use {@link #setScript(AbstractScript)}. */ @Deprecated public Builder withScript(final AbstractScript script) { this.script = script; return this; } } @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } private ScriptAppenderSelector( final String name, final Filter filter, final Layout<? extends Serializable> layout, final Property[] properties) { super(name, filter, layout, true, Property.EMPTY_ARRAY); } @Override public void append(final LogEvent event) { // Do nothing: This appender is only used to discover and build another appender } }
Builder
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateForceCompletionHeaderInAggregationStrategyTest.java
{ "start": 1094, "end": 2193 }
class ____ extends ContextTestSupport { @Test public void testCompletePreviousOnNewGroup() throws Exception { getMockEndpoint("mock:aggregated").expectedBodiesReceived("AAA", "BB"); getMockEndpoint("mock:aggregated").allMessages().header(Exchange.AGGREGATION_COMPLETE_ALL_GROUPS).isNull(); getMockEndpoint("mock:aggregated").allMessages().exchangeProperty(Exchange.AGGREGATION_COMPLETE_ALL_GROUPS).isNull(); template.sendBody("direct:start", "A,A,A,B,B"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").split(body()).to("log:input?showAll=true") .aggregate(simple("${body}"), new MyAggregationStrategy()) .completionPredicate(exchangeProperty(Exchange.SPLIT_COMPLETE)).to("log:aggregated", "mock:aggregated"); } }; } public static
AggregateForceCompletionHeaderInAggregationStrategyTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteEventsEndpointBuilderFactory.java
{ "start": 6421, "end": 12133 }
interface ____ extends EndpointConsumerBuilder { default IgniteEventsEndpointBuilder basic() { return (IgniteEventsEndpointBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedIgniteEventsEndpointBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedIgniteEventsEndpointBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedIgniteEventsEndpointBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedIgniteEventsEndpointBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedIgniteEventsEndpointBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedIgniteEventsEndpointBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } } public
AdvancedIgniteEventsEndpointBuilder
java
spring-projects__spring-security
access/src/test/java/org/springframework/security/web/access/channel/ChannelProcessingFilterTests.java
{ "start": 5686, "end": 6375 }
class ____ implements ChannelDecisionManager { private String supportAttribute; private boolean commitAResponse; MockChannelDecisionManager(boolean commitAResponse, String supportAttribute) { this.commitAResponse = commitAResponse; this.supportAttribute = supportAttribute; } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException { if (this.commitAResponse) { invocation.getHttpResponse().sendRedirect("/redirected"); } } @Override public boolean supports(ConfigAttribute attribute) { return attribute.getAttribute().equals(this.supportAttribute); } } private
MockChannelDecisionManager
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/TreatException.java
{ "start": 317, "end": 532 }
class ____ extends HibernateException { public TreatException(String message) { super( message ); } public TreatException(String message, @Nullable Throwable cause) { super( message, cause ); } }
TreatException
java
spring-projects__spring-boot
module/spring-boot-jackson/src/main/java/org/springframework/boot/jackson/JacksonMixinModuleEntries.java
{ "start": 5024, "end": 5646 }
class ____ * @return {@code this}, to facilitate method chaining */ public Builder and(String typeClassName, String mixinClassName) { this.entries.put(typeClassName, mixinClassName); return this; } /** * Add a mapping for the specified classes. * @param type the type class * @param mixinClass the mixin class * @return {@code this}, to facilitate method chaining */ public Builder and(Class<?> type, Class<?> mixinClass) { this.entries.put(type, mixinClass); return this; } JacksonMixinModuleEntries build() { return new JacksonMixinModuleEntries(this); } } static
name
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/util/UniqueId.java
{ "start": 118, "end": 432 }
class ____ may be used as Serializable key * for entries that need to retain identity of some kind, but where * actual appearance of id itself does not matter. * Instances NEVER equal each other, only themselves, even if generated * ids might be same (although they should not be). * * @since 3.0 */ public
that
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/RouterStatePBImpl.java
{ "start": 1887, "end": 6753 }
class ____ extends RouterState implements PBRecord { private FederationProtocolPBTranslator<RouterRecordProto, Builder, RouterRecordProtoOrBuilder> translator = new FederationProtocolPBTranslator<RouterRecordProto, Builder, RouterRecordProtoOrBuilder>(RouterRecordProto.class); public RouterStatePBImpl() { } public RouterStatePBImpl(RouterRecordProto proto) { this.translator.setProto(proto); } @Override public RouterRecordProto getProto() { return this.translator.build(); } @Override public void setProto(Message proto) { this.translator.setProto(proto); } @Override public void readInstance(String base64String) throws IOException { this.translator.readInstance(base64String); } @Override public void setAddress(String address) { RouterRecordProto.Builder builder = this.translator.getBuilder(); if (address == null) { builder.clearAddress(); } else { builder.setAddress(address); } } @Override public String getAddress() { RouterRecordProtoOrBuilder proto = this.translator.getProtoOrBuilder(); if (!proto.hasAddress()) { return null; } return proto.getAddress(); } @Override public void setStateStoreVersion(StateStoreVersion version) { RouterRecordProto.Builder builder = this.translator.getBuilder(); if (version instanceof StateStoreVersionPBImpl) { StateStoreVersionPBImpl versionPB = (StateStoreVersionPBImpl)version; StateStoreVersionRecordProto versionProto = (StateStoreVersionRecordProto)versionPB.getProto(); builder.setStateStoreVersion(versionProto); } else { builder.clearStateStoreVersion(); } } @Override public StateStoreVersion getStateStoreVersion() throws IOException { RouterRecordProtoOrBuilder proto = this.translator.getProtoOrBuilder(); if (!proto.hasStateStoreVersion()) { return null; } StateStoreVersionRecordProto versionProto = proto.getStateStoreVersion(); StateStoreVersion version = StateStoreSerializer.newRecord(StateStoreVersion.class); if (version instanceof StateStoreVersionPBImpl) { StateStoreVersionPBImpl versionPB = (StateStoreVersionPBImpl)version; versionPB.setProto(versionProto); return versionPB; } else { throw new IOException("Cannot get State Store version"); } } @Override public RouterServiceState getStatus() { RouterRecordProtoOrBuilder proto = this.translator.getProtoOrBuilder(); if (!proto.hasStatus()) { return null; } return RouterServiceState.valueOf(proto.getStatus()); } @Override public void setStatus(RouterServiceState newStatus) { RouterRecordProto.Builder builder = this.translator.getBuilder(); if (newStatus == null) { builder.clearStatus(); } else { builder.setStatus(newStatus.toString()); } } @Override public String getVersion() { RouterRecordProtoOrBuilder proto = this.translator.getProtoOrBuilder(); if (!proto.hasVersion()) { return null; } return proto.getVersion(); } @Override public void setVersion(String version) { RouterRecordProto.Builder builder = this.translator.getBuilder(); if (version == null) { builder.clearVersion(); } else { builder.setVersion(version); } } @Override public String getCompileInfo() { RouterRecordProtoOrBuilder proto = this.translator.getProtoOrBuilder(); if (!proto.hasCompileInfo()) { return null; } return proto.getCompileInfo(); } @Override public void setCompileInfo(String info) { RouterRecordProto.Builder builder = this.translator.getBuilder(); if (info == null) { builder.clearCompileInfo(); } else { builder.setCompileInfo(info); } } @Override public void setDateStarted(long dateStarted) { this.translator.getBuilder().setDateStarted(dateStarted); } @Override public long getDateStarted() { return this.translator.getProtoOrBuilder().getDateStarted(); } @Override public void setDateModified(long time) { if (getStatus() != RouterServiceState.EXPIRED) { this.translator.getBuilder().setDateModified(time); } } @Override public long getDateModified() { return this.translator.getProtoOrBuilder().getDateModified(); } @Override public void setDateCreated(long time) { this.translator.getBuilder().setDateCreated(time); } @Override public long getDateCreated() { return this.translator.getProtoOrBuilder().getDateCreated(); } @Override public void setAdminAddress(String adminAddress) { this.translator.getBuilder().setAdminAddress(adminAddress); } @Override public String getAdminAddress() { return this.translator.getProtoOrBuilder().getAdminAddress(); } }
RouterStatePBImpl
java
quarkusio__quarkus
extensions/spring-boot-properties/deployment/src/main/java/io/quarkus/spring/boot/properties/deployment/ConfigPropertyBuildItemCandidateUtil.java
{ "start": 3484, "end": 3854 }
class ____ that is setting a field value, we remove that field from // the candidates list if the field was part it. if (opcode == Opcodes.PUTFIELD) { candidates.removeIf(candidate -> candidate.getFieldName().equals(name)); } super.visitFieldInsn(opcode, owner, name, descriptor); } } }
constructor
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/cluster/RedisClusterStressScenariosIntegrationTests.java
{ "start": 2288, "end": 8477 }
class ____ extends TestSupport { private static final String host = TestSettings.hostAddr(); private static RedisClient client; private static RedisClusterClient clusterClient; private static ClusterTestHelper clusterHelper; private final Logger log = LogManager.getLogger(getClass()); private StatefulRedisConnection<String, String> redis5; private StatefulRedisConnection<String, String> redis6; private RedisCommands<String, String> redissync5; private RedisCommands<String, String> redissync6; protected String key = "key"; protected String value = "value"; @BeforeAll public static void setupClient() { client = RedisClient.create(TestClientResources.get(), RedisURI.Builder.redis(host, ClusterTestSettings.port5).build()); clusterClient = RedisClusterClient.create(TestClientResources.get(), Collections.singletonList(RedisURI.Builder.redis(host, ClusterTestSettings.port5).build())); clusterHelper = new ClusterTestHelper(clusterClient, ClusterTestSettings.port5, ClusterTestSettings.port6); } @AfterAll public static void shutdownClient() { FastShutdown.shutdown(client); } @BeforeEach public void before() { clusterHelper.flushdb(); ClusterSetup.setupMasterWithReplica(clusterHelper); redis5 = client.connect(RedisURI.Builder.redis(host, ClusterTestSettings.port5).build()); redis6 = client.connect(RedisURI.Builder.redis(host, ClusterTestSettings.port6).build()); redissync5 = redis5.sync(); redissync6 = redis6.sync(); clusterClient.refreshPartitions(); Wait.untilTrue(clusterHelper::isStable).waitOrTimeout(); } @AfterEach public void after() { redis5.close(); redis6.close(); } @Test public void testClusterFailover() { log.info("Cluster node 5 is master"); log.info("Cluster nodes seen from node 5:\n" + redissync5.clusterNodes()); log.info("Cluster nodes seen from node 6:\n" + redissync6.clusterNodes()); Wait.untilTrue(() -> getOwnPartition(redissync5).is(RedisClusterNode.NodeFlag.UPSTREAM)).waitOrTimeout(); Wait.untilTrue(() -> getOwnPartition(redissync6).is(RedisClusterNode.NodeFlag.REPLICA)).waitOrTimeout(); String failover = redissync6.clusterFailover(true); assertThat(failover).isEqualTo("OK"); Wait.untilTrue(() -> getOwnPartition(redissync6).is(RedisClusterNode.NodeFlag.UPSTREAM)).waitOrTimeout(); Wait.untilTrue(() -> getOwnPartition(redissync5).is(RedisClusterNode.NodeFlag.REPLICA)).waitOrTimeout(); log.info("Cluster nodes seen from node 5 after clusterFailover:\n" + redissync5.clusterNodes()); log.info("Cluster nodes seen from node 6 after clusterFailover:\n" + redissync6.clusterNodes()); RedisClusterNode redis5Node = getOwnPartition(redissync5); RedisClusterNode redis6Node = getOwnPartition(redissync6); assertThat(redis5Node.is(RedisClusterNode.NodeFlag.REPLICA)).isTrue(); assertThat(redis6Node.is(RedisClusterNode.NodeFlag.UPSTREAM)).isTrue(); } @Test public void testClusterFailoverWithTakeOver() { log.info("Cluster node 5 is master"); log.info("Cluster nodes seen from node 5:\n" + redissync5.clusterNodes()); log.info("Cluster nodes seen from node 6:\n" + redissync6.clusterNodes()); Wait.untilTrue(() -> getOwnPartition(redissync5).is(RedisClusterNode.NodeFlag.UPSTREAM)).waitOrTimeout(); Wait.untilTrue(() -> getOwnPartition(redissync6).is(RedisClusterNode.NodeFlag.REPLICA)).waitOrTimeout(); String failover = redissync6.clusterFailover(false, true); assertThat(failover).isEqualTo("OK"); Wait.untilTrue(() -> getOwnPartition(redissync6).is(RedisClusterNode.NodeFlag.UPSTREAM)).waitOrTimeout(); Wait.untilTrue(() -> getOwnPartition(redissync5).is(RedisClusterNode.NodeFlag.REPLICA)).waitOrTimeout(); log.info("Cluster nodes seen from node 5 after clusterFailover:\n" + redissync5.clusterNodes()); log.info("Cluster nodes seen from node 6 after clusterFailover:\n" + redissync6.clusterNodes()); RedisClusterNode redis5Node = getOwnPartition(redissync5); RedisClusterNode redis6Node = getOwnPartition(redissync6); assertThat(redis5Node.is(RedisClusterNode.NodeFlag.REPLICA)).isTrue(); assertThat(redis6Node.is(RedisClusterNode.NodeFlag.UPSTREAM)).isTrue(); } @Test public void testClusterConnectionStability() { StatefulRedisClusterConnection<String, String> clusterConnection = clusterClient.connect(); RedisAdvancedClusterAsyncCommandsImpl<String, String> clusterAsyncCommands = (RedisAdvancedClusterAsyncCommandsImpl<String, String>) clusterConnection .async(); RedisChannelHandler<String, String> statefulConnection = (RedisChannelHandler) clusterConnection; clusterAsyncCommands.set("a", "b"); ClusterDistributionChannelWriter writer = (ClusterDistributionChannelWriter) statefulConnection.getChannelWriter(); StatefulRedisConnectionImpl<Object, Object> statefulSlotConnection = (StatefulRedisConnectionImpl) writer .getClusterConnectionProvider().getConnection(ConnectionIntent.WRITE, 3300); final RedisAsyncCommands<Object, Object> slotConnection = statefulSlotConnection.async(); slotConnection.set("a", "b"); statefulSlotConnection.close(); Wait.untilTrue(() -> !statefulSlotConnection.isOpen()).waitOrTimeout(); assertThat(statefulSlotConnection.isClosed()).isTrue(); assertThat(statefulSlotConnection.isOpen()).isFalse(); assertThat(clusterConnection.isOpen()).isTrue(); assertThat(statefulConnection.isOpen()).isTrue(); assertThat(statefulConnection.isClosed()).isFalse(); try { clusterAsyncCommands.set("a", "b"); } catch (RedisException e) { assertThat(e).hasMessageContaining("Connection is closed"); } clusterConnection.close(); } }
RedisClusterStressScenariosIntegrationTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/jdk/JDKTypeSerializationTest.java
{ "start": 920, "end": 1081 }
class ____ { public InetAddress value; public InetAddressBean(InetAddress i) { value = i; } } // [databind#2197] static
InetAddressBean
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/StreamComponentBuilderFactory.java
{ "start": 1868, "end": 5352 }
interface ____ extends ComponentBuilder<StreamComponent> { /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default StreamComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default StreamComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default StreamComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } }
StreamComponentBuilder
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/TestingUtil.java
{ "start": 648, "end": 4039 }
class ____ { private TestingUtil() { } public static <A extends Annotation> Optional<A> findEffectiveAnnotation( ExtensionContext context, Class<A> annotationType) { if ( !context.getElement().isPresent() ) { return Optional.empty(); } final AnnotatedElement annotatedElement = context.getElement().get(); final Optional<A> direct = AnnotationSupport.findAnnotation( annotatedElement, annotationType ); if ( direct.isPresent() ) { return direct; } if ( context.getTestInstance().isPresent() ) { return AnnotationSupport.findAnnotation( context.getRequiredTestInstance().getClass(), annotationType ); } return Optional.empty(); } public static <A extends Annotation> Collection<A> collectAnnotations( ExtensionContext context, Class<A> annotationType, Class<? extends Annotation> groupAnnotationType) { return collectAnnotations( context, annotationType, groupAnnotationType, (methodAnnotation, methodAnnotations, classAnnotation, classAnnotations) -> { final List<A> list = new ArrayList<>(); if ( methodAnnotation != null ) { list.add( methodAnnotation ); } else if ( classAnnotation != null ) { list.add( classAnnotation ); } if ( methodAnnotations != null ) { list.addAll( Arrays.asList( methodAnnotations ) ); } else if ( classAnnotations != null ) { list.addAll( Arrays.asList( classAnnotations ) ); } return list; } ); } public static <A extends Annotation> Collection<A> collectAnnotations( ExtensionContext context, Class<A> annotationType, Class<? extends Annotation> groupAnnotationType, TestAnnotationCollector<A> collector) { if ( !context.getElement().isPresent() ) { return Collections.emptyList(); } final AnnotatedElement annotatedElement = context.getElement().get(); final A methodAnnotation = annotatedElement.getAnnotation( annotationType ); final A classAnnotation = context.getTestInstance().map( i -> i.getClass().getAnnotation( annotationType ) ).orElse( null ); final Annotation methodPluralAnn = annotatedElement.getAnnotation( groupAnnotationType ); final Annotation classPluralAnn = context.getTestInstance().map( i -> i.getClass().getAnnotation( groupAnnotationType ) ).orElse( null ); final A[] methodAnnotations; final A[] classAnnotations; if ( methodPluralAnn != null ) { try { methodAnnotations = (A[]) groupAnnotationType.getDeclaredMethod( "value", null ).invoke( methodPluralAnn ); } catch (Exception e) { throw new RuntimeException( e ); } } else { methodAnnotations = null; } if ( classPluralAnn != null ) { try { classAnnotations = (A[]) groupAnnotationType.getDeclaredMethod( "value", null ).invoke( classPluralAnn ); } catch (Exception e) { throw new RuntimeException( e ); } } else { classAnnotations = null; } return collector.collect( methodAnnotation, methodAnnotations, classAnnotation, classAnnotations ); } public static <A extends Annotation> boolean hasEffectiveAnnotation(ExtensionContext context, Class<A> annotationType) { return findEffectiveAnnotation( context, annotationType ).isPresent(); } @SuppressWarnings("unchecked") public static <T> T cast(Object thing, Class<T> type) { assertThat( thing, instanceOf( type ) ); return type.cast( thing ); } public
TestingUtil
java
elastic__elasticsearch
x-pack/plugin/sql/sql-client/src/main/java/org/elasticsearch/xpack/sql/client/JreHttpUrlConnection.java
{ "start": 12433, "end": 14126 }
enum ____ { UNKNOWN(SQLException::new), SERIAL(SerialException::new), CLIENT_INFO(message -> new SQLClientInfoException(message, emptyMap())), DATA(SQLDataException::new), SYNTAX(SQLSyntaxErrorException::new), RECOVERABLE(SQLRecoverableException::new), TIMEOUT(SQLTimeoutException::new), SECURITY(SQLInvalidAuthorizationSpecException::new), NOT_SUPPORTED(SQLFeatureNotSupportedException::new); public static SqlExceptionType fromRemoteFailureType(String type) { switch (type) { case "analysis_exception": case "resource_not_found_exception": case "verification_exception": case "invalid_argument_exception": return DATA; case "planning_exception": case "mapping_exception": return NOT_SUPPORTED; case "parsing_exception": return SYNTAX; case "security_exception": return SECURITY; case "timeout_exception": return TIMEOUT; default: return null; } } private final Function<String, SQLException> toException; SqlExceptionType(Function<String, SQLException> toException) { this.toException = toException; } SQLException asException(String message) { if (message == null) { throw new IllegalArgumentException("[message] cannot be null"); } return toException.apply(message); } } }
SqlExceptionType